Q
Problem solve Get help with specific problems with your technologies, process and projects.

Passing values to an "in" expression in query

I'm using a stored procedure parameter to assign the list of expressions to be used in a WHERE clause that contains an "in" logical operator.

Example:
A simple select statement:

 Select TotalSales from SalesTable where year in (1999, 2000, 2001)
Now I want to create a stored procedure for this query, and allow the user (or my application) to pass in an arbitrary number of specific years to be used within the "in" expression of the where clause:
 create spSelectByYears @Yearelected ???declaration??? as Select TotalSales from SalesTable where year in @YearsSelected
Is this possible to do? If so, how do I specify YearsSelected? I started with something like: @YearsSelected varchar(100) = '(1998, 1999)' But that was no good. Then I tried various combinations of quotes, double quotes, square brackets, and anything else I could think of. No luck. Any help would be appreciated.

You cannot have dynamic predicates in this way. Your must use dynamic SQL to achieve this. Example:

 create spSelectByYears @Yearelected varchar(8000) as Declare @SQL varchar(8000) Select @SQL='Select TotalSales from SalesTable where year in ' + @YearsSelected

 

For More Information

This was last published in April 2003

Dig Deeper on Microsoft SQL Server Installation

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchBusinessAnalytics

SearchDataCenter

SearchDataManagement

SearchAWS

SearchOracle

SearchContentManagement

SearchWindowsServer

Close