日期:2014-05-17 浏览次数:20492 次
declare @sql nvarchar(max)
set @sql = N'select a.*'+
ltrim(isnull((select ','+name from sys.columns b
where object_id = object_id('dbo.tableB', 'u')
and not exists
(
select 1
from sys.columns a
where object_id = object_id('dbo.tableA', 'u')
and b.name = a.name
)
for xml path('')),''))
+' from a,b where a.id=b.id'
--select @sql
exec(@sql)
use Test
if OBJECT_ID('A') is not null
drop table A
create table A(id int identity(1,1),col_1 nvarchar(20),col_2 nvarchar(20))
go
insert into A(col_1,col_2)
select 'AAA','AAA1' union all
select 'BBB','BBB1' union all
select 'CCC','CCC1'
if OBJECT_ID('B') is not null
drop table B
create table B(id int identity(1,1),单号 nvarchar(20),col2 nvarchar(20),col3 nvarchar(20),col4 nvarchar(20))
go
insert into B(单号,col2,col3,col4)
select 'A001','A1','A2','A3' union all
select 'B001','B1','B2','B3' union all
select 'C001','C1','C2','C3'
declare @sql nvarchar(2000)
select @sql=isnull(@sql+',','')+'b.'+name from syscolumns where id=object_id('B') and name<>'单号'
set @sql='select a.*,b.单号,'+@sql+' from a,b where a.id=b.id'
exec(@sql)