且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 2008中select子句中的动态列数

更新时间:2022-11-26 08:55:14

最后通过生成一个动态查询字符串然后执行它来实现这一点.

Finally achieved this by generating a dynamic query string then executing it.

要生成动态字符串,我首先使用"with"获取固定的列,然后使用每行运行函数.如下所示.

To generate dynamic string I first take the fixed columns using "with" and then with each row running function. Something as below.

set @str = ';with fn as (select ... fixed-columns from table) select x.*'

while (condition)
begin
   set @cols = @cols + function_to_generate_dynamic_columns(@params)
   set @i=@i+1
end

set @str = @str + @cols + ' from fn x '

EXECUTE(@str)