Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Is there a way using a single stored procedure to select a record with a given key, then - if that record exists - update it, or to insert a new record if it does not exist? Or will this require multiple procedures? Thanks.
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2009-06-15 : 13:20:57
yup..its possible. the code will be something like
CREATE PROC DataEntry@Key int,... other fieldsASIF NOT EXISTS (SELECT 1 FROM YourTable WHERE PK=@Key)BEGIN INSERT INTO YourTable (PK,...) VALUES (@Key,...)ENDELSEBEGIN UPDATE YourTable SET Field1=@Val1, .... WHERE PK=@KeyENDGO
raky
Aged Yak Warrior
767 Posts
Posted - 2009-06-15 : 13:23:13
single procedure is enoughsyntax is some thing like this
create proc usp_test( @key int, @a varchar(30), @b int)asset nocount onbegin if exists ( select 1 from tablename where [key] = @key ) begin update tablename set a = @a, b= @b where [key] = @key end else begin insert into tablename ( a, b ) values ( @a , @b ) endendset nocount off
Lamprey
Master Smack Fu Yak Hacker
4614 Posts
Posted - 2009-06-15 : 13:24:09
You can also flip it around and try to update first:
CREATE PROC DataEntry@Key int,... other fieldsASUPDATE YourTableSET Field1=@Val1,....WHERE PK=@KeyIF @@ROWCOUNT = 0BEGIN INSERT INTO YourTable (PK,...) VALUES (@Key,...)ENDGO