gpt4 book ai didi

sql - 使用随机名称更新 SQL Server 表

转载 作者:行者123 更新时间:2023-12-04 02:14:32 24 4
gpt4 key购买 nike

我正在尝试以下操作:

update [Employees] set Last_User = 

(select top 1 name from
(select 'John' as name
union select 'Tim' as name
union select 'Jane' as name
union select 'Jack' as name
union select 'Steve' as name
union select 'Ann' as name
)

as names order by newid())

但继续为所有行获取相同的名称。我怎样才能让它有所不同?

注意:名称是在查询中输入的,而不是来自另一个表。

谢谢

最佳答案

您正在尝试更新整列而不是更新每一行,因此生成的第一个值会更新到所有行,您可以使用 T-SQL 完成预期任务

DECLARE @counter int = 1

WHILE @counter <= (SELECT COUNT(1) FROM [Employees]) --or any speific row set you want to modify
BEGIN

UPDATE a
set Last_User =
(SELECT top 1 name from
(SELECT 'John' as name
UNION SELECT 'Tim' AS name
UNION SELECT 'Jane' AS name
UNION SELECT 'Jack' AS name
UNION SELECT 'Steve' AS name
UNION SELECT 'Ann' AS name
)

AS names ORDER BY NEWID())
FROM (SELECT *,ROW_NUMBER() OVER (ORDER BY Last_User)rnum FROM [Employees])a
WHERE a.rnum = @counter

SET @counter = @counter + 1

END

关于sql - 使用随机名称更新 SQL Server 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35122989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com