这是我拥有的 XML:
<?xml version="1.0" encoding="UTF-8"?>
<Data>
<Record>
<ServerId>1</ServerId>
<CompanyId>1</CompanyId>
<InstanceId>2</InstanceId>
<TemplateId>23</TemplateId>
<ContactId>11052</ContactId>
<RecordId>11462</RecordId>
<TaskId>677</TaskId>
<EntryDate>2016-04-21 14:17:02:813</EntryDate>
<EntryKey>key_test_1</EntryKey>
<EntryValue>value_test_1</EntryValue>
</Record>
<Record>
<ServerId>1</ServerId>
<CompanyId>1</CompanyId>
<InstanceId>2</InstanceId>
<TemplateId>23</TemplateId>
<ContactId>11052</ContactId>
<RecordId>11462</RecordId>
<TaskId>677</TaskId>
<EntryDate>2016-04-21 14:17:02:873</EntryDate>
<EntryKey>key_test_2</EntryKey>
<EntryValue>value_test_2</EntryValue>
</Record>
<Record>
<ServerId>1</ServerId>
<CompanyId>1</CompanyId>
<InstanceId>2</InstanceId>
<TemplateId>23</TemplateId>
<ContactId>11052</ContactId>
<RecordId>11462</RecordId>
<TaskId>677</TaskId>
<EntryDate>2016-04-21 14:17:02:935</EntryDate>
<EntryKey>key_test_1</EntryKey>
<EntryValue>value_test_3</EntryValue>
</Record>
</Data>
这是将这些数据插入或更新到单个表中的 MERGE 语句:
merge WRF_REPOSITORY_CUSTOM_DATA rep
using (select
entity.value('ServerId[1]', 'int') as ServerId,
entity.value('CompanyId[1]', 'int') as CompanyId,
entity.value('InstanceId[1]', 'int') as InstanceId,
entity.value('TemplateId[1]', 'int') as TemplateId,
entity.value('ContactId[1]', 'bigint') as ContactId,
entity.value('RecordId[1]', 'bigint') as RecordId,
entity.value('TaskId[1]', 'bigint') as TaskId,
entity.value('EntryDate[1]', 'datetime') as EntryDate,
entity.value('EntryKey[1]', 'varchar(max)') as EntryKey,
entity.value('EntryValue[1]', 'varchar(max)') as EntryValue
from @xmlInsertOrReplace.nodes('/Data/Record') as T(entity)) as dat
on
rep.ServerId = dat.ServerId and
rep.CompanyId = dat.CompanyId and
rep.InstanceId = dat.InstanceId and
rep.TemplateId = dat.TemplateId and
rep.ContactId = dat.ContactId and
rep.RecordId = dat.RecordId and
rep.EntryKey = dat.EntryKey
when MATCHED then update set
rep.TaskId = dat.TaskId,
rep.EntryDate = dat.EntryDate,
rep.EntryValue = dat.EntryValue
when NOT MATCHED then
insert (ServerId, CompanyId, InstanceId, TemplateId, ContactId, RecordId, TaskId, EntryDate, EntryKey, EntryValue)
values (dat.ServerId, dat.CompanyId, dat.InstanceId, dat.TemplateId, dat.ContactId, dat.RecordId, dat.TaskId, dat.EntryDate, dat.EntryKey, dat.EntryValue);
当表中没有记录时,我期望的是第一条 xml 记录将被插入,第二条 xml 记录将被插入,第三条 xml 记录将更新第一个表记录,因为它符合条件。实际发生的是我得到 3 个插入而不是 2 个插入和 1 个更新。
有没有办法在每次插入或更新后强制 MERGE 语句执行 COMMIT 或其他操作?我不想对 xml 记录进行分组或选择最大/最后一个。
更新:
我使用了一个类似于第一个的合并操作。唯一的区别是这个连接了值。
when MATCHED then update set
rep.TaskId = dat.TaskId,
rep.EntryDate = dat.EntryDate,
rep.EntryValue = case len(isnull(rep.EntryValue, '')) when 0 then dat.EntryValue else rep.EntryValue + ';' + dat.EntryValue end
预期的结果应该是:
key_test_1 | value_test_1;value_test_3
key_test_2 | value_test_2