SELECT query from within a stored procedure

DB Version:10gR2
For auditing purpose, i just want to execute the query within the IF condition, and get the results for spooling. But i am getting PLS-00428 error. Can't i just execute a SELECT query and get its results displayed in SQLPLUS so that i can spool them?
SQL> create or replace procedure ship_dtl_aud
  2  is
  3  v_exists number;
  4 
  5  begin
  6  
  7  Select count(1) into v_exists
  8  From ship_dtl
  9  WHERE track_code = 10
10  AND mod_date_time < SYSDATE - 1/(24*60);
11 
12   if v_exists>0
13   then
14            select s.username,s.sid, s.serial#, s.terminal,p.spid
15   from v$session s, v$process p
16   where s.paddr = p.addr and s.sid in (select SESSION_ID from V$LOCKED_OBJECT);
17 
18          end if; 
19  end;
20  /
Warning: Procedure created with compilation errors.
SQL> show errors
Errors for PROCEDURE ship_dtl_aud:
LINE/COL ERROR
14/11    PLS-00428: an INTO clause is expected in this SELECT statement

Within PL/SQL code, the results of a query have to be returned from the SQL engine to the PL/SQL engine, hence why it is asking you to include an INTO within your query. Note that the PL/SQL engine is running on the database server so it has no interface to display output to. To output from within PL/SQL you would have to write the data out yourself to whatever output you want e.g. use DBMS_OUTPUT to put the data to the standard output buffer (which can then be read by SQL*Plus if serveroutput is set to "on") or written out to a file on the server, or written out to a table.
You are assuming that because you can execute SQL from SQL*Plus and spool the output, you can do the same within PL/SQL. This is not the case. When SQL*Plus issues a SQL statement, it goes to the SQL engine and the results of that cursor (as an SQL query is a cursor) are collected by SQL*Plus and it displays them itself. When PL/SQL issues a SQL statement, it goes to the SQL engine and the results of that cursor come back to PL/SQL. PL/SQL doesn't have a display mechanism, so the results have to be collected INTO something.
Hope that's clear.

