如何使用insert select语句插入下一个最大值

时间:2014-02-02 06:22:32

标签: sql sql-server sql-server-2008 tsql sql-server-2012

我有两张桌子。如果table2中的记录不存在于table2中,我想将table1数据插入table2。

我能做到这一点。我查询的主要问题。

 create table #Customer
(
    ID int,
    Name nvarchar(20),
    Email nvarchar(20)
)

create table #Customer2
(
    ID int,
    Name nvarchar(20),
    Email nvarchar(20),
    Value varchar(20)
)

insert into #Customer values (1,'AAA','A@mail.com')
insert into #Customer values (2,'BBB','B@mail.com')
insert into #Customer values (3,'CCC','C@mail.com')
insert into #Customer values (4,'DDD','D@mail.com')
insert into #Customer values (5,'EEE','E@mail.com')
insert into #Customer values (6,'FFF','F@mail.com')
insert into #Customer values (7,'GGG','G@mail.com')


insert into #Customer2 values (3,'x','asa@mail.com','10001')
insert into #Customer2 values (6,'y','B@mail.com','10002')
insert into #Customer2 values (8,'z','z@mail.com','10003')



update C2
set C2.Email = C1.Email, C2.Name = C1.Name 
from  #Customer C1
inner join #Customer2 C2  on C2.ID = C1.ID

insert into #Customer2 
select C1.ID, C1.Name, C1.Email, (SELECT MAX(CONVERT(int, Value))+1 from #Customer2
) from  #Customer C1
left join #Customer2 C2 on C2.ID = C1.ID
where C2.ID is null


select ID,value  from #Customer2

drop table #Customer
drop table #Customer2

结果是

id值

3 10001

6 10002

8 10003

1 10004

2 10004

4 10004

5 10004

7 10004

我希望它为

id值

3 10001

6 10002

8 10003

1 10004

2 10005

4 10006

5 10007

7 10008

请指教!

在期待中感谢你。

1 个答案:

答案 0 :(得分:1)

您可以使用Row_NumberCustomer1表中的最大值开始生成客户2中的ID,使用except运算符来插入不存在的数据:

INSERT INTO #Customer2(ID,Name,Email,Value)
select ID,name,email, (SELECT MAX(value) from #customer2) + row_number() over (order by id) value 
from (select ID,Name,email from #Customer
except SELECT ID,name,email from #Customer2)ValueForInserting