0

I am having a query like :

declare @aID varchar(max)='1'
declare @pID varchar(max)=' '
SELECT * from Table1 WHERE 
(PId = @PID or @pID='') AND (AID = @aID or @aID = '')

This query works fine. But now, I want to use 'IN' clause.

declare @aID varchar(max)='1,2'
SELECT * from Table1 WHERE 
(PId = @PID or @pID='') AND (AID IN (@aID) or @aID = '')

But this last query gives me an error.

Error : 'Conversion failed when converting the varchar value '1,2' to data type int'

I do not want to change the design of my Table1

How can I make this possible ?

1
  • Declaring your parameter AS XML offers you the chance to pass what ever structured data you want into a SP or and UDF... It's quite easy to deal with (simple) XML, SQL-Server does a great job here... Commented Jul 10, 2015 at 21:45

2 Answers 2

1

@vars are inserted as a single "chunk". it's not the DB's job to decide that it's actually MULTIPLE separate comma-separated values.

If you want 1,2 to be treated as two values, you''ll have to use dynamic sql, e.g.

query = "SELECT ... IN (" + @var + ")";
exec query;
Sign up to request clarification or add additional context in comments.

3 Comments

I did that, it works only If i specify a value. If no value is passed then I get an error. For example query = "SELECT ... IN (" + @var + ") or (" + @var + ") = '''' "; exec query; will give me an error when I pass empty spring
then put in some conditinoal log to add the in clause if you pass in something, otherwise skip it entirely.
MarcB the OP wants @AID to be eventually be a paramter from a strored proc. I don't think I need to say why this changes things
0

Rather than trying to use a comma dilimited value for your in you might want to use a table variable

declare @ids table ( aid int ) ;
INSERT INTO @ids (aid) Values (1)(2);

declare @idCount  int;
SELECT @idCount = COUNT(aID) FROM @ids;  

SELECT * from Table1 
WHERE 
(PId = @PID or @pID='') 
 AND (
         AID IN (SELECT aid from @ids) 
       or @idCount =0)

If you really wanted to keep the comma delimited values you can also use a split function

SELECT * from Table1 
    WHERE 
    (PId = @PID or @pID='') 
     AND (
             AID IN (SELECT item from dbo.SplitString(@aid, ',') ) 
           or @aid = "")

7 Comments

I am having this as a Store Proc. How can I insert values 1,2 ?
Are you saying that @aID is a parameter?
For the other part, I get Error as Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Yes, @aID is a Parameter.
You should have said. In that case see Parameterize an SQL IN clause I pefer this answer which uses table-values parmeters
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.