MS SQL Server で次の MERGE 操作を行っています。
DECLARE @data as xml
DECLARE @id as int
DECLARE @version as rowversion
SET @data = ?
SET @id = ?
<# if ( tw.local.enableOptimisticLocking == true ) { #>
SET @version = CAST(? as rowversion)
<# } #>
MERGE [<#=tw.local.dbSchema#>].[<#=tw.local.tableName#>] AS target
USING (Select @id as id, @version version ) as source ON target.id = source.id
WHEN MATCHED <# if ( tw.local.enableOptimisticLocking == true ) { #> AND target.version = source.version <# } #> THEN
UPDATE SET data = @data
WHEN NOT MATCHED THEN
INSERT (data) VALUES (@data)
OUTPUT $action as _action<# if ( tw.local.enableOptimisticLocking == true ) { #>, CAST( inserted.version as BigInt) as [version]<# } #>, inserted.id;
上記のMERGEの結果に基づいていくつかの列を更新するために、別のDBとテーブルへのINSERT / UPDATEステートメントが必要です。
MERGE 内に他の INSERT/UPDATE を含めることができるかどうか、または MERGE から INSERT/UPDATE したいすべてのデータを取得するために Output を使用する必要があるかどうかわかりません。
以下を試してみましたが、うまくいきません....
DECLARE @data as xml
DECLARE @id as int
DECLARE @version as rowversion
SET @data = ?
SET @id = ?
<# if ( tw.local.enableOptimisticLocking == true ) { #>
SET @version = CAST(? as rowversion)
<# } #>
MERGE [<#=tw.local.dbSchema#>].[<#=tw.local.tableName#>] AS target
USING (Select @id as id, @version version ) as source ON target.id = source.id
WHEN MATCHED <# if ( tw.local.enableOptimisticLocking == true ) { #> AND target.version = source.version <# } #> THEN
UPDATE SET data = @data
WHEN NOT MATCHED THEN
INSERT (data) VALUES (@data)
OUTPUT $action as _action<# if ( tw.local.enableOptimisticLocking == true ) { #>, CAST( inserted.version as BigInt) as [version]<# } #>, inserted.id, inserted.version, inserted.data;
IF EXISTS (SELECT INSERTED.* FROM INSERTED LEFT JOIN DELETED ON INSERTED.ID = DELETED.id WHERE DELETED.ID IS NULL)
BEGIN
INSERT INTO [EMEAworkflowBPM].[cmf].[BusinessContextReporting] (id, version, data, updatedOn, toProcess)
SELECT i.id, i.version, i.data, GETDATE(), 1
FROM Inserted i
LEFT JOIN [EMEAworkflowBPM].[cmf].[BusinessContextReporting] bcr
ON i.id = bcr.id AND i.version = bcr.version
WHERE bcr.id IS NULL;
END
ELSE IF EXISTS (SELECT INSERTED.* FROM 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
FROM Inserted AS i
LEFT JOIN [EMEAworkflowBPM].[cmf].[BusinessContextReporting] AS bcr
ON i.id = bcr.id;
END
あなたの時間と助けを前もって感謝します。