Similar Messages

  • Creating a table/view or temporary table from within a stored procedure

    Hi Gurus,
    Can someone tell me if it is possible to create a table (or view) from within a stored procedure.
    PROBLEM:
    In fact I need to create a report at back end (without using oracle developer forms or reports). This report requires creating several tables to hold temporary report data. If I create a sql*plus script for this, i works fine, because it can run DDL and other sql or pl/sql statements sequencialy. But this sql*plus script cannot be called from application. So, application needs an stored procedure to do this task and then application call that procedure. But within stored procedure, i am unable to create table (or run any ddl statement). Can somebody help me in this?
    Thanks in Advance.

    Denis,
    The problem with Nicholas' suggestion isrelated to the fact that now you have two components
    (a table and a stored procedure)
    I don't see any problem to have "two
    components" here. After all, what about all others
    tabes ? This is only one more, but I don't understand
    why want manage less objects, that implies more code,
    more maintenance, and more difficulties to debug.
    Needless to say about performance...
    Nicolas.The same reasons apply if you were forced to declare all PL/SQL variables publicly (outside the stored proc.) rather than privately (from inside the stored proc). Naming conflicts for one. If the name that you want to use for the GTT already exists, you need to find a new name. With the SQL Server type local/private declarations, you wouldn't have that problem.
    I can see how performance would be the same or better using GTTs. If the number of records involved is low, this is likely negligable.

  • Sending email from within a stored procedure

    Is it possible to send and email within a stored procedure written in PL/SQL. I have searched this site and the web for an Oracle package which simulates a mail agent written in PL/SQL, but I have not had any success.
    null

    Well, on NT one way we did it was to link to kernel32.dll so we could execute OS commands (WinExec), and did the email that way.
    Here's a bit of script to try:
    connect sys/@db;
    drop library kernellib;
    CREATE LIBRARY kernellib as 'c:\winnt\system32\kernel32.dll';
    show errors
    CREATE OR REPLACE PACKAGE UTIL IS
    function run(lpCmdLine IN varchar2, nCmdShow IN binary_integer) return binary_integer;
    end;
    show errors
    CREATE OR REPLACE PACKAGE BODY UTIL IS
    function run(lpCmdLine IN varchar2, nCmdShow IN binary_integer) return binary_integer
    AS EXTERNAL
    NAME "WinExec"
    LIBRARY kernellib
    parameters (lpCmdLine STRING, nCmdShow long);
    end;
    show errors
    Then you just call util.run() with an appropriate command line to send email. Bit of a hack, but it depends on what you want to do with it. Another hack would be to use the UTL_HTTP package to submit a form to your web server and use a CGI program to send the email.

  • Running "Host" From Within a Stored Procedure

    Hellow
    Wanna Run a "Host" Command from Within A SP
    or DB Trigger
    Any Help is Appreciated !!
    Regards
    Tariq

    the only way to run an OS command from within the database is through extproc
    (works from 8.x onwards).
    Essentially, you have to:
    - modify the database listener to support external procedure calls
    - create a library object
    - create a C - program and compile it as a shared library
    - write a wrapper function in PL/SQL that calls the shared library
    I can send you an example, if you want.
    Regards
    Anton Weindl

  • JDBC/select/async statement to JDBC/stored procedure/sync call

    Hi
    We have JDBC/select/async statement to JDBC/stored procedure/sync call i.e sender and receiver are JDBC.
    PI has to pick all the the records of single internal order number at a time from sender system and upload to receiver JDBc,
    gets the response and routes to sender/insert statement.
    This should run only once per day.
    We will have multiple Internal orders daily, each order consisting of 10 to 20 records but only one IO related records has
    to upload to Receiver/JDBC
    What are the options available ?
    We have thought of following options
    1. SQL query is already to pick, but we have to pick records at one time daily. example: morning,evening or midnight.
       At that time it can pick multiple times but it should not pick through out day
    2. Is there any option in BPM so that we can group IO's at a time and upload ? If so what are the steps need to use
       Any additonal receive step need to be used to pick the records from the table.
    Thanks

    hi
    as i can understando you, you will receive mani IO and you must execute one IO in the receiver SP? if so, you can solve this usssing a ccBPM where you will have to create a mapping(0.N) where the source and the target structure will be the same, the diferrence will be in the occurrance of the target structure which will have to be 0.N (Tab signature in Message Mapping). then back to the ccBPM define a block with the property ForEach. this will  loop any times accord with the number of IO that you receive from the sender. as a result you will execute one SP for each IO.
    so, you ccBPM will be
    RS>TS>BLOCK(Multiline container and single container of source structure)>TS->SS
    RS:Receive Step
    TS:Trans. Step
    SS:Send Step
    Also the container will be:
    source--> type Abs
    source_multiline --> type Abs
    target -->type Abs
    Thanks
    Rodrigo P.
    Edited by: Rodrigo Alejandro Pertierra on Jun 24, 2010 4:54 PM

  • BO v5.1 - creating a report from an oracle stored procedure

    Post Author: newrochelle
    CA Forum: Publishing
    hi to all,
    im using BO 5.1 and i need to create a document from an oracle stored procedure that have only one IN parameter and ten OUT parameters.
    Creating the new report I selected the database connection then I choose the stored procedure name from the list, I inserted the value for the IN parameter and finally I click on Run button.
    I got the following error message:
    ORA-06550: line 1, column 38: :PLS-00103: Encountered the symbol
    "," when expecting one of the following: : : ( - + case mod
    new not null others <an identifier> : <a double-quoted
    delimited-identifier> <a bind variable> avg : count current
    exists max min prior sql stddev sum variance : execute forall
    merge time timestamp interval date : <a string literal with
    character set specification> : <a number> <a single-quoted SQL
    string> pipe : <an alternatively-quoted string literal with
    character set specification> : <an alternatively-q :-6550
    it seems to be caused by the OUT parameters!
    i leaved them without any value.
    it's the first time that I used a stored procedure to create a BO report, but I think the OUT parameters are needed to do that, otherwise what data will be presented in the report???
    can you help me?
    please answear me ASAP.
    Thank's in advance
    Regards
    Andrea

    Post Author: synapsevampire
    CA Forum: Publishing
    Try posting in a BO forum, this is Crystal Reports.
    -k

  • T-sql 2008 r2 place results from calling a stored procedure with parameters into a temp table

    I would like to know if the following sql can be used to obtain specific columns from calling a stored procedure with parameters:
    /* Create TempTable */
    CREATE TABLE #tempTable
    (MyDate SMALLDATETIME,
    IntValue INT)
    GO
    /* Run SP and Insert Value in TempTable */
    INSERT INTO #tempTable
    (MyDate,
    IntValue)
    EXEC TestSP @parm1, @parm2
    If the above does not work or there is a better way to accomplish this goal, please let me know how to change the sql?

    declare @result varchar(100), @dSQL nvarchar(MAX)
    set @dSQL = 'exec @res = TestSP '''+@parm1+''','' '''+@parm2+' '' '
    print @dSQL
      EXECUTE sp_executesql @dSQL, N'@res varchar(100) OUTPUT', @res = @result OUTPUT
    select @result
    A complicated way of saying
    EXEC @ret = TestSP @parm1, @parm2
    SELECT @ret
    And not only compliacated, it introduces a window for SQL injection.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Retrieving a UDT object from a Java Stored Procedure

    I am really having trouble returning a UDT object (AttributeUDT) from a Java stored procedure. I am using Oracle 8.1.6 and JDeveloper 3.2.2. I have successfully used JPublisher to create the Java source code files for my UDT, now I would like to use that in coordination with my Java stored procedure. I've loaded the Java stored procedure into the database using the Deployment option in JDeveloper. However, when it loads the procedure, it translates the 3rd parameter to an OBJECT type, thus making the stored procedure invalid. I can use SQL Navigator to correct the package by changing the OBJECT reference to AttributeUDT (my UDT data type). Unfortunately, my Java stored procedure still does not work. Any help would be greatly appreciated! Thanks in advance for your time!
    In the example below, could anyone please tell me:
    1. How do I register the OUT variable for the UDT?
    2. Is it correct to use the casted call to getObject to retrieve my UDT object?
    3. Is it valid to use the UDT data type in the java stored procedure method signature?
    The call to the Java stored procedure:
    OracleCallableStatement cs3 = (OracleCallableStatement)conn.prepareCall( "{ call sandbox.getQualifiersV3( ?, ?, ?) }");
    cs3.registerOutParameter( 1, Types.VARCHAR);
    cs3.registerOutParameter( 2, Types.VARCHAR);
    cs3.registerOutParameter( 3, ???????);
    cs3.execute();
    System.out.println( "ID: " + cs3.getString( 1));
    System.out.println( "Prompt: " + cs3.getString( 2));
    AttributeUDT attributes = (AttributeUDT)cs3.getObject( 3);
    System.out.println( "Table id: " + attributes.getLogicalTableId());
    System.out.println( "Element id: " + attributes.getElementId());
    cs3.close();
    ===========================================
    The Java stored procedure:
    public static void getQualifiersV3( String ids[], String prompts[],
    AttributeUDT attributes[]) throws SQLException {
    OracleConnection conn = (OracleConnection)new OracleDriver().defaultConnection();
    Statement stmt = conn.createStatement();
    OracleResultSet rs = (OracleResultSet)stmt.executeQuery(
    "SELECT * "
    + "FROM VPS_ABOK_QUALIFIERS "
    + "WHERE qualifier_id = 2001");
    rs.next();
    ids[0] = rs.getString( 1);
    prompts[0] = rs.getString( 2);
    attributes[0] = (AttributeUDT)rs.getCustomDatum( 3, AttributeUDT.getFactory());
    rs.close();
    stmt.close();
    null

    Sounds like your C2 REF TYP1 attribute may be null. Unfortunately you neglected to say where in your code the NullPointerException occurs.

  • How to determine the load on the oracle server within a stored procedure?

    Hi,
    I have a subset of commands in my stored procedure that I would like to execute them only if there is not significant load on the database sever.
    What would be the best way to measure the amount of load on my database server within a stored procedure?
    Thank you,
    Alan

    It is not that easy.
    This stored procedure is called by a job that runs every hour. Half of the stored procedure code are mission critical and must run by any means necessary! The second half must run right after the 1st one and is nice to do.
    If I assign a lower priority it makes the situation worst, because then the job might take 3-4 hours and the same jobs run on top of each other over and over.
    I just oversimplified the situation, The point is I prefer not to run the less important PLSQL code rather than assigning lower priority and stretch it over timeline. These hourly jobs are not Oracle jobs and cannot run on top of each other. Last time this happened and I had to kill 12 sessions! (12 jobs in 12 hour)
    Trust me, estimating the load on the database server is the only solution.
    When I say load on the server I mean the load resulted from other oracle sessions on the same database server. This server is a single instance Oracle 10g Enterprise on Solaris. All I need is just accessing to some meaningful counters.
    Any help would be appreciated,
    Alan

  • Calling a servlet from a Java Stored Procedure

    Hey,
    I'm trying to call a servlet from a Java Stored Procedure and I get an error.
    When I try to call the JSP-class from a main-method, everything works perfectly.
    Java Stored Procedure:
    public static void callServlet() {
    try {
    String servletURL = "http://127.0.0.1:7001/servletname";
    URL url = new URL(servletURL);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty("Pragma", "no-cache");
    conn.connect();
    ObjectInputStream ois = new ObjectInputStream(conn.getInputStream());
    Integer client = (Integer)ois.readObject();
    ois.close();
    System.out.println(client);
    conn.disconnect();
    } catch (Exception e) {
    e.printStackTrace();
    Servlet:
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    Integer id = new Integer(10);
    OutputStream os = response.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(id);
    oos.flush();
    oos.close();
    response.setStatus(0);
    Grant:
    call dbms_java.grant_permission( 'JAVA_USER', 'SYS:java.net.SocketPermission','localhost', 'resolve');
    call dbms_java.grant_permission( 'JAVA_USER','SYS:java.net.SocketPermission', '127.0.0.1:7001', 'connect,resolve');
    Package:
    CREATE OR REPLACE PACKAGE pck_jsp AS
    PROCEDURE callServlet();
    END pck_jsp;
    CREATE OR REPLACE PACKAGE BODY pck_jsp AS
    PROCEDURE callServlet()
    AS LANGUAGE JAVA
    NAME 'JSP.callServlet()';
    END pck_jsp;
    Architecture:
    AS: BEA WebLogic 8.1.2
    DB: Oracle 9i DB 2.0.4
    Exception:
    java.io.StreamCorruptedException: InputStream does not contain a serialized object
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java)
    The Servlet and the class work together perfectly, only when I make the call from
    within the database things go wrong.
    Can anybody help me.
    Thank in advance,
    Bart Laeremans
    ... Desperately seeking knowledge ...

    Look at HttpCallout.java in the following code sample
    http://www.oracle.com/technology/sample_code/tech/java/jsp/samples/jwcache/Readme.html
    Kuassi

  • Applying sort to a query returned by a stored procedure

    I am looking for some advice on the best approach for applying a dynamic sort to a query returned by a stored procedure.
    We have a stored procedure that has 3 inputs fields which are used to specify sort columns and it has an additional 3 fields to indicate if the corresponding input column is to be sorted in ascending or descending order. We presently accomplish this by using dynamic SQL in the procedure but this approach has some drawbacks. Ideally we would like these queries to compile just like any other cursor. We have tried using decodes but this does not seem practical or easy to maintain.
    This procedure is used by a web application that allows the user to click on a column header to specify their sort preference. The previous sort selection becomes the second sort field and the one before that the third.
    Your advice is much appreciated!

    I see, so you want to be able to sort by "name desc, age asc, salary asc", for example.
    there is no built in option. it's either dynamic sql, or decodes.
    the decodes could still work, with only 6 lines, but the problem is handling mixed data types. I'll stick with sort col of 1=name (char), 2=number_col, 3=date_col
    order by
      decode(sort_order1, 'A', decode (sort_col1, 1,name_col, 2,to_char(number_col,'9999999999.00000'), 3,to_char(date_col,'yyyymmddhh24miss'), 'X'),'X'),
      decode(sort_order1, 'D', decode (sort_col1, 1,name_col, 2,to_char(number_col,'9999999999.00000'), 3,to_char(date_col,'yyyymmddhh24miss'), 'X'),'X') DESC,
      decode(sort_order2, 'A', decode (sort_col2, 1,name_col, 2,to_char(number_col,'9999999999.00000'), 3,to_char(date_col,'yyyymmddhh24miss'), 'X'),'X'),
      decode(sort_order2, 'D', decode (sort_col2, 1,name_col, 2,to_char(number_col,'9999999999.00000'), 3,to_char(date_col,'yyyymmddhh24miss'), 'X'),'X') DESC,
      decode(sort_order3, 'A', decode (sort_col3, 1,name_col, 2,to_char(number_col,'9999999999.00000'), 3,to_char(date_col,'yyyymmddhh24miss'), 'X'),'X'),
      decode(sort_order3, 'D', decode (sort_col3, 1,name_col, 2,to_char(number_col,'9999999999.00000'), 3,to_char(date_col,'yyyymmddhh24miss'), 'X'),'X') DESC,Message was edited by:
    shoblock
    forgot to make 3 asc/desc variables

  • Connecting to SQL Server and MYSQL from a Java stored procedure

    hope someone can help with this. i'm trying to connect to different databases (My SQL, SQL Server) from a java stored procedure. when invoking from within an oracle 9i database, i get the java exception error -
    "Cannot connect to MySQL server on 135.177.196.75:3306. Is there a MySQL server running on the machine/port you are trying to connect to?java.security.AccessControlException)".
    this store procedure works fine when invoked from outside of oracle. any replies would be greatly appreciated. thanks!

    the correct drivers have been loaded. it works when called from outside of oracle. only when invoking from within oracle do we get the error message "Cannot connect to MySQL server on 135.177.196.75:3306. Is there a MySQL server running on the machine/port you are trying to connect to?(java.security.AccessControlException)". it sounds like a permissions/security/configuration issue - oracle is not allowing access to the machine/port for the MySQL or SQL Server database. appreciate the responses so far.

  • Call a UNIX shell script from an oracle stored procedure

    We need to call a UNIX shell script from an oracle stored procedure
    i.e. the control should come back to the procedure once the script completes. Can any body help to achieve this ?

    There are various ways in achieving this.
    For Example, you can call a PRO*C-Library residing on the database server.
    This requires a PL/SQL library to be generated and some changes to the Listener configuration.
    It is also possible to implement a java procedure on the database being invoked by a PL/SQL wrapper class.
    In this way (and if used right) there is also granularity regarding the filestructure permissions given and it may be called during a Forms or other PL/SQL session.
    The article below explains a more generic approach how to invoke shell commands from within an Oracle Instance.
    Be careful with this, because it really works ;)
    Refer to :
    http://www.oracle-base.com/articles/8i/ShellCommandsFromPLSQL.php
    Message was edited by:
    user434854

  • Invoking "java myClass" using Runtime.Exec from a Java Stored Procedure

    Hi All,
    This is regarding the use of Runtime.getRunTime().exec, from a java programme (a Java Stored Procedure), to invoke another Java Class in command prompt.
    I have read many threads here where people have been successuful in invoking OS calls, like any .exe file or batch file etc, from withing Java using the Runtime object.
    Even i have tried a sample java programme from where i can invoke notepad.exe.
    But i want to invoke another command prompt and run a java class, basically in this format:
    {"cmd.exe","java myClass"}.
    When i run my java programme (in command prompt), it doesnt invoke another command prompt...it just stays hanging.
    When i run the java programme from my IDE, VisualCafe, it does open up a command prompt, but doesnt get the second command "java myCLass".
    Infact on the title of the command prompt (the blue frame), shows the path of the java.exe of the Visual Cafe.
    and anyway, it doesnt run my java class, that i have specified inside the programme.
    Even if i try to run a JAR file, it still doesnt do anything.
    (the JAR file other wise runs fine when i manually invoke it from the command prompt).
    Well, my question is, actually i want to do this from a Java Stored Procedure inside oracle 8.1.7.
    My feeling is, since the Java Stored Procedure wont be running from the command prompt (i will be actually invoking it through a Oracle trigger), it may be able to invoke the command prompt and run the java class i want. and that java class has to run with the SUn's Java, not Oracle JAva.
    Does any one have any idea about it?
    Has anyone ever invoked a java class or JAR file in command prompt from another Java Programme?
    YOur help will be highly appreciated.
    (P:S- Right now, my database is being upgraded, so i havent actually been able to create a Java Stored procedure and test it. But i have tested from a normal java programme running in command prompt and also from Visual Cafe).
    Thanks in advance.
    -- Subhasree.

    Hello Hari,
    Thanks for your quick reply.
    Can you please elaborate a little more on exactly how you did? may be just copy an dpaste taht part of teh code here?
    Thanks a lot in advance.
    --Subhasree                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem while calling webservice from a plsql stored procedure

    Hi everybody,
    I need to call a webservice from a plsql stored procedure.
    I was following documentation published in the otn at the following link.
    "http://www.oracle.com/technology/tech/webservices/htdocs/samples/dbwebservice/DBWebServices_PLSQL.html"
    I am encountering the following error on my sql prompt-
    SQL> exec dbms_output.put_line(time_service.get_local_time('94065'));
    BEGIN dbms_output.put_line(time_service.get_local_time('94065')); END;
    ERROR at line 1:
    ORA-29273: HTTP request failed
    ORA-06512: at "SYS.UTL_HTTP", line 1022
    ORA-12545: Connect failed because target host or object does not exist
    ORA-06512: at "APPS.DEMO_SOAP", line 65
    ORA-06512: at "APPS.TIME_SERVICE", line 13
    ORA-06512: at line 1
    Has anybody worked on the same example. Please direct me.
    Thanks & Regards
    Kiran Kumar

    Kiran, were you able to solve this?
    I am facing the same error.
    Oracle Server is Unix and webservice is .NET.
    I am able to connect to Java web service.

Maybe you are looking for

  • Prompted to install Yahoo Messenger upon restart even though already installed

    I have Yahoo Messenger (3.0.1 beta) installed on my MacBook Air (Lion OS X 10.7.2). It is working fine, however every time I restart my computer and access the Flash Drive (Go - Computer) or the Applications Folder (Go - Applications) I'm prompted to

  • PDPageDrawContentsToWindowEx takes too much time

    We are using an Acrobat plugin that renders the PDF file to a bitmap in memory. We are using Acrobat Professional X. But same problems also appear on Acrobat 9. We have received several problematic PDF files from our customers that is causing the cal

  • Standard and Detailed Profitability

    Hello Gurus I am a newbie in HPCM. I am aware that there are standard and detailed HPCM available, standard HPCM uses Essbase while detailed HPCM uses a relational database. What are the Pros and Cons and major differences for these two? Thank you ve

  • Semaphore

    synchornized getResource(){ semaphore -- ; if( semaphore < 0 ){ wait(); //thread sleep and procedure pause here do retrieve resource steps here synchronized putResource(){ do put resource steps here semaphore ++; if( semaphore <= 0){ notify(); semaph

  • Integration between Budgeting and Personnel cost planning

    Respect to all HCM consultants, I am working on personnel cost planning and compensation management. I would like to use the value of personnel cost planning scanarios on approval as the value for budget. in other words i want to integrate PCP and bu