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 @YearsSelectedIs 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
- Dozens more answers to tough SQL Server questions from Tony Bain are available here.
- The Best Microsoft SQL Server Web Links: tips, tutorials, scripts, and more.
- The Best SQL Web Links
- Have a SQL Server tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL Server questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
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.