用2输入参数在sql中搜索

时间:2013-05-18 04:09:42

标签: sql sql-server stored-procedures

我有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

3 个答案:

答案 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个字段usernamename,输入参数为nullLike不适用于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 Fiddle

答案 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) )