我将使用 SQL Server 2014 中的 MERGE 表在目标表中插入行。 我想在目标表中自动增量ID列。
CREATE TABLE #targetTable(id int,name varchar(50))
CREATE TABLE #sourceTable(id int,name varchar(50))
INSERT INTO #sourceTable values(1,'John');
INSERT INTO #sourceTable values(1,'Albrt');
INSERT INTO #sourceTable values(1,'Roy');
MERGE #targetTable AS [target]
USING #sourceTable AS [source]
ON [target].id = [source].id
WHEN NOT MATCHED THEN
INSERT (id, Name)
VALUES ((select isnull(max(id),1) + 1 from #sourceTable), source.Name);
select * from #targetTable as T
drop table #targetTable
drop table #sourceTable
我曾尝试这样做 select isnull(max(id),1) + 1 from #sourceTable
但它为所有列提供了相同的 id。这将返回以下输出
2 John
2 Albrt
2 Roy
需要输出,例如
2 John
3 Albrt
4 Roy
我必须对预期输出进行哪些更改?
最佳答案
CREATE TABLE #targetTable(id int, name varchar(50))
CREATE TABLE #sourceTable(id int,name varchar(50))
INSERT INTO #sourceTable values(1,'John');
INSERT INTO #sourceTable values(1,'Albrt');
INSERT INTO #sourceTable values(1,'Roy');
MERGE #targetTable AS [target]
USING
(
select id,
name,
ROW_NUMBER() OVER(ORDER BY id) as rnk
from #sourceTable
) AS [source]
ON [target].id = [source].id
WHEN NOT MATCHED THEN
INSERT (id, Name)
VALUES (rnk, source.Name);
select * from #targetTable as T
drop table #targetTable
drop table #sourceTable
关于sql-server - 如何在 SQL SERVER 中自动增加合并表不匹配大小写的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36217729/