使用新ID复制记录

时间:2016-03-07 08:04:51

标签: sql sql-server sql-server-2008

我在同一台服务器上有2个数据库。 DB1有一个名为E1的表,DB2有一个名为E1的表。

E1

ID名称

1   A
2   B
3   C

E2

ID  Name
1   A
2   C
3   D

我想复制表E1中的名称,而不是表格E2中存在新的" ID"。 所以E2将是

E2

ID  Name
1   A
2   C
3   D
4   B

我的查询是:

SET IDENTITY_INSERT [TEST_DB].[dbo].[E1] ON 
INSERT INTO [TEST_DB].[dbo].[E1](ID,Name) 
  SELECT ID,Name FROM [TestDB].[dbo].[E1]AS a 
  WHERE NOT EXISTS( 
  SELECT a.ID , a.Name FROM [TEST_DB].[dbo].[E1] AS b WHERE a.ID = b.ID and a.Name = b.Name ) 
SET IDENTITY_INSERT [TEST_DB].[dbo].[E1] off 

4 个答案:

答案 0 :(得分:0)

insert into e2 (name)
    select name from e1
    where name not in (select name from e2
                       where name is not null)

假设id是一个自动增量列。

答案 1 :(得分:0)

insert into e2 (id, name)
values ((select max(id) from e2)+1, (select name from e1 where name not in (select name from e2)

id自动递增。

答案 2 :(得分:0)

如果我理解正确的话,你可以加入表格并检查你在E2中没有的东西,只插入那些...正如你所说ID是自动增量...只需选择你需要的东西使用 LEFT JOIN

if object_ID('tempdb..#E1') IS NOT NULL DROP TABLE #E1
create table #E1 (Name nvarchar(10))
insert into #E1 (Name) values ('A'), ('B'), ('C')

if object_ID('tempdb..#E2') IS NOT NULL DROP TABLE #E2
create table #E2 (Name nvarchar(10))
insert into #E2 (Name) values ('A'), ('C'), ('D')

Select * from #E2

Insert into #E2 (Name)
Select e1.Name from #E1 e1
LEFT JOIN #E2 e2 on e1.Name = e2.Name
where e2.Name IS NULL

Select * from #E2

答案 3 :(得分:0)

INSERT INTO [dbo].[E2] (Name)
SELECT A.Name FROM [dbo].[E1] A 
WHERE A.Name NOT IN ( SELECT B.Name FROM [dbo].[E2] B)