How can I use more than one Stored Procedure in a crystal report? - sql

I have two stored procedures I wish to use in my stored procedure, but once I do that it fails to load with the error: "Invalid Argument provided, no rowset retrieved." If I remove either one of them it starts working again.
I have the crystal report set up something like this:
Report:
Group By Tenant.ReferedBy
stored proc here that calculates the tenant's balance
and the second stored proc is in the Select for the report. I only want to select tenant's by a status flag, and I'm getting the status flag from a stored proc.
Neither of the two procedures are linked together in anyway. One returns one value (the one in the select), the other returns multiple (the one in the group by). Neither take any parameters and are both just simple SQL statements stored on the database.
First Proc: GetAllTenantBalances
SELECT (SUM(tblTransaction.AmountPaid) - SUM(tblTransaction.AmountCharged)) AS TenantBalance, tblTransaction.TenantID
FROM tblTransaction
GROUP BY tblTransaction.TenantID
Second Proc: [GetTenantStatusID_Current]
SELECT ID FROM tblTenantStatus WHERE Description = 'Current'
Can anyone tell me why I can't do this, and how to get around it?

You could change the first sp to only sum 'Current' tenants. Or, if you must keep two sp you will have to go to the database expert and join them by the tenant_id.

You could also use sub-reports to give you the data you want. Use on SP on the main, and then another SP on a sub-report.
-JFV

Unless something has changed, you can't call multiple procs from a report. I doubt you can call multiple select statements. You will either need to create one proc that returns both pieces of data or create a subreport for the second proc.

Related

How to save the last result set of SP which is returning multiple result sets into a temp table in SSIS?

I have a Stored Procedure: myProcedure returning 2 different resultset in the end like:
select * from #alldata where <condition1>
and
select * from #allData where <condition2>
Please note that I am not allowed to modify the SP.
What I need is to get the second (last) result set returned from the SP and save it in a temp table in SSIS 2012.
I managed to do is by using a script task including the line:
DataSet ds = db.ExecStoredProcedureDataSet("[myProcedure]", sqlFilters).Tables[1];
I wonder if there is a way to handle it by using "Execute SQL Task" instead.
When I check the topic below, it seems it would be possible if the SP returned one resultset only, but couldn't find a way in my situation where the SP returns multiple resultset and I need the last one saved in a temp table only. Any help would be appreciated.
Insert results of a stored procedure into a temporary table
Edit: It is not duplicate of the indicated topic, I need a solution that would work in Execute SQL Task process in the Control flow of SSIS.
From the docs:
If the Execute SQL task uses the Full result set result set and the
query returns multiple rowsets, the task returns only the first
rowset. If this rowset generates an error, the task reports the error.
If other rowsets generate errors, the task does not report them.
So, SSIS Execute SQL Task cannot access multiple result sets from a single proc. Only the first can be accessed.

How to suppress record sets returned by SELECT statements in a Stored Procedure

