0

Below is my query and error. When I am putting VARCHAR variable and pass in INT value then I am getting error.

Query:

    declare @vid VARCHAR(MAX)
    set @vid= ('3,5,7')

    Select (Stuff((Select ', ' + VehicleClassName 
    From VehicleClass_Master  
    where VehicleClassId  in (@VID) FOR XML PATH('')),1,2,''))

Error:

Msg 245, Level 16, State 1, Line 3 Conversion failed when converting the varchar value '3,5,7' to data type int.

TT.
  • 15,774
  • 6
  • 47
  • 88
Rushang
  • 1
  • 3

2 Answers2

1

Your variable @vid is a varchar containing non-numeric characters (,); also it is not a "list" it is simply a string containing a single value that happens to have numbers and commas in it.

To acheive what you want, create @vid as a table variable with a single INT column, then insert each value as a separate row - INSERT @vid_table(vid) VALUES (3),(5),(7);

Finally change your IN (@VID) to IN (SELECT VID FROM @vid_table)

SQLBadPanda
  • 625
  • 5
  • 7
0
declare @vid VARCHAR(MAX),@query varchar(max)
set @vid= ('3,5,7')
SET @query = 'Select (Stuff((Select '', '' + VehicleClassName From VehicleClass_Master  where VehicleClassId  in (' + @vid + ') FOR XML PATH('''')),1,2,''''))'
EXEC (@query)
Ilyes
  • 14,640
  • 4
  • 29
  • 55
Rushang
  • 1
  • 3