2010-01-07 36 views
4

SQL SERVER 2000:用隨機數據隨着NEWID()更新表無法正常工作

我有測試數據(10多萬行)的表,我想用一些隨機數據來更新從另一個表中的列值從另一張桌子。據this question,這就是我想:

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()) 

然而,「類型」字段仍與所有行的值相同;任何想法我做錯了什麼?

[編輯] 我希望這個查詢爲每一行返回一個不同的值,但它並不:

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 

回答

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

你需要強制執行每行計算的新ID的選擇..

這會做的伎倆

UPDATE testdata 
SET type = (SELECT TOP 1 id FROM testtypes ORDER BY outerTT*CHECKSUM(NEWID())) 
FROM testtypes outerTT