Function call in where cluse
Hello
i am trying to execute one statement in stored procedure.
basically i need to pass split string in where clause. it goes like this..
in put is : E,R,T.
i have written the function which will split the string into 'T','R','E'.
CREATE OR REPLACE FUNCTION FN_SPLIT_STRING(P_STR_VALUE VARCHAR2)
RETURN VARCHAR2 is
V_TEMP VARCHAR2(100);
V_VALUE VARCHAR2(100);
V_OUT VARCHAR2(100);
BEGIN
V_TEMP := P_STR_VALUE||',';
WHILE (V_TEMP IS NOT NULL)
LOOP
V_VALUE := SUBSTR(V_TEMP, 1, INSTR(V_TEMP, ',')-1);
--DBMS_OUTPUT.PUT_LINE(V_VALUE);
V_OUT := ''''||V_VALUE||''''||',' ||V_OUT;
V_TEMP := SUBSTR(V_TEMP, INSTR(V_TEMP, ',')+1);
END LOOP;
return(SUBSTR(V_OUT, 1, LENGTH(V_OUT)-1));
END FN_SPLIT_STRING;
i have to execute the below query now
select * from TABLE_X_TXN_VAR
where process_flag IN ( FN_SPLIT_STRING (E,S,T) ) and X_LAST_UPDATE_DATE < To_Date('1/22/2006','MM/DD/YYYY');
i am ideally expecting it to pass Process_flag In ('T','R','E') but it is instead comparing whole string like it is searching for process flag as "('T','R','E')" instead it should do one by one like normal In clause. i.e. first it should check for 'E' then for 'R' then for 'T'.
Explore these threads:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:110612348061
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:210612357425
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2189860818012
and you'll discover several examples.
Similar Messages
-
Function calls in WHERE clause
Hello,
I have several procedures that all share a similar snippet of code in the WHERE clause. I tried to make this a function but, using a function increases the execution time of the calling procedure by a factor of ten. I am currently on 8i and will be moving to 9i soon. Was just wondering if there will be any performance increase from this type of function call on 9i vs. 8i.
Thanks
:)sometimes a perforance hit it worth the maintability factor.I disagree, strongly. The developer's Prime Directive is to make the user's experience a good one. Inflicting poorly performing code on the user in the name of maintinability is not on.
Q: Why does the code have to be maintained so much?
A: Because the users' keep complaining about how slow it runs....
[SOAPBOX]
Of course in the real world things get confused and it can be quite difficult to distinguish programmers' issues - encapsulation, flexibility, maintainability - from users' issues - correctness, completeness, performance.
But the relative worth of these things is easy to assess. A highly-modular parameter driven architecture that delivers the wrong answer and takes an age to do it ain't worth jack. Even if it is so maintainable that it's easy to fix every bug in it.
[SOAPBOX]
"Whatever waits for us behind those doors, we have a better chance of survival if we stick together." Gladiator
Cheers, APC -
Problem using function call in WHERE part of a Report's SQL query
I tried doing some searches on this, but couldn't find anything. I'm trying to run something similar to the following query in my report, but keep getting a "Query cannot be parsed within the Builder" error:
SELECT function1(TABLE2.ID) A
FROM TABLE1, TABLE2
WHERE TABLE1.ID = TABLE2.ID AND
TABLE1.NAME = 'BLAH' AND
TABLE2.DATE > SYSTIMESTAMP AND
(function2(TABLE2.ID) = 'YES' OR
function3(:USER_ID) = 'YES')
ORDER BY TABLE1.NAMEWhy won't this work? I can take out the 2 lines with function calls from the WHERE clause, and it works, so I'm assuming that APEX doesn't like something about my function calls. I know the functions are valid and work properly, because I tested them independently. Can anyone see what the problem is? Thanks!Here's the actual query:
SELECT BUILD_EXT_RES_LIST(EXT_FILE.ID) A
FROM EXT_FILE_RES, EXT_FILE
WHERE EXT_FILE_RES.ON_OWNER_PROFILE = 'Y' AND
EXT_FILE.OWNER_ID = :PROFILE AND
EXT_FILE.ID = EXT_FILE_RES.EXT_ID AND
(RES_SUBSCRIBER_YN(EXT_FILE.ID,:CURR_ID) = 'YES' OR
ADMINYESNO(:CURR_ID,:PROFILE) = 'YES')
ORDER BY EXT_FILE.FILE_NAMEAnd here's the actual error message:
1 error has occurred
Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the ''generic columns'' checkbox below the region source to proceed without parsing. ORA-00904: "SER_IS_ADMINYESNO": invalid identifier -
Using rowconcat in where cluse
hi all
i need to use rowconcat function in my where cluse
ex:
select id,name
from emp
where id in (select rowconcat('select emp_id from emp_test') from dual);
select rowconcat('select emp_id from emp_test') from dual = returned (2,10,14,20)
plz helpWhy not:
select id,name
from emp
where id in (select emp_id from emp_test);Again, I don't know your business logic, but assuming there is a need for dynamic SQL I'd use pipelined table function:
create or replace
type NumList
as
table of number
create or replace
function num_list(
v_stmt varchar2
return NumList
pipelined
is
v_num number;
v_cur sys_refcursor;
begin
open v_cur for stmt;
loop
fetch v_cur
into v_num;
exit when v_cur%notfound;
pipe row(v_num);
end loop;
close v_cur;
return;
end;
select id,
name
from emp
where id in (select * from table(num_list('select emp_id from emp_test')))
/SY.
P.S. You can also make pipelined function to run in parallel. -
Function is called in Where clause
I am analyzing the script and found one function is called within the SQL statement in where clause. I like to know is there any alternate way to improve the performance.
If I move the function call prior to this select statement and update the result of function value in new column in existing table/ are in new tmp table. Will there be performance improvement
Or any other better way... Plz suggest me.
- MaheshYou should include the query code as well as the execution plan.
I figure out you mean your arguments in the where clause are evaluating a function and this prevents the index from being used, provoking a reduced query performance. If this is the case, then you should consider using function based indexes instead.
~ Madrid
http://hrivera99.blogspot.com/ -
Call a function in a where clause of a select
hello,
is it possible to call a function in a where clause of a select????
ex: select col1, col2
from my_table
where my_package.my_function(32199, 2008, col3, 'P');
and i have error message "ORA-00920: invalid relational operator"
FUNCTION my_function(v_matricule IN NUMBER,
v_Year IN NUMBER,
v_date IN DATE,
v_type IN CHAR DEFAULT 'P')
RETURN BOOLEAN;
@+Rosagiouser10225229 wrote:
hello,
is it possible to call a function in a where clause of a select????
ex: select col1, col2
from my_table
where my_package.my_function(32199, 2008, col3, 'P');
and i have error message "ORA-00920: invalid relational operator"
FUNCTION my_function(v_matricule IN NUMBER,
v_Year IN NUMBER,
v_date IN DATE,
v_type IN CHAR DEFAULT 'P')
RETURN BOOLEAN;You can call a function if it returns a datatype that is supported by SQL. BOOLEAN is NOT supported by SQL. -
Is there a way to avoid the function call ?
Given the following test case
CREATE USER TESTER
IDENTIFIED BY "tester"
DEFAULT TABLESPACE USERS
TEMPORARY TABLESPACE TEMP
GRANT CONNECT, RESOURCE TO TESTER
GRANT CREATE TYPE TO TESTER
GRANT CREATE SESSION TO TESTER
GRANT CREATE PROCEDURE TO TESTER
GRANT CREATE TABLE TO TESTER
GRANT UNLIMITED TABLESPACE TO TESTER
ALTER USER TESTER QUOTA UNLIMITED ON USERS
COMMIT
CONNECT TESTER/tester
CREATE OR REPLACE TYPE TESTER.PATTERN_LIST AS TABLE OF VARCHAR2(1023 CHAR)
SHOW ERRORS
CREATE TABLE TESTER.PARENT_TABLE
FIELD_ID NUMBER(10) NOT NULL,
FIELD_NAME VARCHAR2( 255 CHAR) NOT NULL,
FIELD_PATH VARCHAR2(1023 CHAR) NOT NULL,
FIELD_VALUE VARCHAR2( 255 CHAR)
CREATE TABLE TESTER.CHILD_TABLE
FIELD_PATH VARCHAR2(1023 CHAR) NOT NULL,
MIN_STR_LEN NUMBER(10),
MAX_STR_LEN NUMBER(10),
PATTERNS TESTER.PATTERN_LIST
NESTED TABLE PATTERNS STORE AS PATTERN_TABLE RETURN AS VALUE
ALTER TABLE TESTER.PARENT_TABLE ADD (
CONSTRAINT PARENT_TABLE_PK
PRIMARY KEY
(FIELD_ID))
INSERT ALL
INTO TESTER.PARENT_TABLE
VALUES (1, 'FIELD_A', '/A', NULL)
INTO TESTER.PARENT_TABLE
VALUES (2, 'FIELD_AB', '/A/B', '20090731')
INTO TESTER.PARENT_TABLE
VALUES (3, 'FIELD_AC', '/A/C', '2167')
INTO TESTER.PARENT_TABLE
VALUES (4, 'FIELD_AC', '/A/C', '1144')
INTO TESTER.PARENT_TABLE
VALUES (5, 'FIELD_AD', '/A/D', 'XS10')
INTO TESTER.PARENT_TABLE
VALUES (6, 'FIELD_AB', '/A/B', '20090229')
INTO TESTER.PARENT_TABLE
VALUES (7, 'FIELD_AD', '/A/D', 'ART')
INTO TESTER.PARENT_TABLE
VALUES (8, 'FIELD_AD', '/A/D', 'TESTED')
INTO TESTER.CHILD_TABLE
VALUES ('/A', NULL, NULL, PATTERN_LIST())
INTO TESTER.CHILD_TABLE
VALUES ('/A/B', NULL, NULL, PATTERN_LIST( '[12][0-9]{3}[0][13578]([0][1-9]|[12][0-9]|[3][01])'
, '[12][0-9]{3}[0][469]([0][1-9]|[12][0-9]|[3][0])'
, '[12][0-9]{3}[1][02][3][1]'
, '[12][0-9]{3}[1][1][3][0]'
, '[12][0-9]{3}[0][2][2][8]'
, '([2][048]|[1][26])([02468][048]|[13579][26])[0][2][2][9]'))
INTO TESTER.CHILD_TABLE
VALUES ('/A/C', NULL, NULL, PATTERN_LIST( '[0-1][0-9][0-5][0-9]'
, '[2][0-3][0-5][0-9]'))
INTO TESTER.CHILD_TABLE
VALUES ('/A/D', 3, 4, PATTERN_LIST('[^0-9]*'))
SELECT * FROM DUAL
CREATE OR REPLACE FUNCTION TESTER.MATCH_PATTERN(p_value IN VARCHAR2, p_patterns IN TESTER.PATTERN_LIST) RETURN NUMBER
AS
v_count NUMBER := 0;
BEGIN
SELECT COUNT(*)
INTO v_count
FROM TABLE(p_patterns)
WHERE REGEXP_SUBSTR(p_value, COLUMN_VALUE) = p_value;
RETURN v_count;
END MATCH_PATTERN;
SHOW ERRORS
COMMIT
/the query
SELECT FIELD_ID
, FIELD_PATH
, ERRINDEX
, FIELD_VALUE
FROM (
SELECT a.FIELD_ID
, a.FIELD_PATH
, b.PATTERNS
, CASE
WHEN ((b.MIN_STR_LEN IS NOT NULL) AND ((a.FIELD_VALUE IS NULL) OR (LENGTH(a.FIELD_VALUE) < b.MIN_STR_LEN))) THEN 1
END AS ERRINDEX_1
, CASE
WHEN ((b.MAX_STR_LEN IS NOT NULL) AND ((a.FIELD_VALUE IS NULL) OR (LENGTH(a.FIELD_VALUE) > b.MAX_STR_LEN))) THEN 2
END AS ERRINDEX_2
, CASE
WHEN ((b.PATTERNS IS NOT EMPTY) AND ((SELECT COUNT(*) FROM TABLE(b.PATTERNS) WHERE REGEXP_SUBSTR(a.FIELD_VALUE, COLUMN_VALUE) = a.FIELD_VALUE) = 0)) THEN 4
END AS ERRINDEX_4
, a.FIELD_VALUE
FROM TESTER.PARENT_TABLE a
INNER JOIN TESTER.CHILD_TABLE b ON a.FIELD_PATH = b.FIELD_PATH
UNPIVOT
ERRINDEX
FOR COL IN (ERRINDEX_1, ERRINDEX_2, ERRINDEX_4)
)gives me ORA-03113: end-of-file on communication channel
If on the other hand, I replace the nested single-row SELECT with the function call like this
SELECT FIELD_ID
, FIELD_PATH
, ERRINDEX
, FIELD_VALUE
FROM (
SELECT a.FIELD_ID
, a.FIELD_PATH
, b.PATTERNS
, CASE
WHEN ((b.MIN_STR_LEN IS NOT NULL) AND ((a.FIELD_VALUE IS NULL) OR (LENGTH(a.FIELD_VALUE) < b.MIN_STR_LEN))) THEN 1
END AS ERRINDEX_1
, CASE
WHEN ((b.MAX_STR_LEN IS NOT NULL) AND ((a.FIELD_VALUE IS NULL) OR (LENGTH(a.FIELD_VALUE) > b.MAX_STR_LEN))) THEN 2
END AS ERRINDEX_2
, CASE
WHEN ((b.PATTERNS IS NOT EMPTY) AND (TESTER.MATCH_PATTERN(a.FIELD_VALUE, b.PATTERNS) = 0)) THEN 4
END AS ERRINDEX_4
, a.FIELD_VALUE
FROM TESTER.PARENT_TABLE a
INNER JOIN TESTER.CHILD_TABLE b ON a.FIELD_PATH = b.FIELD_PATH
UNPIVOT
ERRINDEX
FOR COL IN (ERRINDEX_1, ERRINDEX_2, ERRINDEX_4)
)the query gives the correct results which should be
FIELD_ID FIELD_PATH ERRINDEX FIELD_VALUE
6 /A/B 4 20090229
3 /A/C 4 2167
5 /A/D 4 XS10
8 /A/D 2 TESTEDIs there a way to do this without the PL/SQL function call and at the same time avoid the ORA-03113 ? Or, have I hit a bug on 11.1.0.7 ?
Many thanks in advance
Best Regards
PhilipI found the Oracle Bug on my own in the end, in the most unlikely of places !
The following code
SELECT FIELD_ID
, FIELD_PATH
, ERRINDEX
, FIELD_VALUE
FROM (
SELECT a.FIELD_ID
, a.FIELD_PATH
, CASE
WHEN ((b.MIN_STR_LEN IS NOT NULL) AND ((a.FIELD_VALUE IS NULL) OR (LENGTH(a.FIELD_VALUE) < b.MIN_STR_LEN))) THEN 1
END AS ERRINDEX_1
, CASE
WHEN ((b.MAX_STR_LEN IS NOT NULL) AND ((a.FIELD_VALUE IS NULL) OR (LENGTH(a.FIELD_VALUE) > b.MAX_STR_LEN))) THEN 2
END AS ERRINDEX_2
, CASE
WHEN ((b.PATTERNS IS NOT EMPTY) AND ((SELECT COUNT(*) FROM TABLE(b.PATTERNS) WHERE REGEXP_SUBSTR(a.FIELD_VALUE, COLUMN_VALUE) = a.FIELD_VALUE) = 0)) THEN 4
END AS ERRINDEX_4
, a.FIELD_VALUE
FROM TESTER.PARENT_TABLE a, TESTER.CHILD_TABLE b
WHERE a.FIELD_PATH = b.FIELD_PATH
UNPIVOT
ERRINDEX
FOR COL IN (ERRINDEX_1, ERRINDEX_2, ERRINDEX_4)
)works as intended i.e. like a charm !
The only difference between the one that gives the ORA-03113 and the above is the way the join is written. The ANSI way (INNER JOIN) fails, the old way (WHERE clause) succeeds.
I will open a SR with Oracle so that it may be recorded and fixed.
Best Regards
Philip -
Is it possible to pass table name as parameter to function calls?
Let's say I would like to retrieve data from table BSAD, BSID, BSIS, BSAS with the exact same WHERE conditions.
I.E.
SELECT SINGLE * FROM bsis
WHERE bukrs = zbukrs
AND belnr = zbelnr
AND gjahr = zgjahr
AND buzei = bseg-buzei.
SELECT SINGLE * FROM bsas
WHERE bukrs = zbukrs
AND belnr = zbelnr
AND gjahr = zgjahr
AND buzei = bseg-buzei.
Is there a way that I could put them into a function and do something like?
perform select_table_bsas using 'bsas'.
perform select_table_bsis using 'bsis'.
and I should get SELECT * FROM passed from the function calls.
Thanks.Hello,
You can try something like this
DATA : LV_DBTAB1 LIKE DD02L-TABNAME.
DATA : DREF TYPE REF TO DATA.
FIELD-SYMBOLS: <ITAB> TYPE ANY TABLE. " used to store dynamic tables
LV_DBTAB1 = 'MARA'. " in caps
CREATE DATA DREF TYPE STANDARD TABLE OF (LV_DBTAB1)
WITH NON-UNIQUE DEFAULT KEY.
ASSIGN DREF->* TO <ITAB> .
* chooses only english values
SELECT * FROM (LV_DBTAB1) INTO TABLE <ITAB> WHERE SPRAS = 'E'.
here, even the internal table is dynamic, but that can be static if you know the structure for sure -
Java.lang.VerifyError - Incompatible object argument for function call
Hi all,
I'm developing a JSP application (powered by Tomcat 4.0.1 in JDK 1.3, in Eclipse 3.3). Among other stuff I have 3 classes interacting with an Oracle database, covering 3 use cases - renaming, adding and deleting an database object. The renaming class simply updates the database with a String variable it receives from the request object, whereas the other two classes perform some calculations with the request data and update the database accordingly.
When the adding or deleting classes are executed, by performing the appropriate actions through the web application, Tomcat throws the following:
java.lang.VerifyError: (class: action/GliederungNewAction, method: insertNewNode signature: (Loracle/jdbc/driver/OracleConnection;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V) Incompatible object argument for function call
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:120)
at action.ActionMapping.perform(ActionMapping.java:53)
at ControllerServlet.doResponse(ControllerServlet.java:92)
at ControllerServlet.doPost(ControllerServlet.java:50)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
...The renaming works fine though. I have checked mailing lists and forums as well as contacted the company's java support but everything I have tried out so far, from exchanging the xerces.jar files found in JDOM and Tomcat to rebuidling the project didn't help.
I just can't explain to myself why this error occurs and I don't see how some additional Java code in the other 2 classes could cause it?
I realize that the Tomcat and JDK versions I'm using are totally out of date, but that's company's current standard and I can't really change that.
Here's the source code. I moved parts of the business logic from Java to Oracle recently but I left the SQL statements that the Oracle stored procedures are executing if it helps someone.
package action;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import oracle.jdbc.driver.OracleConnection;
* This class enables the creation and insertion of a new catalogue node. A new node
* is always inserted as the last child of the selected parent node.
public class GliederungNewAction implements Action {
public String perform(ActionMapping mapping, HttpServletRequest request,
HttpServletResponse response) {
// fetch the necessary parameters from the JSP site
// the parent attribute is the selected attribute!
String parent_attribute = request.getParameter("attr");
String catalogue = request.getParameter("catalogue");
int parent_sequenceNr = Integer.parseInt(request.getParameter("sort_sequence"));
// connect to database
HttpSession session = request.getSession();
db.SessionConnection sessConn = (db.SessionConnection) session.getAttribute("connection");
if (sessConn != null) {
try {
sessConn.setAutoCommit(false);
OracleConnection connection = (OracleConnection)sessConn.getConnection();
int lastPosition = getLastNodePosition( getLastChildAttribute(connection, catalogue, parent_attribute) );
String newNodeAttribute = createNewNodeAttribute(parent_attribute, lastPosition);
// calculate the sequence number
int precedingSequenceNumber = getPrecedingSequenceNumber(connection, catalogue, parent_attribute);
if ( precedingSequenceNumber == -1 ) {
precedingSequenceNumber = parent_sequenceNr;
int sortSequence = precedingSequenceNumber + 1;
setSequenceNumbers(connection, catalogue, sortSequence);
// insert the new node into DB
insertNewNode(connection, catalogue, newNodeAttribute, parent_attribute, "Neuer Punkt", sortSequence);
connection.commit();
} catch(SQLException ex) {
ex.printStackTrace();
return mapping.getForward();
* Creates, fills and executes a prepared statement to insert a new entry into the specified table, representing
* a new node in the catalogue.
private void insertNewNode(OracleConnection connection, String catalogue, String attribute, String parent_attribute, String description, int sortSequence) {
try {
String callAddNode = "{ call fasi_lob.pack_gliederung.addNode(:1, :2, :3, :4, :5) }";
CallableStatement cst;
cst = connection.prepareCall(callAddNode);
cst.setString(1, catalogue);
cst.setString(2, attribute);
cst.setString(3, parent_attribute);
cst.setString(4, description);
cst.setInt(5, sortSequence);
cst.execute();
cst.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
// String insertNewNode = "INSERT INTO vstd_media_cat_attributes " +
// "(catalogue, attribute, parent_attr, description, sort_sequence) VALUES(:1, :2, :3, :4, :5)";
// PreparedStatement insertStmt;
// try {
// insertStmt = connection.prepareStatement(insertNewNode);
// insertStmt.setString(1, catalogue);
// insertStmt.setString(2, attribute);
// insertStmt.setString(3, parent_attribute);
// insertStmt.setString(4, description);
// insertStmt.setInt(5, sortSequence);
// insertStmt.execute();
// insertStmt.close();
// } catch (SQLException e) {
// e.printStackTrace();
* This method returns the attribute value of the last child of the parent under which
* we want to insert a new node. The result set is sorted in descending order and only the
* first result (that is, the last child under this parent) is fetched.
* If the parent node has no children, "parent_attr.0" is returned.
* @param connection
* @param catalogue
* @param parent_attribute
* @return attribute of the last child under this parent, or "parent_attr.0" if parent has no children
private String getLastChildAttribute(OracleConnection connection, String catalogue, String parent_attribute) {
String queryLastChild = "SELECT attribute FROM vstd_media_cat_attributes " +
"WHERE catalogue=:1 AND parent_attr=:2 ORDER BY sort_sequence DESC";
String lastChildAttribute;
PreparedStatement ps;
try {
ps = connection.prepareStatement(queryLastChild);
ps.setString(1, catalogue);
ps.setString(2, parent_attribute);
ResultSet rs = ps.executeQuery();
/* If a result is returned, the selected parent already has children.
* If not set the lastChildAttribute to parent_attr.0
if (rs.next()) {
lastChildAttribute = rs.getString("attribute");
} else {
lastChildAttribute = parent_attribute.concat(".0");
rs.close();
return lastChildAttribute;
} catch (SQLException e) {
e.printStackTrace();
return null;
* This helper method determines the position of the last node in the attribute.
* i.e for 3.5.2 it returns 2, for 2.1 it returns 1 etc.
* @param attribute
* @return position of last node in this attribute
private int getLastNodePosition(String attribute) {
StringTokenizer tokenizer = new StringTokenizer(attribute, ".");
String lastNodePosition = "0";
while( tokenizer.hasMoreTokens() ) {
lastNodePosition = tokenizer.nextToken();
return Integer.parseInt(lastNodePosition);
* This method calculates the attribute of a node being inserted
* by incrementing the last child position by 1 and attaching the
* incremented position to the parent.
* @param parent_attr
* @param lastPosition
* @return attribute of the new node
private String createNewNodeAttribute(String parent_attr, int lastPosition) {
String newPosition = new Integer(lastPosition + 1).toString();
return parent_attr.concat("." + newPosition);
* This method checks if the required sequence number for a new node is already in use and
* handles the sequence numbers accordingly.
* If the sequence number for a new node is NOT IN USE, the method doesn't do anything.
* If the sequence number for a new node is IN USE, the method searches for the next free
* sequence number by incrementing the number by one and repeating the query until no result
* is found. Then all the sequence numbers between the required number (including, >= relation)
* and the nearest found free number (not including, < relation) are incremented by 1, as to
* make space for the new node.
* @param connection
* @param catalogue
* @param newNodeSequenceNumber required sequence number for the new node
private void setSequenceNumbers(OracleConnection connection, String catalogue, int newNodeSequenceNumber) {
// 1. check if the new sequence number exists - if no do nothing
// if yes - increment by one and see if exists
// repeat until free sequence number exists
// when found increment all sequence numbers freeSeqNr > seqNr >= newSeqNr
String query = "SELECT sort_sequence FROM vstd_media_cat_attributes " +
"WHERE catalogue=:1 AND sort_sequence=:2";
PreparedStatement ps;
try {
ps = connection.prepareStatement(query);
ps.setString(1, catalogue);
ps.setInt(2, newNodeSequenceNumber);
ResultSet rs = ps.executeQuery();
// if no result, the required sequence number is free - nothing to do
if( rs.next() ) {
int freeSequenceNumber = newNodeSequenceNumber;
do {
ps.setString(1, catalogue);
ps.setInt(2, freeSequenceNumber++);
rs = ps.executeQuery();
} while( rs.next() );
// increment sequence numbers - call stored procedure
String callUpdateSeqeunceNrs = "{ call fasi_lob.pack_gliederung.updateSeqNumbers(:1, :2, :3) }";
CallableStatement cst = connection.prepareCall(callUpdateSeqeunceNrs);
cst.setString(1, catalogue);
cst.setInt(2, newNodeSequenceNumber);
cst.setInt(3, freeSequenceNumber);
cst.execute();
cst.close();
// String query2 = "UPDATE vstd_media_cat_attributes " +
// "SET sort_sequence = (sort_sequence + 1 ) " +
// "WHERE catalogue=:1 sort_sequnce >=:2 AND sort_sequence <:3";
// PreparedStatement ps2;
// ps2 = connection.prepareStatement(query2);
// ps2.setString(1, catalogue);
// ps2.setInt(2, newNodeSequenceNumber);
// ps2.setInt(3, freeSequenceNumber);
// ps.executeUpdate();
// ps.close();
} // end of if block
rs.close();
} catch (SQLException e) {
e.printStackTrace();
* This method finds the last sequence number preceding the sequence number of a node
* that is going to be inserted. The preceding sequence number is required to calculate
* the sequence number of the new node.
* We perform a hierarchical query starting from the parent node: if a result is returned,
* we assign the parent's farthest descendant's node sequence number; if no result
* is returned, we assign the parent's sequence number.
* @param connection
* @param catalogue
* @param parent_attr parent attribute of the new node
* @return
private int getPrecedingSequenceNumber(OracleConnection connection, String catalogue, String parent_attr) {
int sequenceNumber = 0;
String query = "SELECT sort_sequence FROM vstd_media_cat_attributes " +
"WHERE catalogue=:1 " +
"CONNECT BY PRIOR attribute = parent_attr START WITH parent_attr=:2 " +
"ORDER BY sort_sequence DESC";
try {
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, catalogue);
ps.setString(2, parent_attr);
ResultSet rs = ps.executeQuery();
if ( rs.next() ) {
sequenceNumber = rs.getInt("sort_sequence");
} else {
// TODO: ggf fetch from request!
sequenceNumber = -1;
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
return sequenceNumber;
}After further googling I figured out what was causing the problem: in eclipse I was referring to external libraries located in eclipse/plugins directory, whereas Tomcat was referring to the same libraries (possibly older versions) in it's common/lib directory.
-
Java function call from Trigger in Oracle
Moderator edit:
This post was branched from an eleven-year-old long dead thread
Java function call from Trigger in Oracle
@ user 861498,
For the future, if a forum discussion is more than (let's say) a month old, NEVER resurrect it to append your new issue. Always start a new thread. Feel free to include a link to that old discussion if you think it might be relevant.
Also, ALWAYS use code tags as is described in the forum FAQ that is linked at the upper corner of e\very page. Your formulae will be so very much more readable.
{end of edit, what follows is their posting}
I am attempting to do a similar function, however everything is loaded, written, compiled and resolved correct, however, nothing is happening. No errors or anything. Would I have a permission issue or something?
My code is the following, (the last four lines of java code is meant to do activate a particular badge which will later be dynamic)
Trigger:
CREATE OR REPLACE PROCEDURE java_contact_t4 (member_id_in NUMBER)
IS LANGUAGE JAVA
NAME 'ThrowAnError.contactTrigger(java.lang.Integer)';
Java:
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "ThrowAnError" AS
// Required class libraries.
import java.sql.*;
import oracle.jdbc.driver.*;
import com.ekahau.common.sdk.*;
import com.ekahau.engine.sdk.*;
// Define class.
public class ThrowAnError {
// Connect and verify new insert would be a duplicate.
public static void contactTrigger(Integer memberID) throws Exception {
String badgeId;
// Create a Java 5 and Oracle 11g connection.
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
// Create a prepared statement that accepts binding a number.
PreparedStatement ps = conn.prepareStatement("SELECT \"Note\" " +
"FROM Users " +
"WHERE \"User\" = ? ");
// Bind the local variable to the statement placeholder.
ps.setInt(1, memberID);
// Execute query and check if there is a second value.
ResultSet rs = ps.executeQuery();
while (rs.next()) {
badgeId = rs.getString("Note");
// Clean up resources.
rs.close();
ps.close();
conn.close();
// davids badge is 105463705637
EConnection mEngineConnection = new econnection("10.25.10.5",8550);
mEngineConnection.setUserCredentials("choff", "badge00");
mEngineConnection.call("/epe/cfg/tagcommandadd?tagid=105463705637&cmd=mmt%203");
mEngineConnection.call("/epe/msg/tagsendmsg?tagid=105463705637&messagetype=instant&message=Hello%20World%20from%20Axium-Oracle");
Edited by: rukbat on May 31, 2011 1:12 PMTo followup on the posting:
Okay, being a oracle noob, I didn't know I needed to tell anything to get the java error messages out to the console
Having figured that out on my own, I minified my code to just run the one line of code:
// Required class libraries.
import java.sql.*;
import oracle.jdbc.driver.*;
import com.ekahau.common.sdk.*;
import com.ekahau.engine.sdk.*;
// Define class.
public class ThrowAnError {
public static void testEkahau(Integer memberID) throws Exception {
try {
EConnection mEngineConnection = new EConnection("10.25.10.5",8550);
} catch (Throwable e) {
System.out.println("got an error");
e.printStackTrace();
}So, after the following:
SQL> {as sysdba on another command prompt} exec dbms_java.grant_permission('AXIUM',"SYS:java.util.PropertyPermission','javax.security.auth.usersubjectCredsOnly','write');
and the following as the user
SQL> set serveroutput on
SQL> exec dbms_java.set_output(10000);
I run the procedure and receive the following message.
SQL> call java_contact_t4(801);
got an error
java.lang.NoClassDefFoundError
at ThrowAnError.testEkahau(ThrowAnError:13)
Call completed.
NoClassDefFoundError tells me that it can't find the jar file to run my call to EConnection.
Now, I've notice when I loaded the sdk jar file, it skipped some classes it contained:
c:\Users\me\Documents>loadjava -r -f -v -r "axium/-----@axaxiumtrain" ekahau-engine-sdk.jar
arguments: '-u' 'axium/***@axaxiumtrain' '-r' '-f' '-v' 'ekahau-engine-sdk.jar'
creating : resource META-INF/MANIFEST.MF
loading : resource META-INF/MANIFEST.MF
creating : class com/ekahau/common/sdk/EConnection
loading : class com/ekahau/common/sdk/EConnection
creating : class com/ekahau/common/sdk/EErrorCodes
loading : class com/ekahau/common/sdk/EErrorCodes
skipping : resource META-INF/MANIFEST.MF
resolving: class com/ekahau/common/sdk/EConnection
skipping : class com/ekahau/common/sdk/EErrorCodes
skipping : class com/ekahau/common/sdk/EException
skipping : class com/ekahau/common/sdk/EMsg$EMSGIterator
skipping : class com/ekahau/common/sdk/EMsg
skipping : class com/ekahau/common/sdk/EMsgEncoder
skipping : class com/ekahau/common/sdk/EMsgKeyValueParser
skipping : class com/ekahau/common/sdk/EMsgProperty
resolving: class com/ekahau/engine/sdk/impl/LocationImpl
skipping : class com/ekahau/engine/sdk/status/IStatusListener
skipping : class com/ekahau/engine/sdk/status/StatusChangeEntry
Classes Loaded: 114
Resources Loaded: 1
Sources Loaded: 0
Published Interfaces: 0
Classes generated: 0
Classes skipped: 0
Synonyms Created: 0
Errors: 0
.... with no explanation.
Can anyone tell me why it would skip resolving a class? Especially after I use the -r flag to have loadjava resolve it upon loading.
How do i get it to resolve the entire jar file?
Edited by: themadprogrammer on Aug 5, 2011 7:15 AM
Edited by: themadprogrammer on Aug 5, 2011 7:21 AM
Edited by: themadprogrammer on Aug 5, 2011 7:22 AM
Edited by: themadprogrammer on Aug 5, 2011 7:23 AM
Edited by: themadprogrammer on Aug 5, 2011 7:26 AM -
Table function sensitive to where clause?
Hi-
In Oracle SQL, you can use the results of a PL/SQL function as a table with the "TABLE()" syntax. Example: "SELECT * FROM TABLE(myfunction(param1,param2)) ..."
Is there any (non-crazy) way for the function to be aware of the conditions in the WHERE clause of that SELECT statement? For example, if I wanted "myfunction" to know that I had specified "WHERE param3=10' without having to put param3 in the function call, could this be done?
Other SQL implementations support this. I know of at least one where you can map a table on top of a function where the "in" parameters can correspond to columns on the mapped table. Does Oracle support a similar syntax or strategy?Not sure if it is too crazy for you ;)
But again I rely on a helper function since I am not sure about the purpose of the whole thing:
SQL> create or replace function set_param (p varchar2) return varchar2
as
begin
dbms_application_info.set_client_info(p);
return p;
end set_param;
Function created.
SQL> create or replace function myfunction
return sys.dbms_debug_vc2coll
as
begin
return sys.dbms_debug_vc2coll (sys_context ('userenv', 'client_info'));
end myfunction;
Function created.
SQL> select *
from table (myfunction())
where set_param (3) is not null
COLUMN_VALUE
3 Hope you get the idea .... -
How to get transaction id of a function called in background
Hi all,
does someone know how to retrieve t-id of a function called in background (tRFC) client side? I found
'ARFC_GET_RECEIVER_TID'
'ARFC_GET_TID'
but these works server side (function called knows its t-id .. caller no). Is there some similiar client side so that after calling function I can retrieve its transaction id ? I know it's not the same context, for explaining better, what I need it's something like fork() in C, where process father (the one that forks) receive as return value process id of process forked.
SEARCHING ON FORUM I see that many people answered on question about transaction id with sy-tcode misunderstanding the question. This transaction id it's not the tcode. This is the char 32 unique transaction code
thank you
regards
GabrieleYou can have a look at function TRFC_RECEIVER_INFO
[qRFC API for the Inbound Queue|http://help.sap.com/saphelp_nw04/helpdata/en/21/5c5f3ca0dd9770e10000000a114084/content.htm] -
Function call in procedure within Package Body
I am a novice in PL/SQL so that I can't find out where the problem is. I am testing a function call in procedure within a Package Body.
But the PL/SQL Complier doesn't compile the package body but I don't know what I do wrong. Plz let me know how to call a function in procedure within a Package Body?
Here are the Packaget test programs..
CREATE OR REPLACE PACKAGE manage_students
IS
PROCEDURE find_sname;
PROCEDURE find_test;
PROCEDURE find_test_called;
FUNCTION GET_LASTMT
RETURN SEQUENCE_TEST.SEQ_NO%TYPE;
END manage_students;
CREATE OR REPLACE PACKAGE BODY manage_students AS
v_max_nbr SEQUENCE_TEST.SEQ_NO%TYPE;
PROCEDURE find_sname
IS
BEGIN
BEGIN
SELECT MAX(SEQ_NO)
INTO v_max_nbr
from SEQUENCE_TEST;
DBMS_OUTPUT.PUT_LINE('MAX NUMBER is : '||v_max_nbr);
EXCEPTION
WHEN OTHERS
THEN DBMS_OUTPUT.PUT_LINE('Error in finding student_id: ');
RETURN;
END;
COMMIT;
EXCEPTION
WHEN OTHERS
THEN DBMS_OUTPUT.PUT_LINE('Error in finding student_id: ');
END find_sname;
PROCEDURE find_test
IS
BEGIN
BEGIN
DBMS_OUTPUT.PUT_LINE('MAX NUMBER Called from another procedure : '||v_max_nbr);
EXCEPTION
WHEN OTHERS
THEN DBMS_OUTPUT.PUT_LINE('Error in finding student_id: ');
RETURN;
END;
COMMIT;
EXCEPTION
WHEN OTHERS
THEN DBMS_OUTPUT.PUT_LINE('Error in finding student_id: ');
END find_test;
FUNCTION GET_LASTMT
RETURN SEQUENCE_TEST.SEQ_NO%TYPE
IS
v_max_nbr SEQUENCE_TEST.SEQ_NO%TYPE;
BEGIN
SELECT MAX(SEQ_NO)
INTO v_max_nbr
from SEQUENCE_TEST;
RETURN v_max_nbr;
EXCEPTION
WHEN OTHERS
THEN
DECLARE
v_sqlerrm VARCHAR2(250) :=
SUBSTR(SQLERRM,1,250);
BEGIN
RAISE_APPLICATION_ERROR(-20003,
'Error in instructor_id: '||v_sqlerrm);
END;
END GET_LASTMT;
PROCEDURE find_test_called
IS
BEGIN
BEGIN
V_max := Manage_students.GET_LASTMT;
DBMS_OUTPUT.PUT_LINE('MAX_NUMBER :'|| V_max);
EXCEPTION
WHEN OTHERS
THEN DBMS_OUTPUT.PUT_LINE('Error in finding student_id: ');
RETURN NULL;
END;
COMMIT;
EXCEPTION
WHEN OTHERS
THEN DBMS_OUTPUT.PUT_LINE('Error in finding student_id: ');
END find_test_called;
END manage_students;
DECLARE
v_max SEQUENCE_TEST.SEQ_NO%TYPE;
BEGIN
manage_students.find_sname;
DBMS_OUTPUT.PUT_LINE ('Student ID: Execute.');
manage_students.find_test;
manage_students.find_test_called;
END;
-----------------------------------------------------------------------------------------------Hi,
Welcome to the forum!
You'll find that there are a lot of people willing to help you.
Are you willing to help them? Whenever you have a problem, post enough for people to re-create the problem themselves. That includes CREATE TABLE and INSERT statements for all the tables you use.
Error messages are very helpful. Post the complete error message you're getting, including line number. (It looks like your EXCEPTION sections aren't doing much, except hiding the real errors. That's a bad programming practice, but probably not causing your present problem - just a future one.)
Never post unformatted code. Indent the code to show the extent of each procedure, and the blocks within each one.
When posting formatted text on this site, type these 6 characters:
\(all small letters, inside curly brackets) before and after each section of formatted test, to preserve the spacing.
For example, the procedure find_test_called would be a lot easier to read like this:PROCEDURE find_test_called
IS
BEGIN
BEGIN
V_max := Manage_students.GET_LASTMT;
DBMS_OUTPUT.PUT_LINE ('MAX_NUMBER :' || V_max);
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.PUT_LINE ('Error in finding student_id: ');
RETURN NULL;
END;
COMMIT;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.PUT_LINE ('Error in finding student_id: ');
END find_test_called;
It's much easier to tell from the code above that you're trying to return NULL from a procedure. Only functions can return anything (counting NULL); procedures can have RETURN statements, but that single word"RETURN;" is the entire statement. -
Validation of recursive function call fails
We want to use a call to a recursive function from a HTMLDB application. It should be used in a page region to generate a query string ("PL/SQL function body returning SQL query"). Everything works fine with a call to a non-recursive function. The recursive function also works fine when called from SQL+.
After pressing "Apply changes" on "HTML DB Home>Builder - Application 148>Page Definition>Edit Page Region"-page I get the following error message after a long delay:
Function returning SQL query: Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the ''generic columns'' checkbox below the region source to proceed without parsing
(ORA-00600: internal error code, arguments: [kohdtf048], [], [], [], [], [], [], [])
I assume that the validation routine follows the recursion until the memory limit is reached.
Please give me a hint how to solve this problem.
DB version: 10.1.0.2.0
HTMLDB version: 1.5.0.00.33
running on Win2000 serverSince the original function is confidential, I have created a simple one showing the same behavior (and the same error). Termination does not depend on session state:
Called function (to replace spaces with #):
create or replace function MF_Test
p_querystring varchar2
return varchar2 is
v_position integer;
begin
v_position:=instr(p_querystring,' ');
if v_position=0 then /* termination condition */
return p_querystring;
else
return substr(p_querystring,1,v_position-1)||'#'||MF_Test(substr(p_querystring,v_position+1));
end if;
end MF_Test;
calling function (from the page region, to generate a query string):
declare
q varchar2(500);
begin
q:='select * from hardware where model=''';
q:=q||mf_test(:P3_SEARCH);
q:=q||'''';
end
Validation seems not to terminate in case of recursive function calls.
Thanks for your input. -
select e.EMPID empid,
e.name name,
aatest.SETVALUES(2) z,
aatest.TEST1() b,
aatest.TEST2() x,
aatest.TEST3() y
from emp e
where e.empid = 101
order by e.name;
when I execute this select statement...the order of function calls is as follows:
setvalues 1st (call no:1)
test1 (call no:2)
test2 (call no:3)
test3 (call no:4)
Now...I introduce a join between the two tacles as mentioned in the query
select e.EMPID empid,
e.name name,
e2.deptno deptid,
aatest.SETVALUES(2) z,
aatest.TEST1() b,
aatest.TEST2() x,
aatest.TEST3() y
from emp e, emp2 e2
where e.empid = e2.empid
order by e.name;
The order of execution of function calls changes to
(I observed this using DBMS_OUTPUT.PUT_LINE)
test3 (call no:1)
setvalues 1st (call no:2)
test1 (call no:3)
test2 (call no:4) (the first and last calls swap!)
i.e: it calls the last function in the select statement at the beginning
instead of calling it at the last. Is it the normal behaviour? or whats going on
here?
Can somebody explain me, please....
Details:
the following four functions are defined in a package called 'aatest' and compiled.
aatest.SETVALUES(2)
aatest.TEST1()
aatest.TEST2()
aatest.TEST3()
the Tables EMP and EMP2 are two tables defined in the same schema.Your "thinking" is wrong here. You can not use the column order to model your program flow. As SQL is set/tupel based, there is no given sequence of the execution order. Otoh you want to have a specific order in wich your functions must be executed otherwise the result will be wrong (or undefined). Thus here you need a procedural approach. This can be done by using PL/SQL for example.
You would code your functions in that way, that they are working correctly independent from the place where they are called ie if function1 needs the setvalues function, this function must be called inside the function1 then.
Are you sure you need all these functions in this procedural approach inside the sql-statement? This is mostly not needed and can be accomplished by using pure SQL. If not, may be your design is broken.
Maybe you are looking for
-
Is there a way to stop and then resume an ipod video conversion process?
I am trying to convert videos to play on my new iPod Classic. The conversion process is painfully slow. I need to move the computer. Is there a way to stop the conversion process and then resume it later where you left off? The only way I have been a
-
13 apple ids connected with one phone number
I've been bumping into this problem for several years now and it 's just getting worse. When Apple started Voice Pass I had to delete 69 registered products to get down to the 7 I currently own. I have always had only one email address, one password,
-
How do i find my iphone if its offline
help me i lost my i phone and it dead and off line and i dont know what to do
-
DVD Menu system on iPod?
I'm converting my dvd's to my iPod. Can iPod recognize and utilize the menu system on DVD's? or can you only add the file that is the whole movie. I don't see why it wouldn't be possible to pick your dvd in iPod and have it start to the dvd menu and
-
Hello, i installed XI r2 from BOE. i dont see CMC, Infoview and few other things in the components , in infoview -new-web intelligence (i dont see web intelligence). in navigating infoview in all types drop down i dont see web intelligence document