Jump to content

Recommended Posts

Hey Everybody,

 

The issue I am having is that I would like to declare a varchar to hold a couple comma separated values to use in an in operator.

 

DECLARE @TEST varchar(1000);
SET @TEST='
''test1'',
''test2''
';

 

to confirm the value is set correctly I run a select on the variable

 

Select @TEST;

 

The result is 'test1','test2' which is what I am looking to place in my where clause:

 

Select *
from testTable
where col in (@TEST);

 

the result should return rows but nothing is returned. I also tried to use where col =any(@TEST) and it errors.

 

If any one can see the error in my ways I would be grateful. Thank you.

Link to comment
https://forums.phpfreaks.com/topic/270685-sql-variable-to-use-for-sql-in-operator/
Share on other sites

You can't do what you're trying to do.  The closest you could get to using a variable with multiple items in the IN clause is to use a table value varaible, such as:

DECLARE @test TABLE (
   s VARCHAR(100)
)

INSERT INTO @test VALUES ('test1'),('test2');

SELECT * FROM testtable
WHERE col1 IN (SELECT s FROM @test)

 

Thank you Kicken,

 

I code in php and was expecting variables to work similarly. Thank you for giving me a work around, I build a report which consists of 10 unions where the criteria corresponds to the example I gave. In the past, I have replaced the criteria by using the replace function and believe that is what I plan on using moving forward.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.