SQL - 联合两个表,每个表都有一些唯一的列

chr*_*ris 2 sql t-sql sql-server sql-server-2008

有两组数据(两个表)用于患者记录,一组1999-2003,另一组2004-2009.每个都有> 100列; Table_A有~8个唯一列,Table_B~25个唯一列(相互比较).我的目标是:

  1. 一张包含1999 - 2009年所有数据的表格
  2. 对于一个表中不在另一个表中的行,只需为该列指定NULL值.例如,如果表A具有Diagnostic_Category_12但Table_B没有,则该值将是表A中的原始值,但在表B中为NULL

我已经看到了一种手动执行此操作的方法: 联合具有不同列数的两个表

但是,此数据集中的列太多,无法输入每个列 - 我只想自动创建列并根据需要插入NULL值.

我正在使用SQL Server 2008R2.

I a*_*ica 6

工作更聪明,而不是更难.

我建议你通过查询你的模式来构建一些SQL ......这样你就不会错过任何手工编写的东西.您可以像这样生成脚本(只需用适当的表名替换@tableName1@tableName2值):

declare
 @tableName1 sysname = 'myfirsttablename'
,@tableName2 sysname = 'mysecondtablename'
,@select varchar(max) = 'select';

declare @columns table
(
     Id int identity(1,1)
    ,ColumName nvarchar(128)
    ,ExistsInTable1 bit
    ,ExistsInTable2 bit
);

-- Get a column listing with flags for their existence in each table
insert @columns
select distinct
 quotename(c.Column_Name)
,iif(c2.Table_Name is null, 0, 1)
,iif(c3.Table_Name is null, 0, 1)
from Information_Schema.Columns as c
    left join Information_Schema.Columns as c2
    on c2.Column_Name = c.Column_Name
    and c2.Table_Name = @tableName1
    left join Information_Schema.Columns as c3
    on c3.Column_Name = c.Column_Name
    and c3.Table_Name = @tableName2 
where c.Table_Name in (@tableName1, @tableName2);

-- Build the select statement for the 1sttable (using null where the column is absent)
select
 @select += char(10) + iif(c.Id = 1, ' ', ',') 
+ iif(c.ExistsInTable1 = 1, c.ColumName, 'null') + ' as ' + c.ColumName
from @columns as c
order by c.Id;

set @select += '
from ' + quotename(@tableName1) + '
union all
select';

-- Build the select statement for the 2ndtable (using null where the column is absent)
select
 @select += char(10) + iif(c.Id = 1, ' ', ',') 
+ iif(c.ExistsInTable2 = 1, c.ColumName, 'null') + ' as ' + c.ColumName
from @columns as c
order by c.Id;

set @select += '
from ' + quotename(@tableName2);

-- Print or execute your sql.
print(@select); -- or exec(@select);
Run Code Online (Sandbox Code Playgroud)

生成SQL后,我建议您:

  1. 验证您的结果并根据需要调整您的查询.
  2. 将最终的SQL放在存储过程中,而不是为每个请求动态生成它.


JNK*_*JNK 5

即使你认为

此数据集中的列太多,无法输入每个列

这是正确的做法.任何其他解决方案基本上都是黑客攻击.

它很容易做到,我经常使用更宽的表(150个字段).

在SSMS中,右键单击两个表中较大的一个,Script Table As- > Select To- > New Query Editor Window.这将向新窗口输出列出该表中每个字段的选择脚本,并且每个字段将位于其自己的行上,因此易于管理.

这实际上将是大约5分钟的工作. 只是第一次就做对了.