简体   繁体   中英

Treat parameter as an empty string or null if user did not enter any value

I have a simple stored procedure that looks something like this:

SET @email = NULL

SELECT * FROM empTable
WHERE email = ISNULL(@email, '')

@email will take input from the user. The problem is, the email column in the table can be an empty string or null (or an email).

If the user doesn't enter any value, it should return all Employees with either NULL or empty string email.

I have tried to following but it didn't work too:

SELECT * 
FROM empTable
WHERE email = ISNULL(@email, '') OR email = ISNULL(@email, NULL)
SELECT * FROM empTable
WHERE email = ISNULL(@email, '') OR (email IS NULL AND @email IS NULL)

Or:

SELECT * FROM empTable
WHERE ISNULL(email,'') = ISNULL(@email, '') 

if email is then condition after second OR will be considered

if email is present then first curly brackets will be considered

SELECT * FROM empTable
WHERE (email=@email) or (@email is null OR email = ISNULL(@email, ''))

Try like this:

IF @email has value then corresponding row will retrieve from DB; else second condition will execute which will retrieve email with NULL and empty string.

SELECT * 
FROM empTable
WHERE email = ISNULL(@email, '') OR (email IS NULL and email = '')

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