Get out values from stored procedure
Hi folks,
I have need of an aid. I have created this stored procedure:
CREATE OR REPLACE PROCEDURE ProceduraDiProva (
p_val1 IN NUMBER DEFAULT 1,
p_val2 IN NUMBER DEFAULT 1,
p_val3 OUT NUMBER,
p_val4 OUT NUMBER)
AS
BEGIN
p_val3 := p_val1 + p_val2;
p_val4 := 999;
END ProceduraDiProva;
I call the procedure into shell script
$ORACLE_HOME/bin/sqlplus -s user/pwd@oracleid > oracle.log << END
spool ciccio.txt
declare
var a_out number;
var b_out number;
begin
var a_out:=0;
exec ProceduraDiProva(1, 2, a_out, b_out);
end;
spool off;
exit
END
I would know as I make to insert 'a_out' and 'b_out' in a shell variables
Tanks in advance
I found an example with windows
Create a file cmd with;
FOR /F "usebackq delims=!" %%i IN (`sqlplus -s %usuario%/%pwd%@%ddbb% @1.sql`) DO set xresult=%%i
echo %xresult%
And the 1.sql:
set timing off
set feedback off
set pages 0
select sysdate from dual;
exit
------------------------------------------------------------------------------------------
Similar Messages
-
How to get return values from stored procedure to ssis packge?
Hi,
I need returnn values from my stored procedure to ssis package -
My procedure look like and ssis package .Kindly help me to oget returnn value to my ssis package
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [TSC]
-- Add the parameters for the stored procedure here
@P_STAGE VARCHAR(2000)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
--SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
truncate table [INPUTS];
INSERT
INTO
[INPUTS_BASE]
SELECT
[COLUMN]
FROM [INPUTS];
RETURN
END
and i am trying to get the return value from execute sql task and shown below
and i am taking my returnn value to result set variableYou need to have either OUTPUT parameters or use RETURN statement to return a value in stored procedures. RETURN can only return integer values whereas OUTPUT parameters can be of any type
First modify your procedure to define return value or OUTPUT parameter based on requirement
for details see
http://www.sqlteam.com/article/stored-procedures-returning-data
Once that is done in SSIS call sp from Execute SQL Task and in parameter mapping tabe shown above add required parameters and map them to variables created in SSIS and select Direction as Output or Return Value based on what option you used in your
procedure.
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Cannot get OUT parameter from stored procedure
Hi,
I am new to stored procedure programming. I wrote a simple java stored procedure as follows:
package fvt;
import java.sql.*;
import java.io.*;
public class FVTProcedures
extends COM.ibm.db2.app.StoredProc {
public void addRecord(int id, String name, int status)
throws SQLException {
java.sql.Statement stmt = null;
java.sql.Connection con = null;
PrintWriter pw = null;
try {
status =3;
pw = new PrintWriter(new FileWriter("c:/temp/fvtproc.txt"));
pw.println("starting...");
// get connection
con =getConnection();
pw.println("Got connection");
stmt = con.createStatement();
stmt.execute("INSERT INTO cmtest (id, name) values (" + id + ",'"+name+"')");
pw.println("Inserted the record");
if (!con.getAutoCommit()) {
con.commit();
pw.println("Committed the connection");
catch (SQLException sqle) {
pw.println(sqle.getMessage());
catch (Exception e) {
pw.println(e.getMessage());
finally {
status =2;
pw.close();
try {
if (stmt != null) {
stmt.close();
catch (SQLException sqle) {}
try {
if (con != null) {
con.close();
catch (SQLException sqle) {}
Then I use the following sql command to create this stored procedure, especially register status as OUT parameter.
CREATE PROCEDURE addRecord (IN id INT, IN name VARCHAR(20), OUT status INTEGER)
FENCED LANGUAGE JAVA EXTERNAL NAME 'fvt.FVTProcedures!addRecord' PARAMETER
STYLE DB2GENERAL
My java program calling this stored proc is as follows:
import java.sql.*;
import javax.sql.*;
public class CallableStmtTest {
COM.ibm.db2.jdbc.DB2ConnectionPoolDataSource ds = null;
public static void main(String args[]) {
CallableStmtTest dt = new CallableStmtTest();
try {
dt.test();
} catch (Exception e) {
e.printStackTrace(System.out);
public CallableStmtTest() {
ds = new COM.ibm.db2.jdbc.DB2ConnectionPoolDataSource();
ds.setUser("username");
ds.setPassword("password");
ds.setDatabaseName("database");
public void test() {
java.sql.Connection conn = null;
CallableStatement cs = null;
String sql = "CALL ADDRECORD(?, ?, ?)" ;
try {
conn = ds.getPooledConnection().getConnection();
conn.setAutoCommit(false);
System.out.println("Got the connection");
cs = conn.prepareCall( sql ) ; /* con is the connection */
System.out.println("Callable statement is prepared");
cs.registerOutParameter(3, java.sql.Types.INTEGER);
cs.setInt(1, 1001 );
cs.setString(2, "1001");
cs.execute() ;
System.out.println("Callable statement is executed, return status: "+cs.getInt(3));
conn.commit();
catch(SQLException sqle) {
sqle.printStackTrace();
finally {
try {
if (cs!=null) {cs.close();}
catch (SQLException sqle1) {
try {
if (conn!=null) {conn.close();}
catch (SQLException sqle1) {
However, the out put is always
Callable statement is executed, return status: 0
while i expect to be
Callable statement is executed, return status: 2
Can anyone tell me what's wrong with that?
thansk,
JSTpublic void addRecord(int id, String name, int status)
throws SQLException {
status =3;In regular java you are never going to see this value (3) outside of that method. Java doesn't work that way.
So unless java inside the DB works really differently from regular java, you are going to have to pass something else. -
Copy values from stored procedure to a text pad
Any Suggestions
We have a table 'A' and wrote a select query to get the values from that table 'A'. I place this select query in Stored procedure and when I run that procedure every month the output should be sent t a text pad. Any suggestions how to write it
thanks
Is there any other method if we dont have the privelage to create directory?
Edited by: user646635 on Oct 2, 2008 7:16 AMuser646635 wrote:
want to store the output in a text file?
we are using oracle 9iHere's a basic example for you...
AS SYS:
create or replace directory TEST_DIR as 'c:\test_dir'; -- This creates an oracle directory object. The actual operating system directory must be created manually
grant read,write on directory test_dir to my_user; -- Grant permission to use that directory object to the required user(s)AS my_user:
declare
cursor cur_emp is
select ename, deptno
from emp;
v_fh UTL_FILE.FILE_TYPE; -- This is a file handle
begin
v_fh := UTL_FILE.FOPEN('TEST_DIR', 'file.txt', 'w', 32767); -- Open the file for writing and obtain a handle to it
FOR i IN cur_emp -- process the query in a loop
LOOP
UTL_FILE.FPUT_LINE(v_fh, i.ename||','||to_char(i.deptno,'fm099')); -- write out lines of text to the file
END LOOP;
UTL_FILE.FCLOSE(v_fh); -- Close the file (also flushes any unwritten buffered data).
end; -
How to capture return value from stored procedure?
Hi All,
I want to capture the retun values from this procedure to a table - CALL SYS.GET_OBJECT_DEFINITION('SCHEMA_NAME', 'TABLE_NAME').
The below approach is not working -
Insert into STG.STG_DDL
Call SYS.GET_OBJECT_DEFINITION('DWG', 'DWG_SITE')
Could you please have a look on the same?
Thank you,
VijeeshThanks a lot Everyone.
Considering the discussed options, and an approach explained in this thread - -http://scn.sap.com/thread/3291461 , I have written an SQL to build the Alter statements to add the columns & Constrains to table.
The below Query will provide the scripts to build a table in another environment.
select * from (
select TABLE_name,'tbl_Create' column_name, 1 as position, 'CREATE TABLE '|| schema_name ||'.'|| table_name ||' ( DUMMY_CLMN INTEGER);' as SQLCMD
from tableS
where schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
UNION ALL
-- MASS change of NOT NULL COLUMNS
-- set to NOT NULL - character data type, double, decimal fixed - need the length but not the scale
select TABLE_name,column_name, position + 100, 'ALTER TABLE '|| schema_name ||'.'|| table_name ||' ADD ('||column_name ||' '||data_type_name ||' (' || length ||') NOT NULL) ;' as SQLCMD
from table_columns
where is_nullable = 'FALSE'
and schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
and data_type_name in ('VARCHAR', 'NVARCHAR', 'DOUBLE')
and scale is NULL
UNION ALL
-- MASS change of NOT NULL COLUMNS
-- set to NOT NULL - character data type, double, decimal fixed - need the length but not the scale
select TABLE_name,column_name, position + 100,'ALTER TABLE '|| schema_name ||'.'|| table_name ||' ADD ('||column_name ||' '||data_type_name ||' (' || length ||') );' as SQLCMD
from table_columns
where is_nullable = 'TRUE'
and schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
and data_type_name in ('VARCHAR', 'NVARCHAR', 'DOUBLE')
and scale is NULL
UNION ALL
-- set to NOT NULL - DECIMAL (FLOATING POINT)- needs length and scale
select TABLE_name,column_name, position + 100, 'ALTER TABLE '|| schema_name ||'.'|| table_name ||' ADD ('||column_name ||' '||data_type_name ||' (' || length ||','|| scale ||') NOT NULL) ;' as SQLCMD
from table_columns
where is_nullable = 'FALSE'
and schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
and data_type_name in ('DECIMAL' )
and scale is not null
UNION ALL
-- set to NOT NULL - DECIMAL (FLOATING POINT)- needs length and scale
select TABLE_name,column_name, position + 100, 'ALTER TABLE '|| schema_name ||'.'|| table_name ||' ADD ('||column_name ||' '||data_type_name ||' (' || length ||','|| scale ||') ) ;' as SQLCMD
from table_columns
where is_nullable = 'TRUE'
and schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
and data_type_name in ('DECIMAL' )
and scale is not null
UNION ALL
-- set to NOT NULL - DECIMAL (FLOATING POINT)- needs length and null scale
select TABLE_name,column_name, position + 100, 'ALTER TABLE '|| schema_name ||'.'|| table_name ||' ADD ('||column_name ||' '||data_type_name ||' (' || length ||') NOT NULL) ;' as SQLCMD
from table_columns
where is_nullable = 'FALSE'
and schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
and data_type_name in ('DECIMAL' )
and scale is null
UNION ALL
-- set to NOT NULL - DECIMAL (FLOATING POINT)- needs length and null scale
select TABLE_name,column_name, position + 100, 'ALTER TABLE '|| schema_name ||'.'|| table_name ||' ADD ('||column_name ||' '||data_type_name ||' (' || length ||') NOT NULL) ;' as SQLCMD
from table_columns
where is_nullable = 'TRUE'
and schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
and data_type_name in ('DECIMAL' )
and scale is null
UNION ALL
-- set to NOT NULL - DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER - don't need length or scale
select TABLE_name,column_name, position + 100, 'ALTER TABLE '|| schema_name ||'.'|| table_name ||' ADD ('||column_name ||' '||data_type_name ||' NOT NULL) ;' as SQLCMD
from table_columns
where is_nullable = 'FALSE'
and schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
and data_type_name in ('DATE', 'LONGDATE', 'TIME', 'SECONDDATE', 'TIMESTAMP', 'TINYINT', 'SMALLINT', 'INTEGER' )
-- and scale is not null
UNION ALL
-- set to NOT NULL - DATE | TIME | SECONDDATE | TIMESTAMP | TINYINT | SMALLINT | INTEGER - don't need length or scale
select TABLE_name,column_name, position + 100, 'ALTER TABLE '|| schema_name ||'.'|| table_name ||' ADD ('||column_name ||' '||data_type_name ||' ) ;' as SQLCMD
from table_columns
where is_nullable = 'TRUE'
and schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
and data_type_name in ('DATE', 'LONGDATE', 'TIME', 'SECONDDATE', 'TIMESTAMP', 'TINYINT', 'SMALLINT', 'INTEGER' )
-- and scale is not null
UNION ALL
select table_name, 'PK' AS column_name, 9990, 'ALTER TABLE '||table_name||' ADD CONSTRAINT Primary_key PRIMARY KEY ('||PK_COLUMN_NAME1||
case when PK_COLUMN_NAME2 is null then ' ' else ','|| PK_COLUMN_NAME2 end ||
case when PK_COLUMN_NAME3 is null then ' ' else ','|| PK_COLUMN_NAME3 end ||
case when PK_COLUMN_NAME4 is null then ' ' else ','|| PK_COLUMN_NAME4 end ||');'
from
(SELECT DISTINCT C1.table_name , C1.COLUMN_NAME AS PK_COLUMN_NAME1, C2.COLUMN_NAME AS PK_COLUMN_NAME2, C3.COLUMN_NAME AS PK_COLUMN_NAME3, C4.COLUMN_NAME AS PK_COLUMN_NAME4
FROM (SELECT * FROM CONSTRAINTS WHERE POSITION=1 AND IS_PRIMARY_KEY = 'TRUE') C1
LEFT JOIN (SELECT * FROM CONSTRAINTS WHERE POSITION=2 AND IS_PRIMARY_KEY = 'TRUE') C2
ON C1.table_name = C2.table_name
LEFT JOIN (SELECT * FROM CONSTRAINTS WHERE POSITION=3 AND IS_PRIMARY_KEY = 'TRUE') C3
ON C2.table_name = C3.table_name
LEFT JOIN (SELECT * FROM CONSTRAINTS WHERE POSITION=4 AND IS_PRIMARY_KEY = 'TRUE') C4
ON C3.table_name = C4.table_name
LEFT JOIN (SELECT * FROM CONSTRAINTS WHERE POSITION=5 AND IS_PRIMARY_KEY = 'TRUE') C5
ON C4.table_name = C5.table_name
) PK
where table_name = 'DWG_PRODUCTION_VOLUME_TRX'
UNION ALL
select table_name, 'UK' AS column_name, 9991, 'ALTER TABLE '||table_name||' ADD CONSTRAINT UNIQUE ('||UK_COLUMN_NAME1||
case when UK_COLUMN_NAME2 is null then ' ' else ','|| UK_COLUMN_NAME2 end ||
case when UK_COLUMN_NAME3 is null then ' ' else ','|| UK_COLUMN_NAME3 end ||
case when UK_COLUMN_NAME4 is null then ' ' else ','|| UK_COLUMN_NAME4 end ||');'
FROM
(SELECT DISTINCT C1.table_name , C1.COLUMN_NAME AS UK_COLUMN_NAME1, C2.COLUMN_NAME AS UK_COLUMN_NAME2, C3.COLUMN_NAME AS UK_COLUMN_NAME3, C4.COLUMN_NAME AS UK_COLUMN_NAME4
FROM (SELECT * FROM CONSTRAINTS WHERE POSITION=1 AND IS_PRIMARY_KEY = 'FALSE') C1
LEFT JOIN (SELECT * FROM CONSTRAINTS WHERE POSITION=2 AND IS_PRIMARY_KEY = 'FALSE') C2
ON C1.table_name = C2.table_name
LEFT JOIN (SELECT * FROM CONSTRAINTS WHERE POSITION=3 AND IS_PRIMARY_KEY = 'FALSE') C3
ON C2.table_name = C3.table_name
LEFT JOIN (SELECT * FROM CONSTRAINTS WHERE POSITION=4 AND IS_PRIMARY_KEY = 'FALSE') C4
ON C3.table_name = C4.table_name
LEFT JOIN (SELECT * FROM CONSTRAINTS WHERE POSITION=5 AND IS_PRIMARY_KEY = 'FALSE') C5
ON C4.table_name = C5.table_name
) UK
where table_name = 'DWG_PRODUCTION_VOLUME_TRX'
UNION ALL
SELECT REFERENCED_TABLE_NAME AS table_name,'FK' AS column_name, 9992,
'ALTER TABLE DWG.'||TABLE_NAME||' ADD FOREIGN KEY ( '||COLUMN_NAME||' ) REFERENCES '|| REFERENCED_TABLE_NAME||'('||COLUMN_NAME||' ) ON UPDATE CASCADE ON DELETE RESTRICT;'
FROM REFERENTIAL_CONSTRAINTS
WHERE REFERENCED_TABLE_NAME = 'DWG_SITE'
UNION ALL
select TABLE_name,'tbl_ClmnDrop' column_name, 9995 as position, 'ALTER TABLE '|| schema_name ||'.'|| table_name ||' DROP ( DUMMY_CLMN );' as SQLCMD
from tableS
where schema_name ='DWG'
and TABLE_name ='DWG_PRODUCTION_VOLUME_TRX'
order by position; -
How to output value from stored procedure
Hi folks, I need to output the OrderFK from a stored procedure not really sure how to achieve this any help or tips much appreciated.
Sql code below
USE [TyreSanner]
GO
/****** Object: StoredProcedure [dbo].[AddCustomerDetails] Script Date: 11/12/2014 20:56:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddCustomerDetails]
/***********************Declare variables ***********************/
/******tblCustomer******/
@Forename nvarchar(50),
@Surname nvarchar(50),
@HouseNo nvarchar(50),
@CustAddress nvarchar(50),
@Town nvarchar(50),
@Postcode nvarchar(50),
@ContactNo nvarchar(50),
@EmailAddress nvarchar(50),
/******tblLink_OrderProduct******/
@ProductQuantity int,
@TotalProductSaleCost decimal,
@ProductFK int,
@FittingDate date,
@FittingTime Time
As
DECLARE @CustomerFK int;
DECLARE @OrderFK int;
Begin TRANSACTION
SET NOCOUNT ON
INSERT INTO [TyreSanner].[dbo].[Customer](Forename, Surname, HouseNo, CustAddress, Town, Postcode, ContactNo, EmailAddress)
VALUES (@Forename,@Surname,@HouseNo,@CustAddress,@Town,@Postcode,@ContactNo,@EmailAddress)
Set @CustomerFK = SCOPE_IDENTITY()
INSERT INTO [TyreSanner].[dbo].[Order] (CustomerFK)
VALUES (@CustomerFK)
SET @OrderFK = SCOPE_IDENTITY()
INSERT INTO [TyreSanner].[dbo].[Link_OrderProduct](OrderFK, ProductFK, ProductQuantity, TotalProductSaleCost, FittingDate, FittingTime)
VALUES
(@OrderFK, @ProductFK, @ProductQuantity, @TotalProductSaleCost, @FittingDate, @FittingTime)
COMMIT TRANSACTIONHi brucey54,
There’re several ways to capture the value from a Stored Procedure. In you scenario, I would suggest 2 options, by an output parameter or by a table variable.
By an output Parameter, you need to make a little bit modification on your code as below:
USE [TyreSanner]
GO
ALTER PROCEDURE [dbo].[AddCustomerDetails]
@Forename nvarchar(50),
@FittingDate date,
@FittingTime Time,
@OrderFK int output
As
DECLARE @CustomerFK int;
--DECLARE @OrderFK int;
Run the following code, Then @OrderFKvalue holds the value you’d like.
DECLARE @OrderFKvalue int;
EXEC AddCustomerDetails(your parameters,@OrderFKvalue output)
Anyway if you don’t like to add one more parameter, you can get the value by a table variable as well. Please append “SELECT @OrderFK;” to your Procedure as below:
USE [TyreSanner]
GO
ALTER PROCEDURE [dbo].[AddCustomerDetails]
SET @OrderFK = SCOPE_IDENTITY()
INSERT INTO [TyreSanner].[dbo].[Link_OrderProduct](OrderFK, ProductFK, ProductQuantity, TotalProductSaleCost, FittingDate, FittingTime)
VALUES
(@OrderFK, @ProductFK, @ProductQuantity, @TotalProductSaleCost, @FittingDate, @FittingTime);
SELECT @OrderFK;
Then you can call the Stored Procedure as below:
DECLARE @T TABLE (OrderFK INT);
INSERT @T EXEC AddCustomerDetails(your parameters) ;
SELECT OrderFK FROM @T;
There’re more options to achieve your requirement, please see the below link:
How to Share Data between Stored Procedures
If you have any question, feel free to let me know.
Best Regards,
Eric Zhang -
Getting result set from stored procedures in database controls in weblogic
I am calling a stored procedure from database control which actually returns a result set
when i call the stored procedure like
* @jc:sql statement="call PROC4()"
ResultSet sampleProc() throws SQLException;
it gives me exception saying
"weblogic.jws.control.ControlException: Method sampleProc is DML but does not return void or int"
I would appreciate any help
Thanks,
UmaThanks for you reply!
1) The stored procedure has head
CREATE OR REPLACE PROCEDURE X_OWNER.DISPLAY_ADDRESS
cv_1 IN OUT SYS_REFCURSOR
AS
err_msg VARCHAR2(100);
BEGIN
--Adaptive Server has expanded all '*' elements in the following statement
OPEN cv_1 FOR
Select ...
commit;
EXCEPTION
WHEN OTHERS THEN
err_msg := SQLERRM;
dbms_output.put_line (err_msg);
ROLLBACK;
END;
If I only run select .. in DBArtisan, it display all 2030,000 rows in 3:44 minutes
2) But when call stored procedure, it will take 80-100 minutes .
3) The stored procedure is translated from sybase using migration tools, it's very simple, in sybase it just
CREATE PROCEDURE X_OWNER.DISPLAY_ADDRESS
AS
BEGIN
select ..
The select part is exact same.
4) The perl code is almost exact same, except the query sql:
sybase verson: my $sql ="exec DISPLAY_ADDRESS";
and no need bind the cursor parameter.
This is batch job, we create a file with all information, and ftp to clients everynight.
Thanks!
Rulin -
How to get a resultset from Stored Procedures
How to efficiently and portably get resultsets from Oracle stored procedures? Oracle does not seem to follow JDBC standards here. A standard way in Oracle is to use a ref cursor and call getObject() on CallableStatement. However, Oracle seems to get all the data in the resultset in getObject(), which is inefficient and leads to large memory usage when the resultset is large.
Another way in Oracle is to use getCursor() on an OracleCallableStatement, which is efficient but not portable across different application servers. For example, in WebSphere, this OracleCallableStatement is not available if we want WebSphere to manager the datasource.
Any ideas will be greatly appreciated. Please email to [email protected]Oracle JDBC did not support return a result set, if you are using Oracle 9i, you can use pipeline function, then using the TABLE() function the get the row.
Good Luck.
Welcome to http://www.anysql.net/en/ -
Can we get data return from stored procedure in a select query ?
Hello,
Suppose i have a function GetSum(x,y) that returns sum of two numbers x and y .We can call this function from within a sql function like this :
select GetSum(4,5) SUM from dual;But is this possible through a stored procedure ? i.e., can i call a stored procedure from within a select query like i have done in above code ?Hi,
bootstrap wrote:
Hello,
Suppose i have a function GetSum(x,y) that returns sum of two numbers x and y .We can call this function from within a sql function like this :
select GetSum(4,5) SUM from dual;But is this possible through a stored procedure ? i.e., can i call a stored procedure from within a select query like i have done in above code ?The short answer has already been given.
Why can't you use a function?
Suppose you could use a procedure. What results would you want to see from:
SELECT my_proc (4, 5)
FROM dual
;? Why?
Explain what you want to do, and somebody will help you find a good way to do it. -
Unable to retrieve the values from stored procedure
Hi all
I written one procedure and when i am trying to invoke that store procedure from jdbc it is throwing the following error .
java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.DelegatingCallableStat
ement
at com.srit.hrnet.helpdesk.grievancemechanism.GrievanceComplaintDAO.getE
mployerGenDetails(GrievanceComplaintDAO.java:895)
at com.srit.hrnet.helpdesk.grievancemechanism.GrievanceComplaintAction.d
eleteComplaints(GrievanceComplaintAction.java:1095)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchActio
n.java:276)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:
196)
at org.apache.struts.action.RequestProcessor.processActionPerform(Reques
tProcessor.java:421)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.ja
va:226)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:116
4)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:397)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:173)
at com.srit.hrnet.filter.SessionValidateFilter.doFilter(SessionValidateF
ilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java
:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.proce
ssConnection(Http11Protocol.java:744)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpo
int.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFol
lowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadP
ool.java:684)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at com.srit.hrnet.helpdesk.grievancemechanism.GrievanceComplaintAction.d
eleteComplaints(GrievanceComplaintAction.java:1098)and my code is
store procedure is
============
create or replace procedure SP_HD_GRIEVANCE_DELETE_DETAILS(in_queryid IN number DEFAULT NULL,RC1 IN OUT globalPkg.RCT1)
as
queryId number(18,0);
BEGIN
SP_HD_GRIEVANCE_DELETE_DETAILS.queryId := SP_HD_GRIEVANCE_DELETE_DETAILS.in_queryid;
IF SP_HD_GRIEVANCE_DELETE_DETAILS.queryId = 1 THEN
BEGIN
OPEN RC1 FOR
select HGRMCODE as compcode,emcode as applyEmpId,EMFNAME as assName,designame as desig,deptname as department ,to_char(HGRMOCCRDT,'DD/MM/YYYY') as occdate,
HGRMSLATYPE as category,HGRMSUBCAT as subcat,HGRMSLAPRIORITY as priority,HGRMSTATUS as status from EMP_MSTR,HD_GRIEVANCE_RM_MSTR,
dept_mstr,desig_mstr where EMCODE=HGRMAPPLYEMCODE and EMDEPTCODE=deptcode and desigcode=EMDESIGCODE order by HGRMCODE;
END;
END IF;
END SP_HD_GRIEVANCE_DELETE_DETAILS;and javacode is
==========
con = new DBConnection().getConnection();
java.sql.CallableStatement stmt = con.prepareCall("{call SP_HD_GRIEVANCE_DELETE_DETAILS(?,?)}");
stmt.clearParameters();
stmt.setInt(1,1);
stmt.registerOutParameter(2, OracleTypes.CURSOR);
stmt.execute();
cursor = ((OracleCallableStatement)stmt).getCursor(1);
list = new ArrayList();
while (cursor.next()) {
compTO = new GrievanceComplaintTO();
list.add(compTO);
}where GrievanceComplaintTO is formbean class
Please Guide me.
Thanks in advance.Obviously, this
cursor = ((OracleCallableStatement)stmt).getCursor(1);fails because you don't get an OracleCallableStatement. -
Multiple Values from Stored Procedure
Hello all,
I have oracle table with 9 fields like startdate,enddate,name,id etc.
Now from this table I want to to some manipulation like if if the startdate>enddate,if true return end date
with
StartDate,EndDate,CalculateEndDate,Name fields.
I need this to be done all the rows in the table and return the result . What method I can for this
I am using .Net as my Front End
Thanks in advanceMy select is too complex to be returned in one Cursor.
I have declared my own type
TYPE myTableType AS TABLE OF myType;
and
TYPE myType AS OBJECT
( a NUMBER,b NUMBER,c VARCHAR2(5),d VARCHAR2(50) )
Procedure p (inputpar IN VARCHAR2, Cur REF CURSOR);
code
LOOP
.. code ..
myData.EXTEND;
myData(myData.COUNT) := myType( variable1, var2, var3, var4);
END LOOP;
And at last returning a refcursor
OPEN Cur FOR
SELECT a,b,c..
FROM TABLE (CAST (myData AS myTableType));
Lars Petersen -
Multiples value from stored Procedure
Hi all,
I have a table with this structure.
ID Startdate EndDate
Now I want to retrive the row rows with time difference is >x , where the x has to passed as parameter.
How can I do this one ?
thanks in advanceAre you date values stored as date or timestamps? It will make a difference. I'm not sure on these, but I'm new to Oracle as well. Give them a shot.
With a date:
where (Startdate - EndDate) > x OR (EndDate-StartDate) > x
With a Timestamp:
where Startdate>(EndDate-x) OR EndDate>(StartDate-x); -
Storing the values from a procedure - help required
Hi All,
I am having a package which consists of two procedures.
Both the procedures need to calculate 6 averages of some of my fields based on unique number.
(These two procedures process different unique numbers).
Now, as same code is implemented in the two procedures for calculation,
I want to move the logic into another procedure/function, with IN parameter as the unique number.
Now how can I get these 6 values from the procedure.
If I use OUT parameters, how can I get the values inside the procedure.
Please suggest me a solution.
Thanks in advance.
Regards
RaghunadhExample of pipelined function...
SQL> CREATE OR REPLACE TYPE myrec AS OBJECT
2 ( col1 VARCHAR2(10),
3 col2 VARCHAR2(10)
4 )
5 /
Type created.
SQL>
SQL> CREATE OR REPLACE TYPE myrectable AS TABLE OF myrec
2 /
Type created.
SQL>
SQL> CREATE OR REPLACE FUNCTION pipedata(p_str IN VARCHAR2) RETURN myrectable PIPELINED IS
2 v_str VARCHAR2(4000) := REPLACE(REPLACE(p_str, '('),')');
3 v_obj myrec := myrec(NULL,NULL);
4 BEGIN
5 LOOP
6 EXIT WHEN v_str IS NULL;
7 v_obj.col1 := SUBSTR(v_str,1,INSTR(v_str,',')-1);
8 v_str := SUBSTR(v_str,INSTR(v_str,',')+1);
9 IF INSTR(v_str,',')>0 THEN
10 v_obj.col2 := SUBSTR(v_str,1,INSTR(v_str,',')-1);
11 v_str := SUBSTR(v_str,INSTR(v_str,',')+1);
12 ELSE
13 v_obj.col2 := v_str;
14 v_str := NULL;
15 END IF;
16 PIPE ROW (v_obj);
17 END LOOP;
18 RETURN;
19 END;
20 /
Function created.
SQL>
SQL> create table mytab (col1 varchar2(10), col2 varchar2(10));
Table created.
SQL>
SQL> insert into mytab (col1, col2) select col1, col2 from table(pipedata('(1,2),(2,3),(4,5)'));
3 rows created.
SQL>
SQL> select * from mytab;
COL1 COL2
1 2
2 3
4 5Although I'm not sure you necessarily need to do it this way. Could you show us the code you are using and more details of what you are trying to do? -
Problems getting a resultset out of a stored procedure
We're having a problem getting a resultset out of a stored procedure with JDBC. The third parameter for the procedure is an out REF CURSOR. Connection to the database is fine, we just keep getting the following error when we do the GetCursor(3) statement:
ORA-00942: table or view does not exist
We know for definate that something is coming out of the database as we can call it from ODBC without any errors. If anyone's got any ideas as to what's going wrong please let me know!
The cut-down code follows:
public class JSMatt extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out = resp.getWriter();
// Load the Oracle JDBC driver
out.println("Registering driver...");
Class.forName("oracle.jdbc.driver.OracleDriver");
// Connect to the DB
out.println("Connecting to database...");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@computer:db",
"username", "password");
// Create a statement using a stored procedure
out.println("Creating query...");
OracleCallableStatement st = (OracleCallableStatement)conn.prepareCall ("BEGIN archive.spSrchLanguage (?, ?, ?); END;");
st.registerOutParameter(3, OracleTypes.CURSOR);
st.setInt(1, 0);
st.setInt(2, 12);
st.execute();
ResultSet rs = ((OracleCallableStatement)st).getCursor(3);
nullFurther study of my colleagues issue reveals that the problem only occurs where we are using a synonym for our package even though the user has permissions to run it (and indeed does when using ODBC or OLEDB).
If we call a procedure in our package which does not return a ref cursor then the procedure is getting called fine (as can be evidenced by the database inserts etc within the procedures).
Ideally we would like to use a synonym (I like to keep nice clean tidy schemas!) so if anyone knows how to get around it please let us know.
Regards
Jason.
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Matthew Butt ([email protected]):
We're having a problem getting a resultset out of a stored procedure with JDBC. The third parameter for the procedure is an out REF CURSOR. Connection to the database is fine, we just keep getting the following error when we do the GetCursor(3) statement:
ORA-00942: table or view does not exist
We know for definate that something is coming out of the database as we can call it from ODBC without any errors. If anyone's got any ideas as to what's going wrong please let me know!
The cut-down code follows:
public class JSMatt extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out = resp.getWriter();
// Load the Oracle JDBC driver
out.println("Registering driver...");
Class.forName("oracle.jdbc.driver.OracleDriver");
// Connect to the DB
out.println("Connecting to database...");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@computer:db",
"username", "password");
// Create a statement using a stored procedure
out.println("Creating query...");
OracleCallableStatement st = (OracleCallableStatement)conn.prepareCall ("BEGIN archive.spSrchLanguage (?, ?, ?); END;");
st.registerOutParameter(3, OracleTypes.CURSOR);
st.setInt(1, 0);
st.setInt(2, 12);
st.execute();
ResultSet rs = ((OracleCallableStatement)st).getCursor(3);
<HR></BLOCKQUOTE>
null -
How can i get all values from jtable with out selecting?
i have one input table and two output tables (name it as output1, output2). Selected rows from input table are displayed in output1 table. The data in output1 table is temporary(means the dat wont store in database just for display purpose).
Actually what i want is how can i get all values from output1 table to output2 table with out selecting the data in output1 table?
thanks in advance.
rajaYou could set the table's data model to be the same:
output2.setModel( output1.getModel() );
Maybe you are looking for
-
How can I restore a old backup of playlist / music from iPod v1 and iPod v2?
I got two old iPod v1and iPod v2. They are both working, well used, both of the got maximum HD sold at that time. I looked at one of my old backup and I got the playlists and music. I remember I spent hours (weeks) converting CD's, manually typing i
-
Event ID 1202 0x534 on Windows 2008 R2 member server
I'm getting the following error on two of my Windows 2008 R2 member servers, but not on my domain controllers. I've followed the instructions and found the account that is causing this issue. It's a local account in "logon as a service", but when I r
-
HomeHub3 Port Forwarding issues...
Hello, I have a BTHomeHub3 and I want to open a port for hosting a game server. I phoned up, and I think the BT tech support got the wrong idea of what I was saying. The guy said I didn't need to open any ports, but I know for a fact, that I do. Unde
-
Hello to all, I am including one program to my main program. itab is defined in include program. I am reading itab in main program using 'read table itab index x'. but after executing main program there is error that this statement is not accessible
-
Z10 won't get past Blackberry word and shuts down
Hello, My Z10 battery died a few days back. I tried charging it, but all the phone did was light the red light for like 5 seconds, then started initiating the startup sequence by displaying the word Blackberry for 2 seconds, and then it just shuts d