declare @sql nvarchar(max),@cols int select @cols=20;--用户定义列数 select @sql='create table t('; if object_id('tempdb..#Inc') is not null drop table #Inc select Id=convert(int,1) into #Inc from sysobjects where 1=2; declare @sql2 nvarchar(max); select @sql2=' insert into #Inc select top '+convert(varchar(20),@cols)+' row_number() over(order by o.id) from sysobjects o,sysobjects o1' exec(@sql2) select @sql=@sql+'col'+convert(varchar(10),Id)+' nvarchar(20) null,' from #Inc select @sql=substring(@sql,1,len(@sql)-1) select @sql=@sql+')' exec(@sql) select * from t drop table t
select @cols=20;--用户定义列数
select @sql='create table t(';
if object_id('tempdb..#Inc') is not null drop table #Inc
select Id=convert(int,1) into #Inc from sysobjects where 1=2;
declare @sql2 nvarchar(max);
select @sql2='
insert into #Inc
select top '+convert(varchar(20),@cols)+' row_number() over(order by o.id)
from sysobjects o,sysobjects o1'
exec(@sql2)
select @sql=@sql+'col'+convert(varchar(10),Id)+' nvarchar(20) null,' from #Inc
select @sql=substring(@sql,1,len(@sql)-1)
select @sql=@sql+')'
exec(@sql)
select * from t
drop table t