Sometimes we're developing applications that require performing searches against database tables in SQL. The search must enable using a set of optional parameters (up to 10 parameters for example) as the main search criteria (a null value indicates not to filter the data, and a non-null value indicate to filter the data by the underlying value). Some developers use complicated T/SQL statements (a handful of if and if/else statements) to implement this requirement, thus making the code illegible. Because I have to deal with this kind of problems, now I'd like to suggest you an alternative technique that I use in my solutions.
Let's supposed that we have the following table:create table CIS_CLIENT( ID int primary key, first_name varchar(50) not null,
last_name varchar(50) null,
case_officer_fk int,
branch_fk int
);
Now, our requirements indicate the option to look up for information by specifying any criteria value (the search parameters are based on the first name , last name, case officer of the client and the the branch office to whom it belongs to).
CREATE PROC st_Search_clients
(
@clientID int = null, @first_name varchar(50) not null,
@last_name null,
@case_officer_fk int,
@branch_fk int
)
as
BEGIN
SELECT * FROM cis_client client
WHERE
(@clientID is null OR @clientID = client.id) AND
(@first_name is null OR @first_name = client.first_name) AND
(@last_name is null OR @last_name = client.last_name ) AND
(@case_officer_fk is null OR @case_officer_fk = client.case_officer_fk) AND
(@branch_fk is null OR @branch_fk = client.branch_fk )
END
The same thing can also be achieved by COALESCE function in where clause :
client.id = COALESCE(@clientID, client.id) AND client.first_name = COALESCE(@first_name, client.first_name) AND client.last_name = COALESCE(@last_name, client.last_name) AND client.case_officer_fk = COALESCE(@case_officer_fk,client.case_officer_fk) AND client.branch_fk = COALESCE(@branch_fk, client.branch_fk)
Thursday, September 25, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment