Wednesday, 16 December 2009

Check if a record exists in a stored procedure

I have users assigning selected items from a list to a group that they have created. I don't want to bother the user with detailed information about whether any particular item they selected was already in the group, I just want to add it if it's not there, and do nothing if it's there already.

The neatest way to do this was to drop the logic into the stored procedure like below. The 'IF NOT EXISTS' condition means I can insert only when there is no record matching the SELECT query.

IF NOT EXISTS(SELECT * from [table] where something = @mySomething)
/**** do insert ****/


No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!