生成两个查询,一个返回要替换的 emp_no,第二个列按顺序编号。另一个对随机数做同样的事情。然后在更新中,根据数字加入他们。
UPDATE employee
SET e.emp_no=r.rand_val
FROM (query1) e
JOIN (query2) r
ON e.number=r.number
query1 可能类似于:
SELECT emp_no,row_number() OVER(ORDER BY emp_no) as number
FROM employee
WHERE employee.emp_no IN (SELECT emp_no FROM employee
GROUP BY emp_no HAVING COUNT(*)>1)
query2 可能类似于:
SELECT rand_val,row_number() OVER(ORDER BY NEWID()) as number
FROM random_values
所以整个事情是:
UPDATE employee
SET e.emp_no=r.rand_val
FROM (
SELECT emp_no,row_number() OVER(ORDER BY emp_no) as number
FROM employee
WHERE employee.emp_no IN (SELECT emp_no FROM employee
GROUP BY emp_no HAVING COUNT(*)>1)) e
JOIN (
SELECT rand_val,row_number() OVER(ORDER BY NEWID()) as number
FROM random_values) r
ON e.number=r.number
已经有一段时间了,您可能必须像这样将它们加入到员工表中:
UPDATE employee
SET e.emp_no=r.rand_val
FROM employee
JOIN
(
SELECT emp_no,row_number() OVER(ORDER BY emp_no) as number
FROM employee
WHERE employee.emp_no IN (SELECT emp_no FROM employee
GROUP BY emp_no HAVING COUNT(*)>1)) e
ON employee.emp_no=e.emp_no
JOIN (
SELECT rand_val,row_number() OVER(ORDER BY NEWID()) as number
FROM random_values) r
ON e.number=r.number
但是,除非您可以通过其他字段区分 emp_no,否则您仍然可能难以为重复项都分配一个新数字(或相同的随机数)。我假设您的真实员工表不止 1 列,并且您需要同时引用连接中的 emp_no 和唯一字段,以确保为它们分配不同的数字,或者消除 query1 中的两个重复项之一。