Add WHERE clauses to SQL dynamically / programmatically

前端 未结 3 1407
野趣味
野趣味 2020-11-30 10:10

How can I add search condition to SQL Stored Procedure programmatically? In my application(C#) I\'m using stored procedure (SQL Server 2008R2)

ALTER PROCEDUR         


        
3条回答
  •  天涯浪人
    2020-11-30 10:43

    You can do this in sql only, like this:

    SELECT * 
    FROM tUsers 
    WHERE 1 = 1
      AND (@userID IS NULL OR RTRIM(Name) = @userID )
      AND (@password IS NULL OR RTRIM(Password) = @password)
      AND (@field2 IS NULL OR Field2 = @field2)
    ....
    

    If any parameter passed to the stored procedure with a NULL value then the whole condition will be ignored.

    Note that: I added WHERE 1 = 1 in order to make the query work in case no parameter passed to the query and in this case alll the result set will be returned, since 1 = 1 is always true.

提交回复
热议问题