November 9, 2010 at 7:30 pm
I have a list of values that I want to store in a variable in SQL server 2005.
DECLARE @State varchar(30)
SET @State = 'VIC', 'QLD'
I get an error.
Incorrect syntax near ','.
Then i want to run a select query
SELECT * FROM address WHERE state IN @State
I do not want to hard code the values as they are used multiple times in my stored proc.
How can I do this?
Thanks
Mark
November 9, 2010 at 7:45 pm
The only way that you can store multiple values in a variable like this is to store them in a string
DECLARE @State varchar(30)
SET @State = '''VIC''', '''QLD'''
Where do the values come from? You can also potentially store these in a table variable or temp table and do a join with your main table.
November 9, 2010 at 7:53 pm
Use a temp table and store your variables in rows and join against it instead of trying to use the IN statement that way.
IE:
DECLARE @filter TABLE (FilterVal VARCHAR(100))
INSERT INTO @filter VALUES ('AZ')
INSERT INTO @filter VALUES ('ND')
SELECT
*
FROM
StateTable AS st
JOIN @filter AS f
ON st.state = f.filter
Never stop learning, even if it hurts. Ego bruises are practically mandatory as you learn unless you've never risked enough to make a mistake.
For better assistance in answering your questions[/url] | Forum Netiquette
For index/tuning help, follow these directions.[/url] |Tally Tables[/url]
Twitter: @AnyWayDBA
November 9, 2010 at 8:17 pm
This data is only for testing.
The @State parameter will be passed into the stored proc from Reporting Services.
November 9, 2010 at 8:54 pm
In that case, you will need to use a function that splits the delimited string into the individual items, and returns them as a table.
Here is the latest version of the Delimited Split Function
You would use it like:
SELECT *
FROM address a
JOIN dbo.DelimitedSplit8K(@State, ',') ds
ON ds.Item = a.State;
You mention that they are used multiple times. You might want to do this instead:
SELECT [State] = Item
INTO #States
FROM dbo.DelimitedSplit8K(@State, ',');
And then join to this temporary table everywhere
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
Viewing 5 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply