Sunday, February 19, 2012

How to use a SP parameter in a where in clause?

I am trying to do a 'WHERE IN' clause by taking the value of a paremeter and using it as the value in the WHERE IN clause such as:

DECLARE @.parm NVARCHAR(1000) = 'IBM, MOT, MSFT'

SELECT * FROM SomeStockTable WHERE TickerSymbol IN (@.parm)

I would like to avoid using an EXEC statement and string-building this whole query, since that is ugle and hard to maintain.

ANy ideas?

TYVM

See the discussion on tmorton's fnSplit:

http://forums.asp.net/304221/ShowPost.aspx

although she recommends using it as part of a join, I'm lazy. I normally do somehting like this (Which should turn out to be fairly equivalent, but easier for me to read):

SELECT *

FROM sometable

WHERE ID IN (SELECT ID FROM dbo.Split(@.param,DEFAULT))

-- My Split function, which is similair to tmorton's has only one field named id, and the default for the second parameter is a comma. I have found the performance to be more than fine, even on very large and complex queries. Some of which tie together 10+ tables, of which have 10 million+ rows.

No comments:

Post a Comment