将参数视为空字符串,如果用户未输入任何值,则返回null

时间:2014-11-10 18:12:52

标签: sql-server stored-procedures

我有一个简单的存储过程,如下所示:

SET @email = NULL

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

@email将接受用户的输入。问题是,表中的email列可以是空字符串或null(或电子邮件)。

如果用户未输入任何值,则应使用Employees或空NULL电子邮件返回所有string

我试过跟随,但它也不起作用:

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

3 个答案:

答案 0 :(得分:1)

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

或者:

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

答案 1 :(得分:0)

如果电子邮件在第二次OR后被视为条件

如果有电子邮件,则会考虑第一个大括号

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

答案 2 :(得分:0)

试试这样:

如果@email有值,那么相应的行将从DB中检索;否则将执行第二个条件,它将检索带有NULL和空字符串的电子邮件。

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