简体   繁体   中英

Ignore parameter in stored procedure If null

I am trying to get a multi input search function on a table to work via stored procedure.

I have four input parameters: a bool and 3 strings. When I run 1 string and a bool I get back the expected row.

As soon as I try to add the 2 and 3 inputs (string) to the search I get back no data. If I have all 3 inputs (strings) filled in it should return the rows that have something related to those strings.

If the input is empty...then it should just skip that part of the query

The stored procedure looks like this:

ALTER PROCEDURE [dbo].[GetUsers]
    @Online BIT = NULL,
    @UserName NVARCHAR(150) = NULL,
    @EmailAddress NVARCHAR(150) = NULL,
    @Location NVARCHAR(50) = NULL
AS
    SELECT *
    FROM Users
    WHERE (ISNULL(@Online, 0) = 0 OR (@Online = 1 AND Online = 1)) 
      AND (ISNULL(@UserName, UserName) = UserName OR UserName LIKE '%' + @UserName + '%' )
      AND (ISNULL(@EmailAddress, EmailAddress) = EmailAddress OR EmailAddress LIKE '%' + @EmailAddress + '%')
      AND (ISNULL(@Location, Location) = Location OR Location LIKE '%' + @Location + '%' )
    ORDER BY 
         Users
    FOR XML PATH('Users'), ROOT('Users')

    RETURN 0

try this

WHERE  (  (@Online Is Null) or  (@Online = 1 AND Online = 1))
      AND ( (@UserName is null)  OR (UserName LIKE '%' + @UserName + '%' ) )
      AND (( @EmailAddress is null) or ( EmailAddress LIKE '%' + @EmailAddress + '%'))
      AND ( (@Location is null)  or   ( Location LIKE '%' + @Location + '%' ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM