小编典典

如何在 SQL 字符串中添加“if 子句”?

all

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

我想要做:

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

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

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

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


阅读 117

收藏
2022-06-18

共1个答案

小编典典

对于您的特定查询,您可以执行以下操作:

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
                     )
2022-06-18