Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedure with optional "WHERE" parameters

I have a form where users can specify various parameters to dig through some data (status, date etc.).

I can produce a query that is:

SELECT * FROM table WHERE: status_id = 3 date = <some date> other_parameter = <value> 

etc. Each WHERE is optional (I can select all the rows with status = 3, or all the rows with date = 10/10/1980, or all the rows with status = 3 AND date = 10/10/1980 etc.).

Given a large number of parameters, all optional, what is the best way to make up a dynamic stored procedure?

I'm working on various DB, such as: MySQL, Oracle and SQLServer.

like image 595
pistacchio Avatar asked Mar 30 '09 15:03

pistacchio


People also ask

Can stored procedures have optional parameters?

If you are executing a stored procedure with a bunch of parameters it can be a bit of a pain if you have to pass a value in for each of them. Fortunately, it's pretty easy to make some parameters required and others optional. You simply give them a default value.

How do you make a parameter optional in SQL?

A parameter is considered optional if the parameter has a default value specified when it is declared. It is not necessary to provide a value for an optional parameter in a procedure call. The default value of a parameter is used when: No value for the parameter is specified in the procedure call.

How do I execute a stored procedure without parameters in SQL Server?

The simplest kind of SQL Server stored procedure that you can call is one that contains no parameters and returns a single result set. The Microsoft JDBC Driver for SQL Server provides the SQLServerStatement class, which you can use to call this kind of stored procedure and process the data that it returns.

Is from optional in SQL?

From the Microsoft SQL Server documentation, FROM is optional.


1 Answers

One of the easiest ways to accomplish this:

SELECT * FROM table  WHERE ((@status_id is null) or (status_id = @status_id)) and ((@date is null) or ([date] = @date)) and ((@other_parameter is null) or (other_parameter = @other_parameter)) 

etc. This completely eliminates dynamic sql and allows you to search on one or more fields. By eliminating dynamic sql you remove yet another security concern regarding sql injection.

like image 164
NotMe Avatar answered Oct 07 '22 05:10

NotMe