我正在使用sql server R2
。我有一个存储过程,我将两个参数传递给@username varchar(100)
和@password varchar(100)
。
现在,当我第一次从我的应用程序创建用户时,密码将为NULL。
我想创建一个返回记录以匹配用户名和密码的查询。问题是代码正在将empty string
传递给stored procedure
。我想要自动考虑或转换empty string to NULL
的内容。我已经使用if condition
获得了解决方案,但我想使用单个查询,而不是条件。
编辑:
它是一个简单的存储过程:
CREATE PROCEDURE [dbo].[Pro_TblP]
(
@userName varchar(100),
@password varchar(100)
)
AS
BEGIN
IF (@password ='')
BEGIN
SELECT * FROM TblP
WHERE username = @userName AND password IS NULL AND IsDeleted = 0
END
ELSE
BEGIN
SELECT * FROM TblP
WHERE username = @userName AND password = @password AND IsDeleted = 0
END
END
GO
我想以单一表示形式组合查询。不要if条件。
答案 0 :(得分:1)
CREATE PROCEDURE [dbo].[Pro_TblP]
(
@userName varchar(100),
@password varchar(100)
)
AS
BEGIN
SELECT * FROM TblP
WHERE username = @userName AND COALESCE(password,'') = @password AND IsDeleted = 0
END
GO
答案 1 :(得分:0)
尝试以下代码: 当@password为空字符串或null时,它将返回所有值。当你在@password变量中传递一个字符串时,它会过滤它。
CREATE PROCEDURE [dbo].[Pro_TblP]
(
@userName varchar(100),
@password varchar(100)
)
AS
BEGIN
SELECT * FROM TblP
WHERE username = @userName AND IsDeleted = 0
And (password = @password OR isnull(@password,'') = '')
END
答案 2 :(得分:0)
试试这个
alter PROCEDURE [dbo].[Pro_TblP]
(
@userName varchar(100),
@password varchar(100)=''
)
AS
BEGIN
BEGIN
SELECT * FROM TblP
WHERE username = @userName AND IsNull(password,'')=@password AND IsDeleted = 0
END
END
答案 3 :(得分:0)
SELECT *
FROM TblP
WHERE username = @userName AND
IsDeleted = 0 AND
(
password = @password OR
password IS NULL AND @password = ''
)