Update a table using CTE and NEWID()

2019-09-05 06:41发布

问题:

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

回答1:

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


回答2:

Guessing...

UPDATE TableX
SET ENDE_NO_Address = (
   SELECT TOP 1 ENDE_NO_Address FROM TableX ORDER BY NEWID()
   )