Link to home
Start Free TrialLog in
Avatar of GordonPrince
GordonPrinceFlag for United States of America

asked on

best way to write stored procedure with option parameter for where clause

What's the best way to create a stored procedure in SQL 2005 so it will run whether or not a parameter is passed in to it? See sample code.

Sometimes I want to run the select statement with no where clause. But if I pass in a parameter when I execute the stored procedure, then I want the where clause applied.

I thought of doing
"where col1 like %@param1%", is that a good approach? If I set the default value of the variable to be null or something like that?

Any suggestions?
create procedure MySP
as
(if I pass in a parameter)
select * from tab1 where col1 = @param1
(if I don't pass in a parameter)
select * from tab1

Open in new window

Avatar of Sharath S
Sharath S
Flag of United States of America image

You can create the SP like this.
create procedure MySP @param1 int = null
as
select * from tab1 where col1 = @param1 or (col1 = col1 and @param1 is null)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Sara bhai
Sara bhai
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GordonPrince

ASKER

Very elegant. Thanks.