Created
December 7, 2012 21:11
-
-
Save chilversc/4236568 to your computer and use it in GitHub Desktop.
MSSQL MERGE runs update triggers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- This behavior is correct, just surprising if you havn't designed your trigger correctly. | |
| -- Standard cause is designing a trigger that expects exactly 1 row and only 1 row to be changed | |
| -- and doesn't account for if no rows are updated, or more than 1 row is updated. | |
| create table foo (id int primary key, value nvarchar(255)); | |
| go | |
| create trigger t_foo_update on foo for update as | |
| set nocount on | |
| select | |
| (select count(*) from inserted) as inserted_count, | |
| (select count(*) from deleted) as deleted_count | |
| go | |
| print 'inserting' | |
| insert into foo (id, value) values (1, 'test'); | |
| GO | |
| print 'updating' | |
| update foo set value = 'bob' where id = 1; | |
| GO | |
| print 'merging - insert new record, note that update is still fired with 0 rows' | |
| merge foo as target | |
| using (select 2, 'jim') as source (id, value) | |
| on target.id = source.id | |
| when matched then update set value = source.value | |
| when not matched then insert (id, value) values (source.id, source.value); | |
| GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment