更新语句和子查询

时间:2014-06-04 10:40:52

标签: sql sql-update subquery

我想使用子查询来确定是否应该对OrderClosed状态进行更新。但我似乎无法做到这一点。

Update Orders 
set orderclosed = 1 
where (
SELECT dbo.orders.ordernr, 
   dbo.orders.orderdate, 
   dbo.orders.salesdate, 
   dbo.orders.deliverydate, 
   dbo.orders.orderclosed, 
   dbo.invoices.invoicenr 
FROM   dbo.orders 
   LEFT OUTER JOIN dbo.invoices 
                ON dbo.orders.id = dbo.invoices.orderid 
WHERE  dbo.invoices.invoicenr IS NOT NULL 
   AND orderclosed = 0 )

还是我想简单?

2 个答案:

答案 0 :(得分:0)

试试这个:

Update Orders 
 set orderclosed = 1 
 where ordernr in 
 (
     SELECT dbo.orders.ordernr
     FROM   dbo.orders 
     LEFT OUTER JOIN dbo.invoices 
         ON dbo.orders.id = dbo.invoices.orderid 
     WHERE  dbo.invoices.invoicenr IS NOT NULL 
     AND orderclosed = 0 
 );`

您的where子句需要具有WHERE VARIABLE_NAME IN (LIST_OF_VARIABLE_NAME_VALUES)

之类的语法

您正在尝试使用与WHERE (LIST_OF_MULTIPLE_VARIABLE_NAMES_AND_VALUES)

类似的语法

答案 1 :(得分:0)

SQL Server中joinupdate的语法不使用where子句。试试这个:

Update o 
    set orderclosed = 1 
FROM dbo.orders o JOIN
     dbo.invoices i
     ON o.id = i.orderid 
WHERE i.orderid IS NOT NULL AND orderclosed = 0;

请注意以下两项更改。首先,left join现在是inner join,因为您希望invoice中的匹配记录(基于where子句)。此版本使用表别名来简化查询的编写(和阅读)。