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

Similar Messages

  • 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,
    uma

    I 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.

  • 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,
    Prashant

    Hello 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 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.

  • 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 Arnswald

    Hello 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 MV

    Hello All,
    Can we have user defined function in the select clause of a materializied view.
    I am aware that we cannot have subquery in the select clause of MV.
    Regards,
    Kumar.

    That's not hard to test ...
    SQL> create function f return varchar2
      2  is
      3  begin
      4    return 'I''m from function f';
      5  end;
      6  /
    Functie is aangemaakt.
    SQL> create materialized view my_mv
      2  as
      3  select empno
      4       , ename
      5       , f
      6    from emp
      7  /
    Gematerialiseerde view is aangemaakt.
    SQL> column f format a30
    SQL> select * from my_mv
      2  /
         EMPNO ENAME      F
          7369 SMITH      I'm from function f
          7499 ALLEN      I'm from function f
          7521 WARD       I'm from function f
          7566 JONES      I'm from function f
          7654 MARTIN     I'm from function f
          7698 BLAKE      I'm from function f
          7782 CLARK      I'm from function f
          7788 SCOTT      I'm from function f
          7839 KING       I'm from function f
          7844 TURNER     I'm from function f
          7876 ADAMS      I'm from function f
          7900 JAMES      I'm from function f
          7902 FORD       I'm from function f
          7934 MILLER     I'm from function f
    14 rijen zijn geselecteerd.If you want the materialized view to be fast refreshable, then the answer is no.
    Regards,
    Rob.

  • 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.
    hong

    Hi 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

  • 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 Lai

    Hi ,
    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.
    Thanks

    Hi 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]

  • 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.
    Hong

    Hi 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 PM

    Don'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

  • Using a User Defined Function as a constraint within a temporary table.

    Hello, 
    I am trying to create a temp table that uses a UDF in a constraint. I'm getting the following error message 
    Msg 4121, Level 16, State 1, Line 1
    Cannot find either column "dbo" or the user-defined function or aggregate "dbo.CK_LoseTeamSportExists", or the name is ambiguous.
    I've tested the function and it works in other contexts. Any idea? All code below:  
    Thanks, 
    - Bryon
    create function dbo.CK_LoseTeamSportExists (@loseteam int, @sportid int)
    returns bit
    as
    begin
    declare @return bit
    if exists 
    select TeamID, sportid from Link_TeamSport
    where 
    TeamID = @loseteam 
    and
    SportID = @sportid
    set @return = 1
    else set @return = 0
    return @return
    end
    go
    create table #check
    SportID int
    ,WinTeamID int
    ,LoseTeamID int
    ,check 
    (dbo.CK_LoseTeamSportExists(LoseTeamID,SportID) = 1)

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    >> I am trying to create a temp table that uses a UDF in a constraint. <<
    You do not understand how SQL or any declarative language works! 
    We do not use UDFs (procedural programming)
    We do not use bit flags (assembly language).
    We do not use temp tables (mag tape files).
    We do not use integer as identifiers (what math do you do on them?)
    Your silly “Link_TeamSport” implies a pointer chain; we have no links in SQL. Where is the DDL? 
    Constraints are always predicates in any declarative language. 
    Do you know why you have to create a local variable to pass the non-relational flag back to the calling environment? FORTRAN I and II! These early languages has to use hardware registers in the first IBM computers to return results. In your ignorance, you mimic
    them! 
    We do not use if-then-else control flow in any declarative language. We have CASE expressions that we put where you have a local variable getting an assignment. 
    I see you also put the comma at the start of the line. We did that with punch cards, so we could re-use them 50 years ago. 
    In SQL, we would use REFERENCES to assure a team reference exists. We use names for teams because they are entities, not quantities: 
    CREATE TABLE Game_Results
    (sport_name CHAR(10) NOT NULL PRIMARY KEY,
     win_team_name CHAR(12) NOT NULL
      REFERENCES Teams(team_name)
       ON DELETE CASCADE,
     lose_team_name CHAR(12) NOT NULL
      REFERENCES Teams(team_name)
       ON DELETE CASCADE,
     CHECK (win_team_name <> lose_team_name)); 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

Maybe you are looking for