我需要从select中插入行,如果key是重复的,则删除条目并插入
Table1
ColumnA ColumnB ColumnC ColumnD
A 1 A1 7/21/2017
B 2 B1 7/22/2017
C 3 C1 7/23/2017
独特的组合ColumnA和ColumnC
Table2
ColumnE ColumnF ColumnG
A 1 A1
A 2 A2
B 3 B1
B 2 B2
C 3 C1
C 1 C2
我应该将表2中的行插入表1
Insert into table1 (columnA, columnB, ColumnC) select columnE, ColumnF, ColumnG from table2
上述查询会出现冲突,说明插入了重复的密钥但需要 一种删除创建冲突并插入该行的行的方法。 最终输出应该是
Table 1
ColumnA ColumnB ColumnC ColumnD
A 1 A1 08/08/2017 - deleted and added as conflict arised
A 2 A2 08/08/2017
B 3 B1 08/08/2017 -deleted and added as conflict arised
B 2 B2 08/08/2017
C 3 C1 08/08/2017
C 1 C2 08/08/2017
答案 0 :(得分:0)
您不必删除然后插入。只需更新$scope.myGrid = {
rowData: $scope.data,
columnDefs: [...],
onModelUpdated: function(event) {
MyFactory.onModelUpdated(this);
}
};
列(或所有非键列),然后从ColumnD
插入新列。我会先命令语句,然后先Table2
然后再UPDATE
,这样INSERT
就可以处理较小的原始行集(在插入之前)。除了UPDATE
之外,它只是普通的MERGE
:
UPDATE-INSERT
现在,在表变量DECLARE
@Conflicted TABLE(
ColumnA char(1),
ColumnB int,
ColumnC char(2),
ColumnD date
)
BEGIN TRAN
UPDATE dst
SET
dst.ColumnD = GETDATE()
OUTPUT
deleted.ColumnA,
deleted.ColumnB,
deleted.ColumnC,
deleted.ColumnD
INTO
@Conflicted
FROM
Table1 AS dst
JOIN Table2 AS src
ON dst.ColumnA = src.ColumnE AND
dst.ColumnB = src.ColumnF AND
dst.ColumnC = src.ColumnG
INSERT INTO Table1(
ColumnA,
ColumnB,
ColumnC,
ColumnD
)
SELECT
t2.ColumnE,
t2.ColumnF,
t2.ColumnG,
GETDATE()
FROM
Table2 AS t2
WHERE
NOT EXISTS(SELECT * FROM Table1 WHERE ColumnA = t2.ColumnE AND ColumnB = t2.ColumnF AND ColumnC = t2.ColumnG)
COMMIT TRAN
中,@Conflicted
中的所有冲突行都已被Table1
中的新行替换。
这是一个Table2
的版本:
MERGE