在SQL Server问题中添加列

在SQL Server问题中添加列,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,如何根据查询结果在临时表中添加新列。考虑下面的代码 declare @ctr int set @ctr = 1 while (@ctr <= (select count(*) from #temp2) begin alter table #temp add (select t2.Value from #temp2 t2 where t2.SysID = @ctr) (select t2.Type from #temp3 t3 where t3.SysID = @ctr) end

如何根据查询结果在临时表中添加新列。考虑下面的代码

declare @ctr int
set @ctr = 1

while (@ctr <= (select count(*) from #temp2)
begin
  alter table #temp
  add (select t2.Value from #temp2 t2 where t2.SysID = @ctr) (select t2.Type from #temp3 t3 where t3.SysID = @ctr)
end
declare@ctr int
设置@ctr=1

据我所知(@ctr),我认为你做不到这一点。你最好的希望可能是创建一个全局临时表(双哈希而不是单哈希),然后在全局临时表上sp_executesql来动态添加列。

你必须使用动态SQL。这是我以前做过的:

SET @sql = 'ALTER TABLE ' + @TableName +
           'ADD ' + CONVERT(VARCHAR(100), @ColName) + ' ' + 
           CONVERT(VARCHAR(100), @TypeName) + 
           CASE WHEN @TypeName IN ('int', 'datetime', 'money', 'uniqueidentifier', 'bit')
                THEN '' ELSE '(' + CONVERT(VARCHAR(10), @Prec) + ')' END + ' NULL'

EXEC(@sql)

这可能不包括所有可能的数据类型,但就我的要求而言,这已经足够了。无论如何,一个好的开始

接受他的答案的地方是给它一个大勾号,而不是(竖起大拇指)。@Rob:或者,你可以竖起大拇指接受这个答案。