Is there a way to do the following in SQL Server:
DECLARE @list nvarchar(MAX) = '1, 2, 3, 4, 5, 6';
SELECT * FROM table WHERE ID IN ( @list );
-- Column ID is type bigint
Error:
Error converting data type nvarchar to bigint.
Is there a way to do the following in SQL Server:
DECLARE @list nvarchar(MAX) = '1, 2, 3, 4, 5, 6';
SELECT * FROM table WHERE ID IN ( @list );
-- Column ID is type bigint
Error:
Error converting data type nvarchar to bigint.
You don't want to convert it to an int. Instead, use like
for the comparison:
select *
from table
where ', '+@list+', ' like ', '+cast(id as varchar(255)) + ', ';
This has the downside that the query will not use indexes. If that is important, then you can use dynamic SQL:
DECLARE @list nvarchar(10) = '1, 2, 3, 4, 5, 6';
declare @sql nvarchar(max) = 'SELECT * FROM table WHERE ID IN ('+ @list +')';
exec sp_executesql @sql;
use Dynamic SQL
.
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @list nvarchar(10) = '1, 2, 3, 4, 5, 6';
SET @SQLQuery = 'SELECT * FROM table WHERE ID IN (' + @list + ')'
EXECUTE(@SQLQuery)