在存储过程中使用LIKE和输入参数

时间:2013-05-17 10:22:51

标签: sql stored-procedures

我有2个输入参数,我想搜索用户名为@Username且用户名为@Name的部分名称为@Username的用户名称的一部分是@Name

SELECT *  
FROM tbl_answer
WHERE 
     an_del = 0 
     AND u_username = ISNULL(LIKE %@Username%, u_username) OR 
         u_name = ISNULL(LIKE @Name, u_name) 

如何在此存储过程中使用LIKE

2 个答案:

答案 0 :(得分:3)

CREATE PROC dbo.SearchAnswers
@Username nvarchar(20),
@Name nvarchar(20)
AS
SELECT *  
FROM tbl_answer
WHERE an_del=0 and u_username LIKE '%' + ISNULL(@Username, u_username) + '%'
  OR u_name LIKE ISNULL(@Name, u_name)

Example for a SQLServer2008

答案 1 :(得分:1)

您需要使用动态sql,例如sql server:

create procedure MyProc
(
  @Username varchar(30),
  @Name varchar(30)
)
as
begin
   exec ('SELECT * from tbl_answer where an_del=0 and 
           u_username=isnull(like ''%'+@Username+'%'',u_username) 
             or u_name=isnull(like '''+@Name+''',u_name)') 
end