循环 - 内存不足错误

时间:2017-10-03 01:34:30

标签: sql sql-server tsql

我正在尝试创建一个快速脚本,通过切换周围的名称来匿名数据库,我使用while循环来执行此操作,这会导致内存不足错误(在崩溃之前它会达到大约950条记录)这是我的代码的一部分:

DECLARE @counter INT;
SET @counter = 1

WHILE @counter < (SELECT MAX(anonID) FROM anon_PersonChangeData)
BEGIN
    SET @Lower = 1 ---- The lowest random number
    SET @Upper = ( SELECT MAX(anonID) + 1 FROM anon_PersonChangeData ) ---- The highest random number
    SET @Random = ( SELECT ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0) )

    WHILE @Random = @counter
    BEGIN
        SET @Random = ( SELECT ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0) )
    END

    UPDATE anon_PersonChangeData 
        SET   personNewFirstName = (SELECT personCurrentFirstName FROM anon_PersonChangeData WHERE anonID = @Random)
            , personNewSurname = (SELECT personCurrentSurname FROM anon_PersonChangeData WHERE anonID = @Random)
    WHERE anonID = @counter

    SET @counter = @counter + 1
END

AnonID只是我从1开始使用的增量字段。

这似乎需要很长时间才能达到950.

任何建议都将不胜感激!

1 个答案:

答案 0 :(得分:2)

ORDER BY NEW()会给你一个随机序列。这对你来说足够好了吗?

; with cte as
(
    select  rn = ROW_NUMBER() over (order by newid()), *
    from    anon_PersonChangeData
) 
update  c1
set personNewFirstName  = c2.personNewFirstName,
    personNewSurname    = c2.personNewSurname 
from    cte c1
    inner join cte c2   on  c1.rn = c2.rn

如果你想要随机的First&amp;姓氏,再次只是inner join cte并从新cte

更新姓氏