SQL Server UPDATE
语句用于在表的所有行中的随机行之间切换值。
我需要在表中所有行的行之间切换特定列的值。哪一行更改值与表上的另一行完全是Ramdow。我正在Oracle,SQL Server和DB2上执行此操作。
示例:
更新前:
ID - Name - LastName
--------------------
1 - Peter - Gonzalez
2 - Max - Green
...
4480 - Maximus - Magna
4495 - Martha - Potter
更新后:
1- Martha - Gonzalez
2- William - Green
...
4480 - Peter - Magna
4495 - otherNameFromAnotherRow - Potter
我检查了以下相关问题:
我试图将执行随机顺序的逻辑与下一行数据的更新与行的更新结合起来,但是我做对了:
UPDATE HR.PERSONS
SET (NAME) = SELECT NAME
FROM
(SELECT t1.NAME
FROM PERSONS t1
ORDER BY dbms_random.value)
WHERE t1.ROWID > PERSONS.ROWID
AND
UPDATE HR.PERSONAS
SET (NOMBRE) = (SELECT NOMBRE
FROM
(SELECT t1.NOMBRE
FROM PERSONAS t1
ORDER BY dbms_random.value)
WHERE ROWNUM = 1)
在这种情况下,子查询仅获取值之一,并将该值设置为所有行。
该示例适用于Oracle(它们在oracle上不起作用),我正在尝试正确地执行该查询,并且也在SQL Server和DB2中完成相同的操作。)
答案 0 :(得分:0)
update myTable
set Name = shuffle.Name
from myTable t
inner join
(select id, row_number() over (order by id) as origId from mytable) orig
on orig.id = t.id
join
(select Name, row_number() over (order by newid()) as [newId] from myTable) shuffle
on orig.OrigId = shuffle.[newId];