c# - SQL check if value exists and return primary key -
i have 2 tables, customer , application, both have primary keys (customerid , applicationid), application has foreign key of customerid.
when user starts application adds customerid application table other information.
what want write sql query/stored procedure first checks if customerid in application table , if don't add again, update information , return applicationid me use.
then if not in table, add customer id , information , return me applicationid.
my code add database is.
insert application (customerid, q5, q11a) values (@customerid,@q5, @q11a);" + "select scope_identity()"; int applicationid = convert.toint32(command.executescalar());
how go turning want do?
you can use merge
statement in order perform insert or update operation. after can use select
statement in order applicationid
. query this:
merge application target using (select @customerid,@q5, @q11a) source (customerid, q5, q11a) on (target.customerid = source.customerid) when matched update set q5 = source.q5, q11a = source.q11a when not matched insert (customerid, q5, q11a) values (source.customerid, source.q5, source.q11a ); select applicationid application customerid = @customerid;
Comments
Post a Comment