简体   繁体   中英

How to use SQL conditional statements

I need to delete a row based upon the value in a column while executing an update query. Here is the code:

 UPDATE tag SET tag_count = tag_count - 1 WHERE tag_id = 1
 IF tag_count < 1
 delete from tag where tag_id = 1

This query here gives me an error.

EDIT I am using inline sql with C# and sql server

In general, the best option in these cases is to wrap the UPDATE and DELETE statements within a transaction:

BEGIN TRANSACTION;

UPDATE tag SET tag_count = tag_count - 1 WHERE tag_id = 1
DELETE from tag where tag_id = 1 and tag_count < 1;

COMMIT TRANSACTION;

Hmm, did you try using Begin and End?

 UPDATE tag 
 SET tag_count = tag_count - 1 
 WHERE tag_id = 1

 IF tag_count < 1
     BEGIN
       DELETE FROM tag 
       WHERE tag_id = 1
     END

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