Question : dynamic  sql CASE statements

For a number of reason to long to explain here I am not able to create a SQL PIVOT.

Is it possible to create a dynamic set of Case statements in sql.

The alias name of each each case would need to be able to change and the number of case statement with would need to able to vary.

Answer : dynamic  sql CASE statements

Hi,

Hope this will give you an idea of how to do it:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
Declare @strSQL varchar(max)
DECLARE @cols NVARCHAR(2000)
 
SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + convert(varchar, yourdatecolumn)
                        FROM    yourtable
                        ORDER BY '],[' + convert(varchar, yourdatecolumn)
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'
 
set @strSQL = 'select ' + @cols +
		' from (
			select column1, column2, yourdatecolumn from yourtable) o
		  pivot (count(column1) for yourdatecolumn in (' + @cols + ')) p'
 
exec(@strSQL)
Open in New Window Select All
Random Solutions  
 
programming4us programming4us