Search code examples
sql-servert-sqlstored-proceduressqlparameter

Dynamic parameters for sql query with "IN" operator


I have an ASP.NET website (c#) and in the code-behind I want to use the IN operator in SQL http://www.w3schools.com/sql/sql_in.asp to get data from my database.

The syntax is:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

I use a stored procedure to get data, inside this procedure I run, in the end, the select.

My question is how to build dynamically the (value1, value2, ...) part of the query? How do I send as SqlParameter(s) the values that appear in the IN operator?

The stored procedure is defined like this:

CREATE PROCEDURE [dbo].[GetAllUsers]
    @ORGANIZATION_ID int = null
AS
BEGIN
    SET NOCOUNT ON;

    begin
       SELECT * 
       from USERS
       where ORGANIZATION_ID = @ORGANIZATION_ID
    end
END

I'd like to replace the WHERE clause with something like:

WHERE ORGANIZATION in (xxxxxxxxxxxxx)

How to do this?

Thank you.


Solution

  • You can use dynamic sql:

    CREATE PROCEDURE [dbo].[GetAllUsers]
        @ORGANIZATION_ID varchar(max) = null
    AS
    BEGIN
        declare @sql varchar(max)
        @sql = 'SELECT * 
                from USERS
                where ORGANIZATION_ID in ('+@ORGANIZATION_ID+')' 
        SET NOCOUNT ON;
            begin
              exec(@sql)  
            end
    END
    

    You have to change type of @ORGANIZATION_ID to varchar and run the procedure with

    one id:

    exec '1' 
    

    or list of ids:

    exec '1,2,3,4'