0

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.

1
  • what DBMS (SQLServer/MySQL/Oracle) are you using? Commented Oct 24, 2012 at 11:50

1 Answer 1

1

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' 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Should I use ORGANIZATION_ID varchar(max) or ORGANIZATION_ID varchar(10000).
It's bad practice to do so, however
@Sklivvz Can you tell me, what is better practice? I will consider it, then I will add new solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.