【问题标题】:SQL Server: Update a colum with Random ValueSQL Server:使用随机值更新列
【发布时间】:2015-10-29 16:56:10
【问题描述】:

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

我想用一组值更新该列:

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

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

【问题讨论】:

  • 为什么你有存储在 Product 表中的流派值?您应该在 Product 表中有一个 Genre 表和一个外键。您的问题的问题在于,您根本不清楚您要做什么。您想为产品表中的每一行随机选择其中一个值吗?
  • 我上面提到的值需要在Product表的Genre列中随机更新。
  • 如果您将流派标准化为一个查找表而不是一遍又一遍地重复这些值,那么您的情况仍然会好得多。

标签: sql sql-server random


【解决方案1】:

试试这样的

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 

【讨论】:

    【解决方案2】:

    认为以下方法可行:

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

    SQL Server 可能会将子查询优化为只运行一次。如果是这种情况,那么相关性子句应该可以解决问题:

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

    【讨论】:

    • 以前从未使用过。它说Lookup Error - SQL Server Database Error: Incorrect syntax near ')'.(关闭 with 语句的括号)
    • @TauseefHussain 。 . .您是否将 . . . 替换为您想要的其他值?
    猜你喜欢
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    相关资源
    最近更新 更多