Error converting data type nvarchar to bigint caused by IN operator in Stored Procedure

Miu picture Miu · Feb 18, 2015 · Viewed 8.3k times · Source

Stored Proc:

ALTER PROCEDURE [dbo].[MyProcedure]
    @CommaSeperatedValues nvarchar(500)
AS
BEGIN
    SET NOCOUNT ON;
    SELECT  Col1, Col2, Col3
    FROM MyTable
    WHERE SomeCol_BigIntDataType IN (@CommaSeperatedValues) 

The Value which is coming from Code is string value: "9010073,9010074"

I tried running the SP like this: exec MyProcedure '9010073,9010074'

This is giving the error 'Error converting data type nvarchar to bigint' while running the SP

If I run the select query separately, like this:

SELECT  Col1, Col2, Col3
    FROM MyTable
    WHERE SomeCol_BigIntDataType IN (9010073,9010074)

Then I'm getting the expected results.

But I want to run from SP.

Answer

Shobhit Walia picture Shobhit Walia · Mar 15, 2016

Here we go. You can do this by Dynamic Query

DECLARE @mystring NVARCHAR(max)
DECLARE @UserId  NVARCHAR(max)
SET @UserId = '9010073,9010074'
SELECT @mystring = 'SELECT  Col1, Col2, Col3 FROM MyTable where UserId IN('+ @UserId +')'
EXEC sp_executesql @mystring