尝试使用随机值更新行时出错

时间:2013-06-29 08:28:39

标签: sql-server random sql-update subquery

我正在尝试使用来自另一个表的随机行的数据更新表中的每一行。这是我目前使用的SQL:

SELECT Data, RowNumber FROM SampleData

SELECT FLOOR(ABS(CHECKSUM(NEWID())) / 2147483647.0 * 3 + 1) FROM Name

UPDATE Name SET Surname = (SELECT Data FROM SampleData WHERE RowNumber = FLOOR(ABS(CHECKSUM(NEWID())) / 2147483647.0 * 3 + 1))

以下是我得到的结果:

Smith   1
Hunt    2
Jones   3

2
2
3
2
1
3
2
.... continues with a random number between 1 and 3 for each row in the Name table

Msg 512, Level 16, State 1, Line 9
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

所以我的问题是为什么SELECT语句每行产生一个随机数,其中UPDATE子查询似乎返回多行。我正在使用SQL Server 2012 SP1,以防万一。

1 个答案:

答案 0 :(得分:1)

您正在尝试使用一组数据更新字段,这会导致所描述的错误。

创建临时映射表并更新名称,形成名称ID与“随机” SampleDate ID

之间的联接

SQLFiddle

SELECT ID,FLOOR(ABS(CHECKSUM(NEWID())) / 2147483647.0 * 3 + 1) as RN
Into #tmp
FROM Name

Update Name set SurName=Data 
from #tmp
join SampleData sd on sd.RowNumber=#tmp.rn
where #tmp.ID=Name.ID

Select * from Name