SQL SERVER 2000:
我有一个包含测试数据的表(大约100000行),我想用另一个表中的一些随机数据更新另一个表中的列值。根据{{3}},这就是我正在尝试的:
UPDATE testdata
SET type = (SELECT TOP 1 id FROM testtypes ORDER BY CHECKSUM(NEWID()))
-- or even
UPDATE testdata
SET type = (SELECT TOP 1 id FROM testtypes ORDER BY NEWID())
但是,“type”字段对于所有行仍然具有相同的值;任何想法我做错了什么?
[修改] 我希望这个查询为每一行返回一个不同的值,但它不会:
SELECT testdata.id, (SELECT TOP 1 id FROM testtypes ORDER BY CHECKSUM(NEWID())) type
FROM testdata
-- however seeding a rand value works
SELECT testdata.id, (SELECT TOP 1 id FROM testtypes ORDER BY CHECKSUM(NEWID()) + RAND(testdata.id)) type
FROM testdata
答案 0 :(得分:4)
您的问题是:您只选择单一值,然后使用该单个值更新所有列。
为了真正实现随机化,您需要执行逐步/循环方法 - 我在SQL Server 2008中尝试过这种方法,但我认为它也适用于SQL Server 2000:
-- declare a temporary TABLE variable in memory
DECLARE @Temporary TABLE (ID INT)
-- insert all your ID values (the PK) into that temporary table
INSERT INTO @Temporary SELECT ID FROM dbo.TestData
-- check to see we have the values
SELECT COUNT(*) AS 'Before the loop' FROM @Temporary
-- pick an ID from the temporary table at random
DECLARE @WorkID INT
SELECT TOP 1 @WorkID = ID FROM @Temporary ORDER BY NEWID()
WHILE @WorkID IS NOT NULL
BEGIN
-- now update exactly one row in your base table with a new random value
UPDATE dbo.TestData
SET [type] = (SELECT TOP 1 id FROM dbo.TestTypes ORDER BY NEWID())
WHERE ID = @WorkID
-- remove that ID from the temporary table - has been updated
DELETE FROM @Temporary WHERE ID = @WorkID
-- first set @WorkID back to NULL and then pick a new ID from
-- the temporary table at random
SET @WorkID = NULL
SELECT TOP 1 @WorkID = ID FROM @Temporary ORDER BY NEWID()
END
-- check to see we have no more IDs left
SELECT COUNT(*) AS 'After the update loop' FROM @Temporary
答案 1 :(得分:2)
您需要在选择新ID时强制执行每行计算..
这可以解决问题
UPDATE testdata
SET type = (SELECT TOP 1 id FROM testtypes ORDER BY outerTT*CHECKSUM(NEWID()))
FROM testtypes outerTT