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

Sql server SQL Server 2008中select子句中的动态列数,sql-server,select,dynamic,user-defined-functions,Sql Server,Select,Dynamic,User Defined Functions,我需要从表中动态获取列值 假设我有一个包含列的表: Name, Date, Col1, Col2, Col3, ... col10 现在,根据某些条件,我想从上面的表中获取col1到col10的不同列,并在select子句中始终保留名称、日期列。e、 g.如下所示 columns in output: (1) Name (2) date (3) col1 + col2 + col3 (4) col4 + col5 set @str = ';with fn as (select ... f

我需要从表中动态获取列值

假设我有一个包含列的表:

Name,
Date,
Col1,
Col2,
Col3,
...
col10
现在,根据某些条件,我想从上面的表中获取col1到col10的不同列,并在select子句中始终保留名称、日期列。e、 g.如下所示

columns in output:  (1) Name (2) date (3) col1 + col2 + col3  (4) col4 + col5
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)
i、 e.列数和列本身(colN)都不同

我怎样才能做到这一点?此外,固定列直接在select子句中指定,如

select Name, Date  ... from Table1

但是,为了获得每行的剩余列值,我使用表值函数。那么,在这个函数中,我怎样才能得到值呢?我可以生成一个动态SQL字符串,但不能在函数中执行它,因此这就是我面临的限制。

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

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

columns in output:  (1) Name (2) date (3) col1 + col2 + col3  (4) col4 + col5
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)

要实现这一点,您肯定需要使用
动态查询