Dynamically creating the IN clause in a stored procedure

Viewed 14099

Possible Duplicate:
Need help in dynamic query with IN Clause

I am using SQL server 2008 and this is the problem that I am facing. I have a table named Cars with a column Company. Now I have a stored procedure that looks something like this

CREATE PROCEDURE FindCars (@CompanyNames varchar(500))
AS
SELECT * FROM Cars WHERE Company IN (@CompanyNames)

I tried something like this and failed

DECLARE @CompanyNames varchar(500)
SET @CompanyNames = '''Ford'',''BMW'''

exec FindCars @CompanyNames

I dont get any rows returned. When I do the following

DECLARE @CompanyNames varchar(500)
SET @CompanyNames = '''Ford'',''BMW'''

Select @CompanyNames

I get the following result

'Ford','BMW'

and if I replace this value in the select statement inside the stored procedure, it works

SELECT * FROM Cars where Company in ('Ford','BMW')

Thus I think that the stored procedure seems to be treating 'Ford','BMW' as one string rather than an array. Could someone please help me with this. How do I dynamically construct the string/array required in the IN clause of the select statement inside the stored procedure.

1 Answers
Related