So here\'s what I want to do on my MySQL database.
I would like to do:
SELECT *
FROM itemsOrdered
WHERE purchaseOrder_ID = \'@purchaseOr
if not exists(select top 1 fromFROM itemsOrdered
WHERE purchaseOrder_ID = '@purchaseOrdered_ID'
AND status = 'PENDING' )
Begin
UPDATE purchaseOrder
SET purchaseOrder_status = 'COMPLETED'
WHERE purchaseOrder_ID = '@purchaseOrder_ID
End
You can use the multiple-table UPDATE
syntax to effect an ANTI-JOIN
between purchaseOrder
and itemsOrdered
:
UPDATE purchaseOrder p LEFT JOIN itemsOrdered i
ON p.purchaseOrder_ID = i.purchaseOrder_ID
AND i.status = 'PENDING'
SET p.purchaseOrder_status = 'COMPLETED'
WHERE p.purchaseOrder_ID = '@purchaseOrder_ID'
AND i.purchaseOrder_ID IS NULL
You can also use the following query to check if the record exists and then update it:
if not exists(select top 1 fromFROM itemsOrdered
WHERE purchaseOrder_ID = '@purchaseOrdered_ID'
AND status = 'PENDING' )
Begin
UPDATE purchaseOrder
SET purchaseOrder_status = 'COMPLETED'
WHERE purchaseOrder_ID = '@purchaseOrder_ID
End
If the table contains millions of records then the following query will work fast.
UPDATE PO
SET PO.purchaseOrder_status = 'COMPLETED'
FROM purchaseOrder PO
LEFT OUTER JOIN itemsOrdered IOD ON IOD.purchaseOrder_ID = PO.purchaseOrdered_ID and IOD.status = 'PENDING'
WHERE IOD.purchaseOrder_ID IS NULL
Since MySQL doesn't support if exists(*Your condition*) (*Write your query*)
, you can achieve an 'if clause' by writing like this:
(*Write your insert or update query*) where not exists (*Your condition*)
You can declare a variable holding the number of returned results on select query. You can then run the update statement if this variable is more than 0
Declare @ResultCount int
SELECT @ResultCount = count(*) FROM itemsOrdered WHERE purchaseOrder_ID = '@purchaseOrdered_ID' AND status = 'PENDING'
If @ResultCount > 0
UPDATE purchaseOrder SET purchaseOrder_status = 'COMPLETED' WHERE purchaseOrder_ID = '@purchaseOrder_ID'