Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Trouble with "IN"

Author  Topic 

dave.bodenheimer
Starting Member

5 Posts

Posted - 2013-05-04 : 13:08:20
I am creating a script where I am querying a table using the IN keyword.
When I type the data inside the IN clause, the query performs as i should. But when I create a variable with the exact same data in it and use the variable inside the IN clause, it does not. Any Ideas???



Here is the query that works
SELECT * FROM scpcommandeventlog WHERE MESSAGEid = 3 AND PARAM1 IN('11416407','11416410','11416413','11416417','11416419','11416421','11416423','11416427','11416432','11416433','11416434','11416435','11416438','11416443','11416446','11416448','11416451','11416454','11416458','11416462')

here is the query that doesn't
SELECT * FROM scpcommandeventlog WHERE MESSAGEid = 3 AND PARAM1 IN(@list)


Here is the query that populates the @list variable

DECLARE @List varchar(max)

SELECT @List = isnull(@List + ',', '') + '''' + cast(itemid as varchar) + ''''
FROM dbo.ItemList
WHERE sortid LIKE @sortid

chadmat
The Chadinator

1974 Posts

Posted - 2013-05-04 : 13:56:39
Because you can't do that. You would need to create the entire query as a string and execute it.

-Chad
Go to Top of Page

dave.bodenheimer
Starting Member

5 Posts

Posted - 2013-05-04 : 14:10:38
Thanks Chad, while waiting for an answer i did that and it works great.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-05-06 : 02:09:16
you can do this though but it may not perform well for large datasets


SELECT * FROM scpcommandeventlog WHERE MESSAGEid = 3 AND ',' + @list + ',' LIKE '%,' + CAST(PARAM1 AS varchar(10)) + ',%'



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2013-05-10 : 18:05:42
You could also split the data in your variable and return it as a table as part of your IN clause. There are a variety of split functions to be found but the best I'[ve run across is Jeff Moden's. It can be found here: http://www.sqlservercentral.com/articles/Tally+Table/72993/

HTH

=================================================
There are two kinds of light -- the glow that illuminates, and the glare that obscures. -James Thurber
Go to Top of Page
   

- Advertisement -