Shaggy
Shaggy

Reputation: 5800

SQL - Conversion failed when converting the varchar value to Int

I am passing varchar values to a SQL function.

But I get this error:

Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the varchar value '201,505,59,43,2202' to data type int.

Sample Code :

Declare @Fault Varchar(Max) = '201,505,59,43,2202'

Select * 
From EventMsg 
Where Event IN (Convert(Int, @Fault))

I tried both CAST & CONVERT functions...but same error.

Upvotes: 0

Views: 2419

Answers (2)

Sergio
Sergio

Reputation: 6948

Just another way is to declare table variable:

DECLARE @errorCodes AS TABLE (
    err INT
)
INSERT INTO @errorCodes (err) VALUES (1), (2), (3)

Select * From EventMsg Where Event IN (SELECT err FROM @errorCodes)

Upvotes: 0

Kane
Kane

Reputation: 16812

If you are passing a comma separated list of integer values as a string and wanting to use each value then you will need to write a function similar to String.Split in the .NET world.

There are a ton of answers on Stack Overflow about this here are some

Upvotes: 1

Related Questions