将具有相同ID的2个表合并为继续ID

时间:2014-06-19 03:02:52

标签: sql sql-server sql-server-2012

所以我在这里遇到了问题 我使用sql server 2012

我的第一张桌子是

       TABLE_A
 |ID   | title  | type |

 |1    | how... | ABC  | 
 .  
 . 
 . 
 |40000|fine....| ABC  |

我的第二张表是

       TABLE_B
 |ID   | title  | type |

 |1    | how... | BBB  | 
 .  
 . 
 . 
 |40000|fine....| BBB  |

如何将它们两者结合起来就像这样

TABLE C
|ID   | title  | type |
|1    | how... | ABC  |
 .
 .
 .
|40000|fine....| ABC  |
|40001| how... | BBB  |
 .
 .
 .
|80000|fine....| BBB  |

我正在使用此查询

SET IDENTITY_INSERT [dbo].[TABLE_C] OFF 
INSERT [dbo].[TABLE_A] (ID, title, type) VALUES (1, 'how...', ABC)
...
INSERT [dbo].[TABLE_A] (ID, title, type) VALUES (40000, 'fine...', ABC)
SET IDENTITY_INSERT [dbo].[TABLE_C] OFF 

然后 我正在使用此查询

SET IDENTITY_INSERT [dbo].[TABLE_C] OFF 
INSERT [dbo].[TABLE_B] (ID, title, type) VALUES (1, 'how...', BBB)
...
INSERT [dbo].[TABLE_B] (ID, title, type) VALUES (40000, 'fine...', BBB)
SET IDENTITY_INSERT [dbo].[TABLE_C] OFF 

但是我收到了以下错误

violation of primary key PK_ID. Cannot insert duplicate key in object TABLE_C. The duplicate key is (1) ---> until (40000)

有人可以给我一些线索或语法,以便在插入table_C

时插入带有继续ID的表B.

3 个答案:

答案 0 :(得分:2)

如何首先使用标识列创建table_c然后插入其中?

create table table_c (
    id int identity(1, 1) primary key,
    title varchar(255),
    type varchar(255)
);

insert into table_c(title, type)
    select title, type
    from table_a
    order by id;

insert into table_c(title, type)
    select title, type
    from table_b
    order by id;

答案 1 :(得分:0)

您是否需要能够确定原始表格?你需要能够将它们合并吗? 如果你这样做,你可以试试像......

select id * 2, title, type
from table_a
UNION ALL
select id * 2 + 1, title, type
from table_b

结合identity_insert,这将为table_b提供奇数编号的id空间,为table_a提供偶数id空间

合并后,id空间是否需要连续? 如果是的话......

select ROW_NUMBER() OVER (ORDER BY id, source_table) as id, title, type
from (
select 'a' as source_table, id, title, type from table_a
UNION ALL
select 'b' as source_table, id, title, type from table_a) c

答案 2 :(得分:0)

试试这个:

SET IDENTITY_INSERT [dbo].[TABLE_C] ON

INSERT INTO TABLE_C(ID, TITLE, TYPE)
SELECT ROW_NUMBER() OVER (ORDER BY GETDATE()), A.TITLE, A.TYPE
FROM 
      (SELECT TITLE, TYPE FROM TABLE_A
       UNION ALL
       SELECT TITLE, TYPE FROM TABLE_B
      ) AS A

SET IDENTITY_INSERT [dbo].[TABLE_C] OFF