2012-03-30 88 views
1

如何将列合并到一个表中?tsql将列合并到一个表

 
declare @map_old table(ID int not null) 
insert into @map_old select 1 
insert into @map_old select 2 

declare @map_new table(ID int not null) 
insert into @map_new select 11 
insert into @map_new select 22 

declare @map(ID int not null, ID2 int not null) 

的结果@map应该是:

 
ID ID2 
1 11 
2 22 

有什么建议?谢谢!

+1

为什么'1 11',而不是'1 22'?你需要并排粘贴表格吗? – danihp 2012-03-30 09:29:13

+0

我需要每一行与第二个表的关系......每个tabe具有相同的行数。 – c0d1ng 2012-03-30 09:34:18

回答

1

,你可以在表中使用的身份类似如下:

declare @map_old table(iden int identity,ID int not null) 
insert into @map_old select 1 
insert into @map_old select 2 

declare @map_new table(iden int identity,ID int not null) 
insert into @map_new select 11 
insert into @map_new select 22 

declare @map table(ID int not null, ID2 int not null) 

insert into @map 
select t.ID, t2.ID from @map_old t join @map_new t2 on t.iden = t2.iden 
+0

正是我在找... – c0d1ng 2012-03-30 09:50:04

1

如果您确信此表将包含的行相同的金额。

那么,也许是这样的:

;WITH CTE 
AS 
(
    SELECT 
     ROW_NUMBER() OVER(ORDER BY ID) AS RowNbr, 
     mapNew.ID 
    FROM 
     @map_new AS mapNew 
),CTE2 
AS 
(
    SELECT 
     ROW_NUMBER() OVER(ORDER BY ID) AS RowNbr, 
     mapOld.ID 
    FROM 
     @map_old AS mapOld 
) 
INSERT INTO @map(ID,ID2) 
SELECT 
    CTE.ID, 
    CTE2.ID 
FROM 
    CTE 
    JOIN CTE2 
     ON CTE.RowNbr=CTE2.RowNbr 

SELECT * FROM @map