SQL Server:使用随机值更新列

时间:2015-08-06 13:47:02

标签: sql sql-server random

我有一个表Product,其中有一个名为Genre的列,其中包含空值/不需要的值。

我想用一组值更新该列:

Documentary
Comedy
Adventure/Action
Drama
Thriller
SF/Fantasy
Animation/Family
Others

更新可以按任何顺序进行,但我希望更新列中的每一行。 我应该怎么做呢?

2 个答案:

答案 0 :(得分:2)

I think the following will work:

with genres as (
      select 'Documentary' as genre union all
      select 'Comedy' union all
      . . .
     )
update product
    set genre = (select top 1 g.genre from genres g order by newid());

It is possible that SQL Server will optimize the subquery to run only once. If that is the case, than a correlation clause should fix the problem:

with genres as (
      select 'Documentary' as genre union all
      select 'Comedy' union all
      . . .
     )
update product
    set genre = (select top 1 g.genre from genres g where g.genre <> product.genre or product.genre is null order by newid());

答案 1 :(得分:2)

尝试这样的事情

UPDATE P
SET    genre = rand_values
FROM   Product p
       CROSS apply (SELECT TOP 1 rand_values
                    FROM   (VALUES ('Documentary'),
                                   ('Comedy'),
                                   ('Adventure/Action'),
                                   ('Drama'),
                                   ('Thriller'),
                                   ('SF/Fantasy'),
                                   ('Animation/Family'),
                                   ('Others')) tc (rand_values)
                    WHERE  p.productid = p.productid -- This is just to correlate the query 
                    ORDER  BY Newid()) cs