MAK
MAK

Reputation: 7270

SQL Server 2008 R2: Assign alias dynamically

I have the following string to make it as expected.

Given String:

DECLARE @String VARCHAR(MAX) = '[ColumnA],[ColumnB],[ColumnC]'
                              /*Will be any numbers of columns*/

Expected String:

SUM([ColumnA]) AS [ColumnA],SUM([ColumnB]) AS [ColumnA],SUM([ColumnC]) AS [ColumnA]

My TRY:

SELECT 'SUM('+ REPLACE(@String,',','),SUM(') + ')'

I am just able to get:

SUM([ColumnA]),SUM([ColumnB]),SUM([ColumnC])

Got stuck to assign the alias infront of each sum.

Upvotes: 2

Views: 35

Answers (1)

Igor Borisenko
Igor Borisenko

Reputation: 3866

I'd used one of split functions and FOR XML.

    SELECT STUFF(
                   (select ', SUM('+sit.items +') AS '+sit.items
                    from dbo.uf_SplitIntoTableStr('[column1],[column2]',',') sit
                    for xml path('')
                 ),1,1,'')

Upvotes: 1

Related Questions