Exec SQLPLUS command from PL/SQL Block
Good Morning:
How I can execute a SQLPLUS command (like SPOOL or DESCRIBE) from PL/SQL Block Procedure?:
DECLARE
BEGIN
ls_command = 'DESCRIBE '||ls_table_name;
EXECUTE SQLPLUS(ls_command);
END;
Thanks a lot for any idea.
That's correct.
However, in the case of the given example we can use DBMS_DESCRIBE package to get table descriptions. And we can use UTL_FILE to spool PL/SQL stuff to a file.
Cheers, APC
Similar Messages
-
Running sqlldr command from PL/SQL Block
DECLARE
BEGIN
END;In SQL * plus we can run DOS commands using the following command
HOST DIR
HOST DIR/P
But When we can't run the HOST command in PL/SQL Block..
I have to Run sqlldr command from PL/SQL Block..
i tried as follows
DECLARE
BEGIN
EXECUTE IMMEDIATE ' host sqlldr control= bad= ';
END;
By
BalaNagaRaju -
Running a OS command from PL/sql Block.
I am using UTL_FILE to write data to a text file from within a stored procedure.Before terminating the procedure i would like to run FTP command on the server to copy the file to a different server. Can this be done..... ? Or is this asking for too much..
nullSearch the forums for 'external procedure'. There are examples that have been posted in the past few weeks.
null -
Calling sql script from pl/sql block
Hi
I want to call a sql script from pl/sql block.
like
CREATE OR REPLACE procedure DataBaseExport(user_name in varchar2, pwd in varchar2)
as
begin
execute immediate '@ C:\Documents and Settings\umesh\emp.sql';
end DataBaseExport;
/Try something like this -
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "Host" AS
import java.io.*;
public class Host
public static void executeCommand(String command)
try {
String[] finalCommand;
if (isWindows())
finalCommand = new String[4];
// Use the appropriate path for your windows version.
finalCommand[0] = "C:\\windows\\system32\\cmd.exe"; // Windows XP/2003
//finalCommand[0] = "C:\\winnt\\system32\\cmd.exe"; // Windows NT/2000
finalCommand[1] = "/y";
finalCommand[2] = "/c";
finalCommand[3] = command;
else
finalCommand = new String[3];
finalCommand[0] = "/bin/sh";
finalCommand[1] = "-c";
finalCommand[2] = command;
final Process pr = Runtime.getRuntime().exec(finalCommand);
pr.waitFor();
new Thread(new Runnable()
public void run()
BufferedReader br_in = null;
try
br_in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String buff = null;
while ((buff = br_in.readLine()) != null)
System.out.println("Process out :" + buff);
try {Thread.sleep(100); } catch(Exception e) {}
br_in.close();
catch (IOException ioe)
System.out.println("Exception caught printing process output.");
ioe.printStackTrace();
finally
try {
br_in.close();
} catch (Exception ex) {}
).start();
new Thread(new Runnable()
public void run()
BufferedReader br_err = null;
try
br_err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String buff = null;
while ((buff = br_err.readLine()) != null)
System.out.println("Process err :" + buff);
try
Thread.sleep(100);
} catch(Exception e) {}
br_err.close();
catch (IOException ioe)
System.out.println("Exception caught printing process error.");
ioe.printStackTrace();
finally
try
br_err.close();
catch (Exception ex) {}
).start();
catch (Exception ex)
System.out.println(ex.getLocalizedMessage());
public static boolean isWindows()
if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1)
return true;
else
return false;
CREATE OR REPLACE PROCEDURE Host_Command (p_command IN VARCHAR2)
AS LANGUAGE JAVA
NAME 'Host.executeCommand (java.lang.String)';
--- THE PERMISSIONS ---
call dbms_java.grant_permission('SYSTEM', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');And, finally,
create or replace procedure call_sql_file(usr in varchar2,
pwd in varchar2,
host_str in varchar2)
is
begin
host('sqlplus -s usr/pwd@host_str C:\UAX_Auto_Count.sql');
exception
when others then
dbms_output.put_line(sqlerrm);
end;Now, you can pass all the argument in order to execute that file.
N.B.: Not Tested...
Regards.
Satyaki De. -
O/s commands from PL/SQL
hi all..
i want to execute operating system commands from PL/SQL..
particulary imp command....
i have used the f/wg approach but while i execute the imp command it does not responds me any output..
I have to kill the process from o/s.
prodn is my user
--AS SYS user
begin
dbms_java.grant_permission( 'PRODN',
'SYS:java.io.FilePermission',
'/oracle/product/9.2.0/bin/imp',
'execute' );
dbms_java.grant_permission
('PRODN',
'java.lang.RuntimePermission',
'writeFileDescriptor' );
end;
---------------------------------AS PRODN user
create or replace and compile
java source named "Util"
as
import java.io.*;
import java.lang.*;
public class Util extends Object
public static int RunThis(String args)
Runtime rt = Runtime.getRuntime();
int rc = -1;
try
Process p = rt.exec(args);
int bufSize = 4096;
BufferedInputStream bis = new BufferedInputStream(p.getInputStream(),
bufSize);
int len;
byte buffer[] = new byte[bufSize];
// Echo back what the program spit out
while ((len = bis.read(buffer, 0, bufSize)) != -1)
System.out.write(buffer, 0, len);
rc = p.waitFor();
catch (Exception e)
e.printStackTrace();
rc = -1;
finally
return rc;
create or replace
function RUN_CMD(p_cmd in varchar2) return number
as
language java
name 'Util.RunThis(java.lang.String) return integer';
create or replace procedure RC(p_cmd in varchar2)
as
x number;
begin
x := run_cmd(p_cmd);
end;
i executed the command as follows in sql>
BEGIN
rc('/oracle/product/9.2.0/bin/imp tim/tim file=/home/oracle/vas4359.dmp log
=log1.log');
END;
it runs fine creates log1.log in / home/oracle but there is no output in
log1.log file.
I have to kill the process as follows after which sql> displays me :
"PL/SQL procedure successfully completed."
[oracle@msebdb oracle]$ ps aux|grep imp
oracle 20052 0.0 0.2 12732 4328 ? S 11:57 0:00 /oracle/product/
.2.0/bin/imp file=/home/oracle/vas4359.dmp log=log1.log
oracle 20102 0.0 0.0 3692 652 pts/2 S 12:03 0:00 grep imp
Note:There is no tim user.. i just want to get error in my log file..
my further steps are to read this log file and send email/notifications to users.
my main program is as f/ws:
/*imp and check log file*/
create or replace procedure abc
as
v_exists boolean;
v_exists_log boolean;
ex_open BOOLEAN;
flen NUMBER;
bsize NUMBER;
vInHandle_open utl_file.file_type;
vInHandle_open_log utl_file.file_type;
v_filelog utl_file.file_type;
v_fl utl_file.file_type;
v_pth varchar2(60);
v_fnm varchar2(60);
v_file_exists varchar2(60);
v_logline varchar2(30) ;
v_search varchar2(30) :='ORA-';
vNewLine VARCHAR2(32767);
cursor c_fname is
select full_pth ,f_name from upld_file_t where f_name in
(select f_name from tbl_file_nm where typ_file='D' AND DEL_FLG='N');
BEGIN
for v_sec in c_fname
loop
utl_file.fgetattr(LOCATION=>'ORALOAD',
FILENAME=>v_sec.f_name,
FEXISTS=>v_exists,
FILE_LENGTH=> flen,
BLOCK_SIZE=>bsize);
if v_exists
THEN
dbms_output.put_line('File Exists' || v_sec.f_name);
v_file_exists:=v_sec.f_name;
--dbms_output.put_line('v_file_exists ' || v_file_exists);
dbms_output.put_line('File Length: ' || TO_CHAR(flen));
dbms_output.put_line('Block Size: ' || TO_CHAR(bsize));
dbms_output.put_line(' before file open');
vInHandle_open := utl_file.fopen('ORALOAD',v_sec.f_name,'R',32767);
-- dbms_output.put_line(' after file open');
-- do whater with teh file data
v_fl:=utl_file.fopen('ORALOAD','v_sec.f_name','W');
dbms_output.put_line('v_sec.f_name');
IF utl_file.is_open(vInHandle_open)
THEN
/*if log file exists..*/
utl_file.fgetattr(LOCATION=>'ORALOAD',
FILENAME=>v_sec.f_name||'.log',
FEXISTS=>v_exists_log,
FILE_LENGTH=> flen,
BLOCK_SIZE=>bsize);
if v_exists_log
then
dbms_output.put_line('file' ||v_sec.f_name||'.log');
v_filelog :=utl_file.fopen('ORALOAD',v_sec.f_name||'.log','W',32767);
LOOP
BEGIN
UTL_FILE.PUT(v_filelog,'ORA-');
exit;
END;
END LOOP;
else
dbms_output.put_line('File not found' || v_sec.f_name);
END IF;
UTL_FILE.fclose(v_filelog);
dbms_output.put_line('Closed File ' || v_sec.f_name|| '.log');
END IF;
/*imp THE FILE and read log file*/
utl_file.fgetattr(LOCATION=>'ORALOAD',
FILENAME=>v_sec.f_name||'.log',
FEXISTS=>v_exists_log,
FILE_LENGTH=> flen,
BLOCK_SIZE=>bsize);
if v_exists_log
then
dbms_output.put_line('file' ||v_sec.f_name||'.log');
v_filelog :=utl_file.fopen('ORALOAD',v_sec.f_name||'.log','R',32767);
LOOP
BEGIN
UTL_FILE.get_line(v_filelog,v_logline);
if v_logline = v_search then
dbms_output.put_line(v_logline);
end if;
UTL_FILE.fclose(v_filelog);
dbms_output.put_line('Closed File ' || v_sec.f_name|| '.log');
exit;
END;
END LOOP;
else
dbms_output.put_line('File not found' || v_sec.f_name);
END IF;
END IF;
END LOOP;
--close the curosr .. check this
EXCEPTION
WHEN UTL_FILE.ACCESS_DENIED THEN
DBMS_OUTPUT.PUT_LINE('No Access!!!');
when others then
dbms_output.put_line('ERROR (open_file) => '||sqlcode);
dbms_output.put_line('MSG (open_file) => '||sqlerrm);
end;Hi,
You might have better luck in the PL/SQL or Java forums. They are located here:
PL/SQL: PL/SQL
Java: http://forums.oracle.com/forums/forum.jsp?forum=99
Good luck,
Mark -
Calling Operating System Commands from PL/SQL using java
Calling Operating System Commands from PL/SQL - The Java Way
wlth help of given thread link,
Calling OS Commands from Plsql
but i had user privilege problem
Declare
x Varchar2(2000);
Begin
x := OSCommand_Run('/tmp/sri/GROUP_ho.sh');
DBMS_OUTPUT.Put_Line(x);
End;
o/p;
can't exec: /tmp/sri/GROUP_ho.sh lacks user privilege
i done the grant privillage also
part
dbms_java.grant_permission('abcd', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
dbms_java.grant_permission('abcd', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
dbms_java.grant_permission('
abcd', 'SYS:java.io.FilePermission','<<ALL FILES>>', 'execute');
again
get
can't exec: /tmp/sri/GROUP_ho.sh lacks user privilege
same error;Process management at the OS level should prevent execution continuing in the calling code until the command has completed (either successfully or with error).
If the low level java code were to spawn child process threads then execution could continue, but I'm guessing the Java function your talking about doesn't do that and just calls the operating system to execute the command and waits for the returning code to come back. -
Sqlplus commands from withing the batch files
Hi,
Oracle9.2
need to execute the sqlplus commands from withing the batch files without calling the .sql file separately . How it can be done ?
With RegardsHi,
I agree with you...but as per your solution, after all you are calling the .sql file while connecting the sqlplus which I know already and I don't want to execute the sql commands like that as shown below.
For example:
for shut down the database and starting it again .sql files will be called as shown below
Note: shutdown.sql file will contain simple database shutdown command.
sqlplus -s "sys/%password%@%tnsname% as sysdba" @D:\shutdown_db.sql
and again for restarting the db i will perform as below
sqlplus -s "sys/%password%@%tnsname% as sysdba" @D:\start_db.sql
But I want to get it executed directly from the DOS batch file.
The thing is I want to execute this both the above database commands from the batch file itself without calling the .sql files separately as shown above.
is it possible, so how it can be done ?
Regards
Edited by: user640001 on Feb 9, 2011 9:53 PM -
Run OS command from Pl/SQL
Is there any way to execute an OS command from pl/sql other than using dbms_pipe & pro*C combo. I have done this way before but it seems there is built-in oracle package which can do this in 8/8i.
Also HOST command in forms will execute the OS coomand from the clinet. Is there any way to execute the OS command on the server from the forms clinet?
thanks,
Ravi.
nullRavi,
Can you send me an example how one can
execute a this command from a PL/SQL
program 'sed 3q /etc/passwd'.
Please write to me at
[email protected]
thanks
Pramod -
Is it possible to call a windows batch file from PL/SQL block ??
Hi gurus,
Would require your help.Is it possible to call a windows batch file from PL/SQL block ??If yes can you give an example for the same or any workaround for the same.
Regards
VijayYou didn't specify a database version, but if you are 10g or higher, it's quite straightforward using an external job type in DBMS_SCHEDULER. Funnily enough i'm looking at something similar myself at the moment.
Useful guide to some of the issues here Guide to External Jobs on 10g with dbms_scheduler e.g. scripts,batch files -
How to: execute operating system commands from PL/SQL
System: IBM pSeries AIX
Oracle: 11g Enterprise
Is there a quick way to execute operating system commands from PL/SQL?
Without creating a JAVA class....
I need to execute a Loader script.
I want to do this from within PL/SQL.
I need to to do 4 things.
Three require SQL scripts.
The fourth is SQL*Loader.
The usual way is with a UNIX script calling 3 SQL scripts and one Loader control file.
Is there way to do all this from within ONE PL/SQL SCRIPT ??
Just let me know.Is there a quick way to execute operating system commands from PL/SQL?
NO
Without creating a JAVA class....
I need to execute a Loader script.
I want to do this from within PL/SQL.
WHY ON EARTH, such action will create a new connection and become a resource hog?
I need to to do 4 things.
Three require SQL scripts.
The fourth is SQL*Loader.
The usual way is with a UNIX script calling 3 SQL scripts and one Loader control file.
Which is perfect for the purpose.
Is there way to do all this from within ONE PL/SQL SCRIPT ??
Just let me know.
NO, there is NOT. Nor should there be. Why create unstable ineffcient Mickey Mouse systems, glued together by hacking?
Sybrand Bakker
Senior Oracle DBA -
Fire OMB Plus commands from PL/SQL
Hi all,
does anyone know if it is possible to fire OMB Plus commands from PL/SQL procedures?
I can imagine that there might be a PL/SQL package in the repository owner schema that accepts OMB Plus commands as strings...or something similar...
Thanks,
ElioHi Elio
I don't know about any existing package that could do that.
What I'd suggest is to build a stored procedure/function/package that could do that. Or even, execute OMB Scripts in the host from a pl/sql program.
Good luck.
Regards,
Marcos -
Copy Command in Pl/Sql block
Can I use Copy command in Pl/Sql.For example :-
Declare
cursor c1 is select table_name from all_tables
where owner = 'LSP' and rownum = 1;
v1 varchar2(2000);
Begin
for c2 in c1 loop
v1:='copy from lsp/lsp123479@dvlaq to scott/[email protected] create '|| c2.table_name ||' using select * from '||c2.table_name;
execute immediate v1;
end loop;
end;
Its not running properly giving an error as invalid Sql statement .
Is it bcoz Copy command cannot be used in a Pl/Sql Block.Is there any other way to move the Table & data to another Data Base .Database link is the obvious one. And the SQL statement would look something like this (on the target database):
SQL> create table FOO nologging as select * from FOO@sourcedb;
However, the first question I always ask if why? What one may think is the solution to a problem is not always the best solution. So one need to identify the problem first, and then see what solutions there are and which one is the best fit.
Other options are replication (using materialised views for example), Data Pump (available with 10G) - even could be Data Guard, a standby database, or a Real Application Cluster... depending on just what the problem and actual requirements are.
Also important to note that SQL*Plus has its own set of commands. Do not confuse these commands (like EXEC, COPY, CONNECT, HOST etc) with the SQL and PL/SQL Languages. Not only are they executed by different software products, SQL*Plus commands are executed on the client and SQL (and PL/SQL) runs inside the Oracle database instance. -
OS command from PL/SQL code
Is there any way of running on OS (Operating System) command from SQL or PL/SQL. i.e. calling an executable from a trigger.
Is there any way of running on OS (Operating System) command from >SQL or PL/SQL. i.e. calling an executable from a trigger. Ashis,
Here's an example of a simple piece of Java you can create using SQL*Plus:
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "RuntimeExample" AS public class RuntimeExample {
public static String runNotepad() {
String returnValue = null;
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec("notepad.exe");
returnValue = p.toString();
} catch (Exception e) {
System.out.println("Exception calling Runtime.exec()->" + e);
/* You can get creative here and
1) Use p.waitFor() to block while the process is running,
2) Send the command to be executed as a parameter to the method, etc. */
return returnValue;
CREATE OR REPLACE FUNCTION runNotepad RETURN VARCHAR2 IS
LANGUAGE JAVA NAME 'RuntimeExample.runNotepad() return java.lang.String';
DECLARE
my_varchar2 VARCHAR2(64);
BEGIN
my_varchar2 := runnotepad;
DBMS_OUTPUT.PUT_LINE(my_varchar2);
END;
Hope this helps,
-Dan
http://www.compuware.com/products/numega/dbpartner/dbpordebug.htm
Debug Java in the Oracle Database -
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 ==================================================== -
Get data from PL/SQL block and generate the data file in UNIX
Hi All
i was executing the following code block from Unix Shell Script. The following code was generating the file count_curdate.txt with all require infomrations. The query gives number of records , group by partition_dt
ABC=`sqlplus -s <<EOF > count_curdate.txt
uname/paswd@connectstring
SET HEADING OFF;
SELECT COUNT(*)||','||partition_dt from XYZ group by partition_dt;
exit;
END`
But now i need to change the above code to use dbms_application_info.set_module in it. Could someone let me know how to generate the file using PL/SQL block in Shell Script. I tried writing following code, but it generate count_curdate.txt file with 0 bytes.
ABC=`sqlplus -s <<EOF > count_curdate.txt
uname/paswd@connectstring
set serveroutput on;
SET HEADING OFF;
set feedback off;
BEGIN
dbms_application_info.set_module ('shm.ksh','get count by day');
FOR reccur IN (SELECT COUNT(*)||','||partition_dt as "dcount" from XYZ group by partition_dt);
LOOP
DBMS_OUTPUT.PUT_LINE(reccur.dcount);
END LOOP;
end;
exit;
END`OK, try this:
ABC=`sqlplus -s <<EOF > count_curdate.txt
uname/paswd@connectstring
set serveroutput on;
SET HEADING OFF;
set feedback off;
BEGIN
dbms_application_info.set_module ('shm.ksh','get count by day');
FOR reccur IN (SELECT COUNT(*)||','||partition_dt dcount from XYZ group by partition_dt);
LOOP
DBMS_OUTPUT.PUT_LINE(reccur.dcount);
END LOOP;
dbms_application_info.set_module (NULL,NULL);
end;
exit;
EOF`Or this:
ABC=`sqlplus -s <<EOF > count_curdate.txt
uname/paswd@connectstring
set serveroutput on;
SET HEADING OFF;
set feedback off;
BEGIN
dbms_application_info.set_module ('shm.ksh','get count by day');
END;
SELECT COUNT(*)||','||partition_dt dcount from XYZ group by partition_dt;
BEGIN
dbms_application_info.set_module (NULL,NULL);
END;
exit;
EOF`Edited by: SeánMacGC on May 11, 2009 6:13 AM
Maybe you are looking for
-
How to connect a 2009 Cinema Display with mini DisplayPort to modern card
Hello: I am ready to install a new NVidia Quadro K5000 for Mac in my not so old Mac Pro 4,1 (2009). I already installed Mountain Lion (10.8.3) as required. The problem is that the Mac Pro came with a Led Cinema Display which apparently only can be co
-
Sharing library for multiple users on same computer
I have 2 non-administrator accounts and an administrator account on one Mac. (G5 running Tiger). I have tried various ways of sharing songs between all of these accounts. What I am trying to do is have the 3 accounts show the same songs when they ope
-
Calendar App: color coded events...
Hello, Like most folks I have a number of calendars - home, personal projects, work, etc. Each is handily color coded in Calendar, which is great. So far, so good. However, in my *single* work calendar (which is served from a company account on Googl
-
Problems While Accessing ASM In Oracle 11.2.0.1
Hi All, In my UAT database I could see all my database services are up and running. oracle@blrvqorasdb01:ARSUATDB [home/oracle] > ps -ef|grep pmon oracle 4409 3229 0 09:34:57 ? 0:12 ora_pmon_ARSUATDB oracle 10111 9608 0 15:59:59 pts/6 0:00 grep pmon
-
Using attribute as a set of data and parsing this data
Hi everyone, I present below a (little) challenge with the use of attributes in XQuery. Consider the following XML document: <showroom> <car id="1"> <name>Clio</name> <family>Renault</family> </car> <car id="n"> <name>Q5</name> <family>Audi</family>