0

我有 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但返回任何数据 看看这个

4

3 回答 3

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 + '%' )
于 2013-05-18T04:12:47.727 回答
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) )
于 2013-05-18T04:39:53.553 回答
0

在这里,您正在搜索 2 个字段usernamename并且输入参数是null
Like将不起作用,null因此您必须独立检查 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 + '%' )

SQL小提琴

于 2013-05-18T04:13:03.193 回答