如何将列合并到一个表中?
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
有什么建议吗? THX!
答案 0 :(得分: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
答案 1 :(得分: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