Update a table using CTE and NEWID()

旧城冷巷雨未停 提交于 2020-01-16 19:59:09

问题


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()
   )


来源:https://stackoverflow.com/questions/6705932/update-a-table-using-cte-and-newid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!