I have the following case statement, as shown below:
Example:
I have a case statement :
case cola when cola between '2001-01-01' and '2001-01-05' then 'G1' when cola between '2001-01-10' and '2001-01-15' then 'G2' when cola between '2001-01-20' and '2001-01-25' then 'G3' when cola between '2001-02-01' and '2001-02-05' then 'G4' when cola between '2001-02-10' and '2001-02-15' then 'G5' else '' end
Note : now I want to create a dynamic case statement due to the date and name values โโpassed as a parameter, and it may change.
Declare @dates varchar(max) = '2001-01-01to2001-01-05,2001-01-10to2001-01-15, 2001-01-20to2001-01-25,2001-02-01to2001-02-05, 2001-02-10to2001-02-15' Declare @names varchar(max) = 'G1,G2,G3,G4,G5'
The values โโin the variables can change in accordance with the requirements, they will be dynamic. Therefore, the case statement must be dynamic without using a loop.
My bad attempt :
DECLARE @Name varchar(max) DECLARE @Dates varchar(max) DECLARE @SQL varchar(max) DECLARE @SQL1 varchar(max) SET @Name = 'G1,G2,G3,G4,G5' SET @dates = '2001-01-01to2001-01-05,2001-01-10to2001-01-15, 2001-01-20to2001-01-25,2001-02-01to2001-02-05, 2001-02-10to2001-02-15' SELECT @SQL = STUFF((SELECT ' ' + Value FROM ( SELECT 'WHEN Cola Between '''' AND '''' THEN ''' + A.Value + '''' AS Value FROM ( SELECT Split.a.value('.', 'VARCHAR(100)') AS Value FROM ( SELECT CAST ('<M>' + REPLACE(@Name, ',', '</M><M>') + '</M>' AS XML) AS Value ) AS A CROSS APPLY Value.nodes ('/M') AS Split(a) ) AS A ) AS B FOR XML PATH (''), type).value('.', 'Varchar(max)'),1,1,'') + '' SET @SQL1 = 'CASE Cola '+@SQL+' ELSE '''' END' PRINT(@SQL1);
Stuck : but stuck to share @dates 2001-01-01to2001-01-05 in BETWEEN '2001-01-01' AND '2001-01-05' .
sql-server sql-server-2008-r2
MAK Dec 11 '14 at 17:10 2014-12-11 17:10
source share