SELECT statement in stored procedure
I want to be able to execute a simple SELECT statement from within a stored procedure and return a stream of data which consists of all the rows from the SELECT statement.
Ultimately, I want to ouput this stream of data to a Crystal Report.
Apparently, Oracle will not allow you to execute a simple SELECT statement from within a stored procedure. It will only allow execution of a SELECT INTO statment, which requires that you define a cursor, etc. etc.
Any way around this?
Thanks
Bill
Look into REF CURSORs. Still not sure about whether APEX uses them though.... Good luck.
Similar Messages
-
How to convert simple SQL Select statements into Stored Procedures?
Hi,
How can I convert following SELECT statement into a Stored Procedure?
SELECT a.empno, b.deptno
FROM emp a, dept b
WHERE a.deptno=b.deptno;
Thanking in advance.
Wajidstored procedure is nothing but a named PL/SQL block
so you can do it like this see below example
SQL> create or replace procedure emp_details is
2 cursor c1 is SELECT a.empno, b.deptno
3 FROM scott.emp a, scott.dept b
4 WHERE a.deptno=b.deptno;
5 begin for c2 in c1
6 LOOP
7 dbms_output.put_line('name is '||c2.empno);
8 dbms_output.put_line('deptno is ' ||c2.deptno);
9 END LOOP;
10 END;
11 /
Procedure created.and to call it use like below
SQL> begin
2 emp_details;
3 end;
4 /
PL/SQL procedure successfully completed.
SQL> set serveroutput on;
SQL> /
empno is 7839
deptno is 10
empno is 7698
deptno is 30
empno is 7782
deptno is 10
empno is 7566
deptno is 20
empno is 7654
deptno is 30
empno is 7499
deptno is 30
empno is 7844
deptno is 30
empno is 7900
deptno is 30
empno is 7521
deptno is 30
empno is 7902
deptno is 20
empno is 7369
deptno is 20
empno is 7788
deptno is 20
empno is 7876
deptno is 20
empno is 7934
deptno is 10Edited by: Qwerty on Sep 17, 2009 8:37 PM -
SELECT QUERY USING STORED PROCEDURE
Hi,
I am using stored procedure in package, i need to execute select statement using
stored procedure.
regards,
p.kumaran? not framed properly i think so if u dnt mind plz check it out once
if u wnt to invoke a proc from package 2 ways r there
1) execute pac_name.proc_name[(arg_list)];
2) pl/sql
[declare]
begin
pac_name.proc_name[(arg_list)];
end;
/ -
MS SQL Server 7 - Performance of Prepared Statements and Stored Procedures
Hello All,
Our team is currently tuning an application running on WL 5.1 SP 10 with a MS
SQL Server 7 DB that it accesses via the WebLogic jConnect drivers. The application
uses Prepared Statements for all types of database operations (selects, updates,
inserts, etc.) and we have noticed that a great deal of the DB host's resources
are consumed by the parsing of these statements. Our thought was to convert many
of these Prepared Statements to Stored Procedures with the idea that the parsing
overhead would be eliminated. In spite of all this, I have read that because
of the way that the jConnect drivers are implemented for MS SQL Server, Prepared
Statments are actually SLOWER than straight SQL because of the way that parameter
values are converted. Does this also apply to Stored Procedures??? If anyone
can give me an answer, it would be greatly appreciated.
Thanks in advance!Joseph Weinstein <[email protected]> wrote:
>
>
Matt wrote:
Hello All,
Our team is currently tuning an application running on WL 5.1 SP 10with a MS
SQL Server 7 DB that it accesses via the WebLogic jConnect drivers.The application
uses Prepared Statements for all types of database operations (selects,updates,
inserts, etc.) and we have noticed that a great deal of the DB host'sresources
are consumed by the parsing of these statements. Our thought was toconvert many
of these Prepared Statements to Stored Procedures with the idea thatthe parsing
overhead would be eliminated. In spite of all this, I have read thatbecause
of the way that the jConnect drivers are implemented for MS SQL Server,Prepared
Statments are actually SLOWER than straight SQL because of the waythat parameter
values are converted. Does this also apply to Stored Procedures???If anyone
can give me an answer, it would be greatly appreciated.
Thanks in advance!Hi. Stored procedures may help, but you can also try MS's new free type-4
driver,
which does use DBMS optimizations to make PreparedStatements run faster.
Joe
Thanks Joe! I also wanted to know if setting the statement cache (assuming that
this feature is available in WL 5.1 SP 10) will give a boost for both Prepared Statements
and stored procs called via Callable Statements. Pretty much all of the Prepared
Statements that we are replacing are executed from entity bean transactions.
Thanks again -
Using Copy statement in Stored procedure
The following statement works in sqlplus session:
copy from comment/password@servername append amcomment_temp using
select * from amcomment
where commentid in(1,2,3,4)
I want to use this in a stored procedure. There is a long datatype in this table. The
procedure will not compile. Have tried execute immediate and compiler rejects this statement also.'COPY' is a SQL*Plus command, not PL/SQL. This is why the PL/SQL compiler throws it out.
-
XmlAgg Order By in SQL Statement vs Stored Procedure - 9.2.0.3.0
Hi All,
I'm having a problem with the XMLAgg function's ORDER BY clause after upgrading to 9.2.0.3.0.
I'm finding that I can succesfully execute a SQL statement with the XMLAgg ORDER BY clause, but cannot compile a stored procedure using ORDER BY. Below are two examples executing against the SCOTT Schema. They use the same code, except one is contained in a procedure.
I'm running 9.2.0.3.0 on Windows XP Pro, SP1
Plain SQL Statement (executes correctly):
SELECT
XMLElement("test",
XMLAgg(
XMLElement("element",
XMLAttributes(Scott.Emp.Ename as "ename", Scott.Emp.Empno as "enum")
) --xmlElement element
ORDER BY Scott.Emp.Ename desc
) --XmlAgg
).getClobVal() --xmlElement test
as TestXML
from Scott.Emp;
Stored Procedure:
create or replace procedure zorder(TestXML OUT clob) is
begin
SELECT
XMLElement("test",
XMLAgg(
XMLElement("element",
XMLAttributes(Scott.Emp.Ename as "ename", Scott.Emp.Empno as "enum")
) --xmlElement element
ORDER BY Scott.Emp.Ename desc
) --XmlAgg
).getClobVal() --xmlElement test
into TestXML
from Scott.Emp;
end zorder;
I get the following errors when attempting to compile the stored procedure:
7 PLS-00306: wrong number of types or arguments in call to 'XMLAGG'
7 PL/SQL: ORA-00904: "XMLAGG": invalid identifier
5 PL/SQL: SQL Statement ignored
Does anybody know why this code executes correctly in a SQL statement, but fails in a procedure? Is the Order By clause not available in a procedure? I need to get this functionality working in the procedure.
Thanks,
BrianA good simple workaround (that doesn't require runtime parsing) is to simply sub-query:
SELECT
XMLElement("test",
    XMLAgg(
        XMLElement(
            "element",
            XMLAttributes(Scott.Emp.Ename as "ename", Scott.Emp.Empno as "enum")
        ) --xmlElement element
    ) --XmlAgg
).getClobVal() --xmlElement test
into TestXML
from (
    SELECT Ename,Empno
    FROM Scott.Emp
    ORDER BY Scott.Emp.Ename desc -
Display select in a stored procedure
Hello,
I have a select statement that I wanna print in a stored procedure. The only way is to create a cursor in the SP, which holds the result of the select, and then iterate through the lines and print each line using dbms_output.put_line?
Thanks.You can pass a ref cursor as an output parameter and print that.
SQL> create or replace procedure p (p_c out sys_refcursor) as
2 begin
3 open p_c for
4 with test_data as
5 (
6 select 1 n, 'a' s from dual union all
7 select 2 n, 'b' s from dual union all
8 select 5 n, 'x' s from dual
9 )
10 select n, s from test_data;
11 end;
12 /
Procedure created.
SQL> var c refcursor
SQL> exec p(:c)
PL/SQL procedure successfully completed.
SQL> print c
N S
1 a
2 b
5 x -
Create table statement in stored procedures
Hi,
I am including the following statement in a stored procedure and receive the following error:
STATEMENT:
create table wrk_date (date date,
qty smallint)
tablespace temptabs;
ERROR:
PLS-00103: Encountered the symbol "CREATE" when expecting one of the following:
begin declare exit for goto if loop mod null pragma raise
return select update while <an identifier>
<a double-quoted delimited-identifier> <a bind variable> <<
close current delete fetch lock insert open rollback
savepoint set sql commit <a single-quoted SQL string>
Is this statement not allowed or is there a possible syntax error above?
I am using Oracle database version 8.0.5.
Thanks.
nullJimmy - You might want to buy the Following book from Oreilley Press Oracle Built in Pacakages it's very very good and came in handy when I has to write dynamic SQL (DBMS_SQL package).
You might want to try www.bookpool.com which has technical books cheaper than amazon.
Hope this helps.
_Satish
Oracle 8 Certified D.B.A.
Sun Certified Sysadmin -
Collable statement and stored procedure problem
Hi,
I am using a collable statement to execute a stored procedure.
The stored procedure is a bit complex since it uses a function to retrieve sequence nextval (newId),
than insert a row and returns the newId.
Anyway, I checked it with sql plus and it works, but when trying to execute it from my Java code, I get the following error message:
java.sql.SQLException: ORA-06550: line 1, column 33:
PLS-00103: Encountered the symbol ";" when expecting one of the following:
. ( ) , * @ % & | = - + < / > at in mod not range rem => ..
<an exponent (**)> <> or != or ~= >= <= <> and or like
between is null is not || indicator is dangling
The symbol ")" was substituted for ";" to continue.
Anyone can help?
Thanks,
MichalMy PL/SQL code:
CREATE OR REPLACE FUNCTION getNotifSeq RETURN NUMBER
IS
newId NUMBER;
BEGIN
SELECT NOTIFICATION_SEQ.NEXTVAL INTO newId FROM DUAL;
RETURN newId;
END;
run
CREATE OR REPLACE PROCEDURE insertNotifMsg (
sentBy IN VARCHAR,
subject IN VARCHAR,
msg IN VARCHAR,
newId OUT NUMBER)
IS
BEGIN
newId := getNotifSeq;
INSERT INTO NOTIFICATIONS(NOTIF_ID,SENT_BY,SUBJECT,MSG)
VALUES(newId,sentBy,subject,msg);
END insertNotifMsg;
run;
My Java code to call the procedure:
try
conn = myDBconn.getConnection();
CallableStatement callStmt = conn.prepareCall("{call insertNotifMsg(?,?,?,?}");
callStmt.setString(1,notif.getSentBy());
callStmt.setString(2,notif.getSubject());
callStmt.setString(3,notif.getMsg());
callStmt.registerOutParameter(4, Types.INTEGER);
ResultSet rs = callStmt.executeQuery();
if (!rs.next()) {
throw new SQLException("ERROR: Notification was not inserted into database!");
long newId = callStmt.getInt(4);
callStmt.close();
notif.setNotifId(newId);
conn.commit();
callStmt.close();
finally
myDBconn.closeConnection(conn);
Thanks,
Michal -
How to select from a stored procedure?
Lets say I have a simple stored procedures
Create Procedure stp_test
As
Begin
Select * from tbl1
End
Go
I would like to be able to do this in SSMS (actually, I want to do this from ADODB)
Select top 10 * from ...stp_test... Order By rowID
It looks like I want to use OpenQuery on the stored Procedure, but I have not been able to do it correctly. How can I query my stored procedure?
Rich PIt looks like I want to use OpenQuery on the stored Procedure, but I have not been able to do it correctly. How can I query my stored procedure?
If you want to use the OPENQUERY method , use the following.. follow this link...
http://stackoverflow.com/questions/209383/select-columns-from-result-set-of-stored-procedure
Please mark as answer, if this has helped you solve the issue.
Good Luck :) visit www.sqlsaga.com for more t-sql code snippets and BI related how to articles. -
SQL query statement for stored procedure / function listing ...
Hi everyone,
Is there a SQL query to list all the stored procedures and functions of an user in an Oracle 8 database?
I have this idea:
select * from USER_SOURCE where TYPE = 'PROCEDURE' or TYPE = 'FUNCTION'
but I am not too sure whether this is correct.
Thanks in advance,
EricYeah
I agree with you Garcia , my above posting was a correction to the query mentioned in the question only.
you are correct
If you only want the name of the object,
SELECT Object_Name from User_Objects where object_type in ( 'PROCEDURE' ,'FUNCTION');
is much faster than Selecting (distinct) from User_Source. -
Prepared Statement and Stored Procedure..
I have about 200 SQL statement in my Java application
I have two options either to convert into
Stored procedures
or to convert into prepared statement ....
Please guide me which options should be best....
I need difference
1)in term of speed.
2)Memory..
Regards
Mahesh
Senior DBAclub your statements on the basis of related functionalities and change it to stored procedures as it will redudce no. of calls to the database and will be faster to fetch data in one go and even reduce the memory requirements.
-
Prepared Statement and Stored Procedure difference?
For SQL in my web applications I use PreparedStatement object alot in my JDBC working with Oracle 9i.
I also heard the term Stored Procedure. What is the difference between Stored Procedure and Prepared Statement?I am new to java programming, can anybody explain
what exactly precompiled means
Thank you
PalspaceWhat does you subject line have to do with your question?
The difference between a stored proc and a prepared statement is mainly this.
A stored proc is stored in the database server permanently and can be used and re-used from a different connections.
A PreparedStatement is not valid across connections.
Stored procs are almost always precompiled. (I am just hedging a bit here just in case but you can consider it 100%)
PreparedStatements MAY be precompiled. Hard to say.
Precompiling means at least one of and perhaps all of the following depending on the database
- The parsing of the SQL statement
- The checking of the SQL against the data dictionary to ensure that the tables and columns referenced actually exist
- The preparation of a query plan
Last but not least Stored procedures may (and often do) contain more than simple queries but are in fact relatively complex programs written in a DB specific language (an offshoot of SQL of some sort). -
Re-use SELECT statement in several procedures (other than copy-and-paste)
Our site uses a procedure of the following procedure construct to generate Excel spreadsheets:
TYPE retCur is REF CURSOR;
PROCEDURE get_data_for_excel (
p_filter1 VARCHAR2
,p_filter2 VARCHAR2
,c_OutCursor out retCur
IS
retCursor retcur
BEGIN
BEGIN
OPEN c_OutCursor FOR
SELECT XMLELEMENT("TR", XMLFOREST(
"col1" AS "TD"
,"col2" AS "TD"
,"col3" AS "TD"
)).getstringval()DATA FROM (SELECT * FROM
SELECT col1, col2, col3
FROM sometable
WHERE somecolumn = p_filter1
AND someothercolumn = p_filter2
) x);
END;
END get_data_for_excel
My question is, the subselect:
SELECT col1, col2, col3
FROM sometable
is used in another procedure. Is there a way to reuse the select from the other procedure into this procedure so we don't copy-and-paste each time the other procedure is changed?
Thanks a lot.This is a design decision you need to make BEFORE it goes into production.
Right now you have
procedure get_data_for_excel (
p_filter1 VARCHAR2
,p_filter2 VARCHAR2
,c_OutCursor out retCur );
What, I think jihuyao is trying to say is: convert it to a pipelined function.
I agree with jihuyao as I have ran into to this problem before.
create type d4e_t as object ( DATA xmltype);
create type d4e_table is table of d4e_t;
create or replace function get_data_for_excel (
p_filter1 VARCHAR2
,p_filter2 VARCHAR2 )
return d4e_table pipelined;
as
begin
for curr in ( --start of SELECT statement
SELECT XMLELEMENT("TR", XMLFOREST(
"col1" AS "TD"
,"col2" AS "TD"
,"col3" AS "TD"
)).getstringval()DATA FROM (SELECT * FROM
SELECT col1, col2, col3
FROM sometable
WHERE somecolumn = p_filter1
AND someothercolumn = p_filter2
) x) )
LOOP
pipe row( d4e_t( curr.data ) );
end loop;
return;
end;
From there, you use it elsewhere as if it were a table.
insert into t
select X.data from table( get_data_for_excel( l_var1, l_var2 ) ) X;
MK -
Sp_executesql vs transaction statement within Stored Procedure
Experts,
Any difference between sp_executesql vs Transaction/Commit statement or try/catch block within Stored Procedure?
What is the best practice to use and why?
Thank You
Regards,
Kumar
Please do let us know your feedback. Thank You - KG, MCTSYour question is a bit strange. sp_executesql is used for dynamic SQL. Unless the problem demands dynamic SQL and, therefore, sp_executesql, there is no need to use it.
For a single statement I would not use transaction and try/catch. For multiple statements you do need to use transaction. It's up to you if you want to use try/catch in the SP or not and trap the error in the client application.
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles
Maybe you are looking for
-
Error while executing Jdev10g Appl
Hi, Please note that I am getting following error while executing my application. Although I have access to update and insert the record on the table,but still it gives the following error. The difference is Its a synonym of the current connected db
-
When I went to go sync my iPod, it shows up on the screen and the iPod seems like it is starting to sync. But then it doesn't and the screen on the iPod goes back the cord picture where it says "Connected_Eject before disconnecting." When I click syn
-
Autocomplete in 1.5 5440
Has anyone succeeded in making the autocomplete work for schema/objects/table/columns like it used to work in 1.2.1 3213??? Is there any workaround for this?? Ctrl + Space bar doesn't work, OS Win XP SP2 Tony
-
User SIMPCDIA has no RFC authorization for function group BBPC
Hello all, I am working with SRM 7.0 and when I try to list all account values in the corresponding matchcode, I have this error message: User SIMPCDIA has no RFC authorization for function group BBPC User SIMPCDIA is a dialog user created in backend
-
Sun IdM newbie - netbeans question
Our Sun IdM configurator consultants have left and I'm trying to open our Development IdM project in Netbeans (just went to admin training and want to poke around). I have all the software ready on the workstation and the Sun IdM Netbeans plugin inst