sp parameter used in WHERE

  • I went through the first couple pages of threads and didn't see anything that would help me, so pardon me if I'm bringing up something that has been covered.

    consider the following,

    select somedataAge,somedataGender from somedatabase where somedataGender=0 and somedataAge=@desiredAge

    The parameter can be null or blank so I need to evaluate that fact in the WHERE clause; so if '@desiredAge' is either null or blank, just return all records otherwise include it.

    How can this be accomplished without having to have identical statements and just select the one to execute based on the procedure parameter?

    Thanks,

    Tim

     

     

     

     

     

     

  • use IS NULL or ISNULL( ) like:

    where colname = ISNULL( @var, '' ) OR colname IS NULL

     

  • SET @DesiredAge = NULLIF(@DesiredAge , '')

    SELECT ....

    WHERE (somedata = @DesiredAge OR @DesiredAge IS NULL)

    _____________
    Code for TallyGenerator

  • I think I left out some important criteria..

    If the parameter is NULL or blank, I don't want to include it in the WHERE clause.

    If it's not null, then I want to include it..

    select column1,column2 from mydatabase where column1=0 [here, I need to include 'and column2=@param1' IF param1 is not null, otherwise ignore @param1]

    Hopefully that makes better sense.

    Thanks!

     

  • Is this what you're looking for ?!?! (run against Pubs database)...

    create procedure testProc 
    @au_id varchar(15) = NULL
    as
    
    if @au_id is NULL
    select * from dbo.authors
    else
    select * from dbo.authors where au_id = @au_id
    go
    
    exec testProc
    exec testProc '172-32-1176'
    
    drop proc testProc
    







    **ASCII stupid question, get a stupid ANSI !!!**

  • > [here, I need to include 'and column2=@param1' IF param1 is not null, otherwise ignore @param1]

    That's exactly what my script is doing.

    _____________
    Code for TallyGenerator

  • Sergiy,

    I'll try that when I get back to the office tomorrow.

    Thanks!

     

  • Hi Sushila,

    Sort off.. I really just want to tack on the 'au_id = @au_id' if @au_id is not null or blank.

    I will try the suggestions everyone offered, tomorrow, when I get back to the office.

    Thanks!

     

  • Thanks john!

Viewing 9 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic. Login to reply