在SQL存储过程中更改变量中文本的顺序

时间:2014-10-06 08:13:33

标签: sql-server sorting variables stored-procedures dynamic

我有一个具有动态变量的SQL存储过程。该变量用于创建逗号分隔的字段名称列表,用于生成数据透视表。

执行时,变量可能包含以下值:

[Qty Actual - Week 1], [Qty Actual - Week 2], [Qty Actual - Week 3],
[Qty Budget - Week 1], [Qty Budget - Week 2], [Qty Budget - Week 3],
[Qty Shipped - Week 1], [Qty Shipped - Week 2], [Qty Shipped - Week 3]

数据透视表的最终结果将导出到Excel,字段按上面的顺序显示。但是,我希望他们这样出来:

[Qty Actual - Week 1], [Qty Budget - Week 1], [Qty Shipped - Week 1]
[Qty Actual - Week 2], [Qty Budget - Week 2], [Qty Shipped - Week 2]
[Qty Actual - Week 3], [Qty Budget - Week 3], [Qty Shipped - Week 3]

我必须按照我现在设置的方式更改整个存储过程。是否有一些命令可用于更改动态变量中列的顺序?

1 个答案:

答案 0 :(得分:0)

INSERT INTO @TAB_VAR
SELECT @VAR

INSERT INTO @TAB_VAR1
SELECT SPLIT.A.VALUE('.', 'VARCHAR(100)')
FROM   (SELECT CAST ('<M>' + REPLACE(COL, ',', '</M><M>') + '</M>' AS XML) AS DATA
        FROM   @TAB_VAR) AS A
       CROSS APPLY DATA.NODES ('/M') AS SPLIT(A)
ORDER  BY SUBSTRING(SPLIT.A.VALUE('.', 'VARCHAR(100)'), LEN(SPLIT.A.VALUE('.', 'VARCHAR(100)')) -  1, 1)

SELECT @VAR = ''

SELECT @VAR = COALESCE(@VAR+',', '') + COL
FROM   @TAB_VAR1

SELECT @VAR