如何在SQL SERVER中使用合并表不匹配的情况自动增加列?

时间:2016-03-25 09:57:13

标签: sql-server

我将在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

我必须为预期的输出做些什么改变?

1 个答案:

答案 0 :(得分:1)

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