简体   繁体   中英

Update statement and Subquery

I would like to use a Subquery to determine whether an update should be done on the OrderClosed status or not. But I can't seem to get this right.

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 )

Or am I thinking to simple?

Try this:

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

Your where clause needs to have syntax like WHERE VARIABLE_NAME IN (LIST_OF_VARIABLE_NAME_VALUES)

You are trying to use syntax similar to WHERE (LIST_OF_MULTIPLE_VARIABLE_NAMES_AND_VALUES)

The syntax for a join in an update in SQL Server doesn't use a where clause. Try this:

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;

Note the following two changes as well. First, the left join is now an inner join , because you want matching records in invoice (based on the where clause). And this version uses table aliases to simplify writing (and reading) the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM