How do I put an 'if clause' in an SQL string?

前端 未结 9 1387
误落风尘
误落风尘 2021-01-29 18:16

So here\'s what I want to do on my MySQL database.

I would like to do:

SELECT *
    FROM itemsOrdered
    WHERE purchaseOrder_ID = \'@purchaseOr         


        
相关标签:
9条回答
  • 2021-01-29 18:41
    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
    
    0 讨论(0)
  • 2021-01-29 18:42

    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
    
    0 讨论(0)
  • 2021-01-29 18:45

    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
    
    0 讨论(0)
  • 2021-01-29 18:49

    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
    
    0 讨论(0)
  • 2021-01-29 18:52

    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*)
    
    0 讨论(0)
  • 2021-01-29 18:53

    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'        
    
    0 讨论(0)
提交回复
热议问题