There are several ways to create parametrized view in Oracle. In this blog I’ll show you how to do that using a context. Assume you want to have a view that depends on some where condition:
select * from emp where deptno = ?
The deptno is known at the run time
You can define a context (or namespace) and define an attribute „deptno“ that holds the value of deptno at runtime. The context is like a container for attribute value pairs. The attribute can be defined using „dbms_session.set_context(context_name,attr,value)„
To create the context (you should have the system privilege create any context) :
create context mycontext using mypackage accessed globally;
Note that the context is associated with a package. This is for security reasons, Oracle only allows to execute the dbms_session.set_context from within the package associated to the context. Furthermore the package does not have to be present at the point when the context is created.
create or replace package mypackage as
procedure def_attr_in_context(attr_nam in varchar2, attr_val in varchar2);
end mypackage;
/
create or replace package body mypackage as
procedure def_attr_in_context(attr_nam in varchar2, attr_val in varchar2) is
begin
dbms_session.set_context('mycontext', attr_nam, attr_val);
end def_attr_in_context;
end mypackage;
Defining the parametrized view with the where condition deptno = SYS_CONTEXT(‚mycontext‘,’deptno‘)
CREATE OR REPLACE VIEW vw_parametrized_view AS
SELECT * FROM emp WHERE deptno = SYS_CONTEXT('mycontext','deptno')
SELECT * FROM vw_parametrized_view
no rows selected
After setting the defining (setting) the attribute deptno
BEGIN
mypackage.def_attr_in_context('deptno','20');
END;
SELECT * FROM vw_parametrized_view
7369 SMITH CLERK 7902 17.12.1980 800,00 20
7566 JONES MANAGER 7839 02.04.1981 2975,00 20
7788 SCOTT ANALYST 7566 19.04.1987 3000,00 20
7876 ADAMS CLERK 7788 23.05.1987 1100,00 20
7902 FORD ANALYST 7566 03.12.1981 3000,00 20










