2013-08-26 78 views
0

我試着合併在SQLServer的2個表,SQLSERVER MERGE語句100+列

下面是桌子,

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列和250個TABLE_2列,

我需要所有TABLE_1 & TABLE_2匹配列,缺少TABLE_1列和失蹤TABLE_2列。

回答

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