动态列交叉应用

时间:2019-02-12 06:57:56

标签: sql-server tsql

我在创建动态cross apply脚本时遇到了一些困难。

源数据如下:

LedgerLink  AccPrev_iBranchID   PrevBal01   PrevBal02   PrevBal03   PrevBal04   PrevBal05   PrevBal06   PrevBal07   PrevBal08   PrevBal09   PrevBal10   PrevBal11   PrevBal12
1442    0    30,056.02   31,506.93   91,055.50   92,885.87   150,895.98      180,883.31      237,646.90      266,985.71      299,143.65      330,267.37      371,292.29      384,210.25 
1502    0    (8,055.00)  (0.00)  (0.00)  (0.00)  (0.00)  (54,588.00)     (25,196.29)     (25,196.29)     (25,196.29)     (3,157.50)  (4,365.00)  (3,157.50)
1543    0    (330,472.91)    (330,472.91)    (330,472.91)    (330,472.91)    (330,472.91)    (330,472.91)    (330,472.91)    (330,472.91)    (330,472.91)    (330,472.91)    (330,472.91)    (330,472.91)

我开发了以下脚本,以将所有以前的值都放在一栏中:

declare @columns varchar(max)

select @columns = stuff((select ',' + '('''+ Column_Name+''', PrevValue)'
from INFORMATION_SCHEMA.COLUMNS
where   TABLE_NAME = 'AccPrev'
and     COLUMN_NAME like 'PrevBal%'
--group by COLUMN_NAME
order by ORDINAL_POSITION
for xml path(''), type).value('.', 'nvarchar(max)'),1,1,'')

--select    @columns

select
    LedgerLink
,   AccPrev_iBranchID
,   Prev.*
from    AccPrev
cross apply
( select @columns)Prev(PrevValue)

它不断给我以下结果,这不是我想要的:

enter image description here

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您应该使用Dynamic SQL执行生成的查询字符串,否则@columns被视为字符串,而不是对实际列的引用。

有关动态列示例,请参见mssqltips中的前几个示例:https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/