Thursday, February 9, 2012

A Good insert record if non existant Stored Procedure

Can anyone spare me a good SP that ...

checks if the record exists - and if so return the identity.

and if the record does not exist

inserts it and returns the identity.

Mine keep flipping up :) so I rather look at someone else and use theirs.

Thanks in advance.

Create Proc Proc1
(
parameters...,
@.out int = null output
)
as

select @.out = identcolumn from table1 where ... (use other parameters to determine what to look for)

if @.out is not null
return

insert into table1 (field list)
values (parameters)

set @.out = @.@.identity

return

You could use EXISTS, but in this case you want the identity column. So, if you use EXISTS, you'd have to do a second query to get the identity. Just do one query, if it's there send back the ID, if not, insert it and send back the ID. You could add another output parameter if want to indicate whether you inserted or not.|||Its the same thing I was doing - somehow mine keeps tripping up. Anyway, I was hoping maybe there was a more efficient means aside from two queries.

Thanks for the insight!|||you could combine the insert with the (not) exists into one batch, but really what's the point? It a bit like those mad people that write whole programs in C on one line.

No comments:

Post a Comment