SQL Function

Hi,
I have built a query
select
EAUT_PCP_ID,count(*) a from EHTH_AUTH_REQMOD
group by EAUT_PCP_ID
order by count(*) desc
and the output comes somewhat like this
P001 4
P002 2
P003 1
P004 1
Can someone please help me in modifying the above query so that it returns me only the maximum of the count(4 in above case)

I. With in PL/SQL Block, you could use
to_number(str1) function, but if the string contains ALPHABETS or NON-NUMERIC characters, it would raise an error,
ERROR:
ORA-01722: invalid number
Then you would catch the error in exception and conclude that it is a non-numeric value.
II. You can also do the following,
Decode(Upper(str1), Lower(str1), 'NUMERIC',
'STRING') from Dual; -- This is what you asked for
Decode(Upper(str1), Lower(str1), to_number(str1),
NULL) from Dual; -- U could extend the usage this way
Thanks,
Sri DHAR

Similar Messages

  • Report- Pl/sql function returning sql query parsing page items as text?

    Hi Team,
    I am facing a strange issue .
    I have four page items namely
    1)JOB_CODE
    2)MIN_EXP
    3) MAX_EXP
    4) SOURCES1
    I have a report of the type "Pl/sql function returning sql query"
    declare
    v_sql varchar2(4000);
    begin
    if (:JOB_CODE IS NOT NULL and :MIN_EXP IS NOT NULL and :MAX_EXP IS NOT NULL and :SOURCES1 IS NOT NULL) then
    v_sql:= 'select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where V_REQUIREMENT = :JOB_CODE and v_experience_years >= :MIN_EXP and v_experience_years <= :MAX_EXP and source like ' || '''' || '%'|| ':SOURCES1' || '%' || '''';
    elsif (:JOB_CODE IS NULL and :MIN_EXP IS NOT NULL and :MAX_EXP IS NOT NULL and :SOURCES1 IS NOT NULL) then
    v_sql := 'select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where v_experience_years >= :MIN_EXP and v_experience_years <= :MAX_EXP and source like ' || '''' || '%'|| ':SOURCES1' || '%' || '''';
    elsif (:MIN_EXP IS NULL and :JOB_CODE IS NOT NULL and :MAX_EXP IS NOT NULL and :SOURCES1 IS NOT NULL) then
    v_sql := 'select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where v_experience_years <= :MAX_EXP and V_REQUIREMENT = :JOB_CODE and source like ' || '''' || '%'|| ':SOURCES1' || '%' || '''';
    elsif (:MAX_EXP is null and :JOB_CODE IS NOT NULL and :MIN_EXP IS NOT NULL and :SOURCES1 IS NOT NULL) then
    v_sql := 'select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where V_REQUIREMENT = :JOB_CODE and v_experience_years >= :MIN_EXP and source like ' || '''' || '%'|| ':SOURCES1' || '%' || '''';
    end if;
    insert into query_list values (v_sql);
    insert into debug values (:JOB_CODE , :MIN_EXP , :MAX_EXP , :SOURCES1);
    return v_sql;
    end;
    Please not that I am insertin the query into a table called Query_list and the page item values into the table called Debug thru the pl/sql function which returns teh query.
    Now I select the data from the debug tables.
    select unique(query) from query_list;
    select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where V_REQUIREMENT = :JOB_CODE and v_experience_years >= :MIN_EXP and v_experience_years <= :MAX_EXP and source like '%:SOURCES1%'
    select * from debug;
    JOBCODE     MINEX     MAXEX     SOURCE
    21     1     10     donkeyHire
    And if I run the query in sql I get some records returned
    select v_candidate_id, v_fname,v_current_employer,v_Experience_years from candidature where V_REQUIREMENT = 21 and v_experience_years >= 1 and v_experience_years <= and source like 'donkeyHire'
    V_CANDIDATE_ID     V_FNAME     V_CURRENT_EMPLOYER     V_EXPERIENCE_YEARS
    2     Vengu     Andale Tech     4
    But the record does not show up in the report!
    does this type of report parse page items as text?
    Why is it so?
    Waiting for an early reply.
    Thanks,
    venkat

    Venkat - You don't want to put ':SOURCES1' in quotes like that.
    Scott

  • Passing Multiple Values from a worksheet to PL/SQL function.

    Hi All,
    Is there any way to pass multiple values selected in a worksheet to a PL/SQL function ?
    I will try to explain the scenario:
    We have a crosstab report that showing all the customer details, deposit sum of a customer in each date in a date range selected. With the customer details we are showing the Rank of a customer based on the deposit in the latest date selected. Filtering is based on the rank, ie Top50 or Top60 etc.( As I said rank is calculating based on the deposit in the latest date).This is working fine.
    Now the new requirement is to : For example, in Top50 report, list all the customers, who were in the Top50 list, in any of the dates selected. We are able to display the daywise rank, but when giving a condition like daywiserank <= 50, the result becomes uncertain. Some blank lines, wrong amounts etc..
    As a work around we tried to find out the rank in a PL/SQL function. But the issue there is : we have some multiple value parameters used in the worksheet.
    Is there any way to pass multiple values selected in a worksheet to a PL/SQL function ?
    Or any other work arounds for the scenario explained?
    Reagrds,
    Jeneesh

    Hi Russ,
    Thanks for the response.
    Russ Proudman wrote:
    1. I thought there was an analytical function similar to rank - or maybe an option of rank - that if there are duplicate records to have them all considered the same rank. So if you had 3 records all the same as rank=2 then a condition saying where rank=2 would return the 3 records. You could check into this.
    We are already using DENSE_RANK. But the issue is the output contains incorrect null values nd repeated rows.
    We got it solved as I explained in the previous post. But will that AGGREGATION MODE setting ( Which discoverer says - not recommended) have any issue? I mean side effects?
    Russ Proudman wrote:
    2. Another thought is that you can create a PL/SQL routine - that's called from a SQL function registered in Discoverer - where a table is created that does the first part of your query. Then a worksheet is created to use the data from that table. So, in essence, the table would have your top50 ranked customers. Then you can write any kind of worksheet against that table. However, DBAs are loath to allow tables - that they didn't create! - many times in a PROD environment.
    Here also the same problem will occur: as the top 50 will depend upon the parameters. I cannot pass those parameters to PL/SQL Function.And storing the top50 ( itmay be top100 or to 150 also) for all combinations of the parameters is impossible
    Russ Proudman wrote:
    3. Finally, are you sure you're rank function is correct in that if you're getting blank lines, maybe the 'over' part is not considering all columns needed to determine the rank?
    Yes the query we are using is correct. The output QUERY of discoverer gives correct results in Sqlplus.
    Regards,
    Jeneesh

  • Show refcursor returned by a PL/SQL function ?

    Is it possible to show the results returned by a
    PL/SQL function that returns a refcursor ?
    In sqlplus it goes like this:
    SQL> variable a refcursor;
    SQL> execute :a := p_front.get_invoice_list;
    PL/SQL procedure successfully completed.
    SQL> print a;
    INVOICE_ID CLIENT_ID INVOICE_D
    101 100 01-APR-06
    100 100 06-APR-06
    If not, this would be on the top of my wishlist...
    By the way: you did a good job on this tool!
    Regards,
    Willem

    Is it possible to show the results returned by a
    PL/SQL function that returns a refcursor ?
    In sqlplus it goes like this:
    SQL> variable a refcursor;
    SQL> execute :a := p_front.get_invoice_list;
    PL/SQL procedure successfully completed.
    SQL> print a;
    INVOICE_ID CLIENT_ID INVOICE_D
    101 100 01-APR-06
    100 100 06-APR-06
    If not, this would be on the top of my wishlist...
    By the way: you did a good job on this tool!
    Regards,
    Willem

  • Application Report Missing PL/SQL Functional Area

    All,
    I just wanted to bring to the ApEx developers something I just noticed... I use the Shared Components > Database Object Dependencies report to make sure all is well before moving applications into production.
    The Parsing Errors feature of that report is WONDERFUL! But it seems to be overlooking buttons that use a conditional display based on PL/SQL Function Body Returning a Boolean.
    Dan

    Hi Dan,
    I think the place is perfect, but I read once somewhere that "Bug" or "Bug Report" should be in the subject so that's easier to find for the Oracle guys.
    Patrick
    My APEX Blog: http://inside-apex.blogspot.com
    The ApexLib Framework: http://apexlib.sourceforge.net
    The APEX Builder Plugin: http://sourceforge.net/projects/apexplugin/

  • Interactive report from PL/SQL function

    Hello All,
    i have a pl/sql function that dynamically builds up a sql query and returns it as a varchar2.
    when i create a new report then i can use this function in the report like
    return f_function(param1,param2,v('APP_ID'), v('APP_SESSION'));
    and this works fine.
    Except i cannot create an interactive report for this function, because it is not allowed !!!!
    So how can i use the function in an interactive report ?
    Thanks in advance,
    Marco

    Marco,
    Another rather extreme approach would be to go all the way and make your function pipelined (that is not only build but also execute the query) and then select from it in your interactive report.
    The disadvantage here would be that any supplementary filtering would act on the result set of the function (not as an addition to the where clause of the original query). But if you can live with that...
    The advantage would be that there's less fiddling with column headers.
    Regards,
    Iulian

  • Interactive Report with PL/SQL Function Source

    Is it possible to create interactive report with PL/SQL function source returing a query? If not, has anyone done any work to simulate the interactive reporting feature for a normal report using API?

    I haven't tried that before but you could:
    1. create a collection from your result set returned by a dynamic query,
    2. create a view on that collection,
    3. use the view in your interactive report.
    The usability of this proposal depends from a question how "dynamic" your query is - does it always have the same number of columns or not.
    Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://www.opal-consulting.de/training
    http://apex.oracle.com/pls/otn/f?p=31517:1
    -------------------------------------------------------------------

  • How to call a SQL function from an XSL expression

    Hi
    In R12, in Payroll Deposit adivce/Check writer, We need to sort the earnings tag <AC_Earnings> in to two different categories as regular and other earnings. In the DB and form level of element defintiion we have a DFF which differentiates between the two kinds of earnings. But the seeded XML that is gerneated by the check writer does not have this field.
    The seeded template displays all the earnings in one column. How can we achieve this in the template without modifying the seeded XML.
    The one approach i have is to write a function and based on the return value sort the data. For this I need to know :
    1) How to call a SQL function from an XSL expression that is allowed in BI template.
    If anyone ahs faced similar requirements please share your approach.
    Thanks
    Srimathi

    Thank u..
    but i'd seen that link wen i searched in google..
    Is it possible without using any 3rd party JARs and all?
    and more importantly plz tell me what should be preferred way to call a javascript function?
    Do it using addLoadEvent() or Windows.Load etc
    OR
    Call it thru Xsl? (I donno how to do dis)
    Thanks in Advance..
    Edited by: ranjjose on Jun 3, 2008 8:21 AM

  • SQL report region source to call a pl/sql function using DB link

    Hi - I have a pl/sql function fn_dbtype(id NUMBER) defined in database X. The pl/sql function executes couple DML statements and returns a string (a SELECT query). I am able to call this function using SQL Plus (Connected to Database X) as below and it works fine:
    declare
    vSQL VARCHAR2(100);
    begin
    vSQL := fn_dbtype(1);
    end;
    The DML operations completed fine and vSQL contains the "Select" query now.
    In APEX:
    I am trying to create a SQL report in APEX using SQL query(PL/SQL function returning a sql statement) option. I am trying to figure out what to put in the region source so that the output of the "Select" query is displayed in the report.
    Moreover APEX is hosted in a different database instance. So I would need to call this pl/sql function using a DB Link.
    Please let me know what I need to put in the region source to execute the pl/sql function which returns the "Select" query thereby displaying the query output in the report. Thanks.
    Edited by: user709584 on Mar 19, 2009 2:32 PM
    Edited by: user709584 on Mar 19, 2009 2:34 PM

    try something like this:
    return fn_dbtype(1)@dblink;

  • Problem to create a link with parameters using a PL/SQL function body

    Hi everybody,
    I need some help to create a link on a SELECT statement.
    I have a region report with type "PL/SQL function body return SQL query".
    I would like to use a link using HTML tag <a href>.
    I know how to do the link, but I don't know to pass a parameters in <a href> statement.
    Always I tried it doesn't work well.
    My PL/SQL anonimous block is, (just with link) :
    DECLARE
    q vARCHAR2(4000);
    BEGIN
    q:='select     "INDICADOR"."NRINDICADOR" as "NRINDICADOR",';
    q:=q||'     "INDICADOR"."DSINDICADOR" as "DSINDICADOR",';
    q:=q||'''<span style="font-weight:bold;">';
    q:=q||'''||TO_CHAR("TOTAL_INDICADOR"."VL_INDICADOR", ''999G999G999G990D00'')||''</span>''';
    q:=q||' as "VL_INDICADOR",';
    q:=q||'     "TOTAL_INDICADOR"."VL_META" as "VL_META" ';
    q:=q||' from     "TOTAL_INDICADOR" "TOTAL_INDICADOR",';
    q:=q||'     "INDICADOR" "INDICADOR" ';
    q:=q||' where "INDICADOR"."NRINDICADOR"="TOTAL_INDICADOR"."NR_INDICADOR"';
    RETURN q;
    END;
    Thanks for any help,
    Alessandra

    Your code is in a default value for an item, right?
    You need to make sure :P33_YEAR is not null and handle the error in the PL/SQL if it is.
    How is P33_YEAR populated? do you pass it in? check to see if it is making it there..
    Message was edited by:
    Bill Carlisle

  • Problem with empty report parameters when passed to PL/SQL function

    Hi,
    We have come across what appears to be a bug in the JRC. When passing a report parameter to a PL/SQL function as a parameter, empty parameters are changed before being sent to the function. More specifically, an empty string "" ends up as the value "(')" in the PL/SQL function parameter. In our report we print the report parameters on the first page so we know that the parameters are OK before being passed to the database.
    The problem exists for version 12.2.203, 12.2.204 and 12.2.205 of the JRC.
    We have identified a workaround, but it is not exactly elegant: Before executing the report we modify all empty  parameters ("") to " " . In the PL/SQL function, we trim all parameters before using them.
    We call the function using a command object with a sql syntax like this example:
    select * from table (qa_batch_release.get_qa_br('{?p_report_id}','{?p_reg_set_number}','{?p_cr_number}','{?p_change_id_decode}','{?p_country_id}','{?p_mfg_item_no}','{?p_4_no}','{?p_5_no}','{?p_7_no}'))
    The PL/SQL function is a table returning function.
    Best regards, Thor

    Hi Kishore,
    using #COLUMN_VALUE# would probably not make much sense, because normally a report has multiple columns and not just the numeric column which you want to verify if it's negative. But APEX will fire the template condition for each column, because the report template is a column cell template.
    What you can do to make it more generic is to use for example
    #CHECK_AMOUNT#
    in the template and provide a not displayed column in your SQL statement which contains your value which is named CHECK_AMOUNT. For example:
    SELECT NAME
         , BALANCE
         , BALANCE AS CHECK_AMOUNT
    FROM XXX;Because this CHECK_AMOUNT column would be a generic name, you can use this template in all your reports as long as you provide this column.
    Thope that helps
    Patrick

  • Passing #COLUMN_VALUE# as parameter to pl/sql function in column template

    Hi all,
    I want to color negative amounts in red in sql report using column template.
    I created a pl/sql function"isNegativeNum" which returns 1 or -1.
    create or replace function isNegativeNum(p_column_value varchar2) return number
    as
    l_dummy number;
    begin
          l_dummy := to_number(p_column_value,'999G999G990D00PR');
          IF l_dummy < 0
             THEN
                RETURN 1;
          else
                return -1;
          END IF;
    exception
    when others then
       RETURN -1;
    end;Below is column template.
    Column Template 1
    <td class="t3dataalt" #ALIGNMENT#><p color=red>#COLUMN_VALUE#</p></td>Column Template 1 Condition
    isNegativeNum('#COLUMN_VALUE#') = -1The issue is #COLUMN_VALUE# value is not being passed to the function, Insert statement in function reveals p_column_value as a string "#COLUMN_VALUE#". When I try without quotes like isNegativeNum(#COLUMN_VALUE#) = -1, I get below error.
    ORA-06550: line 1, column 48: PLS-00103: Encountered the symbol "#" when expecting one of the following: ( ) - + case mod new not null others select table avg count current exists max min prior sql stddev sum variance execute multiset the both leading trailing forall merge year month DAY_ hour minute second timezone_hour timezone_minute timezone_region timezone_abbr time timestamp interval date
         Error      ERR-1025 Error processing PLSQL expression. isNegativeNum(#COLUMN_VALUE#) = 1
    Any help is appreciated.
    Kishore

    Hi Kishore,
    using #COLUMN_VALUE# would probably not make much sense, because normally a report has multiple columns and not just the numeric column which you want to verify if it's negative. But APEX will fire the template condition for each column, because the report template is a column cell template.
    What you can do to make it more generic is to use for example
    #CHECK_AMOUNT#
    in the template and provide a not displayed column in your SQL statement which contains your value which is named CHECK_AMOUNT. For example:
    SELECT NAME
         , BALANCE
         , BALANCE AS CHECK_AMOUNT
    FROM XXX;Because this CHECK_AMOUNT column would be a generic name, you can use this template in all your reports as long as you provide this column.
    Thope that helps
    Patrick

  • Passing parameters to PL/SQL function called in VO

    Hi,
    I am writing a VO that is calling a PL/SQL function. The VO query looks like this.
    select xx_dummy_func (:1,:2) from dual
    Now, how can I assign these two parameter values at run time?
    Generally when we have a query parameters We do xxVO.setwhereclauseparam. But in the above scenario, its not a whereclause but instead a procedure parameter. Please let me know how to do it.
    Thanks in advance,
    Regards,
    -Abm

    Thats correct, basically, setwherecaluse param api, just replaces bind variables with the index values, whereever they are in the query!
    --Mukul                                                                                                                                                                                                                                                                                                                                                       

  • PL/SQL function body returning SQL - report error:ORA-01403: no data found

    Hi,
    I am working on Application Express 4.0.2.00.06, and 11G database.
    I have a problem with classic report area of type - PL/SQL function body returning SQL query. Query works if I define region area as - Use Generic Column Names (parse query at runtime only), and does not when I define it - Use Query-Specific Column Names and Validate Query.
    I am getting error:
    report error:ORA-01403: no data found
    This is my query that is returned from function, and displayed with htp.p, and it works ok and returns data in SQL Developer and SQL Workshop (in Apex).
    <code>
    /* select 1 from dual */ SELECT SIFPRO, NAZIV, VODITELJ, DATPZA,SUM(DECODE(TJEDAN,'2010/46',BRDJEL,null)) as "2010/46" ,SUM(DECODE(TJEDAN,'2010/49',BRDJEL,null)) as "2010/49" ,SUM(DECODE(TJEDAN,'2010/50',BRDJEL,null)) as "2010/50" ,SUM(DECODE(TJEDAN,'2010/51',BRDJEL,null)) as "2010/51" ,SUM(DECODE(TJEDAN,'2010/52',BRDJEL,null)) as "2010/52" ,SUM(DECODE(TJEDAN,'2011/01',BRDJEL,null)) as "2011/01" ,SUM(DECODE(TJEDAN,'2011/02',BRDJEL,null)) as "2011/02" ,SUM(DECODE(TJEDAN,'2011/03',BRDJEL,null)) as "2011/03" ,SUM(DECODE(TJEDAN,'2011/04',BRDJEL,null)) as "2011/04" ,SUM(DECODE(TJEDAN,'2011/05',BRDJEL,null)) as "2011/05" ,SUM(DECODE(TJEDAN,'2011/06',BRDJEL,null)) as "2011/06" ,SUM(DECODE(TJEDAN,'2011/07',BRDJEL,null)) as "2011/07" ,SUM(DECODE(TJEDAN,'2011/08',BRDJEL,null)) as "2011/08" ,SUM(DECODE(TJEDAN,'2011/09',BRDJEL,null)) as "2011/09" ,SUM(DECODE(TJEDAN,'2011/10',BRDJEL,null)) as "2011/10" FROM (SELECT * FROM PMV_PLAN_TVRTKA) GROUP BY SIFPRO, NAZIV, VODITELJ, DATPZA ORDER BY SIFPRO, NAZIV, VODITELJ, DATPZA
    </code>
    As you can see, I even tried with workaround that I found on the previous post on the forum, and that is to put /* select 1 from dual */ to start query.
    Any help would be appriciated.

    /* select 1 from dual */ SELECT SIFPRO, NAZIV, VODITELJ, DATPZA,SUM(DECODE(TJEDAN,'2010/46',BRDJEL,null)) as "2010/46" ,SUM(DECODE(TJEDAN,'2010/49',BRDJEL,null)) as "2010/49" ,SUM(DECODE(TJEDAN,'2010/50',BRDJEL,null)) as "2010/50" ,SUM(DECODE(TJEDAN,'2010/51',BRDJEL,null)) as "2010/51" ,SUM(DECODE(TJEDAN,'2010/52',BRDJEL,null)) as "2010/52" ,SUM(DECODE(TJEDAN,'2011/01',BRDJEL,null)) as "2011/01" ,SUM(DECODE(TJEDAN,'2011/02',BRDJEL,null)) as "2011/02" ,SUM(DECODE(TJEDAN,'2011/03',BRDJEL,null)) as "2011/03" ,SUM(DECODE(TJEDAN,'2011/04',BRDJEL,null)) as "2011/04" ,SUM(DECODE(TJEDAN,'2011/05',BRDJEL,null)) as "2011/05" ,SUM(DECODE(TJEDAN,'2011/06',BRDJEL,null)) as "2011/06" ,SUM(DECODE(TJEDAN,'2011/07',BRDJEL,null)) as "2011/07" ,SUM(DECODE(TJEDAN,'2011/08',BRDJEL,null)) as "2011/08" ,SUM(DECODE(TJEDAN,'2011/09',BRDJEL,null)) as "2011/09" ,SUM(DECODE(TJEDAN,'2011/10',BRDJEL,null)) as "2011/10" FROM (SELECT * FROM PMV_PLAN_TVRTKA) GROUP BY SIFPRO, NAZIV, VODITELJ, DATPZA ORDER BY SIFPRO, NAZIV, VODITELJ, DATPZA

  • PL/SQL function body returning SQL query - ORA-06502: PL/SQL: numeric or value error

    I'm attempting to dynamically generate a rather large SQL query via the "PL/SQL function body returning SQL query" report region option.  The SQL query generated will possibly be over 32K.  When I execute my page, I sometimes receive the "ORA-06502: PL/SQL: numeric or value error" which points to a larger than 32K query that was generated.  I've seen other posts in the forum related to this dynamic SQL size limitation issue, but they are older (pre-2010) and point to the 32K limit of the DNS (EXECUTE IMMEDIATE) and DBMS_SQL.  I found this post (dynamic sql enhancements in 11g) which discusses 11g no longer having the 32K size limitation for generating dynamic SQL.  Our environment is on 11gR2 and using ApEx 4.2.1.  I do not know which dynamic SQL method -- DNS or DBMS_SQL -- ApEx 4.2.1 is using.  Can someone clarify for me which dynamic SQL method ApEx uses to implement the "PL/SQL function body returning SQL query" option?
    As a test, I created a page on apex.oracle.com with a report region with the following source:
    declare
      l_stub varchar2(25) := 'select * from sys.dual ';
      l_sql  clob := l_stub || 'union all ';
      br     number(3) := 33;
    begin
      while length ( l_sql ) < 34000 loop
        l_sql := l_sql || l_stub || 'union all ';
      end loop;
      l_sql := l_sql || l_stub;
      for i in 1 .. ceil ( length ( l_sql ) / br ) loop
        dbms_output.put_line ( dbms_lob.substr ( l_sql, br, ( ( i - 1 ) * br ) + 1 ) );
      end loop;
      return l_sql;
    end;
    The dbms_output section is there to be able to run this code in SQL*Plus and confirm the size of the SQL is indeed larger than 32K.  When running this in SQL*Plus, the procedure is successful and produces a proper SQL statement which can be executed.  When I put this into the report region on apex.oracle.com, I get the ORA-06502 error.
    I can certainly implement a work-around for my issue by creating a 'Before Header' process on the page which populates an ApEx collection with the data I am returning and then the report can simply select from the collection, but according to documentation, the above 32K limitation should be resolved in 11g.  Thoughts?
    Shane.

    What setting do you use in your report properties - especially in Type and in Region Source?
    If you have Type="SQL Query", then you should have a SELECT statement in the Region Source. Something like: SELECT .... FROM ... WHERE
    According to the ERR-1101 error message, you have probably set Type to "SQL Query (PL/SQL function body returning SQL query)". In this situation APEX expects you to write a body of a PL/SQL function, that will generate the text of a SQL query that APEX should run. So it can be something like:
    declare
    mycond varchar2(4000);
    begin
    if :P1_REPORT_SEARCH is not null THEN
    mycond:='WHERE LAST_NAME like :P1_REPORT_SEARCH ||''%''';
    end if;
    return 'select EMPLOYEE_ID, FIRST_NAME, LAST_NAME from EMPLOYEES ' ||mycond;
    end;
    And for escaping - are you interested in escaping the LIKE wildcards, or the quotes?
    For escaping the wildcards in LIKE function so that when the user enters % you will find a record with % and not all functions, look into the SQL Reference:
    http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/conditions007.htm
    (You would than need to change the code of your function accordingly).
    If you are interested in escaping the quotes, try to avoid concatenating the values entered by the user into the SQL. If you can, use bind variables instead - as I have in my example above. If you start concatenating the values into the text of SQL, you are open to SQLInjection - user can enter anything, even things that will break your SQL. If you really need to allow users to choose the operator, I would probably give them a separate combo for operators and a textfield for values, than you could check if the operator is one of the allowed ones and create the condition accordingly - and than still use bind variable for inserting the filtering value into the query.

  • PL/SQL function. ORA-00933: SQL command not properly ended

    This is my first attempt at pl/sql functions with dynamic sql. It will compile, but when I try to test it I get the ORA-00933 error at line 147. line 147 is OPEN retval FOR report_query;
    Please take a look and let me know what it wrong! thanks
    {CREATE OR REPLACE FUNCTION TSARPTS.Stats (v_Hub       IN VARCHAR2,
                                              v_type      IN VARCHAR2,
                                              v_subtype   IN VARCHAR2)
       RETURN SYS_REFCURSOR
    IS
       retval           SYS_REFCURSOR;
       report_query_a   VARCHAR2 (10000)
                           := '
      SELECT hub,
             CASE
                WHEN Total = 0 OR Pass_1st = 0 THEN 0
                ELSE ROUND (Pass_1st / (Total) * 100, 2)
             END
                AS Pass_1st_percent,
             CASE
                WHEN Total = 0 OR Pass_2nd = 0 THEN 0
                ELSE ROUND (Pass_2nd / (Total) * 100, 2)
             END
                AS Pass_2nd_percent,
             CASE
                WHEN Total = 0 OR Pass_3rd = 0 THEN 0
                ELSE ROUND (Pass_3rd / (Total) * 100, 2)
             END
                AS Pass_3rd_percent,
             CASE
                WHEN Total = 0 OR DNM = 0 THEN 0
                ELSE ROUND (DNM / (Total) * 100, 2)
             END
                AS DNM,
             CASE
                WHEN Total = 0 OR Incomplete = 0 THEN 0
                ELSE ROUND (Incomplete / (Total) * 100, 2)
             END
                AS Incomplete
        FROM (  SELECT hub,
                       SUM (DECODE (result, ''Pass_on_1st'', 1, 0)) Pass_1st,
                       SUM (DECODE (result, ''Pass_on_2nd'', 1, 0)) Pass_2nd,
                       SUM (DECODE (result, ''Pass_on_3rd'', 1, 0)) Pass_3rd,
                       SUM (DECODE (result, ''DNM'', 1, 0)) DNM,
                       SUM (DECODE (result, ''INCOMPLETE'', 1, 0)) Incomplete,
                         SUM (DECODE (result, ''Pass_on_1st'', 1, 0))
                       + SUM (DECODE (result, ''Pass_on_2nd'', 1, 0))
                       + SUM (DECODE (result, ''Pass_on_3rd'', 1, 0))
                       + SUM (DECODE (result, ''DNM'', 1, 0))
                       + SUM (DECODE (result, ''INCOMPLETE'', 1, 0))
                          Total
                  FROM employees_vw a, pse_vw b
                 WHERE     a.emplid = b.emplid
                       AND status IN (''S'', ''I'', ''N'')
                       AND TYPE = ''PSE''
       report_query_b   VARCHAR2 (10000)
                           := ' 
    SELECT hub,
           TYPE,
           subtype,
           CASE
              WHEN Total = 0 OR Pass_1st = 0 THEN 0
              ELSE ROUND (Pass_1st / (Total) * 100, 2)
           END
              AS Pass_1st_percent,
           CASE
              WHEN Total = 0 OR Pass_2nd = 0 THEN 0
              ELSE ROUND (Pass_2nd / (Total) * 100, 2)
           END
              AS Pass_2nd_percent,
           CASE
              WHEN Total = 0 OR Pass_3rd = 0 THEN 0
              ELSE ROUND (Pass_3rd / (Total) * 100, 2)
           END
              AS Pass_3rd_percent,
           CASE
              WHEN Total = 0 OR DNM = 0 THEN 0
              ELSE ROUND (DNM / (Total) * 100, 2)
           END
              AS DNM,
           CASE
              WHEN Total = 0 OR Incomplete = 0 THEN 0
              ELSE ROUND (Incomplete / (Total) * 100, 2)
           END
              AS Incomplete
      FROM (  SELECT hub,
       TYPE,
           subtype
                      SUM (DECODE (result, ''Pass_on_1st'', 1, 0)) Pass_1st,
                       SUM (DECODE (result, ''Pass_on_2nd'', 1, 0)) Pass_2nd,
                       SUM (DECODE (result, ''Pass_on_3rd'', 1, 0)) Pass_3rd,
                       SUM (DECODE (result, ''DNM'', 1, 0)) DNM,
                       SUM (DECODE (result, ''INCOMPLETE'', 1, 0)) Incomplete,
                         SUM (DECODE (result, ''Pass_on_1st'', 1, 0))
                       + SUM (DECODE (result, ''Pass_on_2nd'', 1, 0))
                       + SUM (DECODE (result, ''Pass_on_3rd'', 1, 0))
                       + SUM (DECODE (result, ''DNM'', 1, 0))
                       + SUM (DECODE (result, ''INCOMPLETE'', 1, 0))
                          Total
                  FROM employees_vw a, pse_vw b
                 WHERE     a.emplid = b.emplid
                       AND status IN (''S'', ''I'', ''N'')
                     AND TYPE = ''PSE''
       report_query     VARCHAR2 (10000);
    BEGIN
       IF v_hub <> '*'
       THEN
          report_query := report_query_a;
       ELSE
          report_query := report_query_b;
       END IF;
       IF v_hub <> '*'
       THEN
          report_query :=
             report_query || ' and hub = ''' || v_hub || ''' GROUP BY hub )
    GROUP BY hub,
             Pass_1st,
             Pass_2nd,
             Pass_3rd,
             Total,
             DNM,
             Incomplete';
       END IF;
       IF v_type <> '*' AND v_subtype <> '*' AND v_hub <> '*'
       THEN
          report_query :=
                report_query
             || ' and hub = '''
             || v_hub
             || ''' and type = '''
             || v_type
             || ''' and subtype= '''
             || v_subtype
             || '''
              GROUP BY hub,
                     TYPE,
                     subtype,
            GROUP BY hub,
                     TYPE,
                     subtype,
                     Pass_1st,
                     Pass_2nd,
                     Pass_3rd,
                     Total,
                     DNM,
                     Incomplete';
       END IF;
       OPEN retval FOR report_query;
       RETURN retval;
    END;
    Edited by: user10821012 on May 13, 2010 9:56 AM

    What you are seeing is pretty common. When I work with dynamic SQL I usually include some logic to put the dyanmic SQL into a string and a means to see what was generated, something like (untested here)
      v_sql_c := 'select * from dual';
      open refcur for v_sql_c;
    exception
      when others then
         insert into work_table (clob_column) values (v_sql_c);so I can later query the table to get to the generated SQL for debugging, something like
      select * from work_table;I also try to write dynamic SQL so I can paste it from the work table right into query execution without editing.

Maybe you are looking for