Use LIKE in a stored procedure with an input parameter

I have 2 input parameters, and I want to search for users where the o part is the username @Username , and the part of the @Name name is that this user part of the @Username and the part of the @Name 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) 

How can I use LIKE in this stored procedure?

+4
source share
2 answers
 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 SQLServer2008

+3
source

You need to use dynamic sql, for example 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 
+1
source

Source: https://habr.com/ru/post/1481354/


All Articles