Can I write to a local variable from inside a CTE?
I am trying to get a comma delimited string of monthly names from inside a CTE to a varchar variable:
This works fine:
But this is creating the comma delimited string for each row.
I wanted to create the string once and use it in the query final query. I tried this:
This works OK, so I know I can access the variable (but there is nothing in it yet).
This doesn't work:
It won't let me assign the result to the @MonthList variable. But it would work if I took the "@" off, so I know the syntax is correct.
Is there a way to get this to work to write to variable and then use it at the end?
Thanks,
Tom
I am trying to get a comma delimited string of monthly names from inside a CTE to a varchar variable:
This works fine:
Code:
;WITH CTE1 AS
(
SELECT DATENAME(MM,
CAST('1' + '/1' + '/' + '2013' AS datetime)) AS MonthName ,
1 AS MonthPart, 1 AS CTEPart
UNION ALL
SELECT DATENAME(MM,
CAST(CAST(MonthPart AS varchar(2)) + '/1' + '/' +
'2013' AS datetime)) AS MonthName ,
MonthPart + 1 AS MonthPart, 2 AS CTEPart
FROM CTE1
WHERE MonthPart <= 12
)
SELECT [MonthName] ,
MonthList = SUBSTRING(
( SELECT ( ', ' + MonthName )
FROM CTE1
FOR XML PATH('')), 3, 1000)
FROM CTE1
But this is creating the comma delimited string for each row.
I wanted to create the string once and use it in the query final query. I tried this:
Code:
;WITH CTE1 AS
(
SELECT DATENAME(MM,
CAST('1' + '/1' + '/' + '2013' AS datetime)) AS MonthName ,
1 AS MonthPart, 1 AS CTEPart
UNION ALL
SELECT DATENAME(MM,
CAST(CAST(MonthPart AS varchar(2)) + '/1' + '/' +
'2013' AS datetime)) AS MonthName ,
MonthPart + 1 AS MonthPart, 2 AS CTEPart
FROM CTE1
WHERE MonthPart <= 12
)
SELECT [MonthName] ,
@MonthList
FROM CTE1
This works OK, so I know I can access the variable (but there is nothing in it yet).
This doesn't work:
Code:
;WITH CTE1 AS
(
SELECT DATENAME(MM,
CAST('1' + '/1' + '/' + '2013' AS datetime)) AS MonthName ,
1 AS MonthPart, 1 AS CTEPart
UNION ALL
SELECT DATENAME(MM,
CAST(CAST(MonthPart AS varchar(2)) + '/1' + '/' +
'2013' AS datetime)) AS MonthName ,
MonthPart + 1 AS MonthPart, 2 AS CTEPart
FROM CTE1
WHERE MonthPart <= 12
),
CTE2 AS
(
SELECT @MonthList = SUBSTRING(
( SELECT ( ', ' + MonthName )
FROM CTE1
FOR XML PATH('')), 3, 1000)
)
SELECT [MonthName] ,
@MonthList
FROM CTE1
It won't let me assign the result to the @MonthList variable. But it would work if I took the "@" off, so I know the syntax is correct.
Is there a way to get this to work to write to variable and then use it at the end?
Thanks,
Tom