I'm writing a stored procedure which checks for the existence of various tables in various databases, as well as the permissions that the user executing the stored procedure has on those tables. The stored procedure itself resides within a user database (i.e. it's not in the Master db).
To perform my checks, my stored procedure contains lots of SELECT statements. Each of those obviously returns a record set. What I would like is to somehow suppress these record sets so that they are not returned by the stored procedure, and instead return my own, single record set which is just a collection of messages relating to each check the stored procedure performs.
I think the obvious answer is to use a table-valued function instead, but I've not been able to recreate my tests successfully in a Function as they appear in the stored procedure. For starters, I'm having to use temporary tables (not possible in a function) and dynamic SQL (not very compatible with table parameters).
I think I've basically got two choices:
Rewrite my stored procedure as a function and figure out how to do the checks a different way.
Continue using my stored procedure and use an OUTPUT parameter to return my result messages, probably as a delimited string, and in the associated ASP.NET application just ignore all the record sets the stored procedure returns .
Neither of these solutions is very satisfactory. Before I spend any more time pursuing either one, is there a way to discard the record sets produced by the SELECT statements in a stored procedure and explicitly define what record I want it to return?
Hmm, I only can speculate here...
Are you using something like
SELECT ...;
IF ##rowcount > 0
BEGIN
...
END;
?
Then you can rewrite it using something like
IF EXISTS (SELECT ...)
BEGIN
...
END;
or
DECLARE #variable integer;
SELECT #variable = count(*) ...;
IF #variable > 0
BEGIN
...
END;
In general point the results of your queries to a target (variable, table, expression, ...), then they don't get outputted.
And then just execute the query for your desired result in the end.
In my opinion, here is almost no reason to have stored procedures produce record sets. That is what stored functions are for. On occasion, it is needed, because of the use of dynamic SQL or other stored procedures, but not as a general practice. Much, much too often, I see stored procedures being used where stored functions or views are more appropriate.
What should you do? Even SELECT statement in the stored procedure should be one of the following:
Setting (local) variables.
Saving the results in a temporary table or table variable.
The logic for the stored procedure should be working on the local variables. The results should be returned using OUTPUT parameters.
If you need to return rows in a tabular format, you can do that using tables explicitly (such as a global temporary table or real table). Or, you can have one SELECT at the end that does return a single result set. However, if you need this and can phrase the stored procedure as a function, that is better in my opinion.

T-SQL selecting values returned by a stored procedure

I am calling a stored procedure in my current one and it returns 3 SELECT statements.
I need the first SELECT only.
How can I achieve this? I'm new to T-SQL, in C# I would just get those variables but SQL doesn't work that way.
Is it possible to get the values it returns?
I have 3 possibilities:
1) Make a new stored proc without the last 2 sSELECTs.
2) Pass an optional parameter to the stored proc to indicate if the last 2 SELECTs should run or not. (If the parameter is not passed, the SELECTs will run by default.)
3) Not an elegant solution, but this might work for your purposes:
In the second stored proc, output the first SELECT into a global temp table, then SELECT * from that temp table. (This will keep everything the same for anything else using the stored proc.)
In the first stored proc, select * from the temp table after you call the 2nd stored proc. (This will give you the results that you are looking for.) At the end of your first stored proc, drop the global temp table.
Some caveats:
If you have several people hitting the stored proc at once, this won't work with a single global temp table- you'll have to figure out some sort of naming convention so that each user gets their own separate table to play with.
If you have a lot of data in the result set, your tempdb database isn't going to be happy.

Calling a stored procedure returning multiple table results inside another stored procedure

