Question

In SQL Server, I am passing String as parameter :

@Param1 = Test,Test1,Test2

I am formatting it to:

@Param1 = 'Test','Test1','Test2'

When I am trying to use this in SELECT statement with IN parameter, it is not returning any data

SELECT * FROM TABLE1 where COLUMN1 IN (@Param1)

What is the correct syntax?

Was it helpful?

Solution

As pointed out already in the comments by marc_s, IN requires a list of values not simply one variable.

But you could provide those values in a SELECT from a simple table variable like this:

DECLARE @Param1 TABLE (Value NVARCHAR(255));
INSERT INTO @Param1 (Value)
    SELECT 'Test1'
    UNION
    SELECT 'Test2'
    UNION
    SELECT 'Test3'

SELECT
        *
    FROM TABLE1
    WHERE
        COLUMN1 IN
            (SELECT Value FROM @Param1)

OTHER TIPS

I wish there were array vars like that! :-)

But you can convert it to a table using a function, and then use the table with your IN clause as you're attempting.

Here is how that would look:

DECLARE @Param1 nvarchar(max)
SET @Param1 = 'Test,Test1,Test2'

SELECT * 
FROM myTable 
WHERE myField In (Select ParsedString From dbo.ParseStringList(@Param1))

And here is (at least one way to write) the function:

CREATE Function [dbo].[ParseStringList]  (@StringArray nvarchar(max) )  
Returns @tbl_string Table  (ParsedString nvarchar(max))  As  

BEGIN 

DECLARE @end Int,
        @start Int

SET @stringArray =  @StringArray + ',' 
SET @start=1
SET @end=1

WHILE @end<Len(@StringArray)
    BEGIN
        SET @end = CharIndex(',', @StringArray, @end)
        INSERT INTO @tbl_string 
            SELECT
                Substring(@StringArray, @start, @end-@start)

        SET @start=@end+1
        SET @end = @end+1
    END

RETURN
END
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top