Display no records if parameters are empty

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Bill Obby

    Display no records if parameters are empty

    I have a stored procedure which accepts up to four optional parameters. This works fine, but if all the text boxes which (feed the parameters)are empty then I get all records displayed which I do not want.

    Code:
    ALTER PROCEDURE [dbo].[sp_threekeywordsearch]
    @keyword1 VARCHAR(255) = null,
    @keyword2 VARCHAR(255) = null ,
    @keyword3 VARCHAR(255) = null,
    @composer varchar(255) = null
    
    
    AS
    SELECT description, TrackTitle,CDTitle,Source
    FROM dbo.NON_STOP_PLAYLIST
    where   (keywords like '%' + @keyword1 + '%' or @keyword1 IS NULL)  
        and  
        (keywords like '%' + @keyword2 + '%' or @keyword2 IS NULL)  
    and  
        (keywords like '%' + @keyword3 + '%' or @keyword3 IS NULL)  and
        (composer like '%' + @composer + '%' or @composer IS NULL)
  • NeoPa
    Recognized Expert Moderator MVP
    • Oct 2006
    • 32653

    #2
    As the logic you wish to apply for all NULLs is the opposite of the logic used for NULLs when any keywords are present I suggest you will need to use CASE to handle all NULLs as a special situation.

    Comment

    • Bill Obby

      #3
      Hi NeoPa,

      Do you have a simple example of the syntax for this ?

      Bill

      Comment

      • sandeep M

        #4
        Dear Frnd...

        this may help you..

        Code:
        if(@keyword1 is null and @keyword2 is null  and  @keyword3=null and @composer is null)
        	SELECT description, TrackTitle,CDTitle,Source FROM dbo.NON_STOP_PLAYLIST where 1<>1
        else
        SELECT description, TrackTitle,CDTitle,Source 
        FROM dbo.NON_STOP_PLAYLIST 
        where   (keywords like '%' + @keyword1 + '%' or @keyword1 IS NULL)   
            and   
            (keywords like '%' + @keyword2 + '%' or @keyword2 IS NULL)   
        and   
            (keywords like '%' + @keyword3 + '%' or @keyword3 IS NULL)  and 
            (composer like '%' + @composer + '%' or @composer IS NULL)
        Last edited by NeoPa; Nov 5 '10, 11:40 PM. Reason: Please use the [code] tags provided.

        Comment

        • NeoPa
          Recognized Expert Moderator MVP
          • Oct 2006
          • 32653

          #5
          CASE (Transact-SQL) gives you examples as well as the full syntax specification.

          Comment

          • Sandeep M

            #6
            its very bad.. not posting reply, if someone posted an answer found worked or not .... I'm leaving out from this forum.. I feel so bad

            Comment

            • MMcCarthy
              Recognized Expert MVP
              • Aug 2006
              • 14387

              #7
              Sandeep your post has been displayed. The moderation queue can be a little slow sometimes. You can avoid this by registering as a member.

              Comment

              Working...