User Defined function in Where clause
DB:- 11.2
Input:- 'ACCOUNTING,SALES'
Output:- ('ACCOUNTING','SALES')
WITH T AS (select 'ACCOUNTING,SALES' str from dual)
select '('||regexp_replace(str,'([[:alpha:]]+)','''\1''')||')' from t /*this works*/I've created a function to use this in a where clause
create or replace function ss(dname varchar2)
return varchar2 is
begin
RETURN '('||regexp_replace(dname,'([[:alpha:]]+)','''\1''')||')';
end;
select ss('ACCOUNTING,SALES') from dual --this worksBut when I am using this function in a where clause result is not coming..any thing i am missing?
select * from dept where dname in ss('ACCOUNTING,SALES') --no rows
940838 wrote:
Output:- ('ACCOUNTING','SALES')Wrong. ('ACCOUNTING','SALES') is a list of two strings 'ACCOUNTING' and 'SALES' while your function returns a single string '(''ACCOUNTING'',''SALES'')'.
IN clause requires a comma-separated list of values while your function, again, returns just one value. So query is comparing 'SALES' whith '(''ACCOUNTING'',''SALES'')', not with ('ACCOUNTING','SALES') and obviously no match. What you are trying to do is called dynamic SQL. There are plenty examples on how to use it. But you don't need it. Use nested table or varray. I'll use Oracle supplied varray type sys.OdciVarchar2List:
select *
from dept
where dname in (
select *
from table(sys.OdciVarchar2List('ACCOUNTING','SALES'))
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
30 SALES CHICAGO
SQL>SY.
Similar Messages
-
Using user defined function in where clause
Hi,
I have defined function to get maximum date before passed date on the table 'A' and I'm using the same function to get details on that date from the same table 'A' in where clause.
for ex:
SELECT x,y,z
FROM A
WHREE a.date = max_date;
But on one database instance it is running fine and on other it is going in a infinite loop.
Pls help me out
Thanks in advance,
PrashantHello Siva,
sorry, but I don't understand your reply:
This is not right forum to posting this question.
You are from which module or working any 3rd party application.
MaxDB 7.7.07.16 is the community version of MaxDb,
we are not using it for SAP
and no 3rd party software is required to reproduce my problem,
Sql Studio or Database Studio will do.
Regards,
Silke Arnswald -
Strange errors when using user defined function in where clause
Hello,
I am having trouble with a function that, when used in the where clause of a select will cause an error if the first column selected is of type INTEGER. Not sure whether I am doing something wrong or whether this is a bug.
Here is a very simple test case:
create table test(
col1 integer not null,
col2 varchar(20) ascii default ''
insert into test values(1,'2011-03-15 05:00:00')
insert into test values(2,'2011-03-15 07:00:00')
CREATE FUNCTION BTR_TAG RETURNS VARCHAR AS
VAR ret VARCHAR(20);
SET ret='2011-03-15 06:00:00';
RETURN ret;
Select * from test where col2 >= BTR_TAG()
Select col1,col2 from test where col2 >= BTR_TAG()
=> Error in assignment;-3016 POS(1) Invalid numeric constant
Select '',* from test where col2 >= BTR_TAG()
Select col2,col1 from test where col2 >= BTR_TAG()
=> works as it should
MaxDB V 7.7.07.16 running on Windows Server 2003
I can replicated the test case above with Sql Studio and other ODBC based tools.
Thanks in advance,
Silke ArnswaldHello Siva,
sorry, but I don't understand your reply:
This is not right forum to posting this question.
You are from which module or working any 3rd party application.
MaxDB 7.7.07.16 is the community version of MaxDb,
we are not using it for SAP
and no 3rd party software is required to reproduce my problem,
Sql Studio or Database Studio will do.
Regards,
Silke Arnswald -
User defined function in where IN clause
Hi,
I have a Function who returns in priview:
(1,2,3,4)
Now i am using this function in SQL where clause
Select from debug where id in debug.debug_process()
On execute select i am getiing ORA-01722 invalid number , i understand that functions return not only numbers but character symbols too '(,)'
Are it posible to use user defined function who do not return NUMBER in Where clause IN statement ? If not what tips can sugest me for getting list of values for use in IN Clause?
ID.
Thanks!Hi,
Please try:
You can use SYS REFCURSOR for return your data.
create or replace function get_debug return sys_refcursor is
v_rc sys_refcursor;
begin
open v_rc for 'select * from debug where id in '|| debug.debug_process();
return v_rc;
end;
Function created.
Now, if we look at using this through SQL*Plus we first create ourselves a ref cursor variable to accept the results of the function, and then call the function to get the ref cursor back..
SQL> var rc refcursor
SQL> exec :rc := get_debug ;
SQL> print rc;
Regards
Mahir M. Quluzade -
User-defined function in FILTER clause
hi,
can i create the user-defined functions and use them in the FILTER clause in the sem_match function? there are some built-in functions for the FILTER clasue. however, only one function (DATATYPE(literal)) support for date/time in the built-in functions. i want to implement some user-defined funcitons in the FILTER clause which can check time intervals in ontology. there are some functions about valid time in the WorkSpace Manager such as WM_OVERLAPS, WM_CONTAINS,WM_MEETS, etc. so, can i write some functions using the these valid time functions in WM and use them in the FILTER clause? thanks a lot in advance.
hongHi Hong,
You don't need user-defined functions to do time interval comparisons. You can directly compare xsd:dateTime values with the built-in comparison operators: <, >, =, !=, <=, >=
For example, the query pattern below could find events that happened during event1 if we have data such as:
:event1 :startTime "2013-01-01T03:15:00Z"^^xsd:dateTime .
:event1 :endTime "2013-02-01T02:15:00Z"^^xsd:dateTime .
:event2 :startTime "2013-01-11T14:15:00Z"^^xsd:dateTime .
:event2 :startTime "2013-01-14T12:15:00Z"^^xsd:dateTime .
SELECT ?e2
WHERE
{ :event1 :startTime ?e1_st; :endTime ?e1_et .
?e2 :startTime ?e2_st; endTime ?e2_et .
FILTER (?e1_st < ?e2_st && ?e2_et < ?e1_et) }
In general, it is trivial to convert interval relations such as meets and overlaps to conditions on start and end times.
Hope this helps.
- Matt -
How to use a user defined function in where cluase condition
Hi,
I have designed a query by selecting some columns in the tables and some columns are retrieved directly from table and some columns are passing to a user defined function. Now my requirement is i need to use that user defined function result in oracle where condition clause.
Ex : select marketing_user_id,get_name(marketing_user_id),item_id,get_item_name(item_id),get_country_name(country_id),
from
where get_item_name(item_id) in ('x','y','z')
and get_country_name(country_id) in ('India','America','China');
When am i trying the query by above format i am getting the wrong resultset.
BR,
umaI am not sure why your getting the wrong results but you should seriously reconsider the approach your are taking. Using functions like this is very ineffecient and should be avoided at all cost.
-
Where are User Defined Functions and Stored Procedures kept in SQL Server?
Hi,
I have a growing list of Stored Procedures and User-Defined Functions in SQL Server, and would like to be able to list all my user SP and UDF easily.
Is it possible to write a query to list all SP and UDF?
I saw the following specimen code in an SQL book, but am not sure this is what I need because I could not make it work.
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE SPECIFIC_SCHEMA = N'CustomerDetails'
AND SPECIFIC_NAME = N'apf_CusBalances'
I tried:
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
but it does not work.
Suppose all my SP are named following this pattern:
dbo.usp_Storeproc1
How would I modify the above code? or is there a better code?
Thanks
Leon LaiHi ,
try this to get list of all stored procedures:
SELECT *
FROM sys.procedures where name like 'dbo.usp%'
Thanks,
Neetu -
Find the Database where user defined function is ??
Hi,
I have one user defined function , but i couldn't find where the function is and where the function is using.. anyone pls help me to overcome this one.
ThanksHi again,
This is a combination of both previews response. I used
Latheesh's script to execute, but since sys.sql_expression_dependencie contains information in the current database, therefore I used
Praveen Rayan idea of using sp_MSforeachdb in order to check all databases (I used sp_MSforeachdb and not sp_foreachdb as I recomend to do usually).
DECLARE @ObjectName NVARCHAR(100)
SET @ObjectName = N'Ariely' --Give your function
Declare @MyQuery NVARCHAR(MAX) = N'
USE [?]
SELECT DISTINCT
SourceSchema = OBJECT_SCHEMA_NAME(sed.referencing_id)
,SourceObject = OBJECT_NAME(sed.referencing_id)
,ReferencedDB = ISNULL(sre.referenced_database_name, DB_NAME())
,ReferencedSchema = ISNULL(sre.referenced_schema_name,
OBJECT_SCHEMA_NAME(sed.referencing_id))
,ReferencedObject = sre.referenced_entity_name
FROM sys.sql_expression_dependencies sed
CROSS APPLY sys.dm_sql_referenced_entities(OBJECT_SCHEMA_NAME(sed.referencing_id) + ''.'' + OBJECT_NAME(sed.referencing_id), ''OBJECT'') sre
WHERE sed.referenced_entity_name like ''%' + @ObjectName + '%'' AND sre.referenced_entity_name like ''%' + @ObjectName + '%''
PRINT @MyQuery
EXEC sp_MSforeachdb @MyQuery
I hope that ths give you what you need :-)
[Personal Site] [Blog] [Facebook] -
Error encounter when calling function in where clause
I have created on e user define function.when i am trying to call in select statement it is working fine but when I try to call in where clause it gives me this
error
The following error has occurred:
ORA-06503: PL/SQL: Function returned without value
ORA-06512: at "KINTANA.COMPARE_DATE", line 33
suggest me possible solution
Thanks ChandaHi,
i am trying to call in select statement it is working fine but when I try to call in >>where clause it gives me this I am suspecting the same function call is working fine in SELECT and not in WHERE clause.
Please have a look:
1 CREATE OR REPLACE FUNCTION f1
2 RETURN NUMBER IS
3 BEGIN
4 return 1;
5 EXCEPTION
6 WHEN OTHERS THEN
7 return -1;
8* END;
SQL>/
Function created.
SQL>
SQL>SELECT f1 FROM DUAL;
F1
1
1 row selected.
SQL>SELECT sysdate FROM dual WHERE 1=f1;
SYSDATE
15-MAY-06
1 row selected.
"afiedt.buf" 10 lines, 140 characters
1 CREATE OR REPLACE FUNCTION f1
2 RETURN NUMBER IS
3 BEGIN
4 NULL;
5 EXCEPTION
6 WHEN OTHERS THEN
7 return -1;
8* END;
9 /
Function created.
SQL>SELECT f1 FROM dual;
SELECT f1 FROM dual
ERROR at line 1:
ORA-06503: PL/SQL: Function returned without value
ORA-06512: at "AVINASHT.F1", line 7
SQL>SELECT sysdate FROM dual where 1=f1;
SELECT sysdate FROM dual where 1=f1
ERROR at line 1:
ORA-06503: PL/SQL: Function returned without value
ORA-06512: at "AVINASHT.F1", line 7
SQL>DECLARE
2 a NUMBER ;
3 BEGIN
4 a := 0;
5 a := f1;
6 END;
7 /
DECLARE
ERROR at line 1:
ORA-06503: PL/SQL: Function returned without value
ORA-06512: at "AVINASHT.F1", line 7
ORA-06512: at line 5It would be better to understand if you post your function and how you are calling.
Regards -
Hi All,
Can anyone know how to use the user defined function in the where clause of the SQL statement.
Thanks in Advance,
Madhu N.Hi,
Boolean is a pls variable.. and cannot be used in a where clause returned from a function.
Simple can we define a variable of type boolean in sql*plus?
Rgds
Srinivas.. -
Converting the iif function in MS Access97 to an user defined function in Oracle
Hi ,
I have a problem here we are working with Visual Basic 6.0(ADOs 2.5) with Oracle 8i release 2. we have some queries stored in the tables which contains the iif function of MS Access 97 do we have a similar built in function in Oracle which replaces this iif function of Ms Access 97.
we cannot use decode (built in function) of oracle b'cos it cannot be used in a where clause and we cannot write a user defined function also because it cannot be generalized for use b'cos sometimes we use
field names and sometimes values as expression in the iif functions
If anybody could suggest me some idea
please mail me at [email protected]
with best regards
Jai<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Jai:
Hi ,
I have a problem here we are working with Visual Basic 6.0(ADOs 2.5) with
Oracle 8i release 2. we have some queries stored in the tables which contains the iif function of MS Access 97 do we have a similar built in function in Oracle which replaces this iif function of Ms Access 97.we cannot use DECODE (built in function) of oracle b'cos it cannot be used in a where clause and we cannot write a user defined function also because it cannot be generalized for use b'cos sometimes we use field names and
sometimes string values as expression in the iif functions. is there any other built in function ? can anybody suggest me some idea
please mail me at [email protected]
regards
Jai<HR></BLOCKQUOTE>
Hi,
You still can use the seccond approach - with a udf IIF() that you place in a package and OVERLOAD it. See the documentation for limitations of Overloading
Overloading permits you to declare several functions with the same name but havind different behaviours depending on the number and type of the parameters.
George -
About user defined function in user defined rule
Hi,
I am wondering if I can use a user defined function in a user defined rule in oracle sem.. I've seen examples of user defined function used in sparql query filter clause in that dev. guide. However, I don't know if I can define a function in oracle sem. database and use it in the rule body or head. For example, I want to define a duration function that calculate the date difference between two dates. Then, I want to define a rule like this: event1 :has_start_date d1 and event1: has_end_date d2 and duration (24, d1,d2) then event1:date_satisfiable "yes". Does oracle support this kind of rule? Thank you very much.
HongHi Hong,
The user defined rules are quite similar to a CONSTRUCT SPARQL query, where the FILTER clause is implemented in SQL.
I think we have already written rules like you want :
You have to write a PL/SQL FUNCTION that returns a NUMBER (not a BOOLEAN, think you are in SQL) :
FUNCTION DURATION(HOURS INTEGER, D1 VARCHAR2, D2 VARCHAR2) RETURN INTEGER
IS
BEGIN
IF(.................)
THEN RETURN 1;
ELSE RETURN 0;
END IF;
END;
Maybe you will have to GRANT EXECUTE ON DURATION TO MDSYS.
Then include the following in the FILTER clause of the Rulebase "[owner].duration (24, TO_CHAR(d1),TO_CHAR(d2)) = 1"
Hope this helps. -
Urgent Help Needed - Associating Statistics with User-Defined Functions
Hello,
We have an appication uses cost-based optimizer and uses a lot of TO_DATE and SYSDATE calls in FROM and WHERE clauses. For certain reasons, every call to TO_DATE and SYSDATE has been replaced by MY_TO_DATE and MY_SYSDATE respectively (which in turn call built-in functions). However, cost based optimizer is behaving strangely, which is understanble, based on the lack of user-defined functions statistics. I am under the impression that I should use something like:
ASSOCIATE STATISTICS WITH FUNCTIONS my_to_date DEFAULT SELECTIVITY ?;
ASSOCIATE STATISTICS WITH FUNCTIONS my_to_date COST (?,?,?);
ASSOCIATE STATISTICS WITH FUNCTIONS my_sysdate DEFAULT SELECTIVITY ?;
ASSOCIATE STATISTICS WITH FUNCTIONS my_sysdate COST (?,?,?);
but what should the values (?) be?. I guess I want to replicate TO_DATE and SYSDATE values, but how would I find out what they are? Thanks in advance...
P.S. I am also looking for workarounds (I cannot create a synonym for TO_DATE right?), so any help is welcome!!!Hi emmalou69 ,
You told your actual parameter is
5, 5, 7.3 and 'z'
so change your method like
public static int test(int x, int y, double d, char ch)
because 5 - int; 7.3- float or double; z is char.
your method returns
public static int.
so you should return only int variable. but in your code you mentioned double. it's not correct.
The original code should look like
public class rubbish
public static void main(String args[]){
rubbish f = new rubbish();
f.test(5, 5, 7.3 ,'z');
public static int test(int x, int y, double d, char ch)
int value;
x = 5;
y = 5;
d= 7.3;
ch = 'z';
value =((int) d + x + y + ch);
System.out.println( x + ch + d + y);
return value;
}//here int value of z is 122.
and int(7.3) is 7
so 7+5+5+122 = 139.3
but value =((int) d + x + y + ch); returns 139. because you convert double to int that is 7.3 to 7
If it is useful, rate me duke dollars,
Thanks -
Error in conditional map using User Defined Function
All,
In my mapping I basically have a user defined function that returns the filename of my inbound file from the adapter-specific message attributes (file adapter). I know this is coded properly because if I simply assign this function to my destination field I can see the filename in the payload XML.
However if I conditionally check that returned value using if,then,else I get an error message stating:
"During the application mapping com/sap/xi/tf/_MaterialData2ZcustProdMastMulti_ a com.sap.aii.utilxi.misc.api.BaseRuntimeException was thrown: RuntimeException in Message-Mapping transformation"
Essentially in my if I'm checking if the value returned by my user defined function is equal to the constant "SOMECONSTANT" then I'm setting my destination field to some other constant value. Otherwise it's equal to a different constant value.
Any thoughts?Claus,
Thanks for the help. I actually had figured the problem out on my own. Sorry for not updating the thread sooner. What happened was this (as I suspected it wasn't related to my user defined function). For the newbies out there (of which I'm one) the problem was I was comparing strings in the graphical mapping tool using the Boolean "EQUALS" rather than the Text "EQUALSS".
Can you give yourself points for solving -
User Defined Function VS join - Performance....
Hi All,
while linking the mulitple table and getting the values ....which one is the best ?
Joining or User defined function.....
single row function
select a.name , get_salary(empid) from emp a;
Note : get_salary function will return the salary from salary tables.
Using joins
select a.name ,b.salary from emp a, salary b
where a.empid=b.empid;
which is the performancewise best ?
also if you give any related document also fine.
Thanks in advance.
Edited by: BASKAR NATARAJAN on Jan 6, 2011 10:09 PMDon't use such functions for joins. The function itself has to query the salary table. It will run the query against the salary table separately for each row that it reads from the emp table. You will end up with multiple recursive calls and possibly inconsistency in the output. (Imagine what would happen if the salary table were updated and commited while this query was running -- some rows would have been read with the pre-update values and others with the updated values).
Specifying the join in the query ensures that a single SQL call is executed and provides read consistency across all the rows it reads. And it is much faster, being one single parse and execute.
Hemant K Chitale
http://hemantoracledba.blogspot.com
Maybe you are looking for
-
Help - iPod not playing purchased songs.
For some reason, my iPod is no longer playing songs that I have purchased through iTunes. I can get music from CDs to play fine, but when I put a purchased tune on there, it simply displays the song, then skips it. If I put all purchased songs in one
-
New 'resume' feature not working properly
Hi All! As there does not seem to be a manual for Lion, I am hoping someone can answer the following questions for me: I have assigned various applications to different desktops (spaces). Unfortunately, after a system restart, these are not restored
-
Problem in importing two different classes with same name...
I have to import two different classes in my program with the same name.... import org.apache.lucene.document.Document; import org.w3c.dom.Document; // I AM USING THE DOCUMENT FROM W3C PACKAGE HERE.... DocumentBuilderFactory factory = DocumentBuil
-
Scanning not working b/c ICMP or SNMP is blocked?
I'm having a terrible time getting scanning over the network functioning on 10.6.1 with my Brother printer/scanner. (Printing works fine.) Because scanning works over USB, I suspected something was being blocked by the Mac. I turned of the firewall a
-
@[at]- Button doesn't work with the normal shortcut alt+L
A few days ago my MBP, MacOS 10.8.4 doesn't wrote the @ with the shortcut alt+L. I have to press ctrl+alt+L to write it. Is there any Option to bring back the old shortcut alt+L? I have the same thing with the €-Button. Thanks for helping me. Cheerz