T-SQL Coalesce用于构造动态sql select语句

时间:2015-11-29 06:18:01

标签: sql-server sql-server-2012 dynamic-sql

DECLARE @sumh VARCHAR(MAX)
DECLARE @sql VARCHAR(MAX)

SELECT 
    @sumh = COALESCE(@sumh+Name+']) AS ['+Name+'],SUM([' ,'') 
FROM
    Hals

SELECT 
    @sumh = 'SUM(['+@sumh+ ']) AS Sum'

SET @sql = '

SELECT 
    Category = ISNULL(CATEGORY,''Total''),CatID,'+@sumh+' 
FROM
    (--My Pivot Query Here
    ) AS P 
GROUP BY GROUPING SETS ((CATEGORY,CatID),())'

PRINT (@sql)

正在制作

SELECT 
    Category = ISNULL(CATEGORY,'Total'),CatID,SUM([Bc-Def]) AS [Bc-Def],SUM([Cd-Def]) AS [Cd-Def],SUM([De-Efg]) AS [De-Efg],SUM([Ef-Fgh]) AS [Ef-Fgh],SUM([Fg-Ghi]) AS [Fg-Ghi],SUM([]) AS Sum  FROM
(--My Pivot Query Here
) AS P 
GROUP BY GROUPING SETS ((CATEGORY,CatID),())

我有两个问题,你可能已经注意到了。表格' Hals'中的第一行('名称')被Coalesce忽略了,而且,任何方式我都可以摆脱最后的" SUM([])AS Sum"

为了说清楚,我希望它返回如下

SELECT Category=ISNULL(CATEGORY,'Total'),CatID,SUM([Ab-Bcd]) AS [Ab-Bcd],SUM([Bc-Def]) AS [Bc-Def],SUM([Cd-Def]) AS [Cd-Def],SUM([De-Efg]) AS [De-Efg],SUM([Ef-Fgh]) AS [Ef-Fgh],SUM([Fg-Ghi]) AS [Fg-Ghi]  FROM
(--My Pivot Query Here
) AS P 
GROUP BY GROUPING SETS ((CATEGORY,CatID),())

我在这里有一个sql小提琴,以明确http://sqlfiddle.com/#!3/c7d29/3 我愿意接受其他解决方案。 (列类别和类别ID是从我的数据透视查询返回的,当我手动传入测试列名时,测试工作正常。我只需要帮助来构建动态选择。

由于

1 个答案:

答案 0 :(得分:0)

你可以这样做:

DECLARE @sumh VARCHAR(MAX)
DECLARE @sql VARCHAR(MAX)
SET @SumH = ''
SELECT @sumh = COALESCE(@sumh+' SUM([' + Name+']) AS ['+Name+'] ', ' -- SHOULD NEVER OCCUR -- ') 
FROM Hals

SET @sql = '
SELECT Category=ISNULL(CATEGORY,''Total''),CatID '+@sumh+' FROM
(
--My Pivot Query Here
) AS P 
GROUP BY GROUPING SETS ((CATEGORY,CatID),())
'
select @sql

当@SumH永远不为null时,它会在COEALESCE中占用第一个参数,这样你就可以使代码更清晰,至少就像我理解的那样。