Non puoi dipendere da concatenazioni come:
SELECT @result = COALESCE(@result + ',', '') + [Title]
FROM Episodes
...
Esempio dipendente da CTE/tabella temporanea/piano di esecuzione otterrai risultati diversi:
DECLARE @text VARCHAR(MAX) = ''
,@text2 VARCHAR(MAX) = '';
SELECT CAST(ROW_NUMBER() OVER (ORDER BY name) AS INT) AS number
INTO #numbers
FROM master..spt_values
;WITH numbers (number)
AS
(
SELECT CAST(ROW_NUMBER() OVER (ORDER BY name) AS INT) AS number
FROM master..spt_values
),a AS
(
SELECT number FROM numbers WHERE number < 10
)
SELECT @text = @text + LTRIM(STR(a.number))
FROM a
ORDER BY a.number DESC
;WITH numbers (number)
AS
(
SELECT number FROM #numbers
),
a
AS
(
SELECT number FROM numbers WHERE number < 10
)
SELECT @text2 = @text2 + LTRIM(STR(a.number))
FROM a
ORDER BY a.number DESC
SELECT @text, @text2;
Ho creato un campione e la tua prima query funziona SqlFiddleDemo . Ma la tua soluzione dipende fortemente dal piano di esecuzione.
Usa XML + STUFF invece per la concatenazione.