sql server - SQL Merge statement not working in Stored Procedure -


the following code not seem work. if address not exist, not insert new record. however, if address exist, updated.

alter procedure [users].[updateaddress]     @userid int,     @address1 varchar(100),     @address2 varchar(100),     @town varchar(100),     @county varchar(50),     @postcode varchar(50),     @country varchar(50),     @type int  merge [users].[addresses] target using (select userid [users].[addresses] userid = @userid) source on (source.userid = target.userid)  when matched     update set target.address1 = @address1,     target.address2 = @address2,     target.town = @town,     target.county = @county,     target.postcode = @postcode,     target.country = @country when not matched target     insert ([userid], [address1], [address2], [town], [county], [postcode], [country], [modified], [type])     values(@userid, @address1, @address2, @town, @county, @postcode, @country, getdate(), @type); 

you're source shouldn't rely upon target table. try instead:

merge [users].[addresses] target using (select @userid,@address1,@address2,@town,@county,@postcode,@country,@type)     source (userid,address1,address2,town,county,postcode,country,type) on (source.userid = target.userid) when matched     update set target.address1 = source.address1,     target.address2 = source.address2,     target.town = source.town,     target.county = source.county,     target.postcode = source.postcode,     target.country = source.country when not matched target     insert ([userid], [address1], [address2], [town], [county], [postcode], [country], [modified], [type])     values(source.userid, source.address1, source.address2, source.town, source.county, source.postcode, source.country, getdate(), source.type); 

at moment, you're creating zero-row source rowset, of course nothing happens in merge.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -