Update a table using CTE and NEWID()

2019-09-05 06:21发布

I want try update a table using random values from the same table, but the original table don´t have a identity to follow or any other number column...

WITH cteTable1 AS (
SELECT
    ROW_NUMBER() OVER (ORDER BY NEWID()) AS n,
    ENDE_NO_Address
FROM TableX
)
UPDATE TableX SET ENDE_NO_Address = (
   SELECT ENDE_NO_Address 
   FROM cteTable1
   WHERE cteTable1.n = This is the problem...

tnks for the help

2条回答
【Aperson】
2楼-- · 2019-09-05 06:34

Guessing...

UPDATE TableX
SET ENDE_NO_Address = (
   SELECT TOP 1 ENDE_NO_Address FROM TableX ORDER BY NEWID()
   )
查看更多
爷的心禁止访问
3楼-- · 2019-09-05 06:39
declare @T table(Col1 varchar(10))

insert into @T values (1),(2),(3),(4),(5)

;with cte as
(
  select *,
         row_number() over(order by newid()) as rn1,
         row_number() over(order by Col1) as rn2
  from @T
)

update C1 set
  Col1 = C2.Col1
from cte as C1
  inner join cte as C2
    on C1.rn1 = C2.rn2

Edit:

WITH cte AS (
SELECT
    ROW_NUMBER() OVER (ORDER BY NEWID()) AS n1,
    ROW_NUMBER() OVER (ORDER BY (select 1)) AS n2,
    ENDE_NO_Address
FROM TableX
)
update C1 set
  ENDE_NO_Address = C2.ENDE_NO_Address
from cte as C1
  inner join cte as C2
    on C1.n1 = C2.n2
查看更多
登录 后发表回答