Spool in PLSQL
I'm in a PLSQL loop and I need to do a spool for a select statement. This doesn't work because within plsql, it needs a select Into clause. Is there anyway of sending the output to a file?
Use REF CURSOR as out parameter of the procedure. Open the ref cursor for a query inside the procedure.
SQL> var x REFCURSOR
SQL> exec proc1(:x);
SQL> print x
Similar Messages
-
Spooling from PL/SQL Block
Hi,
Is it possible to do spooling from a pl/sql block.The spool cannot be the first command because I want to give the spool file name in a loop and each time the spool name should change based on the value.
I tried all possiblities,but I couldn't can anyone give me some idea on how to do this.
I cannot use UTL_FILE option ,because the client agreed only for spooling.
Is it possible to write the spool data is excel format..
Please find below an example of my requirement..
DECLARE
CurSor Cur_Designation IS
Select Designation from tbl_Designation;
N_Desig Cur_Designation%RowType;
Cursor Cur_Emp(Desig Number) IS
Select Emp_no,Emp_name
From Employee Where Emp_Designation = Desig;
N_Emp Cur_Emp%RowType;
BEGIN
Open Cur_Designation ;
Loop
Fetch Cur_Designation INTO N_Desig;
EXIT WHEN Cur_Designation %NOTFOUND;
--Here I want to give the spool file name
Spool --Should be designation name
Open Cur_Emp(N_Desig.Designation);
Loop
Fetch Cur_Emp INTO N_Emp ;
EXIT WHEN Cur_Emp %NOTFOUND;
-- All employee details I need to come to log file
End Loop;
Close Cur_Emp;
End Loop;
Close Cur_Desingnation;
End;
Please advice me how to do this..
Thanks,
Bindu<< I cannot use UTL_FILE option ,because the client agreed only for spooling. >>
<< I want to use it in a PL/SQL Block.I have some variables to declare and some cursors to be used.
So where should I use the spool command.
I tried to given after a fetch command ,but it is not working. >>
you can't use SPOOL inside PLSQL
you may use dbms_output calls in PLSQL
so create a procedure test2 instead of sqlscript test2 and you will be fine
rem =========== procedure test2 ================
create or replace
procedure test2 (p_param number) is
begin
dbms_output.enable (1000000);
dbms_output.put_line('A' || chr(9) || 'B' || chr(9) || 'C' ) ;
FOR i_rec in (select a,b.c from xyz where a = p_param) LOOP
dbms_output.put_line (to_char(a) || chr(9) || b || chr(9) || c ) ;
END LOOP ;
end ;
REM ==================================================== -
Using owa_util.showpage
Hi,
I just learning how the package owa_util works in my db 10g and I don't Know why the code that I describe below give me a few errors:
CREATE TABLE feds_data (
tid NUMBER(9),
serial_no VARCHAR2(30),
mfg_abbr VARCHAR2(8),
type_code VARCHAR2(5),
mod_dt DATE,
mod_by VARCHAR2(30));
INSERT INTO feds_data
(tid, serial_no, mfg_abbr, type_code, mod_dt, mod_by)
VALUES
(1, '42', 'BCAG', 'ABC', SYSDATE, USER);
INSERT INTO feds_data
(tid, serial_no, mfg_abbr, type_code, mod_dt, mod_by)
VALUES
(1, '666', 'MSC', 'XXX', SYSDATE, USER);
commit;
CREATE OR REPLACE PACKAGE feds_pkg IS
PROCEDURE get_data;
END feds_pkg;
CREATE OR REPLACE PACKAGE BODY feds_pkg IS
PROCEDURE get_data IS
CURSOR gmi_cur IS
SELECT tid, serial_no, mfg_abbr,
type_code, mod_dt, mod_by
FROM feds_data
ORDER BY tid;
ProcName VARCHAR2(61) := 'feds_pkg.get_data';
HeadText VARCHAR2(2000) := 'Demo Page Header';
FootText VARCHAR2(500) := 'Demo Page Footer';
BEGIN
htp.p(HeadText);
htp.p('<form method="POST"><center>');
htp.p('<table border="1" width="30%">');
FOR i IN gmi_cur LOOP
htp.p('<tr>');
htp.p('<td align="center">');
htp.p('<font face="Arial" color=#000000">');
htp.p('<input type=text size=3 maxlength=3 name="tid"');
htp.p('value = ' || i.tid || '></font>');
htp.p('</td>');
htp.p('<td align="center">');
htp.p('<font face="Arial" color=#000000">');
htp.p('<input type=text size=8 maxlength=8 name="serial_no"');
htp.p('value = ' || i.serial_no || '></font>');
htp.p('</td>');
htp.p('<td align="center">');
htp.p('<font face="Arial" color=#000000">');
htp.p('<input type=text size=6 maxlength=6 name="serial_no"');
htp.p('value = ' || i.mfg_abbr || '></font>');
htp.p('</td>');
htp.p('<td align="center">');
htp.p('<font face="Arial" color=#000000">');
htp.p('<input type=text size=1 maxlength=1 name="serial_no"');
htp.p('value = ' || i.type_code || '></font>');
htp.p('</td>');
htp.p('<td align="center">');
htp.p('<font face="Arial" color=#000000">');
htp.p('<input type=text size=7 maxlength=7 name="serial_no"');
htp.p('value = ' || TO_CHAR(i.mod_dt, 'MM-DD-YYYY') ||'></font>');
htp.p('</td>');
htp.p('<td align="center">');
htp.p('<font face="Arial" color=#000000">');
htp.p('<input type=text size=6 maxlength=6 name="serial_no"');
htp.p('value = ' || i.mod_by || '></font>');
htp.p('</td>');
htp.p('</tr>');
END LOOP;
htp.p('<p align=center>');
htp.p('<input type=submit name="Submit" value="Save"></p>');
htp.p('</form></center>');
htp.p('</table>');
htp.p(FootText);
END get_data;
END feds_pkg;
set serveroutput on
spool c:\PLSQL\demopage.html
exec feds_pkg.get_data;
exec owa_util.showpage;
spool offthe output error is:
ORA-06502: PL/SQL: error numérico o de valor
ORA-06512: en "SYS.OWA_UTIL",
línea 356 ORA-06512: en "SYS.HTP",
línea 1368 ORA-06512: en "SYS.HTP",
línea 1443 ORA-06512: en "SYS.HTP",
línea 1735 ORA-06512: en "HR.FEDS_PKG",
línea 15 ORA-06512: en línea 1Thanks in advance....The htp package is meant for procedures that you call from the browser, not from sqlplus. Try this procedure call from your browser.
There is a way to get a preview via sqlplus, but you need to fake a CGI environment. Search this forum, I know this topic has been addressed before.
Here is one link:
Re: HTML not working in PL/SQL block..Help me ASAP
Edited by: InoL on May 20, 2011 3:40 PM -
How Can i get PLSQL Procedure out values in Shell Script?
Hi,
I need to use PLSQL Procedure out values in shell script by using that parameter i need to check and call the other procedure. Please can you guide me how can i?
#!/bin/ksh
# Function to call validation program
SQL_PKG_CALL()
echo "Inside SQL_PKG_CALL for $file"
sqlplus -s /nolog << EOF
whenever sqlerror exit failure
connect ${APPS_LOGIN}
variable exit_value NUMBER
set serveroutput on size 100000
DECLARE
l_errbuf VARCHAR2(10000) := NULL; l_retcode NUMBER := NULL;lv_test VARCHAR2(4000) := NULL;
BEGIN
fnd_global.apps_initialize ( USER_ID => ${USER_ID}, RESP_ID => ${RESP_ID}, RESP_APPL_ID => ${RESP_APPL_ID}
, SECURITY_GROUP_ID => ${SECURITY_GROUP_ID}
#Calling PLSQL procedure for create and attache document
XXAFPEEP_SO_DOC_ATTACH_INT.DOCUMENT_ATTACH (p_errbuf => l_errbuf, p_retcode => :RETMSG, p_fileName => $file
, p_debug => 'Y', p_rettest => lv_test);
# to print the procedure return values
DBMS_OUT.PUT_LINE('Return Message: '|| lv_test);
#${RETCODE}=l_retcode;
print :RETMSG;
END;
EXIT 0
EOF
# Program starts here
echo "+---------------------------------------------------------------------------+"
echo "Program Start"
APPS_LOGIN=${1} # Apps Login
USER_ID=${2} # User ID
RESP_ID=${5} # Responsiblity ID
RESP_APPL_ID=${6} # Responsiblity Application ID
SECURITY_GROUP_ID=${7} # Security Group ID
DIRECTORY_PATH=${8} # Directory --Attached file locations
DIRECTORY_NAME=${9} # Directory Name for plsql
echo "User ID : $USER_ID"
echo "Responsibility ID : $RESP_ID"
echo "Responsibilith Application ID : $RESP_APPL_ID"
echo "Security Goup ID : $SECURITY_GROUP_ID"
echo "Directory Path : $DIRECTORY_PATH"
echo "Direcotry Name : $DIRECTORY_NAME"
echo
#files direcotry
cd $DIRECTORY_PATH
echo Present Working Directory: `pwd`
echo
#for all file names
ALL_FILES=`ls *.pdf`
for file in $ALL_FILES
do
if [ -f $file ]
then
#log "Processing $file" # future
echo Processing: $file
# Calling the PL/SQL Program
SQL_PKG_CALL;
#echo "Retcode : $RETCODE"
echo "RetMessage : $RETMSG"
else
log "Skipped $file: invalid file"
echo "Skipping current file $file: not a valid file."
fi
done
Thanks
SudheerSaubhik's provided the solution, but just for fun:
Test procedure:
create or replace procedure get_ename
( p_empno in emp.empno%type
, p_ename_out out emp.ename%type )
is
begin
select ename into p_ename_out
from emp
where empno = p_empno;
end get_ename;Test data:
SQL> select empno, ename from emp order by 1;
EMPNO ENAME
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
14 rows selectedTest call from SQL*Plus to show it working:
SQL> declare
2 v_ename emp.ename%type;
3 begin
4 get_ename(7844,v_ename);
5 dbms_output.put_line(v_ename);
6 end;
7 /
TURNER
PL/SQL procedure successfully completed.Demo shellscript (borrowing the function idea from Saubhik):
#!/bin/ksh
empno=${1:-NULL}
exec_sql() {
sqlplus -s william/w@//vm.starbase.local:1521/eleven <<END_SQL
spool get_out_value.sh.log
set serverout on size 2000 feedback off
declare
v_name emp.ename%type;
begin
get_ename(${empno},v_name);
dbms_output.put_line('# ' || v_name);
end;
spool off
exit
END_SQL
ename=$(exec_sql ${empno} | awk '/^# / {print $2}')
print Employee ${empno} = ${ename}Demo:
/Users/williamr: get_out_value.sh 7844
Employee 7844 = TURNER
/Users/williamr: get_out_value.sh
Employee NULL =Note this substitutes the word NULL if no empno is passed, and it ignores error output or anything else by only looking for lines beginning '# ' and then taking the following word. Error messages will appear in the logfile. (In this example it probably doesn't need the NULL substitution because a missing parameter would cause a syntax error which the script will handle anyway, but it could be useful in more complex examples.)
For a production script you should probably use an OS authenticated account so you don't have to deal with password strings. -
Calling sql script in plsql procedure
Hello,
I have a sql script named mytest.sql and i want to execute this from a stored procedure.
following is the contents of this script
spool d:\mytestsql.txt
select * from tab;
spool off
Actually i want my sql script to run daily to export some tables data.
I can execute this script from a sql prompt but i want to run it from enterprise manager.
I am using oracle 10gR2 on windows2000 system.
Any idea about scheduling the sql script to run automatically??
How to execute this sql script from a plsql procedure??
ThanksHi all,
Thanks for all the replies. I have found the solution with external procedures.
Following is the complete step by step guide.
1. Create the OSCommand Java Class using the following statement:
connect as any user:
create or replace and compile java source named oscommand as
import java.io.*;
public class OSCommand{
public static String Run(String Command){
try{
Runtime.getRuntime().exec(Command);
return("0");
catch (Exception e){
System.out.println("Error running command: " + Command +
"\n" + e.getMessage());
return(e.getMessage());
2. Create the following Wrapper Function using the following statement:
CREATE or REPLACE FUNCTION OSCommand_Run(Command IN STRING)
RETURN VARCHAR2 IS
LANGUAGE JAVA
NAME 'OSCommand.Run(java.lang.String) return int';
3. connect as sys
Execute dbms_java.grant_permission( 'FKHALID','SYS:java.io.FilePermission', '<<ALL FILES>>','execute');
execute dbms_java.grant_permission( 'FKHALID','SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '*' );
execute dbms_java.grant_permission( 'FKHALID','SYS:java.lang.RuntimePermission', 'readFileDescriptor', '*' );
commit;
note: here fkhalid is the oracle user.
connect as fkhalid user:
Declare
expdp_cmd Varchar2(2000);
Begin
expdp_cmd := OSCommand_Run('cmd /c sqlplus fkhalid@mtcedwt/pwd @d:\ORA_DUMPS\mydbexp.sql');
DBMS_OUTPUT.Put_Line(expdp_cmd);
End;
In Unix
Set Serverout On
Declare
x Varchar2(2000);
Begin
x := OSCommand_Run('/home/test/myoscommand.sh')
DBMS_OUTPUT.Put_Line(x);
End;
I will check the dbms_scheduler also and will let you know the results.
Thanks -
Different plsql for different Oracle versions
Hi everyone,
I am working on a plsql script which may be run on multiple databases. Unfortunately, I have a need to run one query type if the version is 10g, and another if it is 9i. The 10g query is preferable for the type & amount of information it returns, but 9i does not have the same level of support. I wrote the below (dumbed down for posting purposes) to do this:
spool sqlLog.txt append
set heading off;
SET NEWPAGE 0;
SET SPACE 0;
SET LINESIZE 32767;
SET PAGESIZE 0;
--SET ECHO OFF;
SET FEEDBACK OFF;
SET VERIFY OFF;
SET HEADING OFF;
SET MARKUP HTML OFF;
SET TERMOUT OFF;
SET TRIMOUT ON;
SET TRIMSPOOL ON;
SET WRAP OFF ;
SET LONG 4000;
SET LONGCHUNKSIZE 500;
set serverout on;
set serveroutput on;
declare
ver VARCHAR2(64);
BEGIN
select v.version into ver from product_component_version v where product like '%Oracle%';
ver:=substr(ver,0,2); --remove anything but the highest version number, a.k.a. 9 or 10.
dbms_output.put_line('ver: '||ver);
--10g
IF to_number(ver)>=10
THEN
for csr_10g in (SELECT sql_fulltext, a.parsing_schema_name, b.name, b.value_string
FROM V$SQL a left outer join v$sql_bind_capture b ON a.SQL_ID = b.SQL_ID)
loop
dbms_output.put_line(csr_10g.sql_fulltext||';'|| csr_10g.parsing_schema_name||';'|| csr_10g.name||';'|| csr_10g.value_string);
end loop;
ELSE
--9i
for csr_9i in (SELECT a.sql_Text, b.Schemaname
FROM v$sqlarea a left outer join v$session b ON a.parsing_schema_id=b.schema#
loop
dbms_output.put_line(csr_9i.sql_text||';'|| csr_9i.schemaname||';');
end loop;
END IF;
END;
--run;
spool off;
exit;If I run this on a 10g database, it works correctly, spooling the query return to a file.
If I run this on a 9i database, it will not run, and i get these errors:
FROM V$SQL a left outer join v$sql_bind_capture b ON a.SQL_ID = b.SQL_ID --combine to also find the bound variables used
ERROR at line 13:
ORA-06550: line 13, column 35:
PL/SQL: ORA-00942: table or view does not exist
ORA-06550: line 12, column 17:
PL/SQL: SQL Statement ignored
ORA-06550: line 27, column 30:
PLS-00364: loop index variable 'CSR_10G' use is invalid
ORA-06550: line 27, column 9:
PL/SQL: Statement ignored
Am I doing something wrong with my syntax, or is there another way to go about this?
Thanks!Hi,
Dynamic SQL, like John suggested, might be the most elegant solution, but here are some others to consider:
(1) Create dummy objects. Your code guarantees that you'll never get a run-time error trying to query v$sql in Oracle 9, but the problem is that you're getting a compile-time error just by referencing it. So create a v$sql: a dummy table in your own schema, a synonym to the Oracle 10 data dictionary via a database link, anything just so it compiles.
(2) Create real objects. For example, in your Oracle 9 database, create a view called v$sql, based on v$sqlarea and v$session, that has all the same columns you use in Oracle 10. If you can do this, you won't even need an IF statement in your PL/SQL; the same code that runs against the data dictionary v$sql in Oracle 10 will run against your own schema's v$sql in Oracle 9.
(3) Isolate the problems. Write two different versions of a package, one for each version, and put all version-dependent code in the package. In most of your code, call the procedure to do the version-dependent stuff. For example, don't open a cursor in your program: instead, call the package to open a cursor.
(4) Comment Out. Klugy but cute. Write your PL/SQL without IF statements, like this:
BEGIN
&v10 for csr_10g in (SELECT sql_fulltext, a.parsing_schema_name, b.name, b.value_string
&v10 FROM V$SQL a left outer
&v9 for csr_9i in (SELECT a.sql_Text, b.Schemaname
&v9 FROM v$sqlarea a left outer join v$session b ON a.parsing_schema_id=b.schema#
&v9 join v$sql_bind_capture b ON a.SQL_ID = b.SQL_ID)
loop
&v10 dbms_output.put_line(csr_10g.sql_fulltext||';'|| csr_10g.parsing_schema_name||';'|| csr_10g.name||';'|| csr_10g.value_string);
&v9 dbms_output.put_line(csr_9i.sql_text||';'|| csr_9i.schemaname||';');
end loop;
END;Compile your PL/SQL in SQL*Plus.
Define two substitution variables: v10 and v9.
In Oracle 10, v10 make " " and make v9 "--".
In Oracle 9, v10 make "--" and make v9 " ".
You can do the assignments on the fly with the SQL*Plus "COLUMN ... NEW_VALUE" command.
In either database, code that only works in the other version will be commented out. Your code will look like hell (good spacing and comments will make it less hard to read), but it will compile and work.
None of these ideas are mutually exclusive. You might want to do dynamic SQL in some places, and use on dummy objects in others, for example. -
Export info to excel. (spool ? )
Hi experts..
I have this problem...
I am running oracle 10g and need to export a big query to an excel file...
Im using the spool technique... but.. this is not working when i Have a really big query ( like about 6000 characters....)
I always get an empty excel file..
and the sql file i create, with plsql instrucctions doesnt contain the query to export....
Any oher idea, to create an excel file, and compatible with java 1.4.2 (if posible) will be very well apreciated).
The example only works well whe the query is small....
Here is an example of what I am doing :
datos_xls := ' BIG SQL QUERY WITH ALOT OF concatenations using || ';
xplsql:=' set pagesize 5000 ; set echo off ; set termout off; set feedback off; set feed off markup html on spool on; '
||' spool '||:EXCEL.PATH||'\' ||excel_filename||'; '||datos_xls||'; set markup html off; spool off; exit;';
-- SEND ALL INSTRUCCTIONS TO AN SQL FILE
xpos:=1;
x:=1;
while x<50 and instr(xplsql,';',1,x) <> 0 loop
sqlstr:=substr(xplsql,xpos,instr(substr(xplsql,xpos),';',1,1));
sqlstr:='echo '||sqlstr||' >> '||:EXCEL.PATH||'\'||file_sql;
HOST(sqlstr);
x:=x+1;
xpos:=instr(xplsql,';',1,x)+1;
end loop;
-- NOW EXECUTE THE INSTRUCCTIONS IN THE SQL FILE -----
sqlstr:='sqlplus username/pwd@server @'||:EXCEL.PATH||'\'||file_sql;
HOST(sqlstr);
-- SHOW THE RESULT XLS FILE ON BROWSER--------------
sqlstr:='http://192.168.1.x/'||excel_filename;
WEB.SHOW_DOCUMENT(sqlstr, '_blank');
MESSAGE('<ENTER> DOCUMENT DONE...');
PAUSE;
EXCEPTION
WHEN OTHERS THEN
MESSAGE('***ERROR: '||SQLERRM);
PAUSE;
END;
Thanks in advance.As John has repeated the comment "the author doesn't like URLs to plugins posted here", I'll clarify that it isn't links that I object to - it's the endless flow of tenuously-relevant links/mentions of a poster's own plugins.
-
To automate the SQL scripts using PLSQL Code
Hi All,
I have 20 database server (11.2.0.3) hosted on unix and Windows platforms.
Every day I have to kill inactive sessions from all the these 20 database servers. So I have made a below script::
connect sys/&&sys_password@&&tns_database_name as sysdba
SPOOL E:\DELETE_INACTIVE_SESSIONS.SQL
set PAGESIZE 1000
set LIN 5000
SET ECHO OFF;
SET FEEDBACK OFF;
SET HEADING OFF;
select 'alter system kill session '||'`'||SID||','||SERIAL#||'`'||' immediate;' from v$session where status='INACTIVE' and username in ('OSS_DICTIONARY','ADMINISTRATOR');
SPOOL OFF;
@@E:\DELETE_INACTIVE_SESSIONS.SQL
Is there any way so that this execution of script can be automated in PLSQL code for 20 servers so and that code could be put in batch file for execution(i.e. can be execute through batch file from my windows laptop).
ThanksShrma wrote:
Is there no way to handle the sql scripts in PLSQL code?
Well, remember that PL/SQL is executed on a specific server by a certain user so you are already connected when executing a PL/SQL code.
You could actually use a SQL Plus script to connect to different servers using connect and run your script.
i.e.:
SQL> connect sys/pwd_server1@db_server1
SQL> @killinactive.sql
SQL> connect sys/pwd_server2@db_server2
SQL> @killinactive.sql
But it does not make so much difference with my previous solution.
Please explain exactly what you would like to do.
Regards.
Al -
SQL> spool on D:\rakesh\abc
Started spooling to C:\Program Files\PLSQL Developer\on D:\rakesh\abc\allqueries.lst
SQL> @D:\abc\allqueries.sql;
Table created
Table created
Table altered
Table altered
Table created
Table created
Table altered
Table altered
Table created
Table created
Table altered
Table altered
Table created
Table created
Table altered
Table altered
SQL> commit;
SQL> spool off;
Stopped spooling to C:\Program Files\PLSQL Developer\on D:\rakesh\abc\allqueries.lst
SQL>
I m unable to find the generated spool file, neither in D:\rakesh\abc folder nor C:\Program Files\PLSQL Developer\ MorOver, i searched allqueries.lst and *.lst but couldn`t find latest generated spool file.
Any Suggestions, whats matter?
Message was edited by:
The_RockCheck this:
spool on D:\rakesh\abc
spool syntax is:
Usage: SPOOL { <file> | OFF | OUT }
where <file> is file_name[.ext] [CRE[ATE]|REP[LACE]|APP[END]]
if you set on, it will create an on.lst file, you should specify one single file where you want your spool file to be created:
Example:
spool mySpoolFile.log
~ Madrid -
Is it possible to automate the extraction using spool command?
Hi,
I am trying to export data from table to excel. But the result i am getting will be in million records. Till now i am manually extracting the data using plsql developer. but it is hampering my work alot when i am extracting.
i am able to extract the data using below spool command in sqlplus
set feed off markup html on spool on
spool 'd:\filename.xls'
select * from ca_trial_milestones;
spool off
set markup html off spool off
But is it possible to run it in sql/plsql developer and schedule it on night time.
U r replies will help me alot.
Thanks alot in advance981145 wrote:
Hi,
I am trying to export data from table to excel. But the result i am getting will be in million records. Till now i am manually extracting the data using plsql developer. but it is hampering my work alot when i am extracting.
i am able to extract the data using below spool command in sqlplus
set feed off markup html on spool on
spool 'd:\filename.xls'
select * from ca_trial_milestones;
spool off
set markup html off spool off
But is it possible to run it in sql/plsql developer and schedule it on night time.
U r replies will help me alot.
Thanks alot in advanceYou can create a batch file in window and then setting appropriate environment setting you can do
sqlplus user/pass@connect @scriptnamewhere scriptname is you above script.
You can then schedule this in windows schduler
However excel can not handle more than 1,048,576 rown as of version 2010
You can save the spool as html file and you will able to view the resultset. -
The below code is a shell script to run it as a batch job. The insert code works in a Toad but in unix it doesn't seem to recognize from the declare? what could be the issue?
function insertNewData
printf "Extracting previous month data records \n"
sqlplus -s $USERID_PASSWORD@$ORACLE_SID << THE_END >> $FILENAME
SET NEWPAGE 0
SET SPACE 0
SET LINESIZE 476
SET PAGESIZE 0
SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET TERMOUT OFF
whenever sqlerror exit sql.sqlcode
-- spool $FILENAME
DECLARE
MinCount NUMBER;
BEGIN
SELECT TO_NUMBER(T2.PROP_VAL) INTO MinCount FROM LMN.XYZ_CONFIG T2 WHERE T2.PROP_NAM='CountMin';
INSERT INTO LMN.XYZ_XYZ_ T1
(_ID, STATCD, NUM, CRTE_DT, ENTERED_DTTM, ENTERED_USER_ID,
LAST_UPD_DTTM, LAST_UPD_USER_ID, VER_ID)
SELECT LMN.XYZ_XYZ__SEQ.nextval, 'AP', V1._N, TRUNC(SYSDATE), TRUNC(SYSDATE), 'XYZ_BATCH', TRUNC(SYSDATE),
'XYZ_BATCH', 0
FROM (SELECT DISTINCT V2._NUM N, SUM(V2.CNT) _COUNT
FROM LMN.XYZ_PQR__VW V2
WHERE V2._CNT >= MinCount
GROUP BY V2._NUM ) V1
WHERE NOT EXISTS ( SELECT * FROM LMN.XYZ_XYZ_ WHERE V1._N = LMN.XYZ_XYZ_._NUM);
END;
-- spool off
THE_END
RC=$?
if [ $RC -ne 0 ]
then
printf "Error occurred while Inserting New Alerts Data into LMN.XYZ_XYZ_ Table!\n"
exit -1
fi
# MAIN PROCESSING SECTION
# Set environment
. /apps_01/XYZ/etc/XYZEnv
APP=`basename $0`
TODAY=`date '+%m%d%Y%H%M%S'`
# Set logfile directory and log files
LOG=${XYZ_LOG}/${APP}.log.${TODAY}
#LOG=/home/XYZ/log/${APP}.log.${TODAY}
# Direct all stdout and stderr to the log file
exec >>$LOG 2>&1
printf "\n${APP} processing started at `date` \n"
printf "${APP} data extract started at `date` \n"
#Create the output filename
FILENAME=$XYZ_LOG/XYZAcctDtl.out.${TODAY}
#FILENAME=/home/XYZ/log/XYZAcctDtl.out.${TODAY}
# Retrieve user i and passwoctABM.shrd
USERID_PASSWORD=`cat $XYZ_ETC/userid.dat`
# Do processing
insertNewPQRData
# Data extractr done! Start file transfer
printf "${APP} data purge/insert completed successfully at `date` \n"
RETURN_CD=$?
# Return successful/unsuccessful code
echo "Return Code::::$RETURN_CD"
exit $RETURN_CDOracle version is 9i. Actually there is no error messages. I also have tow other functions but is has only SQL statements . not a pl/sql bloc. These two functions work fine when the scriptis run but dont c any chnges as far as Insert is concerned.
Shell script doesn't throw error.
If i take out the Plsql block and run it on Toad it works fine ?
Any experience dealing with this before.
Tiger -
Plsql developer - cannot run a script
Hi,
I have created some scripts to create some tables, triggers and sequences. To run these scripts I have another script which is like:
set echo on
set feedback on
spool <path>
@@ <first script>
@@ <second script>
so on and at the end closed or ended the spool...........
I am trying to run this script in plsql developer but it gives me an error ............. on every statement .......
Can any one help me how do I run this script........Well the actual scripts (something similar) would have helped.
But since we dont have that let me start with basics
Hope you are running those commands in the COMMAND Window and not sql window?Is that so?
Cheers!!!
Bhushan -
Passing value from plsql back to UNIX
I have a shell script which calls out to a plsql program using sqlplus command, but how do I return the values from the plsql program (a simple SELECT statement) back to the Unix script? Thanks.
JamesCreate one UNIX script
eg :- C2_ATG_Insert.sh
#!/usr/bin/ksh
#Variables to store the values
count=0
Count_ILX_EXCH=0
Count_ILX_CBOE_SERIES=0
Count_ILX_UNDLY_INST=0
Count_STOCK_TIPS=0
Count_TIPSSUM=0
# Block to check whether date is passed as a parameter
if (($# != 1))
then
echo "Usage: C2_ATG_Insert.sh dd-mon-yy"
exit 1
fi
# Assign the trade date to a variable
Temp_Date=$1
# Call the sql, Count_Temp.sql with date as parameter
sqlplus usernam/password@Database_Name @Counts_Temp.sql $Temp_Date
# remove the blank lines
sed '/^$/d' Counts_Temp.lst > Counts_C2ATG.lst
# Store variables from the spooled file which gets generated in Count_Temp.sql into variables defined
while read myline
do
count=$(($count + 1))
case $count in
1) Count_ILX_EXCH=$myline ;;
2) Count_ILX_CBOE_SERIES=$myline ;;
3) Count_ILX_UNDLY_INST=$myline ;;
4) Count_STOCK_TIPS=$myline ;;
5) Count_TIPSSUM=$myline ;;
esac
done < Counts_C2ATG.lst
echo "ILX_EXCH Count $Count_ILX_EXCH"
echo "ILX_CBOE_SERIES Count $Count_ILX_CBOE_SERIES"
echo "LX_UNDLY_INST Count $Count_ILX_UNDLY_INST"
echo "STOCK_TIPS Count $Count_STOCK_TIPS"
echo "TIPSSUM Count $Count_TIPSSUM"
if [ $Count_ILX_EXCH -eq 0 ] || [ $Count_ILX_CBOE_SERIES -eq 0 ] || [ $Count_ILX_UNDLY_INST -eq 0 ] || [ $Count_STOCK_TIPS -eq 0 ] || [ $Count_TIPSSUM -eq 0 ]
then
echo "*********** Count in one of the tables is Zero *****************"
exit 1
fi
Create the SQL File eg Count_Temp.sql
SET heading off
SET VERIFY OFF
SET PAUSE OFF
SET ECHO OFF
SET TIMING OFF
spool Counts_Temp.lst;
select count(*) from ILX_EXCH where trade_date= '&&1'
UNION ALL
select count(*) from ILX_NONCBOE_SERIES where trade_date= '&&1'
UNION ALL
select count(*) from ILX_UNDLY_INST where trade_date = '&&1'
UNION ALL
select count(*) from STOCK_TIPS where trade_date = '&&1'
UNION ALL
select count(*) from TIPSSUM where trade_date ='&&1
spool off;
exit;
Do reply in case you are unable to undertand any part of the scripts -
(SQLPlus) SPOOL
HI,
can anyone help me on this? i want to create a csv file that will have a certain filename coming from a variable from a query. the ff codes does not work :( any help pls! THANKS in advance
BROKEN
select customer_name into v_name from demo_customers where cust_id = 1;
SPOOL ..\data\order_&v_name&.csv
SELECT
order_id || ',' ||
order_total || ',' ||
order_datetime
FROM
demo_orders
WHERE
customer_id =1;
SPOOL OFF;
exit;
------------------------------------------------------------------------------------------------------------------to a bind variable yes, in plsql. To a "define" variable no.
SQL> var n number
SQL> set autopri on
SQL> exec select 1+1 into :n from dual;
PL/SQL procedure successfully completed.
N
2 -
SPOOL_INTERNAL_ERROR spool overflow when submitting the same program
I am submitting the same program via job with different seletion screen values after JOB_OPEN, and then SUBMIT statement and JOB_CLOSE FM. But this job get cancelled with message "ABAP/4 processor: SPOOL_INTERNAL_ERROR" . The submit is as follows:
SUBMIT (sy-repid) USER sy-uname
VIA JOB 'ZTP_SAl_REG_MONITOR_JOBS'
NUMBER l_jobcount
TO SAP-SPOOL
SPOOL PARAMETERS fp_user_print_params
NEW LIST IDENTIFICATION 'X'
WITHOUT SPOOL DYNPRO
WITH rb_monit EQ 'X'
WITH s_jobcnt IN s_jobcnt
WITH p_date EQ p_date
WITH rb_row EQ rb_row
WITH rb_col EQ rb_col
AND RETURN.
Is it possible to use the same program to be scheduled....Let me include that the submit is happening with rb_monit = X and it has separate branch...so infinite looping can not happen.Hi Sumit,
I hope that the flag is ensuring that it doesnt go into infinite loop. You may wish to check that once bcz Spool overflow seems to be bcz of infinite loop or bcz of layout issue.
Goto SP01 in the same client where you have scheduled the job.
Check the spool no. which was generated bcz of the job.
Double click on the STATUS of the spool ( it should be in red background color).
System will give a popup with status details.
Again double click on the status. System will again give a popup.
The popup will give the details of why the spool ran into errors.
Also check the layout.
Thanks,
Best regards,
Prashant
Maybe you are looking for
-
Apps Adapter error while creating hire_applicant
Hi, I tried to create a Oracle Apps adater which converts applicant to employee using HR_APPLICANT_API.HIRE_APPLICANT.But in the design time itself it is showing error "Error while writing WSDL file Exception :the wrapper procedure HR_APPLICANT_API$H
-
I am in trouble any one can solve my problem
sir i make a jar file name abc.jar which contain a folder named images. images have one property file i read to try it but still fail so the path is abc.jar\images\user.properties i use the following code try{ URL u1=null; Properties prop=new Propert
-
HT201343 AirPlay Mirroring. The ATV3 screen goes black.
When my mid MBP 2011 connects via AirPlay Mirroring. Mountain Lion. The screen goes black. It has worked before. Now it doesn't. I checked firewall, graphics switching and rebooting all devices. Streaming via iTunes works fine. ATV3 can access my M
-
I updated to Mavericks and have Logic 10.0.4 I keep getting crashes!!!! *** error for object 0x618000212330: Heap corruption detected, free list canary is damaged Can anybodt help pls. I have removed all my Waves plug ins - just have soundtoys now an
-
I get the message thet my version - Acrobat X - is not real.... - I am a creative Cloud member. ???