Multiple results set - missing from callablestatement
I am using callablestatement to call a store procedure and it will return several resultsets and my code is kind of like the following:
ResultSet rs = callablestatement.executeQuery();
do {
if (!rs.next()) {
} else {
rsmd = rs.getMetaData();
int col_count = rsmd.getColumnCount();
for (int i = 0; i < col_count; i++) {
// create table headings
do {
for (int i = 0; i < col_count; i++) {
// get data
while (rs.next());
while (callablestatement.getMoreResults() || (callablestatement.getUpdateCount() != -1));
The problem I am having is that if say I am expecting 4 resultsets back, and the 3rd one contains empty row, the above would think there is no more resultset and it will stop and it will never return me the 4th resultset which is non-empty. I think the 3rd resultset is returned as null or something but I am sure.
Has anyone seen this problem or what is the best way to handle multiple resultsets?
Hi,
I can promise you that
No matter how you run your code, you always could get
the last three rows.
Because you have such a instruction
if(!rs.next()) {..}
being run first before you start fetch your rows.
good luck,
Alfred Wu
Similar Messages
-
Callable Statatement returning multiple Result Sets
Hello all,
I've got a stored procedure that will be returning multiple result sets and i was wondering if someone could show me how to pull the multiple result sets out of the CallableStatement object. Any help would be greatly appreciated.Here is a sample that does what you want. You will have to substitute the call to DBConn.getConnection() with your own DB connection. Also remove the import of com.ovotron.util.*.import com.ovotron.util.*;
import java.sql.*;
public class MultiSQL {
private static Connection conn = null;
public static void main(String[] args) {
// Just gets a connection to the DB.
conn = DBConn.getConnection();
getResults(conn);
* Cycles through multiple result sets returned from a stored procedure.
* Only the first column is output.
* <p>
private static void getResults(Connection conn) {
// Not sure which DBMS you are using. This is the syntax for
// SQLServer V7.0.
String sql = "{call getMultiResults}";
CallableStatement stmt = null;
ResultSet rs = null;
int setNo = 0;
try {
stmt = conn.prepareCall(sql);
boolean found = stmt.execute();
while (found) {
setNo++;
rs = stmt.getResultSet();
while (rs.next()) {
System.out.println("Result set " + setNo +
": value: " + rs.getString(1));
System.out.flush();
rs.close();
found = stmt.getMoreResults();
catch (SQLException e) {
e.printStackTrace();
finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
catch (SQLException e) {
// Tried already to clean up.
}The procedure I used is:CREATE PROCEDURE [getMultiResults] AS
select col1 from tab1;
select col2 from tab1;
select col3 from tab1;Of course you will need to create and populate tab1. -
Multiple result sets from stored procedure into CachedRowSet
How can you obtain multiple sets of data from a stored procedure that returns multiple result sets, when you'd like to use CachedRowSet rather than ResultSet?
My database's stored procedures return multiple result sets, but I'm not sure how to manipulate that using CallableStatements and CachedRowSets... I read the RowSet tutorial from java.sun.com but that didn't cover the case of multiple result sets and CallablStatements.
How might I do this? Thanks a lot.SELECT columns..
FROM table
FOR XML PATH('NodeName'),('Rootname')
Thank you for replying.
I dont have to generate XML from a query. I have to generate from a SP and that too without modifying it.
Thanks,
Tauhid
thats ok you can do like this
1. Create a table with structure same as SP resultset
2. Populate table with SP result as per below
INSERT table
EXEC SPName param1value,...
3. Add a query like below
SELECT columns..
FROM tablename
FOR XML PATH('NodeName'),('RootName')
see
http://visakhm.blogspot.com/2014/05/t-sql-tips-fun-with-for-xml-path.html
4. Use sp_send_dbmail to sent it through mail
http://msdn.microsoft.com/en-IN/library/ms190307.aspx
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Stored Procedure With Multiple Result Sets As Report Source : Crosspost
Hello Everyone,
I have an issue where i have created a stored procedure that returns multiple result sets
/* Input param = @SalesOrderID */
SELECT * FROM Orders TB1
INNER JOIN OrderDetails TB2 ON TB1.ID = TB2.ID
WHERE TB1.OrderID = @SalesOrderID
SELECT * FROM Addresses
WHERE Addresses.OrderID = @SalesOrderID AND Addresses.AddressType = 'Shipping'
SELECT * FROM Addresses
WHERE Addresses.OrderID = @SalesOrderID AND Addresses.AddressType = 'Billing'
This is just a quick sample, the actual procedure is a lot more complex but this illustrates the theory.
When I set the report source in Crystal X to the stored procedure it is only allowing me to add rows from the first result set.
Is there any way to get around this issue?
The reason that I would prefer to use a stored procedure to get all the data is simply performance. Without using one big stored procedure I would have to run at least 6 sub reports which is not acceptable because the number of sub reports could grow exponentially depending on the number of items for a particular sales order.
Any ideas or input would be greatly appreciated.
TIA
- Adam
P.S
Sorry for the cross post, I originally posted this question [here|/community [original link is broken];
but was informed that it might be the wrong forum
Edited by: Adam Harris on Jul 30, 2008 9:44 PMAdam, apologies for the redirect, but it is better to have .NET posts in one place. That way anyone can search the forum for answers. (and I do not have the rights to move posts).
Anyhow, as long as the report is created, you should be able to pass the datasets as:
crReportDocument.Database.Tables(0).SetDataSource(dataSet.Tables("NAME_OF_TABLE"))
Of course alternatively, (not sure if this is possible in your environment) you could create a multi-table ADO .NET dataset and pass that to the report.
Ludek -
Hi
I have a problem while handling multiple result sets. To fix that problem i need to upgrade my JDBC version2.0 to 4.0.
My Problem is that i dont know which jars need to be downloaded to upgrade my JDBC version.Mallika_23 wrote:
Is that any more ideas ???1. Learn how google works.
2. Find the drivers
3. Read the documentation
4. Ask questions here once you have actually read the documentation. -
Oracle 8.1.6 Thin Driver with Multiple Result Sets
We're using Oracle 8.1.6 on NT using the latest driver release.
Java 1.2.2
We're experiencing problems with resultSet.next when we have multiple result sets open. What appears to be happening when you've read the last result set entry do a .next() call which should result in a false value we actually get java.sql.SQLException: ORA-01002: fetch out of sequence.
This seems to us that the driver is trying to go beyond the end of the result set.
We've checked JDBC standards (and examples on this site) and the code we've got is compliant. We've also found that the code produces the correct results under Oracle 7.3.4 and 8.0.4.
I can also say that there is no other activity on the db, so there are no issues such as roll back segments coming into play.
Any solutions, help, advice etc would be gratefully appreciated!
nullPhil,
By "multiple result sets open", do you mean you are using REF Cursors, or do you have multiple statements opened, each with its own ResultSet? If you could post an example showing what the problem is, that would be very helpful.
You don't happen to have 'for update' clause in your SQL statement, do you?
Thanks -
Reading multiple result sets using executeQuery
Hi - We have a database Proc that returns multiple result sets as the out params.
Following is the line that does the DB call.
rows = DynamicSQL.executeQuery(sentence : query, implname : "Sql Server");
The 'rows' param above is able to get only the first result set after. It ignores the rest of the Out params.
Do we have any way other than changing the proc to send one out param to handle this?
Thanks!
VVPThis worked:
rows = myDynamic.executeQuery(sentence : SaveQueryForMAPS, implname : "MAPS");
foreach (row in rows) {
//status = 0;
status = row[1];
display("status" +status);
Thank you so much for your idea Andrea! -
How do you report from a multiple-result-set stored procedure?
Team,
I am writing a report against a canned stored procedure which returns eight result sets. That is, inside the stored procedure, there are eight SELECT statements which pump to the output. In ADO, you would read the first one, then use SqlDataReader.NextResult to advance the reader to the next one until you have done all eight.
Q1: Have you ever written a Crystal Report against such a sproc? How?
Q2: I see that I could pull this data using ADO.NET if I knew this: Have you ever read such a sproc into a dataset? When I drag-and-drop the sproc into the dataset designer, it only makes a table schema for the first result set. I desire to have a table schema for all eight.
Thanks,
~ ShaunQ1: Have you ever written a Crystal Report against such a sproc? How?
- best answered in the Crystal Reports Design forum, so please post there:
SAP Crystal Reports
Q2: I see that I could pull this data using ADO.NET if I knew this: Have you ever read such a sproc into a dataset? When I drag-and-drop the sproc into the dataset designer, it only makes a table schema for the first result set. I desire to have a table schema for all eight.
- not a Crystal reports question. Perhaps better posted to some MS / .NET developer forum(?)
Ludek -
Returning a result set/record from a dynamic query
There seems to be plenty of examples for using Native Dynamic Sql to formulate and execute a dynamic query, however there are no examples of returning a result set or records which contain the rows of data that are retrieved by executing the query. Could someone give us an example?
Welcome to the Oracle forum....
CREATE OR REPLACE PACKAGE curspkg_join AS
TYPE t_cursor IS REF CURSOR ;
Procedure open_join_cursor1 (n_EMPNO IN NUMBER, io_cursor IN OUT t_cursor);
END curspkg_join;
Create the following Oracle package body on the Oracle server:
CREATE OR REPLACE PACKAGE BODY curspkg_join AS
Procedure open_join_cursor1 (n_EMPNO IN NUMBER, io_cursor IN OUT t_cursor)
IS
v_cursor t_cursor;
BEGIN
IF n_EMPNO <> 0
THEN
OPEN v_cursor FOR
SELECT EMP.EMPNO, EMP.ENAME, DEPT.DEPTNO, DEPT.DNAME
FROM EMP, DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO
AND EMP.EMPNO = n_EMPNO;
ELSE
OPEN v_cursor FOR
SELECT EMP.EMPNO, EMP.ENAME, DEPT.DEPTNO, DEPT.DNAME
FROM EMP, DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO;
END IF;
io_cursor := v_cursor;
END open_join_cursor1;
END curspkg_join;
Dim Oraclecon As New OracleConnection("Password=pwd;" & _
"User ID=uid;Data Source=MyOracle;")
Oraclecon.Open()
Dim myCMD As New OracleCommand()
myCMD.Connection = Oraclecon
myCMD.CommandText = "curspkg_join.open_join_cursor1"
myCMD.CommandType = CommandType.StoredProcedure
myCMD.Parameters.Add(New OracleParameter("io_cursor", OracleType.Cursor)).Direction = ParameterDirection.Output
myCMD.Parameters.Add("n_Empno", OracleType.Number, 4).Value = 123
Dim myReader As OracleDataReader
Try
myCMD.ExecuteNonQuery()
Catch myex As Exception
MsgBox(myex.Message)
End Try
myReader = myCMD.Parameters("io_cursor").Value
Dim x, count As Integer
count = 0
Do While myReader.Read()
For x = 0 To myReader.FieldCount - 1
Console.Write(myReader(x) & " ")
Next
Console.WriteLine()
count += 1
Loop
MsgBox(count & " Rows Returned.")
myReader.Close()
Oraclecon.Close()
The above code is working in one of our application; which is using ref cursor as result set and get from procedure. I hope you can found more code by google and/or search in this forum as well; if above code is not useful to you.
HTH
Girish Sharma -
SQL Server 2012: Import and Export Wizard - Exporting Multiple Result Sets at Once?
I'm working in SQL Server 2012 trying to export some data from our database into an Excel file. My SQL statement has two separate Select statements. They are not joined by a union. When I Execute them inside of SQL Server Management Studio, with Results
set to go to a Grid, I get two result sets back. Two full tables of data.
However, when I use the Import and Export Wizard, the Excel sheet only has the first set of data.
What do I need to do to have it so both result sets show up in the excel file?Why cant use merge them using union/union all if intention is to get them to same sheet? Is it like the metadata is different so that they cant be merged to single sheet?
If that being the case you need to do it in two steps.
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
Reg. Multiple Result set in OBIEE
Hi All,
I would like to have some pointers or any documentation reg. the processing of mutiple result sets from a DB2 stored procedure, by the OBIEE layer.
Thanks in Advance,
RockyHi Radha,
If you want to cache the results in the Oracle BI Server, you should check that option. When you run a query the Oracle BI Server will get its results from the cache, based on the persistence time you define. If the cache is expired, the Oracle BI Server will go to the database to get the results.
If you want to use caching, you should enable caching in the nqsconfig.ini file.
Cheers,
Daan Bakboord -
Populating multiple result sets properly
Hi,
I am attempting to create 2 resultsets within a servlet from a mysql db.
I am at present creating 2 connections, query strings. statements and resultsets but my second resultset is not being populated correctly and is null.
Is there something wrong with my implementing 2 result sets like this? and if so, how should I create 2 resultsets? I have posted my code below.
Thanks
Connection con = DriverManager.getConnection( url, "root", "password");
//2nd connection for second result set processing
Connection con2 = DriverManager.getConnection( url, "root", "password" );
Statement stmt = con.createStatement ();
Statement stmt2 = con2.createStatement ();
ResultSet rs = stmt.executeQuery (query);
ResultSet rs2 = stmtAI.executeQuery (query2);
printResultSet ( resp, rs );
useSecondResultset ( rs, rs2 );
rs.close();
rs2.close();
stmt.close();
stmt2.close();
con2.close();You shouldn't have ResultSets in a JSP, IMO.
JSPs are only for display. And scriptlet code is not a good thing.
Move that SQL stuff into a Java Bean that you can set off line. Have that bean take the data out of ResultSets and put it into a data structure or object and immediately close the ResultSet.
Once you get it running, have the JSP call its methods and access the results from the object or data structure.
% -
Returning multiple result sets
I would like to populate multiple tables in a typed
DataSet in a single call to OracleDataAdapter.Fill
(one round trip to the database). I have found examples
that do this with REF CURSOR output parameters from a
stored procedure that is defined in a package. However,
my SELECT statements are dynamically generated. Is there
any way to execute multiple dynamic SELECT statements in
a single Command used by OracleDataAdapter.Fill? Or is
there some other way to do this with dynamic SQL?
Thanks,
Dennis
[email protected]Neeraj,
I tried doing this, but the call to Fill did not put any
rows into my DataSet when using an anonymous SQL block.
Do you have a working example that you could sent to me?
Thanks,
Dennis
Here's the stored procedure, which works:
CREATE OR REPLACE PACKAGE BODY cr_mccarthyd_odpnet AS
PROCEDURE GetAttributes (DefCur OUT RefCur,
ValCur OUT RefCur)
IS
LocalValCur RefCur;
LocalDefCur RefCur;
BEGIN
OPEN LocalDefCur FOR
Select * from ATTRIBUTES;
OPEN LocalValCur FOR
Select * from ATTRIBUTE_VALUES;
DefCur := LocalDefCur;
ValCur := LocalValCur;
END GetAttributes;
END cr_mccarthyd_odpnet;
And here's the anonymous SQL block, which does not throw
an error, but does not produce any data either:
DECLARE
TYPE RefCur IS REF CURSOR;
LocalValCur RefCur;
LocalDefCur RefCur;
BEGIN
OPEN LocalDefCur FOR
Select * from ATTRIBUTES;
OPEN LocalValCur FOR
Select * from ATTRIBUTE_VALUES;
END
Finally, here is the C# calling ODP.NET:
// Open a connection.
OracleConnection conn = new OracleConnection("Data Source=CR-DEV;User ID=CR01;Password=CR01");
conn.Open();
// Create a command for calling the stored procedure.
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "cr_mccarthyd_odpnet.GetAttributes";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("LocalValCur",OracleDbType.RefCursor,DBNull.Value,ParameterDirection.Output);
cmd.Parameters.Add("LocalDefCur",OracleDbType.RefCursor,DBNull.Value,ParameterDirection.Output);
// Create an adapter to populate the data set.
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
adapter.TableMappings.Add("Table", "Attributes");
adapter.TableMappings.Add("Table1", "AttributeValues");
// Create the typed data set and fill it.
TrueNorth.AttributeDataSet dataset = new AttributeDataSet();
try
adapter.Fill(dataset);
catch (Exception ex)
System.Windows.Forms.MessageBox.Show(ex.Message);
return dataset; -
Multiple Result Set Using Nested Table
Package declaration------------
CREATE or REPLACE PACKAGE dummy
AS
TYPE CResValues IS TABLE OF VARCHAR2(2000);
FUNCTION GetValue(p_user IN VARCHAR2,
p_owner IN VARCHAR2, p_resource IN VARCHAR2,
ResValues OUT CResValues) RETURN INTEGER; END dummy;
Package Body declaration------------
CREATE OR REPLACE PACKAGE BODY dummy
BEGIN
FUNCTION GetValue(p_user IN VARCHAR2,
p_owner IN VARCHAR2,
p_resource IN VARCHAR2,
ResValues OUT CResValues) RETURN INTEGER IS
----implementation
END dummy;
/* Problems While executing HELP*/
DECLARE
TYPE CResValues IS TABLE OF VARCHAR2(2000);
resvalues CResValues;
total INTEGER; BEGIN
select dummy.GetValue('tt', 'test', 'test', resvalues) INTO total FROM DUAL;
END;
/////////ERROR in PL/SQL////////////////
ERROR at line 5:
ORA-06550: line 5, column 8:
PLS-00306: wrong number or types of arguments in call to 'dummy'
ORA-06550: line 5, column 1:
PL/SQL: SQL Statement ignored
nullThank you for the response.
I used the XMLType and Queue is created so far ok. This queue is actually used through Event Based Queue in Scheduler. Now when i use the XMLTYpe payload and specify that in event_condition as follows in dbms_scheduler.create_job it throws "ORA-25448: rule . has errors".
following is the code. Does this mean dbms_scheduler queue spec does not support XMLType payload?
dbms_scheduler.create_job(
job_name => v_name,
job_type => 'stored_procedure',
job_action => v_action,
start_date => systimestamp,
queue_spec => v_qspec,
event_condition => 'tab.user_data.xdata.extract(''/Application/@name'') = '''||v_event1||''' and tab.user_data.extract(''/Application/Scripts/Procedure/@name'')= '''||v_event2||'''',
enabled => true,
auto_drop => true);
dbms_scheduler.set_attribute(name => v_name, attribute => 'max_runs', value => 1);
dbms_scheduler.set_attribute(
name => v_name,
attribute => 'raise_events',
value => dbms_scheduler.job_all_events);
exception when others then
dbms_output.put_line(sqlerrm);
my xml message is like below
<?xml version="1.0"?>
<Application id="1" name="TEST" module="EXP">
<Scripts> ||chr(10)||<Procedure id=1 name="sp_init"/>||chr(10)||</Scripts>||chr(10)||
</Application> -
Hi, I'm a new Java programmer.
Right now, I'm working with databases in JSP.
Is it possible to include different ResultSets within each other?
For example:
ResultSet set1 = stmt.executeQuery(query1);
while(set1.next())
{ ResultSet set2 = stmt.executeQuery(query2);
while(set2.next())
{ //....code goes here
If this can't be done, is there another way to do this with JSP?
Thanks a lot!Well, yes and no. You can't do it the way you're specifying. You need two database connections and each one has to be processing a separate ResultSet. Doing two from one connection will cause errors.
stmt1 = conn1.createStatement();
stmt2 = conn2.createStatement();
rst1 = stmt1.executeQuery(query1);
while (rst1.next()) {
rst2 = stmt2.executeQuery(query2);
while (rst2.next()) {
// code goes here.
Michael Bishop
Maybe you are looking for
-
A/P Invoice added with incorrect price
Good Moorning Experts. I've i little problem. I've added a A/P invoice generated from 7 GRPO with incorrect price in the row of the invoice. How can i do to change the price? I can not do a credit memo cause all goods have been sold, so i don't have
-
IPod Sync error -48, cannot update any longer
An intractable and frustrating problem has surfaced on my iPod and I'd appreciate any advice. System: Powermac G5 Dual 2.0, iPod 80GB. All newest software, firmware, etc. installed. Problem: A few weeks ago, after adding songs ripped from a CD, the i
-
Need quick help on .mov to "DVD ready"
hi, i have a .mov file that i was using in DVDSP. i thought it might be better to go ahead and run it through compressor first. my source fill has video and audio --how do i get a final file that is separated into two files? it seems to me i'd have t
-
I would like to be able to do this: http://www1.ap.dell.com/content/products/productdetails.aspx/xpsdt_710?c=au&cs=audhs1&l=en &s=dhs Do I need any special plugin? I realise one of the steps is taking photos, but how do I stitch them together in Flas
-
Creating html table using FLEX
Hi I am new to flex,can any one help me how to create a simple html table using flex. regards pr@veen