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, MCTS
Your 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
Similar Messages
-
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 -
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
BillLook into REF CURSORs. Still not sure about whether APEX uses them though.... Good luck.
-
How to call CLOB to BLOB conversion function within stored procedure?
I have a tiny APEX application from which I need to be able to print. I’ve used these two resources: (Is there an inexpensive APEX report printer for invoices/checks/statements? and http://download.oracle.com/docs/cd/E14373_01/appdev.32/e13363/up_dn_files.htm#CJAHDJDA)
I guess that in order to be able to download the RTF document stored in CLOB, I need to convert it into BLOB. I’ve found this function for this purpose on Oracle forums:
CREATE OR REPLACE FUNCTION c2b( c IN CLOB ) RETURN BLOB
-- typecasts CLOB to BLOB (binary conversion)
IS
pos PLS_INTEGER := 1;
buffer RAW( 32767 );
res BLOB;
lob_len PLS_INTEGER := DBMS_LOB.getLength( c );
BEGIN
DBMS_LOB.createTemporary( res, TRUE );
DBMS_LOB.OPEN( res, DBMS_LOB.LOB_ReadWrite );
LOOP
buffer := UTL_RAW.cast_to_raw( DBMS_LOB.SUBSTR( c, 16000, pos ) );
IF UTL_RAW.LENGTH( buffer ) > 0
THEN
DBMS_LOB.writeAppend( res, UTL_RAW.LENGTH( buffer ), buffer );
END IF;
pos := pos + 16000;
EXIT WHEN pos > lob_len;
END LOOP;
RETURN res; -- res is OPEN here
END c2b;And I am trying to use it in the modified download procedure that I also have found on Oracle forums:
CREATE OR REPLACE PROCEDURE DOWNLOAD_WO(v_id IN NUMBER)
AS
v_mime VARCHAR2(48);
v_length NUMBER;
v_file_name VARCHAR2(2000):= 'WO_Download.rtf';
lob_loc CLOB;
v_blob BLOB;
v_company jobs_vw.company%TYPE;
v_project jobs_vw.project%TYPE;
v_description jobs_vw.description%TYPE;
v_date_ jobs_vw.date_%TYPE;
v_job_no jobs_vw.job_no%TYPE;
v_apqwo jobs_vw.apqwo%TYPE;
-- v_mime VARCHAR2(48) := 'application/msword';
BEGIN
SELECT mime_type, report, DBMS_LOB.GETLENGTH(report)
INTO v_mime,lob_loc,v_length
FROM report_layouts
WHERE rl_id = 22332925279634283;
-- JOB_VW record:
SELECT job_no
,date_
,description
,apqwo
,project
,company
INTO v_job_no
,v_date_
,v_description
,v_apqwo
,v_project
,v_company
FROM jobs_vw
WHERE id = 214;
-- Replace holders with actual values:
lob_loc := REPLACE(lob_loc, '#COMPANY#', v_company);
lob_loc := REPLACE(lob_loc, '#PROJECT#', v_project);
lob_loc := REPLACE(lob_loc, '#DESCRIPTION#', v_description);
lob_loc := REPLACE(lob_loc, '#DATE_#', TO_CHAR(v_date_, 'DD/MM/YYYY'));
lob_loc := REPLACE(lob_loc, '#JOB_NO#', v_job_no);
lob_loc := REPLACE(lob_loc, '#APQWO#', v_apqwo);
-- set up HTTP header
-- use an NVL around the mime type and
-- if it is a null set it to application/octect
-- application/octect may launch a download window from windows
owa_util.mime_header( nvl(v_mime,'application/octet'), FALSE );
-- set the size so the browser knows how much to download
htp.p('Content-length: ' || v_length);
-- the filename will be used by the browser if the users does a save as
htp.p('Content-Disposition: attachment; filename="'||replace(replace(substr(v_file_name,instr(v_file_name,'/')+1),chr(10),null),chr(13),null)|| '"');
-- close the headers
owa_util.http_header_close;
-- download the BLOB
-- wpg_docload.download_file( Lob_loc );
v_blob := c2b(lob_loc);
wpg_docload.download_file( v_blob );
end DOWNLOAD_WO;
/Unfortunately when I try to compile the download_wo stored procedure I am getting this error:
Error at line 64: PL/SQL: Statement ignoredThe 64th line is:
v_blob := c2b(lob_loc);How should I correctly call c2b within download_wo? Any advice is greatly appreciated.
Thank you for your time.
DanielHello there,
Well, its invalid :(
Object C2B is Invalid. I didn't know since when I run the create ... function, I only get this feedback:
Statement processed.
0.19 secondsI am investigating.
Daniel -
JDO transaction, caching and stored procedures
I currently retreive an existing object, update the object, and then call
a stored procedure - all in one transaction. The issue I am running into
is that the stored proc must have the modified data available when it
selects the row (modified object) from the table. This is currently not
happening. For example, if the initial field was null, then it is updated
and the proc called, the proc only sees null. How do I specify that the
changes should be processed w/in the transaction (not commited) and
available for other processes reading the data in the same tx?
Note: everything works perfect if I manually execute the update statement
through a Statement on the connection for the stored proc. I have tried
flush().
Any ideas would be greatly appreciated!Here is a dumbed down version... I also tried doing a Query with JDO and
that returns the modified value. Basically, the code below find the
existing object, modifies a field, and then calls a stored proc to do some
processing. Unfortunately, the stored proc needs to be able to "see" the
modified data in the transaction.
public void modifyFoo( UserToken userToken,
Foo newFoo,
Integer applicationId )
PersistenceManager pm = null;
Transaction tx = null;
Integer applicationId = producerApplication.getId();
try
pm = JDOFactory.getPersistenceManager( userToken );
tx = pm.currentTransaction();
tx.begin();
FooBoId appId = new FooBoId();
appId.fooBolId = applicationId;
FooBo appDbVo = (FooBo)pm.getObjectById( appId, true );
appDbVo.setEffectiveDate( newFoo.getEffectiveDate() );
String fooNumber = executeFooBar( userToken, applicationId
appDbVo.setFooNumber( fooNumber );
tx.commit();
private String executeFooBar( UserToken userToken, Integer
applicationId )
throws PulsarSystemException, ValidationException
String licenseNumber = null;
try
// Get a connection from the persistence manager
Connection connection = JDOFactory.getConnection( userToken );
connection.setAutoCommit( false );
CallableStatement cs = connection.prepareCall( "{call
sys_appl_pkg.fooBar(?,?,?,?,?,?)}" );
// Register the type of the return value
cs.registerOutParameter( 4, Types.NUMERIC );
cs.registerOutParameter( 5, Types.NUMERIC );
cs.registerOutParameter( 6, Types.VARCHAR );
// Set parameters:
cs.setString( 1, "Test" );
cs.setInt( 2, applicationId.intValue() );
cs.setInt( 3, 0 );
catch( SQLException ex )
ex.printStackTrace();
return licenseNumber;
Patrick Linskey wrote:
Can you post the code that you're executing?
-Patrick
On Mon, 14 Jul 2003 20:38:09 +0000, Josh Zook wrote:
I currently retreive an existing object, update the object, and then call
a stored procedure - all in one transaction. The issue I am running into
is that the stored proc must have the modified data available when it
selects the row (modified object) from the table. This is currently not
happening. For example, if the initial field was null, then it is updated
and the proc called, the proc only sees null. How do I specify that the
changes should be processed w/in the transaction (not commited) and
available for other processes reading the data in the same tx?
Note: everything works perfect if I manually execute the update statement
through a Statement on the connection for the stored proc. I have tried
flush().
Any ideas would be greatly appreciated!
Patrick Linskey
SolarMetric Inc. -
Syntax for delete statement within a procedure
within a procedure i tried to delete the table using
delete table tablename;
but it is showing error that
PL/SQL: SQL Statement ignored
PL/SQL: ORA-00903: invalid table name
whether we have to use execute immediate delete table tablename;
or this syntax is correctHi ,
i think if you want to use the delete
then it shld be delete from tablename --> this'll delete all rows
but if u want to use execute immediate then you might as well use TRUNCATE --> provided you need not have these data written to the log file (if you need for recovery later better use DELETE)
i.e EXECUTE IMMEDIATE ('TRUNCATE TABLE tbl_name');
hope this helps -
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 -
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 -
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). -
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 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 -
How to use dbms_Scheduler.Create_Job from within stored procedure?
Hello,
using 10g (10.1.0.2.0) on Windows 2000 I had problems to create scheduler jobs from within a stored procedure (see example below). What easily succeeds using anonymous blocks failed when calling from a stored procedure, due to ORA-27486. Only when I compile the procedure with invoker's rights the call to dbms_Job.Create_Job is successfull!? From my knowledge there is no difference between invoker's and definer's rights, if I compile and call with the same user, is there?
Does anyone know the reason for this behaviour or is it simply a bug?
Have a nice day.
Björn Hachmann
Hamburg / Germany
-- Example start.
create table t
a number(1),
b date default sysdate
create or replace procedure sched1
is
begin
dbms_scheduler.create_job(
job_name => 'TEST_JOB1',
job_type => 'PLSQL_BLOCK',
job_action => 'BEGIN insert into t values (1); END;',
repeat_interval => 'freq=secondly',
enabled => TRUE
commit;
end;
create or replace procedure sched2
authid current_user
is
begin
dbms_scheduler.create_job(
job_name => 'TEST_JOB2',
job_type => 'PLSQL_BLOCK',
job_action => 'BEGIN insert into t values (2); END;',
repeat_interval => 'freq=secondly',
enabled => TRUE
commit;
end;
exec sched1; -- This call fails with ORA-27486.
exec sched2; -- This call succeeds!
/* Cleanup.
exec dbms_scheduler.drop_job('TEST_JOB1', true);
exec dbms_scheduler.drop_job('TEST_JOB2', true);
drop table t;
*/Your example code ran without problems for me on 10.1.0.3.0 so it probably is a bug.
-
Delay in execution of statements within a procedure!
Dear All,
My Database is Oracle 11gR2 on Linux.
I have to schedule delete in 5 tables. For this i will write a procedure with delete queries and schedule the procedure to run daily in night.
I want to give delay in the execution of delete queries within procedure? How can i add this functionality within a procedure?
I don't want to lock the tables as other queries may be accessing the same table meanwhile.
Looking for your help.
Regards,
ImranOther queries accessing the table meanwhile is a perfectly normal reason to lock the tables, as writers don't block readers.
Implementing 'delays' is definitely an amateurish hack to result into more problems.
Locking and transactions are one of the core functions of any RDBMS, and it is better to understand them, than to implement hack on hack on hack to turn a Ferrari like Oracle in a broken bike with a flat tire.
After several years of asking doc questions you should know better.
BTW can you explain why you end all of your questions with an unnecessary exclamation mark?
If you can't explain this, can you stop doing so?
There is no reason to yell here.
Thank you
Sybrand Bakker
Senior Oracle DBA
Maybe you are looking for
-
Laser jet professional utility doesn't work (Mac OSX 10.7)
I've been having connection issues with my LaserJet P1102w lately so I decided to try to set it up for wireless connection (instead of USB). I found that the Ulitity (HP LaserJet Professional Utility), when launched, doesn't do anything. The applicat
-
I was moving my laptop while the iPod was plugged in and I accidently pulled on the cord halfway out of the iPod's plug. I pushed it back in but all of my music wsa deleted and even after trying to restore the iPod to factory settings I cannot get an
-
GE70 2PE Apache Pro - Bluetooth not fully functional
Hi. I just bought the laptop mentioned in the subject line and I have not been able to get Bluetooth to work fully. Everything shows up normally and correctly in the Device Manager and the System Tray, but connecting to my iPhone sometimes works and
-
Linked Images : Automatic Folder Creation for linked images?
Best Rgards Mac OSX 10.9.3 InDesign CC (9.2.1) Presently: 120 page Blurb publishing with 190 images I have created a large number of INDD documents that I piece together from many sources, such as file folders, internet searches, external drives, ema
-
FTP Data Transfer with SAPFTPA
Hello, I would like to use the ftp-command "! ls -l". As I use the " ! " in ftp, the command should be executed on the local pc/application server (not on the remote server). When I use the rfc_destination SAPFTP the command runs perfect and I get as