Friday, February 24, 2012

Best way to use listbox selection in WHERE ... IN (...) clause?

I need to use the list of items from a multiselect listbox in a parameter of a query's IN clause.
Example:
I assemble the list from the listbox and set the paramter value so @.CityList = 'London','Paris','Rome' ... etc.
A sample SQL would be:
SELECT * FROM Customers
WHERE City IN (@.CityList)
However, the SQL will not work. It seems the whole string is put inanother set of single quotes by the compiler so it's treated as onestring literal instead of a list.
Is there a way around this?

The returned value should be like this
@.CityList = ('London','Paris','Rome')
in order to be working
regards

|||Try these links:
Arrays and Lists in SQL Server
Passing a list/array to SQL Server

|||Hi,
You can build a query string using something like below...
DECLARE @.SQL NVARCHAR(4000)
SELECT @.SQL ='SELECT * FROM Customers WHERE City IN (' + @.CityList + ')'
Then run the @.SQL query using
EXEC (@.SQL)

Eralper
http://www.kodyaz.com


|||

eralper wrote:


You can build a query string using something like below...

DECLARE @.SQL NVARCHAR(4000)
SELECT @.SQL ='SELECT * FROM Customers WHERE City IN (' + @.CityList + ')'
Then run the @.SQL query using
EXEC (@.SQL)


Eralper, in the link I provided (Arrays and Lists in SQL Server) that is identified as one of the solutions to stay away from. I do not recommend that method.

No comments:

Post a Comment