How to use conditional SQL expressions

I need to delete a row based on the value in a column when executing an update request. 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 use embedded sql with C # and sql servers

+4
source share
2 answers

In general, the best option in these cases is to wrap the UPDATE and DELETE statements in 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; 
+6
source

Hmm, have you tried 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
source

Source: https://habr.com/ru/post/1299283/


All Articles