带有“Where exisits”的SQL更新代码未按预期运行

时间:2015-10-05 15:08:18

标签: sql sql-server exists

我尝试制作一些SQL更新代码,在notes字段中添加一行where where子句,但它不断更新表中的每条记录,我不知道我搞砸了什么。如果你在下面的代码中看到我的错误,可以帮助我非常感谢你。

UPDATE Orders
SET notes = 'Basic Confirmation Issued by TaskCentre: ' + CONVERT(varchar(10),getdate(),121)
WHERE EXISTS (SELECT  * 
FROM  Orders INNER JOIN Order_Lines ON orders.ORDER_NUMBER = Order_Lines.ORDER_NUMBER 
WHERE Orders.ORDER_DATE >= '20150630 00:00:00' 
AND Order_Lines.PRODUCT_CODE LIKE '15CONF%%' 
AND Orders.Email > ' ')

2 个答案:

答案 0 :(得分:3)

问题是你的第一个查询(更新)与第二个查询没有关系。因此,如果有任何结果,您基本上都在更新我的订单:

SELECT  * 
FROM  Orders INNER JOIN Order_Lines ON orders.ORDER_NUMBER = Order_Lines.ORDER_NUMBER 
WHERE Orders.ORDER_DATE >= '20150630 00:00:00' 
AND Order_Lines.PRODUCT_CODE LIKE '15CONF%%' 
AND Orders.Email > ' '

您需要以第一个与第二个相关的方式重写查询。或者您也可以做的是,而不是使用*作为您的选择,返回ID。然后更新第一个查询的WHERE子句以在第二个查询中搜索密钥,类似于:

UPDATE Orders
SET notes = 'Basic Confirmation Issued by TaskCentre: ' + CONVERT(varchar(10),getdate(),121)
WHERE order_number IN (SELECT  ORDER_NUMBER 
FROM  Orders INNER JOIN Order_Lines ON orders.ORDER_NUMBER = Order_Lines.ORDER_NUMBER 
WHERE Orders.ORDER_DATE >= '20150630 00:00:00' 
AND Order_Lines.PRODUCT_CODE LIKE '15CONF%%' 
AND Orders.Email > ' ')

你需要仔细检查按键,只需要知道出了什么问题。

答案 1 :(得分:0)

我选择这个:

UPDATE o
SET notes = 'whatever'
FROM orders o
WHERE o.ORDER_DATE >= '20150630 00:00:00' 
  AND o.Email > ' '
  AND o.ORDER_NUMBER IN 
      ( SELECT ol.ORDER_NUMBER 
        FROM Order_Lines ol 
        WHERE ol.PRODUCT_CODE LIKE '15CONF%%'
      ) 

如果你有很多订单我会添加一个索引:

create index order_date on orders(order_date) 
  include ( order_number)
  where email > ' '; 

fiddle