Sample discussion table
create table t1 (id int identity primary key, other int); insert t1 select 2;
This TSQL makes the final choice at the end, which will end up being the result for ExecuteNonQuery
set nocount on declare @tmp table (action sysname) ; with new(id,other) as (select 1,4) merge top(1) into t1 using new on t1.id = new.id when matched then update set other = new.id when not matched then insert values (other) output $action into @tmp ; set nocount off select action from @tmp
This works well for TOP (1), since it only creates one line in @tmp, but the example below shows what happens when there are several entries continuing from the above
set nocount on declare @tmp table (action sysname) ; merge into t1 using (values(1,4),(2,5)) new(id,other) on t1.id = new.id when matched then update set other = new.id when not matched then insert values (other) output $action into @tmp ; set nocount off select action from @tmp
Output:
action ====== UPDATE INSERT
- Does the additional temp table variable and SELECT statement in SP affect performance?
That would be negligible, you can ignore it.
- Should I βwrapβ 2 in a transaction (my application is multithreaded)?
No. The insert in @tmp is atomic, and the selection comes from the temp table, which is session specific (nothing can interfere with it)
source share