如何在SQLstring中添加“if子句”?

所以这就是我想要在我的MySQL数据库上做什么。

我想要:

SELECT * FROM itemsOrdered WHERE purchaseOrder_ID = '@purchaseOrdered_ID' AND status = 'PENDING' 

如果这不会返回任何行,这可能通过if(dr.HasRows == false) ,我现在将在purchaseOrder数据库中创build一个UPDATE

 UPDATE purchaseOrder SET purchaseOrder_status = 'COMPLETED' WHERE purchaseOrder_ID = '@purchaseOrder_ID' 

我怎样才能使这个过程更短一点?

对于您的具体查询,你可以做:

 UPDATE purchaseOrder SET purchaseOrder_status = 'COMPLETED' WHERE purchaseOrder_ID = '@purchaseOrder_ID' and not exists (SELECT * FROM itemsOrdered WHERE purchaseOrder_ID = '@purchaseOrdered_ID' AND status = 'PENDING' ) 

但是,我可能会猜测你正在更高层次上循环。 要设置所有这些值,请尝试以下操作:

 UPDATE purchaseOrder SET purchaseOrder_status = 'COMPLETED' WHERE not exists (SELECT 1 FROM itemsOrdered WHERE itemsOrdered.purchaseOrder_ID = purchaseOrder.purchaseOrdered_ID AND status = 'PENDING' limit 1 ) 

您可以使用多表UPDATE语法来实现purchaseOrderitemsOrdered之间的ANTI-JOIN

 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 

由于MySQL不支持, if exists(*Your condition*) (*Write your query*) ,你可以通过这样写:“if子句”

 (*Write your insert or update query*) where not exists (*Your condition*) 

您还可以使用以下查询来检查logging是否存在,然后进行更新:

 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 
 Select FROM t1 WHERE s11 > ANY (SELECT col1,col2 FROM t2 WHERE NOT EXISTS (SELECT * FROM t3 WHERE ROW(5*t2.s1,77)= (SELECT 50,11*s1 FROM t4 UNION SELECT 50,77 FROM (SELECT * FROM t5) AS t5))); 
 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 

它可以帮助你,当你在sql中使用合并插入,更新和删除基于SQL Server中的匹配语句,例如它可以帮助你https://technet.microsoft.com/en-us/library/bb522522(v=sql。; 105)的.aspx