How can i get the total of a rows dynamically generated columns in a select query

坚强是说给别人听的谎言 提交于 2020-01-15 09:33:25

问题


DECLARE @DynamicColumns VARCHAR(MAX)
SET @DynamicColumns = '[Mon, Oct 31 2016], [Tue, Nov  1 2016], [Wed, Nov  2 2016], [Thu, Nov  3 2016],[Many More Columns Can be Added]'

I have a temp table that has columns FirstName & LastName. The table will also contain dynamically generated columns depending on the parameters passed to the stored procedure. The dynamically added columns could be 10, 100 or 2.

I can access the names of the generated column in the @DynamicColumns variable i have declared above.

The Columns names are in the format shown above and separated by a comma (,)

PROBLEM: If i write the query below, i can get all rows i want with all the dynamically added columns.

SELECT * FROM ##TempTable1

But how can i compute the sum of the dynamically added columns and return it as an extra "Total" column for each row.

I would have writen something like

SELECT *, [Mon, Oct 31 2016] + [Tue, Nov  1 2016] + [Wed, Nov  2 2016] + [Thu, Nov  3 2016] AS Total
FROM ##TempTable1

but the columns are going to be dynamic, so that wouldn't work.(but i have access to the column names in variable @DynamicColumns)

What i need is something like below but how can i extract my column names from the variable @DynamicColumns and get their sum?

SELECT *, SUM(@DynamicColumns) AS Total -- the Sum of all columns in @DynamicColumns
FROM ##TempTable1

回答1:


You can create new dynamic T-SQL statement:

DECLARE @DynamicSQLStatement NVARCHAR(MAX) = N'
SELECT *, ' + REPLACE(@DynamicColumns, ',', '+') + '  AS Total 
FROM ##TempTable1;'

exec @DynamicSQLStatement

I have just see, that you have , in the column names, so you can replace ], [ instead comma.

REPLACE(@DynamicColumns, '], [', '] + [')


来源:https://stackoverflow.com/questions/40906513/how-can-i-get-the-total-of-a-rows-dynamically-generated-columns-in-a-select-quer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!