4

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

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer, it is always best to avoid a procedural approach when a declarative one is available. Use conditionals and other control flow structures only as a last resort in a stored procedure.
@Luke101: Yes sure, it will work. Since you are using C#, you may want to check this short example which uses a similar transaction to yours: aspnettutorials.com/tutorials/database/…
0

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

2 Comments

In this case, you would still need to SELECT tag_count FROM tag WHERE tag_id=1 before the condition statement. However this is not necessary since you can easily specify the condition in the DELETE statement.
sql server does not recognize "tag_count" in the IF conditional as a valid column when I tried this code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.