views:

82

answers:

2

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

+6  A: 

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;
Daniel Vassallo
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.
JohnFx
will this work with inline sql?
Luke101
@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: http://www.aspnettutorials.com/tutorials/database/sql-transaction-csharp.aspx
Daniel Vassallo
wow..I tried it and it worked just fine. Thank you Daniel!!
Luke101
A: 

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
rockinthesixstring
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.
Daniel Vassallo
sql server does not recognize "tag_count" in the IF conditional as a valid column when I tried this code.
Luke101