Open cursor for and bind variables
Hello all,
how can I assign values to a bind variable before opening a cursor?
example code:
DECLARE
TYPE ref_cur_t IS REF CURSOR;
l_ref_cur ref_cur_t;
l_query VARCHAR2 (100)
:= 'select * from table t1 where ndx= :var_index' ;
BEGIN
-- assign a value to :var_index
OPEN l_ref_cur FOR l_query;
END;Thanks!
Something like this ->
scott@ORCL>
scott@ORCL>DECLARE
2 l_ref_cur sys_refcursor;
3 l_query VARCHAR2 (100) := 'select * from emp where empno = :var_index';
4 l_empno number(4);
5 BEGIN
6 l_empno := &emno;
7 -- assign a value to :var_index
8 OPEN l_ref_cur FOR l_query using l_empno;
9 END;
10 /
Enter value for emno: 7698
old 6: l_empno := &emno;
new 6: l_empno := 7698;
PL/SQL procedure successfully completed.
Elapsed: 00:00:19.78
scott@ORCL>Regards.
Satyaki De.
Similar Messages
-
This is reports 11g
I've got a clob column. Reports seems to recognize its type, but if I try to reference it in a format trigger, I get this error at compile time:
"No pl/sql translation for the blind type given for this bind variable"Actually, Reports is in something better than Forms.
Neither Forms nor Reports do not have "complete" SQL engine (both have only "complete" PL/SQL engine), but have their own SQL parser, which does not understand SQL commands after the database 8.0.
But, in Reports Data Model - SQL Query Statement, we can write "modern" SQL statement (> database 8.0), because Reports sent it directly to the database, without using their own SQL parser.
For example, in Reports Data Model - SQL Query Statement, we can write this (scalar subquery expressions, in bold):
select empno,
ename,
deptno,
(select dname from dept where deptno = emp.deptno) dname
from emp
order by empno;
although scalar subquery expressions was introduced in the database 9.0.1, and in databases 8.0 and 8.1 we should write someting like this:
select emp.empno,
emp.ename,
emp.deptno,
dept.dname
from emp,
dept
where dept.deptno = emp.deptno
order by empno;
Regards,
Zlatko -
PreparedStatement and bind variable
We are experiencing some werid performance break downs where database server looks healthy and our java applications are down to their knees.
I was wondering if someone could help me clarify the comparison between PreparedStatement and bind variable. When I execute a PreparedStatement in java through the JDBC thin driver, would the database consider it a dynamic SQL or is it a SQL using bind variable? If this same statement is executed 100000 times, is it parsed 100000 times? We are using JDK131. How does it work?
Is there any memory leak in PreparedStatement implementation in JDBC thin driver? Is there any known symptom to this problem? What is the recommended solution?
Thank you very much!If PreparedStatement is parsed and cached, why is there setting to set implicit statement caching and explicit statement caching? Our DBA insists that it is parsed every single time. How would I find out for sure?
The SQLs have not been changed. This sudden performance degradation started when a new client went live and we experienced higher than usual volumn. We are connecting using JDBC thin client from weblogic server to Oracle 8.1.7. It's been happening everyday since the client went live and the only way to get the performance back is to shutdown and restart the database server.
I tried to search JDBC related issues. The only complain that I've found so far is that there may be some potential memory leak for a PreparedStatement. However, I have not found anything from Oracle's website that concurs to that.
What is my best bet? -
Open cursor for ...using...
Hi all
1 general question- can someone explain me how 'using keyword in 'open cursor for ...' statement works.
Does it replace where clause and how?
open cur_xx for qry_xxx using text_xxx
where 'text_xxx' is going to be my codition in select statement
Tahnks everyonehttp://oraclesvca2.oracle.com/docs/cd/B10501_01/appdev.920/a96624/13_elems35.htm
-
How to fix different execution plan for different bind variable values?
Please find the below query. The execution plan is fine. The problem That I am facing is in some cases for different bind variable values execution plan gets changed and degrades performance. I have used 6 tables here and all of the tables have histogram on all columns. Database version is Oracle 10g and the value of method_opt is 'For all columns size auto'
SELECT l.LineNumber INTO :b0
FROM Lines l ,LineVersions lv ,Statuses s
WHERE (((((((((((l.serviceContractId=:b1 AND l.LineId<>:b2)
AND lv.LineId=l.LineId) AND lv.StatusId=s.StatusId)
AND s.Code IN ('EPR','ERE','EEP','ERP','PRP','PRD','AAC'))
AND NOT (s.CODE='AAC' AND lv.activeto<TO_DATE(:b3,:b4)))
AND lv.EquipmentDetailId=:b5) AND lv.RouteDetailId=:b6)
AND (lv.cargoDetailId=:b7 OR lv.cargoDetailId IN
(SELECT i_cd1.cargoDetailId
FROM CargoDetails i_cd1 ,CargoDetails i_cd2 ,CargoCommodities i_cc1 ,
CargoCommodities i_cc2 WHERE
((((((i_cd2.cargoDetailId=:b7 AND i_cd1.cargoDetailId<>:b7)
AND i_cd1.ServiceContractId=:b1) AND i_cd1.cargoTypeId=i_cd2.cargoTypeId)
AND i_cc1.cargoDetailId=i_cd1.cargoDetailId)
AND i_cc2.cargoDetailId=i_cd2.cargoDetailId)
AND i_cc1.commodityId=i_cc2.commodityId))))
AND ((lv.customerGroupId IS NULL AND :b11=0) OR lv.customerGroupId IN
(SELECT cgm1.customerGroupId
FROM CustomerGroupMembers cgm1 ,CustomerGroupMembers cgm2 ,CustomerGroups cg1
WHERE (((cgm2.customerGroupId=:b11 AND cgm1.customerNoId=cgm2.customerNoId)
AND cg1.CustomerGroupId=cgm1.CustomerGroupId)
AND cg1.ServiceContractId=l.ServiceContractId)))) AND lv.linetype='C')
AND ROWNUM=1)
After searching in several blogs I have found the below solutions. Please see it and let me know it is correct or not
Solution 1:-Get rid of histogram that does nothing but messes up execution plan by giving below command
exec dbms_stats.gather_table_stats(owner, tablename, method_opt => 'for all columns size 1', cascade => true);
As 6 tables are there I need to execute above command 6 times.
Solution 2:- Use stored outline. Not sure how to get the best execution plan.
I am looking for answers ASAP. Thanks in advanceAs you have probably read, bind variables and histograms do not mix well.
Histograms suggest that you have skew in your data such that different values should get different plans
Bind variables exist so that SQL with different supplied values can be shared.
Mix the two together and at parse time with bind variable peeking you get plans for specific values shared for all values.
The solutions you have mentioned are the common approaches, together with a third - use literals not binds if you've got data skew (i.e. your histograms are justified) and don't want shared SQL.
I would have thought that getting rid of some of these histograms may be the right approach if you're none of your application SQL is using literals to benefit from them.
Can you confirm your version of Oracle.
Further reading:
http://jonathanlewis.wordpress.com/2009/05/06/philosophy-1/
http://structureddata.org/2008/03/26/choosing-an-optimal-stats-gathering-strategy/
http://richardfoote.wordpress.com/2008/01/04/dbms_stats-method_opt-default-behaviour-changed-in-10g-be-careful/ -
Invalid Identifier for a bind variable
I am running a sql query and am using bind variables for dates. Running the querry and after putting values for the bind variable I get a message invalid identifier. Could any one help me and tell me what I am doing wrong.
1 SELECT D.NAME_LAST||', '||D.NAME_FIRST DEBTOR,
2 F.CDCS_NBR,
3 F.CDCS_SEQ,
4 F.POSTING_DATE,
5 F.PAYMENT_AMOUNT,
6 ( GREATEST ( NVL ( F.ACCRUED_INT_CAP, 0 ), NVL ( F.ACCRUED_INTEREST, 0 ) )
7 + NVL ( F.ACCRUED_FINE_INTEREST, 0 ) )
8 ACCRUED_INT_CAP,
9 DECODE(CLASS,'V', RUN_INTEREST,'R',(RUN_FINE_INTEREST + RUN_INT_CAP)) RUN_INTEREST
10 FROM TA_DEBT_DEBTOR_LIAB_VW D,
11 TA_FINANCE F
12 WHERE F.POSTING_DATE BETWEEN TO_DATE(&A, 'DD-MON-YYYY') AND
13 TO_DATE(&B, 'DD-MON-YYYY')
14 AND
15 F.FINANCE_CODE = 'PMNT'
16 AND F.PAYMENT_AMOUNT <
17 ( GREATEST ( NVL ( F.ACCRUED_INT_CAP, 0 ), NVL ( F.ACCRUED_INTEREST, 0 ) )
18 + NVL ( F.ACCRUED_FINE_INTEREST, 0 ) )
19 AND F.DEBTORID = D.DEBTORID
20 AND F.CDCS_NBR = D.CDCS_NBR
21 AND F.CDCS_SEQ = D.CDCS_SEQ
22* ORDER BY D.NAME_LAST, D.NAME_FIRST
SQL> /
Enter value for a: 10-JAN-2003
old 12: WHERE F.POSTING_DATE BETWEEN TO_DATE(&A, 'DD-MON-YYYY') AND
new 12: WHERE F.POSTING_DATE BETWEEN TO_DATE(10-JAN-2003, 'DD-MON-YYYY') AND
Enter value for b: 10-JUN-2006
old 13: TO_DATE(&B, 'DD-MON-YYYY')
new 13: TO_DATE(10-JUN-2006, 'DD-MON-YYYY')
TO_DATE(10-JUN-2006, 'DD-MON-YYYY')
ERROR at line 13:
ORA-00904: "JUN": invalid identifierReplace this line...
12 WHERE F.POSTING_DATE BETWEEN TO_DATE(&A, 'DD-MON-YYYY') AND
with...
12 WHERE F.POSTING_DATE BETWEEN TO_DATE('&A', 'DD-MON-YYYY') AND -
Lexical and bind variables in RUN_PRODUCT
Hi all,
I have the following RUN_PRODUCT but it gives me "bad bind variable:
DECLARE
pl_id ParamList;
BEGIN
pl_id := Create_Parameter_List('tmpdata');
Add_Parameter(pl_id,'CATEGORY',TEXT_PARAMETER,(:CATEGORY));
Add_Parameter(pl_id, 'PARAMFORM', TEXT_PARAMETER, 'NO');
Add_Parameter(pl_id, 'DESTYPE', TEXT_PARAMETER, 'Screen');
Run_Product(REPORTS, 'C:\Pled', SYNCHRONOUS, RUNTIME, FILESYSTEM, pl_id, NULL);
Destroy_Parameter_List( pl_id );
END;
How can I define both lexical and bind variables in a RUN_PRODUCT. Please assist!Hello Nicky,
The correct way to call Reports from Forms in 6i using the RUN_PRODUCT built-in using bind parameters would be something like the code given below. This example assumes that you have a form module parameter and a report parameter called 'category'.
declare
pl_id paramlist;
begin
pl_id := create_parameter_list('tmpdata');
add_parameter(pl_id, 'category', text_parameter, :parameter.category);
add_parameter(pl_id, 'paramform', text_parameter, 'no');
add_parameter(pl_id, 'destype', text_parameter, 'screen');
run_product(reports, 'c:\test_report.rdf', synchronous, runtime, filesystem, pl_id, null);
destroy_parameter_list( pl_id );
end;
Thanks,
The Oracle Reports Team. -
Open cursor for string and select from partition (cannot bind)
Hi,
i don't manage to use a bind variable for a select ... from ... PARTITION(...).
It doesn't work to use something like
open cur for 'select ... from ... PARTITION(:1) where ...' using 'NDAY_20120301';So i have to create the cursor string with string functions each time i change the partition.
But that means, that the string changes each time.
Doesn't that prevent from re-use in library_cache?
best regards,
Frank>
So i have to create the cursor string with string functions each time i change the partition.
But that means, that the string changes each time.
>
Yes it does.
Doesn't that prevent from re-use in library_cache?
>
Yes it does.
So why do you care? Unless you have large numbers of partitions what difference does it make? Bind variables are useful to keep Oracle from doing hard parses of queries that are basically the same but use different filter values. Such as an INSERT statement that uses different values FOR EACH ROW rather
You are just constructing the main (non-filter) part of the query one time and need a single value for the entire query regardless of how many rows - that isn't really a use case for bind variables and isn't going to provide any real benefit.
So the real question is why do you even care about something that wouldn't provide any benefit to you even if you could do it?
Looks like you just want to 'roll your own' parallel processing rather that use, and pay for, Oracle's parallel functionality.
If each partition uses its own tablespace you could filter on the FILE Id of the ROWIDs since the file number will be different for each tablespace and datafile.
1. Determine the list of file numbers for each partitions tablespace.
2. Use a WHERE DBMS_ROWID.ROWID_RELATIVE_FNO (ROWID) = :n filter (or use IN (:n1, :n2))to filter rows based on file number(s) for the partition you want
See DBMS_ROWID.ROWID_RELATIVE_FNO in the PL/SQL Packages and Types doc
http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_rowid.htm#i1004259 -
Open a CURSOR for a CLOB variable in 9i
Hi Friends,
I have a procedure which has a CLOB variable,and a sys_refcursor as inputs.
procedure proc1 ( p_sql clob, cur1 sys_refcursor);
I need to open this cur1 for p_sql clob.
OPEN CUR1 FOR P_SQL;
But it gives an error. I went through webs and found that it is not possible to do it in 9i. Do u know any alternate ? How can I do it ?vishwa wrote:
Hi Friends,
I have a procedure which has a CLOB variable,and a sys_refcursor as inputs.
procedure proc1 ( p_sql clob, cur1 sys_refcursor);
I need to open this cur1 for p_sql clob.
OPEN CUR1 FOR P_SQL;
But it gives an error. I went through webs and found that it is not possible to do it in 9i. Do u know any alternate ? How can I do it ?Consider upgrading a an Oracle version that has been supported during the current Century.
If you installed a newer version DB, it could be used to access the exist V9 DB;
without any changes to the V9 DB itself. -
Why 'open cursor for variable' dosnt work?
Hi....
I have this package:
create or replace package body filter_frmtrialjoinbatch_pkg is
procedure join_batch(cdescription varchar2,
cdepartment char,
cemployee_function char,
cemployee char,
c_cursor out c_cursor_ref)
is
vSqlText varchar2(4000);
text varchar2(500);
begin
vSqlText := '';
vSqltext := 'Select Distinct a.batch_id ' ||
'from trl_batch a, ' ||
'trl_employee_batch b, '||
'trl_employee c where ';
if (cdescription is not null) then
vSqlText := vSqlText || ' upper(a.description) like '||''''|| '%'|| cdescription ||'%'||'''';
end if;
if (cdepartment is not null) then
vSqlText := vSqlText || ' upper(a.department_id) like ' ||''''|| '%'|| cdepartment ||'%'||'''';
end if;
if (cemployee_function is not null) then
vSqlText := vSqlText || ' upper(b.function) like ' ||''''|| '%'|| cemployee_function ||'%'||'''';
end if;
if (cemployee is not null) then
vSqlText := vSqlText || ' upper(c.employee_id) like ' ||''''|| '%'|| cemployee ||'%'||'''';
end if;
vSqlText := vSqlText || ' and a.batch_id = b.batch_id ';
vSqlText := vSqlText || ' and b.employee_id = c.employee_id ';
vSqlText := vSqlText || ';';
open c_cursor for vSqlText;
end join_batch;
end filter_frmtrialjoinbatch_pkg;
and the line : open c_cursor for vSqlText is returning me an error message!!!
why?? i verified the variable vSqlText and it is ok?
can u help me?
thank you...
Alessandro FalanqueHi,
You are making mistake in the following statement:-
vSqlText := vSqlText || ';';
Here you are appending a semicolon to your sql statement. It is not necessary. Just remove this and I feel it should work properly.
Regards,
Sunil Mohite. -
Help setting Parameters using JDBC and Bind Variables for Oracle List
I fully understand the concept of using Bind Variables when using JDBC to avoid hard parses everytime my SQL statement is executed when only a certain value changes. For example, perhaps I have the following statement:
PreparedStatement ps = con.prepareStatement("select salary from employees where employee_id = ?");
I would then set the value of the question mark (the first and in this case only parameter) using:
ps.getStmt().setString(1,empId1);
That is assuming I have the variable empId1 populated with what I want. Anyway, my question has to do with Oracle lists. In other words, if I am just executing the statement against the db, it might look like:
select salary from employees where employee_id in ('123','456','789');
I still want to use bind variables and I can do it in JDBC with something like:
select salary from employees where employee_id in ('123','456','789');
ps.getStmt().setString(1,empId1);
ps.getStmt().setString(2,empId2);
ps.getStmt().setString(3,empId3);
BUT, what if I just want to construct my list of ids upfront as a string and do something like:
select salary from employees where employee_id in (?)
ps.getStmt().setString(1,listOfEmpIds);where listOfEmpIds would look something like '123','456','789'.
That's what I want to do but it doesn't work. It would be treating the list as a single parameter as opposed to lots of individual parameters. Can someone please tell me the syntax for this if it is possible? I have tried where XX in (?) and where XX in ? (and the string I substitute has the parenthesis in it), but neither work.
Thank you for your help.I always build the list myself.
You could, however, pass the list as a varchar to a stored proc and then have the stored proc parse (or dynamically execute) using it.
The second method might even be faster although I would suspect that is only going to be the case if the list is very large. Or it might not. -
Dynamic sql and bind variables
Hi,
I have a stored procedure which filters a table on 5 five columns. The filters come from the input parameters,
and these 5 parameters can come in any combination, I mean some of them may be null and some of them may not be null.
So I constructed the where filter of the query with IF blocks like the following:
dynamic_query := 'select * from TESTTABLE where 1= 1';
IF (P1 is not null) THEN
dynamic_query := dynamic_query || ' AND column1 = :1';
END IF;
IF (P2 is not null) THEN
dynamic_query := dynamic_query || ' AND column2 = :2';
END IF;
IF (P3 is not null) THEN
dynamic_query := dynamic_query || ' AND column3 = :3';
END IF;
IF (P4 is not null) THEN
dynamic_query := dynamic_query || ' AND column4 = :4';
END IF;
IF (P5 is not null) THEN
dynamic_query := dynamic_query || ' AND column5 = :5';
END IF;
OPEN CUR_OUT FOR dynamic_query USING P1, P2, P3, P4, P5;
The problem is how can I construct the USING and bind parameters, I cannot use "USING P1, P2, P3, P4, P5" because some of bind variables
may not be in dynamic query if the input parameters are null. Is there a way to overcome this problem without writing all the 2 ^ 5 combinations?
Any help is greatly appreciated.here it is in the Tomer Cohen way:
IF (P1 is not null) THEN
dynamic_query := dynamic_query || ' AND column1 = :1';
ELSE
dynamic_query := dynamic_query || ' AND :1 IS NULL';
END IF;
IF (P2 is not null) THEN
dynamic_query := dynamic_query || ' AND column2 = :2';
ELSE
dynamic_query := dynamic_query || ' AND :2 IS NULL';
END IF;
IF (P3 is not null) THEN
dynamic_query := dynamic_query || ' AND column3 = :3';
ELSE
dynamic_query := dynamic_query || ' AND :3 IS NULL';
END IF;
IF (P4 is not null) THEN
dynamic_query := dynamic_query || ' AND column4 = :4';
ELSE
dynamic_query := dynamic_query || ' AND :4 IS NULL';
END IF;
IF (P5 is not null) THEN
dynamic_query := dynamic_query || ' AND column5 = :5';
ELSE
dynamic_query := dynamic_query || ' AND -1 = :5';
END IF;
OPEN CUR_OUT FOR dynamic_query USING P1, P2, P3, P4, P5;Amiel Davis -
Open Cursor for insert actually inserts
Have been using code similar to this to prepare an SQL insert
statement before entering a loop to perform the inserts. Find
that the open actually performs an insert when it is executed,
so the table always has an extra row of garbage.
Is there some way to stop this behaviour? ProC compiler option
or open parameter. Currently I am doing a ROLLBACK after the
open to clear it.
Using the prepare because the table name is not known at compile
time.
EXEC SQL AT DB_1 PREPARE insert_cust FROM :szSqlInsertCustomer;
EXEC SQL AT DB_1 DECLARE insert_cust_cursor CURSOR FOR insert_cust;
EXEC SQL AT DB_1 OPEN insert_cust_cursor USING :customerId;
for ( ....)
customerID = ...;
EXEC SQL AT DB_DCMS EXECUTE insert_cust;
Also tried passing in the tablename as a host variable
EXEC SQL INSERT INTO :szTableName (CUSTOMER_ID) VALUES (:customerId);
ProC compiler gives the following error:
INSERT INTO :szTableName (CUSTOMER_ID) VALUES (:customerId);
........................1
PCC-S-02201, Encountered the symbol ":" when expecting one of the following:
( an identifier, a quoted string, date, table, count,
extract, interval, multiset, the, time, timestamp, treat,
trim, avg, max, min, sum, stddev, variance,
ThanksYou don't DECLARE and OPEN an insert statement (just selects). Just use EXECUTE ... USING ...
-
SELECT DISTINCT With OPEN cursor FOR
Hello.
I have the following procedure. All it does is open a cursor for an SQL string passed into it, and return the open cursor.
PROCEDURE sp_execute_dynamic (hold_input_string IN CLOB,
hold_cursor OUT hold_cursor_type) IS
BEGIN
OPEN hold_cursor FOR TO_CHAR(hold_input_string);
END sp_execute_dynamic;
It works fine except when I perform SELECT DISTINCT. I get the following error.
SQL> declare
2 TYPE hold_cursor_type IS REF CURSOR;
3 hold_cursor hold_cursor_type;
4 hold_object_name VARCHAR2(1024);
5 hold_object_type VARCHAR2(1024);
6 begin
7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
8 loop
9 fetch hold_cursor into hold_object_name, hold_object_type;
10 exit when hold_cursor%NOTFOUND;
11 dbms_output.put_line('Object Name = '||hold_object_name||' Object Type = '||hold_object_type);
12 end loop;
13 end;
14 /
declare
ERROR at line 1:
ORA-01007: variable not in select list
ORA-06512: at line 9
It does the same thing with SELECT UNIQUE or SELECT with a GROUP BY. Can anyone tell me why this happens and what I could to to work around it?
Thanks
Chrissee at line 7 you are selecting only one column and at line 9you are fetching into two variables
7 dynamic_sql_pkg.sp_execute_dynamic('select distinct object_name from user_objects where object_
name in (''PLAN_TABLE'',''DBA_OBJECTS'')',hold_cursor);
8 loop
9 fetch hold_cursor into hold_object_name, hold_object_type;
HTH -
Null check for a bind variable in view criteria
Hi, Greetings.
I am using Jdeveloper 11.1.2.0.
I have a view object, LocationsView, for locations table of the XE database.
I want to apply a condition, ((:bind_var is null) or (:bind_var is not null and location_id = :bind_var), in this LocationsView.
That is, I want to apply the condition only if the bind variable value is not null.
How can I construct this condition using a declarative view criteria?
Any help and hints on this regard is greatly appreciated.
Regards,
Guru KHi,
Thanks for the update and it is working perfectly fine.
Now, how can I set the "ignore null values" option as checked if I am constructing the criteria programmatically using view criteria row and view criteria item at runtime.
Thanks and regards,
Guru K
Maybe you are looking for
-
* is coming while priniting smartform of multiple pages for a customer
Hi Experts, I m priniting the smartform for the Customer statement and i m using SFSY-PAGE and SFSY-FORMPAGES for the page number and for total number for pages. There am facing the problem of * in SFSY-FORMPAGES.. If the total no of pages is single
-
Reader 10.0.1 not closing after sending a file to print
Hi all, We have an application that uses the windows file handlers for printing out a report. Since upgrading to Reader X 10.0.0 or to 10.0.1 (using group policy) from Reader 8 or 9 this feature doesnt work. After Reader Opens the file prints out but
-
F-44 Clear Vendor Process Open Items
Dear All Can anyone please tell me how to use transaction code F-44. I want to clear Vendor items. But unable to do it. Thanks & Regards Kanwaljit
-
How to remove device driver?
I have put the wrong driver on my IMac running OSX 10.7.3 and need to go to an older driver. I've tried to find out where the drivers are but no sucess. There is a driver for XBox 360 game controllers that I loaded and it appears in System Preference
-
Retain custom order in albums when exporting to different iPhoto library?
Hi all. To ease resource consumption, I'm placing many of my 20,000 iPhoto9 items into a new iPhoto9 library. I have many albums with pictures in custom order. Any recommendations on how to retain that order when copying the photos/ albums to the new