1

I'm writing an 'advanced search' page for a web application. It basically has a form that goes:

Search for query in the forum forum name posted by username in the last date

The idea is that users can leave fields blank if they wish and the search won't include it.

I'd rather not write a stored procedure for searching based on every possible combination of leaving values blank. Is there a way I can write a stored procedure so that the search changes based on which parameters passed in are blank?

Something like (pseudo code)

SELECT * FROM Table WHERE Message = @query

(if @username isn't null)
AND Username = @Username

(if @forum isn't null)
AND Forum = @forum

..and so on.

Thanks for any help you can provide!

shauneba
  • 2,122
  • 2
  • 22
  • 32

2 Answers2

2

This should work:

SELECT *
FROM YourTable
WHERE   (Message = @query OR @query IS NULL)
AND     (Forum = @forum OR @forum IS NULL)
AND     (Username = @username OR @username IS NULL)
AND     (LastDate = @lastdate OR @lastdate IS NULL)
Lamak
  • 69,480
  • 12
  • 108
  • 116
  • This approach can cause a performance hit, expecially if there are a lot of optional parameters. See Iwo Kucharski's comment above for a more robust solution. – DeanOC Jul 04 '12 at 22:42
1
  CREATE Proc [dbo].[sp_sarch_with_filter]                   
  @param1 varchar(50)=NULL,                                
  @param2 varchar(50)=NULL,                                
  @param3 varchar(50)=NULL,                                

  AS                                  
  Begin                                                                  

  Declare @dynamicsql varchar(max)                  



  Set @dynamicsql='select  * from tabelName where 1=1'                               


  if(@param1 is not null and @param1  <> '')                  
  Set @dynamicsql=@dynamicsql+' and col1 like''%'+@param1 +'%'''                  

  if(@param2 is not null and @param2  <> '')                  
  Set @dynamicsql=@dynamicsql+' and col2 like''%'+@param2 +'%'''                  

  if(@param3 is not null and @param3  <> '')                  
  Set @dynamicsql=@dynamicsql+' and col3 like''%'+@param3 +'%'''                  


  Set @dynamicsql=@dynamicsql+' Order by col4 Desc'

  Print @dynamicsql                  

  Execute(@dynamicsql)                                       
subha
  • 1,050
  • 2
  • 15
  • 42
Zia
  • 921
  • 5
  • 14
  • This is not recommended, as it is vulnerable to SQL injection attacks. https://www.owasp.org/index.php/Top_10-2017_A1-Injection – Stamp Mar 08 '18 at 15:46
  • "like" queries, just like any other query, are very much inject-able when not sanitized. In your specific example, see https://stackoverflow.com/a/15579926/416314 for an example injection attack on a "like" statement – Stamp Oct 19 '18 at 14:33