sqlserver merge语句100+列

时间:2013-08-26 15:13:02

标签: sql-server

我试图在SQLServer中合并两个表,

以下是表格,

Table_1

ID NAME  SALARY
1  MIKE  5000
2  BRIAN 6000
3  RAM   8000

Table_2

ID NAME  AGE
1  MIKE  50
2  BRIAN 20
3  RAM   30

RESULT
ID NAME  SALARY AGE
1  MIKE  5000   50
2  BRIAN 6000   20
3  RAM   8000   30

我尝试了左外连接,

SELECT TB1.ID, TB1.NAME, TB1.SALARY, TB2.AGE FROM TABLE_1 TB1
LEFT OUTER JOIN
TABLE_2 TB2
ON TB1.ID = TB2.ID

这符合预期,但我将使用的实际表格在table_1中有300列,table_2中有250列,

我需要所有table_1& table_2匹配列,缺少table_1列和缺少table_2列。

2 个答案:

答案 0 :(得分:0)

您需要完全外部联接:

SELECT TB1.*, TB2.*
FROM TABLE_1 TB1 FULL OUTER JOIN TABLE_2 TB2 ON TB1.ID = TB2.ID

http://www.w3resource.com/sql/joins/perform-a-full-outer-join.php

这将给出两个表中的所有列和行。如果您只需要匹配行和所有列,则可以根据需要使用左外连接或内连接。

答案 1 :(得分:0)

以下将从指定的两个表

中为您提供第三个表
Declare @Sql1 varchar(MAX) -- if you are using SQL server 2000 then @Sql1 varchar(8000)
Declare @Sql2 varchar(MAX) -- if you are using SQL server 2000 then @Sql2 varchar(8000)

Set @Sql1 = ''

SELECT @Sql1 = @Sql1 + 'Table_1.' + c.name + ','
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE t.name = 'Table_1'

SELECT @Sql1 = @Sql1 + 'Table_2.' + c.name + ','
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE t.name = 'Table_2'
and c.name <> 'ID'

Set @Sql1 = LEFT(@Sql1, (Len(@Sql1) - 1))
Print @Sql1

Set @Sql2 = 'Select ' + @Sql1 + ' Into RESULT From ' + ' Table_1 , Table_2 where Table_1.ID = Table_2.ID'

-- Set @Sql2 = 'Insert into RESULT( ' + @Sql1 + ')'
-- Set @Sql2 = @Sql2 + ' Select ' + @Sql1 + ' from ETProgram , Table_2 where ETProgram.ID = Table_2.ID'

Print @Sql2