I have the following SQL statement:
WITH CTE(Col01,...,Col05) AS
(
...
)
SELECT ....
,CASE ....
WHEN ... THEN CASE ...
WHEN 0 THEN ...
ELSE (SELECT STUFF((SELECT ',' + CAST(Col002 AS NVARCHAR(10)) FROM TableOne WHERE Col05=CTE.Col05 FOR XML PATH('')),1, 1,''))
END
WHEN ... THEN ...
WHEN ... THEN ...
ELSE ...
END
,...
FROM TableOne
CROSS APPLY CTE
WHERE TableOne.Col01=CTE.Col01
I want to return CSV list from column table information – the statements work correctly when I execute it alone, but in the above sql statement syntax its generates the following error:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value ‘101,102,103,108,109,110,112,113,114,115,116,117,118,119,120,121,122,126,130,135,164,165,218’ to data type int.
If I replace the statement just whit ‘1’ or 1 it gets me no error. Why it is trying to convert the CSV list into int?
I am really sorry that I did not provided more information about the query – now I have found what caused the issue I see it is very difficult to find it without the whole picture shown.
The issue was fixed when I cast as nvarchar all return possible values. For some reason, if one of the returns values is int, the SQL server try to convert all of the values as int too.
This link help to solve my problem:
http://www.fmsinc.com/free/newtips/sql/sqltip10.asp
EDIT: I suppose this makes sense – you can have different results by the case – when statement but they should be one type.