sql - Insert Or Update After a Merge -
i have following merge operation on ms sql server.
declare @data xml declare @id int declare @version rowversion set @data = ? set @id = ? <# if ( tw.local.enableoptimisticlocking == true ) { #> set @version = cast(? rowversion) <# } #> merge [<#=tw.local.dbschema#>].[<#=tw.local.tablename#>] target using (select @id id, @version version ) source on target.id = source.id when matched <# if ( tw.local.enableoptimisticlocking == true ) { #> , target.version = source.version <# } #> update set data = @data when not matched insert (data) values (@data) output $action _action<# if ( tw.local.enableoptimisticlocking == true ) { #>, cast( inserted.version bigint) [version]<# } #>, inserted.id;
i wish have insert / update statement db , table update columns based on results of above merge.
i not sure if can have other insert/update inside merge or need use output data want insert/update merge?
i tried following not work....
declare @data xml declare @id int declare @version rowversion set @data = ? set @id = ? <# if ( tw.local.enableoptimisticlocking == true ) { #> set @version = cast(? rowversion) <# } #> merge [<#=tw.local.dbschema#>].[<#=tw.local.tablename#>] target using (select @id id, @version version ) source on target.id = source.id when matched <# if ( tw.local.enableoptimisticlocking == true ) { #> , target.version = source.version <# } #> update set data = @data when not matched insert (data) values (@data) output $action _action<# if ( tw.local.enableoptimisticlocking == true ) { #>, cast( inserted.version bigint) [version]<# } #>, inserted.id, inserted.version, inserted.data; if exists (select inserted.* inserted left join deleted on inserted.id = deleted.id deleted.id null) begin insert [emeaworkflowbpm].[cmf].[businesscontextreporting] (id, version, data, updatedon, toprocess) select i.id, i.version, i.data, getdate(), 1 inserted left join [emeaworkflowbpm].[cmf].[businesscontextreporting] bcr on i.id = bcr.id , i.version = bcr.version bcr.id null; end else if exists (select inserted.* inserted inner join deleted on inserted.id = deleted.id) begin update [emeaworkflowbpm].[cmf].[businesscontextreporting] set version = i.version, data = i.data, updatedon = getdate(), toprocess = 1 inserted left join [emeaworkflowbpm].[cmf].[businesscontextreporting] bcr on i.id = bcr.id; end
many in advance time , help.
you have combine output clause , make updates , inserts new statement following merge.
take @ accepted answer in question:
Comments
Post a Comment