I have to implement SELECT ... FROM ... WHERE .. IN query in my stored procedure.
Below is the code from my stored procedure
ALTER PROCEDURE [dbo].[SP_GetQuestionSetMultiCat]
-- Add the parameters for the stored procedure here
@PIN varchar(50),
@CatIds varchar(50),
@Range int,
@Que_Type varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @qtId as int;
select @qtId = Que_Type_Id from dbo.QuestionType_Tbl where Que_Type=@Que_Type;
-- Insert statements for procedure here
Select Top(@Range)
QId,
Que_Type_Id,
Que_Level_Id,
Que_Category_Id,
Que,
Opt1,
Opt2,
Opt3,
Opt4,
Ans
From
dbo.Que_Tbl
Where
(Que_Category_Id in (cast(@CatIds as varchar)))
and (Que_Type_Id=@qtId)
and (Qid not in (Select Que_Id From dbo.UserQuestion_Mapping where PIN=@PIN and Que_typeID=@qtId))
END
Look at the where condition. The Que_Category_Id is int type. What i want to perform is –
Where Que_Category_Id in (1,2,3,4)
The in values i m passing is a string converted from my C# code.
When I am executing this query like –
exec SP_GetQuestionSetMultiCat '666777','4,5,6',5,'Practice'
it is generating an error –
Conversion failed when converting the varchar value ‘{4,5,6}’ to data type int.
Can anybody help me out how to solve this problem.
Thanks for sharing your valuable time.
1)
Conversion failed when converting the varchar value '{4,5,6}' to data type int.The reason of this error is data type precedence.
INTdata type has “higher” precedence thanVARCHARdata type (16-INT vs. 27-VARCHAR).So, SQL Server is trying to convert
'{4,5,6}'toINTand not vice versa.2) Instead, I would convert
@CatIdstoXMLand then to a table variable (@IDs) using nodes(…) method:3) The next step is to rewrite the query using
IN (SELECT ID FROM @IDs)instead ofin (cast(@CatIds as varchar)):4) Call stored procedure: