使用CTE和NEWID()更新表

时间:2011-07-15 10:52:07

标签: sql-server random common-table-expression

我想尝试使用同一个表中的随机值更新表,但原始表没有要遵循的标识或任何其他数字列...

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...

获取帮助

2 个答案:

答案 0 :(得分:1)

...猜测

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

答案 1 :(得分:0)

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

修改

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