Dynamic SQL using DBMS_SQL Package
Hi,
How do i construct a
"select * from :table_name(input parameter)"
in a store proc in Oracle8 ?
I know this is only possible using DBMS_SQL package in Oracle 8.
I know that this is easily done using native Dyanamic SQL 8i onwards.
Also I want to return the resultset obtained above through a REF cursor.
Please Help !!!
Will be greatly indebted to anyone who can supply the code or direct me to some helpful information on the net.
Thanks in advance.
Peeyush
You are asking for two things here, use the tablename dynamically
as bind variable to fetch the resultset and send the resultset to
a stored procedure.
I thought of doing both of them with REF Cursors, no Dynamic SQL here.
Consider the following test,SQL> create or replace package ref_types as
2 type r_cursor(pSal NUMBER) is ref cursor;
3 end;
4 /
Package created.
-- Please note that I did some quick and dirty coding to switch
-- between the table names to show the results.
SQL> create or replace procedure p_dynamic_table
2 (pRefCur IN ref_types.r_cursor, pTable varchar2) as
3 emp_rec my_emp%ROWTYPE;
4 inv_rec test444%ROWTYPE;
5 begin
6 loop
7 IF UPPER(pTable) = 'MY_EMP' Then
8 fetch pRefcur into emp_rec;
9 Elsif UPPER(pTable) = 'INV' THEN
10 fetch pRefCur into inv_rec;
11 Else
12 exit;
13 End if;
14 exit when pRefcur%NOTFOUND;
15 If UPPER(pTable) = 'MY_EMP' Then
16 dbms_output.put_line(emp_rec.empno);
17 Elsif UPPER(pTable) = 'INV' Then
18 dbms_output.put_line(inv_rec.seq);
19 Else
20 Null;
21 End if;
22 end loop;
23 end;
24 /
Procedure created.
SQL> declare
2 vRefCur ref_types.r_cursor;
3 vTableName Varchar2(30);
4 begin
5 vTableName := 'my_emp';
6 open vRefCur for 'select * from ' || vTableName;
7 p_dynamic_table(vRefCur, vTableName);
8 close vRefCur;
9 vTableName := 'inv';
10 open vRefCur for 'select * from ' || vTableName;
11 p_dynamic_table(vRefCur, vTableName);
12 close vRefCur;
13 end;
14 /
7369
7499
7521
7566
7654
7698
7782
7788
7839
7844
7876
7900
7902
7934
1
2
3
4
5
6
7
8
9
10
PL/SQL procedure successfully completed.Thx,
Sri
Similar Messages
-
Create Table using DBMS_SQL package and size not exceeding 64K
I have a size contraint that my SQL size should not exceed 64K.
Now I would appriciate if some one could tell me how to create a table using
Dynamic sql along with usage of DBMS_SQL package.
Brief Scenario: Users at my site are not given permission to create table.
I need to write a procedure which the users could use to create a table .ALso my SQL size should not exceed 64K. Once this Procedure is created using DBMS_SQL package ,user should pass the table name to create a table.
Thanks/"If a user doesn't have permission to create a table then how do you expect they will be able to do this"
Well, it depends on what you want to do. I could write a stored proc that creates a table in my schema and give some other user execute privilege on it. They would then be able to create a able in my schema without any explicitly granted create table privilege.
Similarly, assuming I have CREATE ANY TABLE granted directly to me, I could write a stroe proc that would create a table in another users schema. As long as they have quota on their default tablespace, they do not need CREATE TABLE privileges.
SQL> CREATE USER a IDENTIFIED BY a
2 DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp;
User created.
SQL> GRANT CREATE SESSION TO a;
Grant succeeded.
SQL> CREATE TABLE a.t (id NUMBER, descr VARCHAR2(10));
CREATE TABLE a.t (id NUMBER, descr VARCHAR2(10))
ERROR at line 1:
ORA-01950: no privileges on tablespace 'USERS'So, give them quota on the tablespace and try again
SQL> ALTER USER a QUOTA UNLIMITED ON users;
User altered.
SQL> CREATE TABLE a.t (id NUMBER, descr VARCHAR2(10));
Table created.Now lets see if it really belongs to a:
SQL> connect a/a
Connected.
SQL> SELECT table_name FROM user_tables;
TABLE_NAME
T
SQL> INSERT INTO t VALUES (1, 'One');
1 row created.Yes, it definitely belongs to a. Just to show that ther is nothing up my sleeve:
SQL> create table t1 (id NUMBER, descr VARCHAR2(10));
create table t1 (id NUMBER, descr VARCHAR2(10))
ERROR at line 1:
ORA-01031: insufficient privilegesI can almost, but not quite, see a rationale for the second case if you want to enforce some sort of naming or location standards but the whole thing seems odd to me.
Users cannot create tables, so lets give them a procedure to create tables?
John -
How to make dynamic query using DBMS_SQL variable column names
First of all i will show a working example of what i intend to do with "EXECUTE IMMEDIATE":
(EXECUTE IMMEDIATE has 32654 Bytes limit, which isn't enough for me so i'm exploring other methods such as DBMS_SQL)
-------------------------------------------------CODE-----------------------------------
create or replace PROCEDURE get_dinamic_query_content
(query_sql IN VARCHAR2, --any valid sql query ('SELECT name, age FROM table')
list_fields IN VARCHAR2) --list of the columns name belonging to the query ( arr_list(1):='name'; arr_list(2):='age';
-- FOR k IN 1..arr_list.count LOOP
-- list_fields := list_fields || '||content.'||arr_list(k)||'||'||'''~cs~'''; )
AS
sql_stmt varchar (30000);
BEGIN
sql_stmt :=
'DECLARE
counter NUMBER:=0;
auxcontent VARCHAR2(30000);
CURSOR content_cursor IS '|| query_sql ||';
content content_cursor%rowtype;
Begin
open content_cursor;
loop
fetch content_cursor into content;
exit when content_cursor%notfound;
begin
auxcontent := auxcontent || '||list_fields||';
end;
counter:=counter+1;
end loop;
close content_cursor;
htp.prn(auxcontent);
END;';
EXECUTE IMMEDIATE sql_stmt;
END;
-------------------------------------------------CODE-----------------------------------
I'm attepting to use DBMS_SQL to perform similar instructions.
Is it possible?Hi Pedro
You need to use DBMS_SQL here because you don't know how many columns your query is going to have before runtime. There are functions in DBMS_SQL to get information about the columns in your query - all this does is get the name.
SQL> CREATE OR REPLACE PROCEDURE get_query_cols(query_in IN VARCHAR2) AS
2 cur PLS_INTEGER;
3 numcols NUMBER;
4 col_desc_table dbms_sql.desc_tab;
5 BEGIN
6 cur := dbms_sql.open_cursor;
7 dbms_sql.parse(cur
8 ,query_in
9 ,dbms_sql.native);
10 dbms_sql.describe_columns(cur
11 ,numcols
12 ,col_desc_table);
13 FOR ix IN col_desc_table.FIRST .. col_desc_table.LAST LOOP
14 dbms_output.put_line('Column ' || ix || ' is ' ||
15 col_desc_table(ix).col_name);
16 END LOOP;
17 dbms_sql.close_cursor(cur);
18 END;
19 /
Procedure created.
SQL> exec get_query_cols('SELECT * FROM DUAL');
Column 1 is DUMMY
PL/SQL procedure successfully completed.
SQL> exec get_query_cols('SELECT table_name, num_rows FROM user_tables');
Column 1 is TABLE_NAME
Column 2 is NUM_ROWS
PL/SQL procedure successfully completed.
SQL> exec get_query_cols('SELECT column_name, data_type, low_value, high_value FROM user_tab_cols');
Column 1 is COLUMN_NAME
Column 2 is DATA_TYPE
Column 3 is LOW_VALUE
Column 4 is HIGH_VALUE
PL/SQL procedure successfully completed.I've just written this as a procedure that prints out the column names using dbms_output - I guess you're going to do something different with the result - maybe returning a collection, which you'll then parse through in Apex and print the output on the screen - this is just to illustrate the use of dbms_sql.
best regards
Andrew
UK -
Delcare Cursor using Dynamic SQL using PL/SQL in Oracle 7.3.4
In Oracle 7.3.4, can I declare a cursor at run time using Dynamic SQL. From the sample code in this website, it seems that Oracle 8 support this function. Please help. Thanks a lot.
If I can do this on Oracle 7.3.4, could you give me some sample codes? Thanks.
Regards,
RaymondHi,
Try using the the following code where you can dynamically build the Valid Select stmt. and call that where ever you want.
declare
Type Cur_ref Is Ref Cursor;
C_ref Cur_ref;
V_Str Varchar2(100);
V_Name Varchar2(100);
Begin
V_Str := 'Select Ename from Scott.emp Where empno = 7369';
Open C_Ref for V_Str;
Fetch C_ref Into V_Name;
close C_Ref;
dbms_output.put_line(V_Name);
End;
regards
gaurav
null -
Avoid Hard Parsing for executing dynamic SQL using DUAL table Oracle
I want to know if dynamic sql statements involving DUAL table can be modified to remove HARD PARSING.
We have several SQL statements are stored in configuration table, here is sample example
-- query 1 before replacing index values as stored in config table ---
select count(*) from dual where 'REPLACE_VALUE_OF_INDEX_3' IN ('K')
AND (('REPLACE_VALUE_OF_INDEX_13' IN ('1053','1095','1199') ) OR ('REPLACE_VALUE_OF_INDEX_13' IN ('1200') ))
AND 'REPLACE_VALUE_OF_INDEX_2' IN ('6')
AND 'REPLACE_VALUE_OF_INDEX_15' IN ('870001305')
-- query 1 after replacing index values--
select count(*) from dual where 'REPLACE_VALUE_OF_INDEX_10' IN ('K')
AND (('1030' IN ('1053','1095','1199') ) OR ('1030' IN ('1200') ))
AND '2' IN ('6')
AND 'X' IN ('870001305')
-- query 2 before replacing index values as stored in config table --
select count(*) from dual where 'REPLACE_VALUE_OF_INDEX_5' IN ('361A','362A')
AND 'REPLACE_VALUE_OF_INDEX_22' BETWEEN '200707' AND '200806'
-- query 2 after replacing index values--
select count(*) from dual where '3MAA' IN ('361A','362A') AND '201304' BETWEEN '200707' AND '200806'If I got it right you have some (maybe lots of) conditions stored in a table (be patient - it's my interpretation)
create table eb_conditions as
select 1 rid,q'{:5 IN ('361A','362A') AND :3 BETWEEN '200707' AND '200806'}' cndtn from dual union all
select 2,q'{:2 IN ('361A','362A') AND :3 BETWEEN '200707' AND '200806'}' from dual union all
select 3,q'{:1 IN ('K') AND ((:2 IN ('1053','1095','1199') ) OR (:4 IN ('1200') )) AND :3 IN ('6') AND :5 IN ('870001305')}' from dual
RID
CNDTN
1
:5 IN ('361A','362A') AND :3 BETWEEN '200707' AND '200806'
2
:2 IN ('361A','362A') AND :3 BETWEEN '200707' AND '200806'
3
:1 IN ('K') AND ((:2 IN ('1053','1095','1199') ) OR (:4 IN ('1200') )) AND :3 IN ('6') AND :5 IN ('870001305')
and you have to check the conditions using values stored in an array
I used a table instead: the vl at rid = 1 representing the value of bind variable :1 in eb_conditions table and so on ...
create table eb_array as
select 1 rid,'K' vl from dual union all
select 2,'1199' from dual union all
select 3,'200803' from dual union all
select 4,'1000' from dual union all
select 5,'870001305' from dual
RID
VL
1
K
2
1199
3
200803
4
1000
5
870001305
You want to check the conditions using select count(*) from dual where <condition with binds substituted fron the array>
Judging from the title Hard Parsing represents the major problem and you cannot avoid it since every condition to be verified is different from every other condition.
I think your best bet is not to evaluate conditions row by row - context shift cannot be avoided and there might be more than one for each iteration.
So try to do it in a single step:
declare
w_cndtn varchar2(4000);
w_clob clob;
w_cursor sys_refcursor;
one number;
two number;
begin
dbms_lob.createtemporary(w_clob,false);
for rw in (select rid,
max(cndtn) cndtn,
listagg(val,',') within group (order by rn)||',' usng
from (select c.rid,c.cndtn,c.rn,c.bind,
replace(rtrim(c.bind),':'||to_char(v.rid),''''||v.vl||'''') val
from (select rid,
cndtn,
regexp_substr(cndtn,':\d+ ',1,level) bind,
level rn
from eb_conditions
connect by level <= regexp_count(cndtn,':')
and prior rid = rid
and prior sys_guid() is not null
) c,
eb_array v
where instr(c.bind,':'||v.rid||' ') > 0
group by rid
loop
w_cndtn := rw.cndtn;
while instr(w_cndtn,':') > 0
loop
w_cndtn := replace(w_cndtn,trim(regexp_substr(w_cndtn,':\d+ ',1,1)),substr(rw.usng,1,instr(rw.usng,',') - 1));
rw.usng := substr(rw.usng,instr(rw.usng,',') + 1);
end loop;
w_cndtn := 'select '||to_char(rw.rid)||' cndtn_id,count(*) from dual where '||w_cndtn||' union all ';
w_clob := w_clob ||' '||w_cndtn;
end loop;
w_clob := substr(w_clob,1,instr(w_clob,'union all',-1,1) - 1);
open w_cursor for w_clob;
loop
fetch w_cursor into one,two;
exit when w_cursor%notfound;
dbms_output.put_line(to_char(one)||':'||to_char(two));
end loop;
dbms_lob.freetemporary(w_clob);
end;
1:0
2:0
3:0
Statement processed.
Regards
Etbin -
Dynamic Sql Using Execute Immediate
I am trying to construct a dynamic statement that takes in a supplied column name (COL_NAME), then do an Update on the column based on a supplied username. The table myTable has 4 columns and I would like to update a column thats supplied each time.
NOT DYNAMIC
PROCEDURE UpdateUser(aauser myTable.USERNAME%Type,COL_NAME varchar2, val varchar2) AS
BEGIN
Update myTable
set userid = '002'
where username= aauser;
[b]DYNAMIC
PROCEDURE UpdateUser(aauser myTable.USERNAME%Type,COL_NAME varchar2, val varchar2) AS
BEGIN
EXECUTE IMMEDIATE 'UPDATE myTable
Set ' ||COL_NAME||' = val
where myTable.username = aauser';
END UpdateUser;
However I get the following error when I execute this statement. Please help me.
Connecting to the database Local.
ORA-00904: "aaUser": invalid identifier
ORA-06512: at "ANOLD.PUB", line 1433
ORA-06512: at line 10
Process exited.
Disconnecting from the database Local.TEST@XE SQL> desc mytable
Name Null? Type
USERNAME VARCHAR2(30)
USERID VARCHAR2(30)
COL3 NUMBER
COL4 NUMBER
TEST@XE SQL> insert into mytable values('TEST','001',1,2);
1 row created.
TEST@XE SQL> create or replace PROCEDURE UpdateUser(aauser myTable.USERNAME%Type,COL_NAME varchar2, val varchar2) AS
2 BEGIN
3 EXECUTE IMMEDIATE 'UPDATE myTable
4 Set ' ||COL_NAME||' = ' || chr(39) ||val|| chr(39) ||
5 ' where myTable.username = ' || chr(39) ||aauser|| chr(39);
6 END UpdateUser;
TEST@XE SQL> /
Procedure created.
TEST@XE SQL> exec UpdateUser('TEST','userid','002');
PL/SQL procedure successfully completed.
TEST@XE SQL> select * from mytable;
USERNAME USERID COL3 COL4
TEST 002 1 2
TEST@XE SQL> exec UpdateUser('TEST','col3',111);
PL/SQL procedure successfully completed.
TEST@XE SQL> select * from mytable;
USERNAME USERID COL3 COL4
TEST 002 111 2
TEST@XE SQL> -
How to reduce Parse time in dynamic SQL
I'm using for a part of my code dynamic SQL with DBMS_SQL Package, this dynamic SQL code is located in a loop with say 1000 repeatations, if we trace the code we see that this sql statement is parsed 1000 times and this causes
a serios performance issue. If i convert this part of code into static PLSQL code , the statement is parsed only one time as expected. i would like
to know how i can resolve this problem in the dynamic SQL code.
Why in case of static SQL, despite it is inside the loop, it is parsed
only one time by ORACLE and in case of dynamic SQL as many as the upper limit of counter.
Why the ORACLE has different behaviour to parse them? Is there any way or trick
to force ORACLE to parse it only one time like static SQL?despite the open cursor is also inside the loop but oracle parse it only one time.That is because PL/SQL is caching your cursor and resuing it. With DBMS_SQL you are opening a new cursor area in the loop for each iteration (DBMS_SQL.OPEN_CURSOR).
what you need to do is open/parse once and bind the value each time through the loop:
DECLARE
expr VARCHAR2(1000);
check_cur PLS_INTEGER;
nDummy PLS_INTEGER;
nFetched PLS_INTEGER;
BEGIN
-- Open Cursor
check_cur := dbms_sql.open_cursor;
expr := 'select 1 from dual where ' || ':bindvar1 ' || '=' ||
' ''bindvar1'' ';
-- Parse Cursor
dbms_sql.parse(check_cur,
expr,
1);
FOR counter IN 1 .. 1000
LOOP
-- Define Column
DBMS_SQL.define_column(check_cur,
1,
1);
-- Do Binding
dbms_sql.bind_variable(check_cur,
':bindvar1',
'bindname1');
-- Execute Cursor
nDummy := DBMS_SQL.EXECUTE(check_cur);
-- Fetch Rows
nFetched := DBMS_SQL.fetch_rows(check_cur);
END LOOP;
-- Close Cursor
dbms_sql.close_cursor(check_cur);
END;
call count cpu elapsed disk query current rows
Parse 1 0.21 0.23 0 0 0 0
Execute 1000 0.11 0.10 0 0 0 0
Fetch 1000 0.03 0.01 0 0 0 0
total 2001 0.35 0.35 0 0 0 0 -
Execute Dynamic SQL statement using procedure builder
i want to execute a dynamic SQL statment using procedure builder not using forms
because my statement depending on a variable table name
i know that i can do that from forms using
FORMS_DDL('SQL_STAT');
but i wanna to use the procedure builder
which function i should use and how?
please explain in example if you don't mind.
thanksHi,
You can very well use DBMS_SQL Package supplied by Oracle for doing this.
Search for DBMS_SQL in OTN. You will get all info regarding this.
Regards.
<BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by itslul:
i want to execute a dynamic SQL statment using procedure builder not using forms
because my statement depending on a variable table name
i know that i can do that from forms using
FORMS_DDL('SQL_STAT');
but i wanna to use the procedure builder
which function i should use and how?
please explain in example if you don't mind.
thanks<HR></BLOCKQUOTE>
null -
Doubt & Error Using Dynamic SQL
Hello,
According to oracle documentation for Dynamic SQL using ' Method 2 ' ... which says ...
Method 2
This method lets your program accept or build a dynamic SQL statement, then process it using the PREPARE and EXECUTE commands. The SQL statement must not be a query. The number of placeholders for input host variables and the datatypes of the input host variables must be known at precompile time. For example, the following host strings fall into this category:
'INSERT INTO EMP (ENAME, JOB) VALUES (:emp_name, :job_title)'
'DELETE FROM EMP WHERE EMPNO = :emp_number'
Now for trying this method i created a procedure .. named .. 'aj_proc_1'
CREATE OR REPLACE PROCEDURE aj_proc_1(p_id IN NUMBER)
IS
BEGIN
EXECUTE IMMEDIATE 'delete from aj_test_1 where id = :p_id';
END aj_proc_1;
And the table which m using in this procedure is ...
SQL> select * from aj_test_1;
ID NAME
1 aijaz
2 melwin
3 aasim
4 satish
5 ashok
So now whn m calling this Procedure & wanted to delete the record with id '2' ... m getting an Error...the way m executing this procedure is ...
SQL> execute aj_proc_1(2);
BEGIN aj_proc_1(2); END;
ERROR at line 1:
ORA-01008: not all variables bound
ORA-06512: at "FA.AJ_PROC_1", line 4
ORA-06512: at line 1
Please Help me .. As i have no idea ..wats goin wrong over here...Now whats Wrong with this 1 ....
CREATE OR REPLACE PROCEDURE aj_proc_1(p_id IN NUMBER)
IS
val_name varchar2(34);
BEGIN
EXECUTE IMMEDIATE 'select name into '||val_name||' from aj_test_1 where id = :p_id'
USING p_id ;
dbms_output.put_line(val_name);
END aj_proc_1;
SQL> exec aj_proc_1(2);
BEGIN aj_proc_1(2); END;
ERROR at line 1:
ORA-00936: missing expression
ORA-06512: at "FA.AJ_PROC_1", line 5
ORA-06512: at line 1
----------------------------------------------------------------------------------- -
Problem using DBMS_SQL in a form
hi,
I am trying to write a procedure which get an input string containing a SQL statement (a SELECT), executes it, fetches the rows and writes them into a Excel sheet. I found this article http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sql.htm describing how to use DBMS_SQL package. My goal is to parse my query and store result in an array (using DEFINE_ARRAY).
I put theese two lines
(declare c number;)
c := dbms_sql.open_cursor;
dbms_sql.parse(c,p_query,dbms_sql.native); (p_query is my input string containing SQL)
But when I compile my program unit I get an error looking like that: "implementation restriction: DBMS_SQL.NATIVE: unable to access a remote package variable or cursor".
Where is the error? should I set something to access the package, or is it not possible to use it inside a form?W1zard is correct. Switch to Exec_SQL. Oracle does not support Forms using DBMS_SQL.
Now... please explain why you are not using a dynamic record group. It is SOOO much easier!
And if you want to look at some code using both methods, Exec_SQL and dynamic record group, you can download my "Quick Access" dynamic utility form, here: Oracle Forms Utilities -
Error in DBMS_SQL Package (Very Urgent)
Hi Fellows,
I have created a procedure with two parameters (eg. disabletrigger(owner, tablename). I have used DBMS_SQL Package. The procedure has compiled successfully but when I run this procedure it returns this message.
ERROR at line 1:
ORA-00911: invalid character
ORA-06512: at "SYS.DBMS_SYS_SQL", line 782
ORA-06512: at "SYS.DBMS_SQL", line 32
ORA-06512: at "HABEEB.DIS", line 32
ORA-06512: at line 1
can any body help me in this ...
Thanks in advance
MustafaHi Mustafa
Since DBMS_SQL package parses the DML or DDL statement that you issue at runtime, your code may have compiled successfully, but at runtime when your SQL/DML statement that you had embedded as a string in DBMS_SQL may be wrong or has syntax problems which gets resoved at runtime.
So check your SQL statement in DBMS_SQL package again.
NOTE: DO NOT GIVE A ";" AT THE END OF YOUR DML/DDL statement in DBMS_SQL package.
THANKS
MOHAMMED R.QURASHI
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Mustafa Butt ([email protected]):
Hi Fellows,
I have created a procedure with two parameters (eg. disabletrigger(owner, tablename). I have used DBMS_SQL Package. The procedure has compiled successfully but when I run this procedure it returns this message.
ERROR at line 1:
ORA-00911: invalid character
ORA-06512: at "SYS.DBMS_SYS_SQL", line 782
ORA-06512: at "SYS.DBMS_SQL", line 32
ORA-06512: at "HABEEB.DIS", line 32
ORA-06512: at line 1
can any body help me in this ...
Thanks in advance
Mustafa<HR></BLOCKQUOTE>
null -
How to obtain IR report dynamic SQL in Apex 4.0
Hello,
I have 2 regions on the same page
Interactive Report –
Chart (Flash Chart) – This is a sub region of the above
Now the requirement is when user applies a filter to the interactive report I would like to apply the same filter criteria to the flash chart so that data representation in flash chart matches with the IR report content. I am fairly new to the Apex, apologies if used any apex terminology in correctly
Appreciate if you can point me in the right direction
Thank you
-RajHello , I did some research how to achieve this , one way is to get the IR report dynamic sql using APEX_IR.GET_REPORT package and apply the same sql for the chart so that the chart representation will match with the IR report data, But the challenge is as i am using the APEX 4.0.0.00.46 version, the APEX_IR package is not available in that version , Any other way we can achieve this in Apex 4.0??
Thanks
-raj -
Dynamic sql versus static sql in a loop
I have a loop that loops around 10 million times.Inside the loop I have a insert statement . To build this insert statement wondering if a) I should use Dynamic sql using bind variables or b) static sql.
I am aware that static sql is always faster than dynamic sql(using bind variable)....but wanted to get some opinion
Please help.mmm some solution could be to write the same insert with decode/case statement and put there the conditions that you want.
maybe something like this:
SQL> ed
Wrote file afiedt.buf
1 begin
2 for i in 1..10 loop
3 insert into t1 (col1,col2,col3)
4 values (i,
5 decode (mod (i,2),0,i,null),
6 decode (mod (i,3),0,i,null));
7 end loop;
8* end;
SQL> /
PL/SQL procedure successfully completed.
SQL> select * from t1;
COL1 COL2 COL3
1
2 2
3 3
4 4
5
6 6 6
7
8 8
9 9
10 10
10 rows selected.
SQL> truncate table t1;
Table truncated.
SQL> insert into t1 (col1,col2,col3)
2 select rownum,
3 decode (mod (rownum,2),0,rownum,null),
4 decode (mod (rownum,3),0,rownum,null)
5 from dual
6 connect by rownum <=10;
10 rows created.
SQL> select * from t1;
COL1 COL2 COL3
1
2 2
3 3
4 4
5
6 6 6
7
8 8
9 9
10 10
10 rows selected.forgot that you are not using anymore the loop :)
Message was edited by:
Delfino Nunez -
ORA-1481 using DBMS_SQL.FETCH_ROWS
Hi all.
I have a package, called from forms 6, that in one of its functions uses DBMS_SQL package.
It has a bunch of DBMS_SQL.DEFINE_COLUMN ....
but fails with ora-1481 in this line (after all the DEFINE_COLUMN)
<quote>
traza := '07 ';
if (DBMS_SQL.FETCH_ROWS(v_cursor)= 0 ) then
traza := '71';
exit;
end if;
traza := '08';
.... more code
<end quote>
The procedure shows, going to the WHEN OTHERS exception, the error 1481 with '07' as traza (trace). Not '71', not '08'.
Someone can help? Thank you all in advance.It could be caused because in the previous DBS_SQL.DEFINE_COLUMN some of the variables used like
- "DBMS_SQL.DEFINE_COLUMN (v_cursor, 71, v_cdclave_sust ,1000 );" -> that (w_cdclave_sust) is a varchar2
- or "DBMS_SQL.DEFINE_COLUMN (v_cursor, 71, v_cdclave_sust_2 );" -> w_cdclave_sust_2 is a number)
are number?
Thanks -
An issue with Dynamic SQL within Package using REF CURSOR
Hi there,
In the following package first two procedures works file but since I have added the third one ( GET_CONTRACT_BY_DYN_SQL) it does not work for me. When I try to compile and save it gives below error.
"Error(6,15): PLS-00323: subprogram or cursor 'GET_CONTRACT_BY_DYN_SQL' is declared in a package specification and must be defined in the package body"
Can you please help?
Package Header
create or replace
PACKAGE CONTRACTS_PKG AS
TYPE T_CURSOR IS REF CURSOR;
PROCEDURE GET_CONRACTS (IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_ID (I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRATID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR);
END CONTRACTS_PKG;
Package Body
create or replace
PACKAGE BODY CONTRACTS_PKG AS
-- Get All Contracts
PROCEDURE GET_CONRACTS(IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS;
IO_CURSOR := V_CURSOR;
END GET_CONRACTS;
-- Get Contract By ID
PROCEDURE GET_CONTRACT_BY_ID(I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS WHERE contract_id = I_CONTRACTID;
IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_ID;
-- Get Contract Using Dynamic SQL
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
V_SQL VARCHAR2(200);
BEGIN
V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS WHERE contract_id = ' || P_CONTRACTID ;
--OPEN V_CURSOR FOR
--EXECUTE IMMEDIATE V_SQL INTO V_CURSOR;
OPEN V_CURSOR FOR V_SQL;
EXECUTE IMMEDIATE V_SQL;
--IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_DYN_SQL;
END CONTRACTS_PKG;
Thanks in advance.
HiteshThanks guys. Finally I have tweaked as per your suggestions and it's working for all 3 cases (stored procedures).
Oracle
======
Package Header
create or replace
PACKAGE CONTRACTS_PKG AS
TYPE T_CURSOR IS REF CURSOR;
PROCEDURE GET_CONRACTS (IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_ID (I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR);
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR);
END CONTRACTS_PKG;
Package Body
create or replace
PACKAGE BODY CONTRACTS_PKG AS
-- Get All Contracts
PROCEDURE GET_CONRACTS(IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS;
IO_CURSOR := V_CURSOR;
END GET_CONRACTS;
-- Get Contract By ID
PROCEDURE GET_CONTRACT_BY_ID(I_CONTRACTID IN NUMBER, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
BEGIN
OPEN V_CURSOR FOR
SELECT * FROM CONTRACTS WHERE contract_id = I_CONTRACTID;
IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_ID;
-- Get Contract Using Dynamic SQL
PROCEDURE GET_CONTRACT_BY_DYN_SQL(P_CONTRACTID IN NUMBER, P_COLS IN VARCHAR2, IO_CURSOR IN OUT T_CURSOR)
IS
V_CURSOR T_CURSOR;
V_SQL VARCHAR2(200);
BEGIN
IF p_contractid > 0 THEN
V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS WHERE contract_id = ' || P_CONTRACTID ;
ELSE
V_SQL := 'SELECT '|| P_COLS || ' FROM CONTRACTS';
END IF;
OPEN V_CURSOR FOR V_SQL;
IO_CURSOR := V_CURSOR;
END GET_CONTRACT_BY_DYN_SQL;
END CONTRACTS_PKG;
ColdFusion (calling app code)
=====================
<cfstoredproc procedure="CONTRACTS_PKG.GET_CONTRACT_BY_ID" datasource="#REQUEST.dsn#">
<cfprocparam cfsqltype="CF_SQL_INTEGER" type="in" value="1" variable="I_CONTRACTID">
<cfprocresult name="qData" resultset="1">
</cfstoredproc>
<br>Single Contract:
<cfdump var="#qData#" label="Single Contract">
<cfstoredproc procedure="CONTRACTS_PKG.GET_CONRACTS" datasource="#REQUEST.dsn#">
<cfprocresult name="qDataAll" resultset="1">
</cfstoredproc>
<br>All Contracts:
<cfdump var="#qDataAll#" label="All Contracts">
<cfstoredproc procedure="CONTRACTS_PKG.GET_CONTRACT_BY_DYN_SQL" datasource="#REQUEST.dsn#">
<cfprocparam cfsqltype="CF_SQL_INTEGER" type="in" value="1" variable="P_CONTRACTID">
<cfprocparam cfsqltype="CF_SQL_VARCHAR" type="in" value="contract_number,contract_title,created_date" variable="P_COLS">
<cfprocresult name="qDataDynSQL" resultset="1">
</cfstoredproc>
<br>Dynamic SQL Query:
<cfdump var="#qDataDynSQL#" label="Dynamic SQL Query">
Thanks,
Hitesh Patel
Maybe you are looking for
-
How to create Dynamic Window in Smartforms
Hi all, Could you please help me out on how to create Dynamic Window in smartforms excluding Main Window. Thanks in Advance. Vinay.
-
What's wrong with my AIR or Lion - won't wake up properly?
If I do a 'scracth and sniff' type of scratch with my trackpad, I can find the log-in box and log in. Otherwise I am stuck. Any suggestions what might be causing this?
-
Problems with sender mail adapter
Hi XI Gurus We have gone through a lot of blogs and searched a lot on the XI forum on how to configure the sender mail adapter with attachments but we still can't get it working at our site. Here are the issues - 1. When we define our data type in th
-
Error While Doing FCC on Sender Side
Hi All, Iam reffering this Blog and doing File to File (FCC at Sender Side) Content Conversion ( The Key Field Problem ) I have the Same Structure for both Source & Target. this is my structure http://img386.imageshack.us/my.php?image=sourcestructym4
-
Logiix Bluepiston not connecting via bluetooth to Macbook Pro
Hello I recently purchased a macbook pro retina in january 2015. I also have a magic mouse which connects fine via bluetooth to the mac. I also have a blue piston speaker which just doesnt seem to connect. it doesnt appear at all under bluetooth pref