views:

398

answers:

3

The stored procedures being written here currently concats the parameters to the queries:

'Select * From Names Where Name = ' || prmName || ' Order By ' || prmSortField

Is it possible to parameterize this query inside the stored procedure? Possibly like:

query = 'select * From Names Where Name = @name Order By ' || prmSortField
call(query, prmName)

Note: In case you wonder why we do so, there are two common parameters for our sp's: sortFieldIndex and sortDirection. Since we cannot directly parameterize these, the query is dynamically generated. But other parameters make the queries open for injection. So I am looking a way to parameterize some of the parameters.

+4  A: 

Absolutely. Use cursors.

DECLARE
  CURSOR c1 (job VARCHAR2, max_wage NUMBER) IS
    SELECT * FROM employees WHERE job_id = job AND salary > max_wage;
BEGIN
  FOR person IN c1('CLERK', 3000)
  LOOP
     -- process data record
    DBMS_OUTPUT.PUT_LINE('Name = ' || person.last_name || ', salary = ' ||
                         person.salary || ', Job Id = ' || person.job_id );
  END LOOP;
END;
cletus
+4  A: 

For a dynamic query with bind values, do this:

procedure p (prmName varchar2, prmSortField varchar2)
is
    query varchar2(100);
    rc sys_refcursor;
    names_rec names%rowtype;
begin
    query = 'select * From Names Where Name = :name Order By ' || prmSortField
    open rc for query using prmName;
    loop
        fetch rc into names_rec;
        exit when rc%notfound;
        -- process this row
    end loop;
    close rc;
end;
Tony Andrews
A: 

For a more elaborate procedure that supports optional parameter values (but uses sys context), check out the following post on Asktom.com

PRATTY -- Thanks for the question regarding 'CURSOR'...

Stew S