【问题标题】:UPDATE script not working - 0 Rows Affected更新脚本不起作用 - 0 行受影响
【发布时间】:2011-12-16 08:27:18
【问题描述】:

我有一个 SQL Server 数据库,我正在尝试在其中一个表上运行更新脚本,但它一直说“0 Rows Affected”。

如果我运行以下脚本,它会显示“33 Rows Affected”

UPDATE [StoreTestDB].[dbo].[ProductVariant]   
SET [IsDefault] = 0,
    [Published] = 0
WHERE ProductID = 19

但如果我运行以下脚本,它会显示“0 行受影响”:

UPDATE [StoreTestDB].[dbo].[ProductVariant]   
SET [IsDefault] = 0,
    [Published] = 0
WHERE ProductID = 19
AND ProductID = 20
AND ProductID = 23
AND ProductID = 24
AND ProductID = 25
AND ProductID = 27
AND ProductID = 28
AND ProductID = 29
AND ProductID = 30
AND ProductID = 31
AND ProductID = 32
AND ProductID = 33
AND ProductID = 54
AND ProductID = 55
AND ProductID = 56
AND ProductID = 57
AND ProductID = 58
AND ProductID = 64
AND ProductID = 71
AND ProductID = 72
AND ProductID = 73
AND ProductID = 74
AND ProductID = 75
AND ProductID = 77
AND ProductID = 105
AND ProductID = 109
AND ProductID = 152
AND ProductID = 157
AND ProductID = 158
AND ProductID = 162
AND ProductID = 164
AND ProductID = 165
AND ProductID = 167
AND ProductID = 169
AND ProductID = 170
AND ProductID = 173
AND ProductID = 174

我在这里做错了什么?

我确定 productID 的 IsDefault = 1 和 Published = 1,这就是我要运行脚本的原因。

有什么想法吗?

【问题讨论】:

    标签: sql sql-server-2005 tsql sql-server-2008 sql-update


    【解决方案1】:

    您的错误是使用 AND。
    想一想:一个产品不能同时有不同的ID;您想要的是更新不同的产品,每个 id 一个。
    所以你必须使用 OR:

    UPDATE [StoreTestDB].[dbo].[ProductVariant]   
    SET [IsDefault] = 0,
        [Published] = 0
    WHERE ProductID = 19
    OR ProductID = 20
    OR ProductID = 23
    OR ProductID = 24
    ...
    

    简洁的语法是:

    UPDATE [StoreTestDB].[dbo].[ProductVariant]   
    SET [IsDefault] = 0,
        [Published] = 0
    WHERE ProductID IN (19, 20, 23, 24, ....)
    

    【讨论】:

    • 谢谢你的解释,你给了我清晰的例子。我已将您的答案标记为我选择的解决方案。非常感谢!
    【解决方案2】:

    您的 WHERE 子句有问题。您不想更新 productID 是所有这些 id 的行(因为每行只能有一个 ProductID,因此您的 WHERE 语句永远不会为真),而是一一更新。您应该使用 IN 代替,如下所示:

    UPDATE [StoreTestDB].[dbo].[ProductVariant]   
    SET [IsDefault] = 0,
        [Published] = 0
    WHERE ProductID IN ( 19, 20, 23 ... etc);
    

    这将单独更新所有行。

    【讨论】:

      【解决方案3】:

      用户 OR 代替。您是说 ProductID 应该同时为 19、20、...。

      【讨论】:

        【解决方案4】:

        好吧,我认为问题在于您将所有 id 加在一起,即产品的 id 为 162 或 164,但不是两者兼有。

        尝试使用 IN 的语句,即:

        ProductID 在哪里 (19,20,21,22 ETC)

        应该有更多的运气!

        【讨论】:

          【解决方案5】:

          两种选择:

          1. 将所有AND改为OR
          2. 使用IN 子句

          【讨论】:

            【解决方案6】:
            UPDATE [StoreTestDB].[dbo].[ProductVariant]   
            SET [IsDefault] = 0,
                [Published] = 0
            WHERE ProductID in (19, 20, 23....164)
            

            【讨论】:

              猜你喜欢
              • 2015-05-04
              • 1970-01-01
              • 2014-03-22
              • 2019-11-20
              • 2011-06-11
              • 1970-01-01
              • 2016-01-19
              • 1970-01-01
              相关资源
              最近更新 更多