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.
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.
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.
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.
From the Microsoft SQL Server documentation, FROM is optional.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With