Is it possible to call a stored procedure (sp1) within another stored procedure (sp2), which is returning multiple table results?
I have to use the returned results in the executed stored procedure (sp2).
As far as I know this is not possible. But I want to make sure.
Is there any alternative to achieve this kind of requirement?
You can use INSERT INTO <table> EXEC <sp> for one result set.
But that won't work for multiple result sets.
And you can't nest it. (SP2 can use it when calling SP1. But SP3 can't do the same thing if it calls SP2.)
If you honestly have multiple result sets to return, you need to insert the results into tables. Then the outer SP can just use those tables.
If the outer SP creates a temp table (CREATE TABLE #temp) then the inner SP can see it an insert into it.
Equally you could use a permanent table. I'd recommend having a column called SPID and use ##spid as the value you insert into it. (##spid identifys each session uniquely.) But then you have to remember to clean up after you've inserted into the table.
All of these option assume you can modify both SPs. If you can't, I'm not sure that you can do this inside SQL Server.
For this you can create a temp table inside the SP2 and use it in the SP1

Access to Result sets from within Stored procedures Transact-SQL SQL Server

I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?
CREATE PROCEDURE getOrder (#orderId as numeric) AS
BEGIN
select order_address, order_number from order_table where order_id = #orderId
select item, number_of_items, cost from order_line where order_id = #orderId
END
I need to be able to iterate through both result sets individually.
EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option.
The result sets returned by the procedures are not the same data types or number of columns.
The short answer is: you can't do it.
From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested.
To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax:
INSERT INTO #Table (...columns...)
EXEC MySproc ...parameters...
You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded.
I was easily able to do this by creating a SQL2005 CLR stored procedure which contained an internal dataset.
You see, a new SqlDataAdapter will .Fill a multiple-result-set sproc into a multiple-table dataset by default. The data in these tables can in turn be inserted into #Temp tables in the calling sproc you wish to write. dataset.ReadXmlSchema will show you the schema of each result set.
Step 1: Begin writing the sproc which will read the data from the multi-result-set sproc
a. Create a separate table for each result set according to the schema.
CREATE PROCEDURE [dbo].[usp_SF_Read] AS
SET NOCOUNT ON;
CREATE TABLE #Table01 (Document_ID VARCHAR(100)
, Document_status_definition_uid INT
, Document_status_Code VARCHAR(100)
, Attachment_count INT
, PRIMARY KEY (Document_ID));
b. At this point you may need to declare a cursor to repetitively call the CLR sproc you will create here:
Step 2: Make the CLR Sproc
Partial Public Class StoredProcedures
<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Shared Sub usp_SF_ReadSFIntoTables()
End Sub
End Class
a. Connect using New SqlConnection("context connection=true").
b. Set up a command object (cmd) to contain the multiple-result-set sproc.
c. Get all the data using the following:
Dim dataset As DataSet = New DataSet
With New SqlDataAdapter(cmd)
.Fill(dataset) ' get all the data.
End With
'you can use dataset.ReadXmlSchema at this point...
d. Iterate over each table and insert every row into the appropriate temp table (which you created in step one above).
Final note:
In my experience, you may wish to enforce some relationships between your tables so you know which batch each record came from.
That's all there was to it!
~ Shaun, Near Seattle
There is a kludge that you can do as well. Add an optional parameter N int to your sproc. Default the value of N to -1. If the value of N is -1, then do every one of your selects. Otherwise, do the Nth select and only the Nth select.
For example,
if (N = -1 or N = 0)
select ...
if (N = -1 or N = 1)
select ...
The callers of your sproc who do not specify N will get a result set with more than one tables. If you need to extract one or more of these tables from another sproc, simply call your sproc specifying a value for N. You'll have to call the sproc one time for each table you wish to extract. Inefficient if you need more than one table from the result set, but it does work in pure TSQL.
Note that there's an extra, undocumented limitation to the INSERT INTO ... EXEC statement: it cannot be nested. That is, the stored proc that the EXEC calls (or any that it calls in turn) cannot itself do an INSERT INTO ... EXEC. It appears that there's a single scratchpad per process that accumulates the result, and if they're nested you'll get an error when the caller opens this up, and then the callee tries to open it again.
Matthieu, you'd need to maintain separate temp tables for each "type" of result. Also, if you're executing the same one multiple times, you might need to add an extra column to that result to indicate which call it resulted from.
Sadly it is impossible to do this. The problem is, of course, that there is no SQL Syntax to allow it. It happens 'beneath the hood' of course, but you can't get at these other results in TSQL, only from the application via ODBC or whatever.
There is a way round it, as with most things. The trick is to use ole automation in TSQL to create an ADODB object which opens each resultset in turn and write the results to the tables you nominate (or do whatever you want with the resultsets). you can also do it in DMO if you enjoy pain.
There are two ways to do this easily. Either stick the results in a temp table and then reference the temp table from your sproc. The other alternative is to put the results into an XML variable that is used as an OUTPUT variable.
There are, however, pros and cons to both of these options. With a temporary table, you'll need to add code to the script that creates the calling procedure to create the temporary table before modifying the procedure. Also, you should clean up the temp table at the end of the procedure.
With the XML, it can be memory intensive and slow.
You could select them into temp tables or write table valued functions to return result sets. Are asking how to iterate through the result sets?