【问题标题】:Updating table with random data With NEWID() does not work使用 NEWID() 使用随机数据更新表不起作用
【发布时间】:2010-01-07 21:20:16
【问题描述】:

SQL 服务器 2000:

我有一个包含测试数据的表(大约 100000 行),我想用另一个表中的一些随机数据更新另一个表中的列值。根据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

【问题讨论】:

    标签: sql-server tsql random sql-server-2000


    【解决方案1】:

    您的问题是:您只选择了一个单个值,然后使用该单个值更新所有列

    为了真正实现随机化,您需要逐步/循环方法 - 我在 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 
    

    【讨论】:

      【解决方案2】:

      您需要在选择新 ID 时强制执行每行计算 ..

      这样就可以了

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

      【讨论】:

        猜你喜欢
        • 2011-01-15
        • 2013-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-31
        • 2013-09-13
        • 1970-01-01
        • 2015-11-01
        相关资源
        最近更新 更多