开发者

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 开发者_如何学Cam 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