views:

256

answers:

2

I'm doing the specification for an application that has to search a table with different conditions in the WHERE clause.

For example (not an actual table):

type 1

select name from employees where active = true;

or type 2

select name from employees where idBoss = 3;

I would rather create one stored procedure with a parameter "type" than create two stored procedures with the same code and different "where" clauses.

Is this possible?

Note: I have 2 programmers; one knows only Informix, one knows only .NET. To minimize problems, I'm doing all the calls to the database with stored procedures so the db programmer and the .net programmer don't have to need each other.

A: 

Why create a stored procedure for something this short?

Consider using Linq. Where is just a filter which takes a lambda/function which returns true/false.

Hamish Grubijan
+2  A: 

You can use dynamic SQL in informix - see this link for more details.

DEFINE v_sql VARCHAR(250);

LET v_sql = "select name from employees";

IF IN_PARAMETER = 1 THEN
   LET v_sql = v_sql || " WHERE active = true"
ELSE
   LET v_sql = v_sql || " WHERE idboss = 3"
END IF;

PREPARE stmt FROM v_sql;
EXECUTE stmt;

FREE stmt;

If you can't use dynamic SQL, the next best thing would be:

IF IN_PARAMETER = 1 THEN
   select name from employees WHERE active = true;
ELSE
   select name from employees WHERE idboss = 3;
END IF;
OMG Ponies
.mmm how do I define and return stmt?
sergiogx
This is better than a stored procedure in that you are less dependent on the underlying SQL database. Also be on guard against SQL Injection attacks (http://en.wikipedia.org/wiki/SQL_injection) if any parts of your query can come from untrusted sources.
Jim Ferrans
Prepared SQL in stored procedures is available as of Informix 11.5.
RET
It depends on what you want to do with the 'returned stmt'. If you mean, how do you execute the statements and get results, then you use an INTO clause to assign the results to variables and a RETURN to return them (possibly WITH RESUME to return many results). You also use a FOREACH loop (or, in the pre-11.50 case, a pair of FOREACH loops) to generate the results. If you want to return the query string, then assign the query to a CHAR or VARCHAR (or LVARCHAR) variable and return it to the caller.
Jonathan Leffler