如何使用20个随机选择的值更新10000条记录?

时间:2012-02-27 10:12:02

标签: sql sql-server sql-server-2008

如何使用20个随机选择的值更新10000条记录?

示例:在一个表中,我有firstname,lastname,emailid等字段,它有10000条记录。我想更新一个带有测试邮件ID列表的emailid字段。

2 个答案:

答案 0 :(得分:5)

感谢Tomek指出原始答案中的错误和冗余

UPDATE PersonalInformation
SET    EmailID = ABS(CAST(NEWID() AS BINARY(6)) % 20)

答案 1 :(得分:1)

以下是一个例子:

declare @EmailList table
(
    EmailIndex int identity(1, 1) primary key,
    EmailAddress nvarchar(100)
)

insert @EmailList (EmailAddress)
    select 'email1@mailserver.com' union all
    select 'email2@mailserver.com' union all
    select 'email3@mailserver.com'
    -- other emails here...

declare @emailListLength int
select @emailListLength = count (*) from @EmailList

update Users set Email = el.EmailAddress
    from
       (select CEILING(RAND(CONVERT(varbinary, newid())) * @emailListLength) as randomEmailIndex, * from Users) rnd
          join @EmailList el on el.EmailIndex = rnd.randomEmailIndex

CEILING(RAND(CONVERT(varbinary, newid()))表达式将生成从1[email list length]的随机数,然后我们使用此随机索引将Users表与预定义的枚举电子邮件列表一起加入。