views:

63

answers:

2

Please consider the following scripts.

Create Table:

IF OBJECT_ID('Colortable') IS NOT NULL
  DROP TABLE ColorTable

CREATE TABLE Colortable (Color VARCHAR(32))
GO

Insert some values:

SET  NOCOUNT ON

INSERT Colortable
  SELECT 'red'

INSERT Colortable
  SELECT 'orange'

INSERT Colortable
  SELECT 'blue'

INSERT Colortable
  SELECT 'green'
GO

Create my Variable (which will become a paramter in SSRS) automatically:

DECLARE @colors VARCHAR(1024)

SELECT @colors =
         COALESCE(
           @colors + '''' + ',' + '''', '') +
         Color
FROM Colortable

When I use "Select @colors" I get the following:

'red','orange','blue','green'

However, my queries do not work as expected.

SELECT *
FROM colortable
WHERE Color IN ('red', 'orange', 'blue', 'green') -- Returns 4 rows. 


SELECT *
FROM colortable
WHERE Color IN (@colors) -- Returns 0 Rows

Can anyone tell me why? I am trying to generate a string of values so that this script will work in SSRS and SSMS (or whatever tool I am using).

+1  A: 

@colors is a single varchar, not a list of varchars. What you can do instead is insert your values into a temp table and join against that.

RedFilter
I can't do that because the SQL Statement is to be used in SSRS (converted to a parameter) and in SSMS as a SQL Statement. If I try to use a table variable, a table of any kind, etc it won't work as a SSRS parameter.
DavidStein
Why can't SSRS call a stored procedure? You can do whatever you want in a stored procedure and not have to deal with the limitations of a single SQL statement.
Aaron Bertrand
I'm not allowed to create SP's in my database per the Vendor Contract. It sucks, but it's what I am stuck with.
DavidStein
+1  A: 

i think you can use sp_executesql may work for you

Pranay Rana
+1: Correct - using a single variable to represent a list of comma separated values means dynamic SQL.
OMG Ponies
+1: http://www.sommarskog.se/dynamic_sql.html#List
etliens
@etliens : there is still one not i.e not +1
Pranay Rana