我有2个输入参数,我想用这些
搜索 CREATE TABLE dbo.tbl_answer
(
an_del INT,
u_username NVARCHAR(50),
u_name NVARCHAR(50) null
)
INSERT dbo.tbl_answer
VALUES(1, 'mohammad', null), (1, 'A13A6C533AF77160FBF2862953FA4530', 'GCV'), (1, 'C', 'GG'), (0, 'AB', 'BB'), (1, 'AC', 'K')
GO
CREATE PROC dbo.SearchAnswers
@Username nvarchar(20),
@Name nvarchar(20)
AS
SELECT *
FROM dbo.tbl_answer
WHERE an_del = 1 AND u_username LIKE ISNULL('%' + @Username + '%', u_username)
and u_name LIKE ISNULL('%' + @Name + '%', u_name)
我运行此命令EXEC dbo.SearchAnswers 'moha', null
但返回任何数据
look at this
答案 0 :(得分:1)
试试这个:
CREATE PROC dbo.Answers
@Username nvarchar(20),
@Name nvarchar(20)
AS
declare @Name2 nvarchar(20)
set @Name2 = ISNULL(@Name, '00')
SELECT *
FROM dbo.tbl_answer
WHERE an_del = 1 AND ( u_username LIKE ISNULL('%' + @Username + '%', u_username)
AND
ISNULL(u_name,'00') LIKE '%' + @Name2 + '%' )
答案 1 :(得分:0)
您正在搜索2个字段username
和name
,输入参数为null
。 Like
不适用于null
因此您必须单独检查空值或为此添加一些补充内容...
CREATE PROC dbo.SearchAnswers
@Username nvarchar(20),
@Name nvarchar(20)
AS
declare @Name2 nvarchar(20)
set @Name2 = ISNULL(@Name, '00')
SELECT *
FROM dbo.tbl_answer
WHERE an_del = 1 AND ( u_username LIKE ISNULL('%' + @Username + '%', u_username)
AND
ISNULL(u_name,'00') LIKE '%' + @Name2 + '%' )
答案 2 :(得分:0)
您的问题是您不允许u_name
在您的表中为空。它是唯一一个u_username
包含“moha”的记录
CREATE PROCEDURE dbo.SearchAnswers
@Username nvarchar(20),
@Name nvarchar(20)
AS
SELECT *
FROM dbo.tbl_answer
WHERE an_del = 1
AND u_username LIKE ISNULL('%' + @Username + '%', u_username)
AND ISNULL(u_name,'') LIKE ISNULL('%' + @Name + '%', u_name)
您还可以对NULL进行第三次条件明确性测试。
AND ( (u_name is null) or (u_name LIKE ISNULL('%' + @Name + '%', u_name) )