Declaration nvl2 function in pl/sql
Hello,
I am a newbie on PL/SQL Programming. I can not execute the program.. The error message is : ORA-00904: "others": invalid identifier
I defined the others but I didn't do in a proper way I guess..I look forward to hearing your advise.
Thanks,
create or replace
procedure PROCEDURE3 AUTHID CURRENT_USER
AS
BEGIN
EXECUTE IMMEDIATE 'CREATE TABLE MARGIN_2 AS
SELECT NVL2(cbyc_oems.oem,cbyc_oems.oem,"others") AS OEM,
world.template_country,
world.template_region,
SUM(thisysales.top)
FROM( ( THISYSALES LEFT JOIN WORLD ON thisysales.country=world.code) LEFT JOIN
oem_cage_codes ON THISYSALES.MFG_CODE=oem_cage_codes.oem_cage_code) LEFT JOIN cbyc_oems ON oem_cage_codes.code=cbyc_oems.oem
GROUP BY
NVL2(cbyc_oems.oem,cbyc_oems.oem,"others").
world.template_country,
world.template_region';
end procedure3;
Note the name of this forum is "SQL Developer *(Not for general SQL/PLSQL questions)*" - so only for issues with the SQL Developer tool. So in the future, please post these questions under the dedicated SQL And PL/SQL forum.
Regards,
K.
Similar Messages
-
How to distinguish built-in SQL functions of PL/SQL?
I m having a hard time to figure out which functions are used ONLY in SQL statements and which are used in regular expr(ie, variable assignment,). Can anyone show me a list of each or perhaps a URL to look for?
I have searched through either the developer's guide and reference but couldn't find any appropriate indication in one place that make it clear.
For instance, I thought I can use CAST function in a variable assginment like the following:
declare
cursor myCur is SELECT Value_varchar2(1) FROM table WHERE id = 1;
myRec myCur%ROWTYPE;
var_a NUMBER(1);
begin
OPEN myCur;
FETCH myCur INTO myRec;
CLOSE myCur;
var_a := CAST(myCur.Value_varchar2(1) AS NUMBER(1));
DBMS_OUTPUT.PUT_LINE('var_a = ' || TO_CHAR(var_a));
end;
. It seems like CAST function can ONLY be used in SQL statement, but no doc so far states that?!
Edited by: HappyJay on 2010/05/12 12:05Sorry to bother you, Bob!
I think I might already found the list. Is it the following list?
---------------------- QUOTED FROM Oracle® Database PL/SQL Language Reference 11g Release 2 (11.2)Part Number E10472-06
SQL Functions in PL/SQL Expressions
In PL/SQL expressions, you can use all SQL functions except:
Aggregate functions (such as AVG and COUNT)
Analytic functions (such as LAG and RATIO_TO_REPORT)
Data mining functions (such as CLUSTER_ID and FEATURE_VALUE)
Encoding and decoding functions (such as DECODE and DUMP)
Model functions (such as ITERATION_NUMBER and PREVIOUS)
Object reference functions (such as REF and VALUE)
XML functions (such as APPENDCHILDXML and EXISTSNODE)
These conversion functions:
BIN_TO_NUM
These miscellaneous functions:
CUBE_TABLE
DATAOBJ_TO_PARTITION
LNNVL
NVL2
SYS_CONNECT_BY_PATH
SYS_TYPEID
WIDTH_BUCKET
PL/SQL supports an overload of BITAND for which the arguments and result are BINARY_INTEGER.
When used in a PL/SQL expression, the RAWTOHEX function accepts an argument of data type RAW and returns a VARCHAR2 value with the hexadecimal representation of bytes that comprise the value of the argument. Arguments of types other than RAW can be specified only if they can be implicitly converted to RAW. This conversion is possible for CHAR, VARCHAR2, and LONG values that are valid arguments of the HEXTORAW function, and for LONG RAW and BLOB values of up to 16380 bytes.
---------------------- -
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. -
Error in report when executing pl/sql function body returning sql query.
Hi,
I have used the pl/sql function body returning sql query for creating a report. I have created a datepicker(
P10_TASK_DATE) which can be submitted.The code is as below
DECLARE
v_sql varchar2(3000);
BEGIN
if :P10_TASK_DATE is not null THEN
v_sql:='select
* from tasks';
return v_sql;
else
v_sql:='select * from discovery';
return v_sql;
END IF;
END;if the date field is empty "select * from discovery" is executed and report is getting generated. But when we give a
date using date picker the page is submitted and i get "report error: ORA-01403: no data found" even
though the "tasks" table has data in it. Plz help
Thanks,
TJhi
Please try this
1. Create 2 region
1st region source=
select * from tasks'
go to the tab -> condition =
item NOT NULL
EXpression1 =:P10_TASK_DATE
this will run whenever the item have any date
2. open your 2 nd region source code= select * from discovery
put the condition
item is NULL
EXpression1 =:P10_TASK_DATE
thanks
Mark Wyatt -
Region source (PL/SQL function body returning SQL query)
Hi, guys.
Here is what i try to do:
Create a region of type SQL Query (PL/SQL function body returning SQL query). In the source area i tried to put this:
DECLARE
v_new VARCHAR2(10);
v_SQL varchar2(32000);
BEGIN
v_new := :P102_HDN_NEW;
-- htp.p(v_new);
IF v_new = 'N-Set' THEN
v_SQL := 'select ' ||
ELSIF v_new = 'Y-Set' THEN
v_SQL := 'select ' ||
END IF;
RETURN v_SQL;
END;
And here is the reply from APEX:
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. The query can not be parsed, the cursor is not yet open or a function returning a SQL query returned without a value.
Now.
1. Variable is set with the right value.
2. Each statement (separately) returns SQL that works with no problems
3. Problem occures if i try to put IF statement around the SQL creation.
4. If i select "Use Generic Column Names (parse query at runtime only)" instead of "Use Query-Specific Column Names and Validate Query" then the script returns SQL properly, however report's column names are set to Col1, Col2,Col3 ......
Thnks in advence
MikeOK. Here is enire statement:
DECLARE
v_new VARCHAR2(10);
v_SQL varchar2(32000);
BEGIN
v_new := :P102_HDN_NEW;
htp.p(v_new);
IF v_new = 'N-Set' THEN
v_SQL := 'select ' ||
'APEX_ITEM.DISPLAY_AND_SAVE(10,c.sdescr) descr, ' ||
'APEX_ITEM.DISPLAY_AND_SAVE(12,DECODE(ld.level,''All'', ''All Categories'',ld.level)) level, ' ||
'apex_item.checkbox(1, ld.opt_in_auto_flag, decode(ld.opt_in_auto_flag,NULL,''disabled'',''Y'',''checked'')) auto_in, ' ||
'apex_item.checkbox(2, ld.opt_in_manual_flag, decode(ld.opt_in_manual_flag,NULL,''disabled'',''Y'',''checked'')) manual_in, ' ||
'apex_item.checkbox(3, ld.opt_out_auto_flag, decode(ld.opt_out_auto_flag,NULL,''disabled'',''Y'',''checked'')) auto_out, ' ||
'apex_item.checkbox(4, ld.opt_out_manual_flag, decode(ld.opt_out_manual_flag,NULL,''disabled'',''Y'',''checked'')) manual_out, ' ||
'DECODE(c.code, ''NMBR'', NULL,''Change to '' || DECODE(ld.level,''All'',''Categories'',''All Categories'')) link_change, ' ||
'APEX_ITEM.DISPLAY_AND_SAVE(11,c.code) code ' ||
'from ' ||
'tbl1 c, ' ||
'tbl2 ld ' ||
'where c.code = ld.code ' ||
'and c.type = ''TYPE1'' ' ||
'and c.active = ''Y'' ' ||
'order by c.sorting ';
ELSIF v_new = 'Y-Set' THEN
v_SQL := 'select ' ||
'APEX_ITEM.DISPLAY_AND_SAVE(10,c.sdescr) descr, ' ||
'APEX_ITEM.DISPLAY_AND_SAVE(12,''All Categories'') level, ' ||
'apex_item.checkbox(1, c.option_1, decode(c.option_1,NULL,''disabled'',''Y'',''checked'')) auto_in, ' ||
'apex_item.checkbox(2, c.option_3, decode(c.option_3,NULL,''disabled'',''Y'',''checked'')) manual_in, ' ||
'apex_item.checkbox(3, c.option_2, decode(c.option_2,NULL,''disabled'',''Y'',''checked'')) auto_out, ' ||
'apex_item.checkbox(4, c.option_4, decode(c.option_4,NULL,''disabled'',''Y'',''checked'')) manual_out, ' ||
'DECODE(c.code, ''AAA'', NULL,''Options by AAA'') link_change, ' ||
'APEX_ITEM.DISPLAY_AND_SAVE(11,c.code) code ' ||
'from ' ||
'tbl1 c ' ||
'where 1 = 1 ' ||
'and c.type = ''TYPE1'' ' ||
'and c.active = ''Y'' ' ||
'order by c.sorting ';
END IF;
RETURN v_SQL;
END;
If i put just this
DECLARE
v_new VARCHAR2(10);
v_SQL varchar2(32000);
BEGIN
v_new := :P102_HDN_NEW;
htp.p(v_new);
v_SQL := 'select ' ||
'APEX_ITEM.DISPLAY_AND_SAVE(10,c.sdescr) descr, ' ||
'APEX_ITEM.DISPLAY_AND_SAVE(12,DECODE(ld.level,''All'', ''All Categories'',ld.level)) level, ' ||
'apex_item.checkbox(1, ld.opt_in_auto_flag, decode(ld.opt_in_auto_flag,NULL,''disabled'',''Y'',''checked'')) auto_in, ' ||
'apex_item.checkbox(2, ld.opt_in_manual_flag, decode(ld.opt_in_manual_flag,NULL,''disabled'',''Y'',''checked'')) manual_in, ' ||
'apex_item.checkbox(3, ld.opt_out_auto_flag, decode(ld.opt_out_auto_flag,NULL,''disabled'',''Y'',''checked'')) auto_out, ' ||
'apex_item.checkbox(4, ld.opt_out_manual_flag, decode(ld.opt_out_manual_flag,NULL,''disabled'',''Y'',''checked'')) manual_out, ' ||
'DECODE(c.code, ''NMBR'', NULL,''Change to '' || DECODE(ld.level,''All'',''Categories'',''All Categories'')) link_change, ' ||
'APEX_ITEM.DISPLAY_AND_SAVE(11,c.code) code ' ||
'from ' ||
'tbl1 c, ' ||
'tbl2 ld ' ||
'where c.code = ld.code ' ||
'and c.type = ''TYPE1'' ' ||
'and c.active = ''Y'' ' ||
'order by c.sorting ';
RETURN v_SQL;
END;
it works fune... -
Use of ROW_NUMBER() function in PL/SQL
I have a Table Emp with the following Structure
SQL> desc emp
Name Null? Type
EMPNO NUMBER(2)
ENAME VARCHAR2(50)
HIREDATE DATE
DEPTNO NUMBER(2)
If I write a following query on this table
SQL> SELECT deptno, hiredate, record_id
2 FROM (SELECT deptno, ename, hiredate, ROW_NUMBER()
3 OVER (ORDER BY hiredate) AS record_id
4 FROM emp)
5 WHERE record_id >= 2
6 AND record_id <=5;
The Result I get is
DEPTNO HIREDATE RECORD_ID
10 22-NOV-01 2
10 22-NOV-01 3
10 22-NOV-01 4
10 22-NOV-01 5
But if I put this query in a cursor in a PL/SQL block. The
pl/sql does not compiles and gives me the following address
SQL> DECLARE
2 CURSOR c_my IS
3 SELECT deptno, hiredate, record_id
4 FROM (SELECT deptno, ename, hiredate, ROW_NUMBER()
5 OVER (ORDER BY hiredate) AS record_id
6 FROM emp)
7 WHERE record_id >= 2
8 AND record_id <=5;
9 BEGIN
10 FOR c_rec IN c_my LOOP
11 dbms_output.put_line(c_rec.ename);
12 END LOOP;
13 END;
14 /
OVER (ORDER BY hiredate) AS record_id
ERROR at line 5:
ORA-06550: line 5, column 13:
PLS-00103: Encountered the symbol "(" when expecting one of the
following:
, from
Question: Can you please tell me how I can use the ROW_NUMBER()
function in PL/SQL. I need to use this for selecting the correct
range of records for Pagination on a website.
Thanks in advance
PrashantAs Andrew said, PL/SQL hasn't caught up with the newer bits of
SQL. I have heard that in 9i, they will be the same, but in 8i
there are still things that you can do in SQL that you cannot do
directly in PL/SQL, such as the new functions like ROW_NUMBER.
However, you can use NDS as a work around. The following does
the same as what you posted:
SET SERVEROUTPUT ON
DECLARE
TYPE c_my_type IS REF CURSOR;
c_my c_my_type;
TYPE c_rec_type IS RECORD
(deptno emp.deptno%TYPE,
ename emp.ename%TYPE,
hiredate emp.hiredate%TYPE,
record_id INTEGER);
c_rec c_rec_type;
v_sql VARCHAR2 (4000);
BEGIN
v_sql :=
'SELECT deptno, ename, hiredate, record_id
FROM (SELECT deptno, ename, hiredate,
ROW_NUMBER() OVER
(ORDER BY hiredate)
AS record_id
FROM emp)
WHERE record_id >= 2
AND record_id <= 5';
OPEN c_my FOR v_sql;
LOOP
FETCH c_my INTO c_rec;
EXIT WHEN c_my%NOTFOUND;
DBMS_OUTPUT.PUT_LINE (c_rec.ename);
END LOOP;
END;
However, you stated that you need it for selecting the correct
range of records for pagination on a website. For that, you
will want something more like this:
CREATE OR REPLACE PACKAGE package_name
AS
TYPE c_my_type IS REF cursor;
PROCEDURE procedure_name
(c_my IN OUT c_my_type,
p_record_id1 IN NUMBER DEFAULT 1,
p_record_id2 IN NUMBER DEFAULT 4);
END package_name;
CREATE OR REPLACE PACKAGE BODY package_name
AS
PROCEDURE procedure_name
(c_my IN OUT c_my_type,
p_record_id1 IN NUMBER DEFAULT 1,
p_record_id2 IN NUMBER DEFAULT 4)
IS
v_sql VARCHAR2 (4000);
BEGIN
v_sql :=
'SELECT deptno, ename, hiredate, record_id'
|| ' FROM (SELECT deptno, ename, hiredate,'
|| ' ROW_NUMBER() OVER'
|| ' (ORDER BY hiredate)'
|| ' AS record_id'
|| ' FROM emp)'
|| ' WHERE record_id >= :a'
|| ' AND record_id <= :b';
OPEN c_my FOR v_sql
USING p_record_id1, p_record_id2;
END procedure_name;
END package_name; -
Pl/sql function body returning SQL query - Print function
Hello all,
I have pl/sql function body returning SQL query for my reports for my new project that I am developing. We dont have any BI tool or anything for APEX so we use Oracle reports to get the same reports to be printed in PDF format. I had been using SQL function for Reports all these days and grabbing the data using SQL query was easy in Oracle reports. But this time we had atleast 8 fields in search criteria and hence I thouhgt PL/sql function body returning SQL query could be something easy to handle that scenario. We have 11 such reports in our project. Now when we tried to use the same PL/sql function to oracle reports , I was told by one of our Oracle reports expert, that we have to write it into functions and use it in SQL query to get the Reports in Oracle reports. Is there any Easy way to convert the same Pl/SQL function or get a PDF format of the same report in APEX without going thru the much pains of rewriting the whole SQL Query.
thank you
DevisriHi,
give this a go.
I can't test it as I don't have the tables in my schema.
create or replace package MK_TEST_PF is
-- Author : MK
-- Created : 21/06/2010 16:30:19
-- Purpose : FOR LUCY_DISCOVER
-- Public type declarations
/* -- just guess the table row types.....
-- otherwise it won't compile
type test_rec is record
(INV REP.inv%type
,cNUMBER REP.cNUMBER%type
,OPENDATE REP.OPENDATE%type
,TARGETDATE REP.ESTCOMPLETE%type
,DATECLOSED REP.COMPLETED%type
,STATUS REP.STATUS%type
,cCODE REP.cCODE%type
,line varchar2(4000)
,SIGc varchar2(4000)
,CLASS REP.CLASS%type
,SUMM REP.SUMM%type
,AREA REP.AREA%type
type test_rec is record
(INV varchar2(4000)
,cNUMBER varchar2(4000)
,OPENDATE varchar2(4000)
,TARGETDATE varchar2(4000)
,DATECLOSED varchar2(4000)
,STATUS varchar2(4000)
,cCODE varchar2(4000)
,line varchar2(4000)
,SIGc varchar2(4000)
,CLASS varchar2(4000)
,SUMM varchar2(4000)
,AREA varchar2(4000)
type test_tab is table of test_rec;
-- Public constant declarations
-- Public variable declarations
-- Public function and procedure declarations
end MK_TEST_PF;
create or replace package body MK_TEST_PF is
-- Private type declarations
-- Private constant declarations
-- Private variable declarations
-- Function and procedure implementations
function get_query_f
(p_inv VARCHAR2 := UPPER(v('P44_INV'))
,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
return varchar2
is
v_sql VARCHAR2(5000);
-- v_inv VARCHAR2(100);
-- v_reg VARCHAR2(100);
-- v_proarea VARCHAR2(100);
-- v_status VARCHAR2(100);
-- v_SIG VARCHAR2(100);
-- v_disp VARCHAR2(100);
-- v_coding VARCHAR2(100);
-- v_inc_sum VARCHAR2(4);
-- v_word VARCHAR2(4000);
v_wildcard VARCHAR2(2000);
-- v_timeframe VARCHAR2(100);
-- v_rec VARCHAR2(5);
v_record VARCHAR2(5);
v_open VARCHAR2(100);
v_closed VARCHAR2(100);
v_PEND VARCHAR2(100);
v_refSIG VARCHAR2(100);
v_refreg VARCHAR2(100);
v_refother VARCHAR2(100);
v_y varchar2(100);
BEGIN
--v_inv := UPPER(v('P44_INV')) ;
v_record := 'R%';
v_wildcard := '%';
v_open := 'OPEN';
v_closed := 'CLOSED';
v_PEND := 'PEND';
v_refSIG := 'REF - SIG';
v_refreg := 'REF - CLASS';
v_refother := 'REF - OTHER';
v_y := 'Y';
v_sql := 'SELECT REP.INV as INV, REP.cNUMBER as cNUMBER, REP.OPENDATE as OPENDATE,
REP.ESTCOMPLETE as TARGETDATE, REP.COMPLETED as DATECLOSED, REP.STATUS as STATUS,
REP.cCODE as cCODE, apex_item.checkbox(1,REP.line,null,'''||v_y||''') line , apex_item.checkbox(1,REP.SIG,null,'''||v_y||''') SIGc ,
REP.CLASS as CLASS, REP.SUMM as SUMM, REP.AREA as AREA from REP where 1=1';
IF p_rec is not null then
IF p_rec = 'E' then
v_sql := v_sql|| ' and upper(REP.cnumber) not like '''||v_record||'''';
ELSIF p_rec = 'D' then
v_sql := v_sql|| ' and upper(REP.cnumber) like '''||v_record||'''';
ELSIF p_rec = 'I' then
v_sql := v_sql|| ' and REP.cnumber = REP.cnumber ';
end if ;
end if ;
IF upper(p_status) not like '%NULL%' then
IF upper(p_status) like '%OPEN%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_open||'''';
ELSIF upper(p_status) like '%CLOSED%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_closed||'''';
ELSIF upper(v_PEND) like '%PEND%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_PEND||'''';
ELSIF upper(v_refSIG) like '%REF - SIG%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_refSIG||'''';
ELSIF upper(v_refreg) like '%REF - CLASS%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_refreg||'''';
ELSIF upper(v_refother) like '%REF - OTHER%' then
v_sql := v_sql||' AND upper(REP.status) like '''||v_refother||'''';
END IF ;
END IF ;
IF p_inv = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.INV),'''||p_inv||''') > 0';
END IF ;
IF p_reg = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.CLASS),'''||p_reg||''') > 0';
END IF ;
IF p_proarea = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.AREA),'''||p_proarea||''') > 0';
END IF ;
IF p_disp = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.disposition),'''||p_disp||''') > 0';
END IF ;
IF p_coding = 'NULL' THEN
v_sql := v_sql||' AND instr(upper(REP.ccode),'''||p_coding||''') > 0';
END IF ;
IF p_SIG = ' ' THEN
v_sql := v_sql||' AND instr(upper(REP.SIG),'''||p_SIG||''') > 0';
END IF ;
IF p_word is not null then
v_sql := v_sql|| ' and
instr(upper(REP.SUMM),
upper(nvl('''||p_WORD_IN_SUMM||''',REP.SUMM))) > 0';
end if ;
If p_timeframe is not null then
if upper(p_timeframe) = 'OPEN' then
v_sql := v_sql|| ' and to_date(REP.opendate) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
elsif upper(p_timeframe) = 'CLOSED' then
v_sql := v_sql|| ' and to_date(REP.completed) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
elsif upper(p_timeframe) = 'EST' then
v_sql := v_sql|| ' and to_date(REP.estcomplete) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
end if;
end if;
v_sql := v_sql ||' order by REP.INV ';
return v_sql;
end get_query_f;
function test_pf
(p_inv VARCHAR2 := UPPER(v('P44_INV'))
,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
RETURN test_tab PIPELINED
is
type test_c is ref cursor;
v_row test_tab;
v_sql varchar2(4000);
v_cursor test_c;
begin
v_sql := get_query_f
(p_inv
,p_reg
,p_proarea
,p_disp
,p_coding
,p_status
,p_SIG
,p_inc_sum
,p_word
,p_timeframe
,p_rec
,p_WORD_IN_SUMM
,p_ON_AFTER
,p_ON_BEFORE
open v_cursor for v_sql;
fetch v_cursor bulk collect into v_row;
close v_cursor;
for i in 1 .. v_row.count loop
pipe row (v_row(i));
end loop;
return;
end test_pf;
end MK_TEST_PF;
/Regards
Michael -
Query on Reoprts-pl/sql function body returning sql query
Hi,
I am facing a starnge problem.. and would like to know the reason for it.
The situation is as follows:
I have a report (pl/sql function body returning sql query based). My query is as follows:
declare
l_query1 varchar2(2000);
begin
if (:P102_min_value is not null and :P102_max_value is null) then
l_query1 := 'select decode(:P102_date,'1',date1) Transaction_Date, decode(:P102_first_name,'2',first_name) First_Name from (
select * from MORTGAGE_LOAN_LEADS where APPRX_LOAN_AMOUNT >=:P102_min_value
return (l_query1);
end if;
end;
This returns the error as :
1 error has occurred
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-06550: line 7, column 20: PLS-00103: Encountered the symbol "1" when expecting one of the following: * & = - + ; < / > at in is mod remainder not rem <> or != or ~= >= <= <> and or like LIKE2_ LIKE4_ LIKEC_ between || multiset member SUBMULTISET_)
How do i correct this? am i right in thinking that the single quotes indicating a string within a select query is creating the problem? Beacuse if i use an sql query report and use the following query, it is working fine...
select
decode(:P102_date,'1',date1) Transaction_Date,
decode(:P102_first_name,'2',first_name) First_Name
from (
select * from MORTGAGE_LOAN_LEADS where APPRX_LOAN_AMOUNT >=:P102_min_value
But i need to write pl/sql function, so that multiple report can be returned based on different conditions. Please guide me.
Thanks,
SumanaDoes that mean that both in if and else we need to have same columns selected?
if thats the case.. any idea how i can implement it in my code. The situation here is that the columns that need to be selected are dynamic and keep on changing...
if i try to implement like this and run the page, it gives the following error:
Query is:
declare
l_query1 varchar2(4000);
begin
if apex_application.get_current_flow_sgid(:APP_ID) = apex_application.get_sgid then
if (:P102_min_value is not null and :P102_max_value is null) then
l_query1 := 'select decode(' || :P102_date|| ',''1'',date1) Transaction_Date, decode(' || :P102_first_name || ',''2'',first_name) First_Name from (
select * from MORTGAGE_LOAN_LEADS where APPRX_LOAN_AMOUNT >=' || :P102_min_value ||'
elsif (:P102_min_value is null and :P102_max_value is not null) then
l_query1 := 'select decode(' || :P102_date|| ',''1'',date1) Transaction_Date, decode(' || :P102_first_name || ',''2'',first_name) First_Name from (
select * from MORTGAGE_LOAN_LEADS where APPRX_LOAN_AMOUNT >=' || :P102_max_value ||'
else
l_query1 := 'select date1,first_name from MORTGAGE_LOAN_LEADS where rownum = 1';
end if;
else
l_query1 := 'select date1,first_name from MORTGAGE_LOAN_LEADS where rownum = 1';
end if;
return l_query1;
--dbms_output.put_line( l_query1);
end;
The Error is:
failed to parse SQL query:
ORA-00936: missing expression
If i try to run the same in command prompt, it always goes to the else part... (else of outer if) -
SQL Query (PL/SQL function body returning SQL query) when using to_char
we are trying to build a report page of Type SQL Query (PL/SQL function body returning SQL query).
our query is so simple, we need to extract the month from the recording_date column.
declare
l_query varchar2(1000);
begin
l_query:='select to_char(recording_date,'MM')from re_productive';
return l_query;
end;
but we are having the following problem for this query
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-06550: line 4, column 42: PLS-00103: Encountered the symbol "MON" when expecting one of the following: . ( * @ % & = - + ; < / > at in is mod remainder not rem <> or != or ~= >= <= <> and or like between || multiset member SUBMULTISET_ The symbol ". was inserted before "MON" to continue.)
Notes:
1-the query is correct and it was tested under Toad and SQL Plus.
2- we tried Use Generic Column Names (parse query at runtime only) option but we get the same problem.
any quick help please.Hi
You haven't escaped your quotes in the string. Try this...
DECLARE
l_query VARCHAR2(32767);
BEGIN
l_query:= 'select to_char(recording_date,''MM'') from re_productive';
RETURN l_query;
END;Cheers
Ben -
How to use union statement with declare & set function?
Hi Experts,
i have small query about how to use union statement with declare & set function?
Example as below :
DECLARE @name AS date
Declare @name2 AS date
/* SELECT FROM [2013].[dbo].[OINV] T0 */
/* WHERE */
SET @name = /* T0.DocDate */ '[%1]'
SET @name2 = /* T0.DocDate */ '[%2]'
select '2013',t5.U_salmannm,t1.CardName,t2.sumapplied as CollectionAmount,t2.DcntSum ,t3.DocTotal as InvoiceTotal,
datediff(dd,t3.DocDate,t1.Docdate) as Days
from 2013.dbo.orct t1
inner join 2013.dbo.RCT2 t2 on t1.DocNum = t2.DocNum
left join 2013.dbo.oinv t3 on
t3.docentry = t2.baseAbs
inner join 2013.dbo.ocrd t4 on t1.Cardcode = t4.CardCode
inner join [2013].[dbo].[@CQ_RTSM] t5 on t4.U_BeatCode = t5.U_RoutCode
where t2.DcntSum <> 0.000000 and t3.DocDate between [%1] and [%2]
Union
/* SELECT FROM [2014].[dbo].[OINV] T0 */
/* WHERE */
SET @name = /* T0.DocDate */ '[%1]'
SET @name2 = /* T0.DocDate */ '[%2]'
select '2014',t5.U_salmannm,t1.CardName,t2.sumapplied as CollectionAmount,t2.DcntSum ,t3.DocTotal as InvoiceTotal,
datediff(dd,t3.DocDate,t1.Docdate) as Days
from 2014.dbo.orct t1
inner join 2014.dbo.RCT2 t2 on t1.DocNum = t2.DocNum
left join 2014.dbo.oinv t3 on
t3.docentry = t2.baseAbs
inner join 2014.dbo.ocrd t4 on t1.Cardcode = t4.CardCode
inner join [2014].[dbo].[@CQ_RTSM] t5 on t4.U_BeatCode = t5.U_RoutCode
where t2.DcntSum <> 0.000000 and t3.DocDate between [%1] and [%2]You have to create stored procedure in SQL only .
Like u must have create for Crystal .
You can execute procedure in query manager but you have to enter parameter manually..
example
Exec @Test '20140101' '20140501'
Every time user has to enter it manually in yyyymmdd format in case of date parameters.
Example
Create Proc [@Test]
as begin
DECLARE @name AS date
Declare @name2 AS date
/* SELECT FROM [2013].[dbo].[OINV] T0 */
/* WHERE */
select '2013',t5.U_salmannm,t1.CardName,t2.sumapplied as CollectionAmount,t2.DcntSum ,t3.DocTotal as InvoiceTotal,
datediff(dd,t3.DocDate,t1.Docdate) as Days
from 2013.dbo.orct t1
inner join 2013.dbo.RCT2 t2 on t1.DocNum = t2.DocNum
left join 2013.dbo.oinv t3 on
t3.docentry = t2.baseAbs
inner join 2013.dbo.ocrd t4 on t1.Cardcode = t4.CardCode
inner join [2013].[dbo].[@CQ_RTSM] t5 on t4.U_BeatCode = t5.U_RoutCode
where t2.DcntSum <> 0.000000 and t3.DocDate between @Name and @Name2
Union
/* SELECT FROM [2014].[dbo].[OINV] T0 */
/* WHERE */
select '2014',t5.U_salmannm,t1.CardName,t2.sumapplied as CollectionAmount,t2.DcntSum ,t3.DocTotal as InvoiceTotal,
datediff(dd,t3.DocDate,t1.Docdate) as Days
from 2014.dbo.orct t1
inner join 2014.dbo.RCT2 t2 on t1.DocNum = t2.DocNum
left join 2014.dbo.oinv t3 on
t3.docentry = t2.baseAbs
inner join 2014.dbo.ocrd t4 on t1.Cardcode = t4.CardCode
inner join [2014].[dbo].[@CQ_RTSM] t5 on t4.U_BeatCode = t5.U_RoutCode
where t2.DcntSum <> 0.000000 and t3.DocDate between
between @Name and @Name2
end -
How to "end" function definition in SQL plus?
I am using Oracle 11g and SQL plus.
I am trying to define a function and get back to the SQL prompt, but it is just not exiting the function definition.
SQL> create function dept_count (dept_name varchar(20))
2 returns integer
3 begin
4 declare d_count integer;
5 select count (* ) into d_count
6 from instructor
7 where instructor.dept_name = dept_name
8 return d_count;
9 end
10 ;
11
12
13
14
15
16 ;;;
17 end dept_count;
18 ;
19
20 ; <--- I was expecting the SQL> prompt here but it doesn't appear.
What should I do? Please help. Thanks.And, to answer probably the most frequently asked question when I was an Oracle instructor ...
If you are saving this statement in a file to execute later, after the "/" at the bottom, hit return, so that your file contains a line feed after the /, rather than your file ending with the /
Otherwise you get the annoying, but completely harmless, error message "Input truncated after (number) characters" when you compile the program. -
Calling function in PL/SQL
Hello everyone,
I would like to know if there is anyway to call a user defined function in an SQL statement from a PL/SQL anonymous block without first creating that function to the database.
For instance:
I have a pl/sql block:
DECLARE
BEGIN
UPDATE Request SET map_No = nts_map_no(parm1, parm2, parm3) WHERE ...
END;
I have tried declaring the function within the declare section of the block as in:
DECLARE
FUNCTION nts_map_no
End nts_map_no;
BEGIN
UPDATE Request SET map_No = nts_map_no(parm1, parm2, parm3) WHERE ...
END;
But Oracle wouldn't allow me to use it in an Update statement.
Thank you.The this might be you are looking for ->
satyaki>
satyaki>select * from v$version;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
Elapsed: 00:00:00.30
satyaki>
satyaki>
satyaki>create table bu_cacy
2 as
3 select empno, ename
4 from emp
5 where 1=2;
Table created.
Elapsed: 00:00:15.38
satyaki>
satyaki>select * from bu_cacy;
no rows selected
Elapsed: 00:00:00.55
satyaki>
satyaki>
satyaki>
satyaki>declare
2 a varchar2(350);
3 b number(5);
4 c varchar2(350);
5
6 function gg_fin(a_str in varchar2)
7 return varchar2
8 is
9 str varchar2(300);
10 begin
11 str := 'IFA-'||a_str;
12 return str;
13 end;
14 begin
15 b := #
16 a := '&str';
17
18 c:= gg_fin(a) ;
19
20 insert into bu_cacy values(b,c);
21 commit;
22 exception
23 when others then
24 rollback;
25 end;
26 /
Enter value for num: 1
old 15: b := #
new 15: b := 1;
Enter value for str: vivi
old 16: a := '&str';
new 16: a := 'vivi';
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.10
satyaki>
satyaki>select * from bu_cacy;
EMPNO ENAME
1 IFA-vivi
Elapsed: 00:00:00.14
satyaki>Regards.
Satyaki De. -
Create procedure or function in pl/sql code
Hi
how can I to build a procedure or function in block PL/SQL using
DECLARE
BEGIN
ENDmay be this
SQL> ed
Wrote file afiedt.buf
1 declare
2 str varchar2(400);
3 begin
4 str:='create or replace procedure test_dy
5 is
6 begin
7 null;
8 end;';
9 execute Immediate str;
10* end;
SQL> /
PL/SQL procedure successfully completed.
SQL> desc test_dy;
PROCEDURE test_dy -
Hi all.
Is some body know can XQuery functions be used/declared in pl sql? More deep, can I cover XQuery function by pl sql function or procedure? And how to input parameters/variables to Xquery function from pl sql?
Any links to manual will be helpful.
Best regards,
Anton.Something like that?:
SQL> create or replace procedure index_scan (index_name varchar2, name varchar2)
as
xml xmltype;
begin
select xmlquery (
if ("article-by-title" = $index_name) then doc("/wiki")/root/page[title=$name]
else if ("article-by-id" = $index_name) then doc("/wiki")/root/page[id=$name]
else if ("link-by-target" = $index_name) then doc("/wiki")/root/page/links/link[@target = $name]
else if ("article-by-cat" = $index_name) then doc("/wiki")/root/page/catlinks/catlink[@target=$name]
else error(fn:QName("http://www.w3.org/2005/xqt-errors", $index_name) , "Some error occured") '
passing index_name as "index_name", name as "name"
returning content)
into xml
from dual;
end index_scan;
Procedure created.
SQL> exec index_scan('My Index Name','My Name')
BEGIN index_scan('My Index Name','My Name'); END;
Error at line 20
ORA-19112: error raised during evaluation: :My Index Name
Detail: Some error occured
ORA-06512: at "MICHAEL.INDEX_SCAN", line 5
ORA-06512: at line 1Don't have your resources - therefore the error! -
Any Function in T-SQL thats similar to GREATEST() IN Orcl.
Is there any Function in T-SQL thats similar to GREATEST() IN Orcl?
Iam trying to find the greatest of two DATETIME datatype Fields in my 'select's.
If there is no in built function, Whats the best approach?MKR,
If you are using SS 2005, you could use the new operator UNPIVOT.
Code Block
DECLARE @MyTable table
( RowID int IDENTITY,
Date1 datetime,
Date2 datetime,
Date3 datetime NOT NULL DEFAULT getdate()
INSERT INTO @MyTable VALUES ( '2007/01/01', '2007/02/01', '2007/01/31' )
INSERT INTO @MyTable VALUES ( '2007/10/10', '2007/11/01', DEFAULT )
INSERT INTO @MyTable VALUES ( '2007/12/01', '2007/12/05', '2007/12/06' )
SELECT
a
.RowID,
a.Date1,
a.Date2,
a.Date3,
b.Greatest
FROM
@MyTable
AS a
INNER JOIN
SELECT
RowID
MAX([Value]) AS Greatest
FROM
@MyTable
UNPIVOT
[Value]
FOR ColumnName IN ([Date1], [Date2], [Date3])
) AS unpvt
GROUP BY
RowID
) AS b
ON a.RowID = b.RowID
ORDER BY
a
.RowID
-- OR
SELECT
a
.*, b.Greatest
FROM
@MyTable
AS a
CROSS APPLY
SELECT
MAX(Value) AS Greatest
FROM
@MyTable
UNPIVOT
[Value]
FOR ColumnName IN ([Date1], [Date2], [Date3])
) AS unpvt
WHERE
unpvt
.RowID = a.RowID
) AS b
ORDER BY
a
.RowID
GO
AMB
Maybe you are looking for
-
How to send the Sales Order to another user id within SAP
Gurus, I have created a sale order through VA01. Sales order number is generated. Now that sales order I want to send it to another user. Is is possible, if how. I know we can send the reports like FBL3N, by selecting list and send there we can giv
-
Thumbnail not displaying when attaching image to email
Suddenly my Mac is not displaying a thumbnail image when I go to attach an image to an email. I have fixed permissions, restarted and relaunched Finder, but it's still not displaying. I've also unchecked and rechecked "show icon preview" in View Opti
-
Defaulting the email address in From field.
Hi , I am working on requirement to default the email address in from field and populate the eligible emails ID 's as drop down in from field based on some condition. So I need to overwrite the standard emails data that are already coming in from fie
-
Having a wierd connection issue on my MBP. The airport card just keeps losing connection like crazy while surfing the net, but when I stream XM radio from the app, the connection is consistent and doesn't drop at all. What could be causing this? Shou
-
Chrome windows 7 do i need both adobe plugin 10 and adobe flash player 11 active x
using chrome, windows 7 do i need adobe air, adobe plugin 10 and adobe flash player 11 active x? or is that why i am constantly getting a shockwave crashed message?