SQL Execute statement IN with CSV NVARCHAR input parameter
Supponete di avere un parametro di input di tipo nvarchar contenente dei valori in formato CSV o similare e avete bisogno di eseguire una query in modo da estrarre le occorrenze con la clausola WHERE Campo IN (…).
Spesso vi sarete ritrovati l’errore seguente: Conversion failed when converting the nvarchar value ‘1,2,3’ to data type int.
Basta una piccola revisione del parametro csv ed il gioco è fatto!
Vediamo come è possibile.
USE Northwind GO DECLARE @CSV_PARAM NVARCHAR(100) SET @CSV_PARAM = '1,2,3' --A QUESTO PUNTO NON E' POSSIBILE ESEGUIRE SELECT CategoryName FROM Categories WHERE CategoryID IN (@CSV_PARAM) --L'ERRORE RESTITUITO E': --Conversion failed when converting the nvarchar value '1,2,3' to data type int. --BENSI' E' POSSIBILE ESEGUIRE LA QUERY IN QUESTO MODO EXECUTE ('SELECT CategoryName FROM Categories WHERE CategoryID IN (' + @CSV_PARAM + ')')
Lascia un commento