SQL stored procedure combine result - sql

I have written two SQL Server stored procedures
For example:
create PROCEDURE query1
AS
SQL code here...
create PROCEDURE query2
AS
SQL code here...
Now I can call them individually using the following command, and the returned value is the following.
exec query1
Study availability
ACR 99.97%
Now I want to combine these stored procedures and get the results in one shot, like :
exec query1
exec query2
and it give result something like following but somehow its now working its giving me syntax error. How do I combine two stored procedures and get results in one report?
This is T-SQL query
Study availability
ACR 99.97%
FOS 87.88%

You can't call them the way you describe (ie exec query1 exec query2). Here is one alternative assuming each proc returns a single value:
declare #result as table (
ACR float,
FOS float
)
INSERT INTO #result(ACR)
exec query1
INSERT INTO #result(FOS)
exec query2
SELECT ACR,FOS from #result

Since they both return the same column headings/data types I recommend combining the 2 separate queries into a single query and use UNION ALL.
EX:
SELECT 'ACR' AS Study,
SomeField AS Availability
FROM SomeTable1
UNION ALL
SELECT 'FOS' AS Study,
SomeField AS Availability
FROM SomeTable2;
It's hard to give more specific advice without seeing your actual Stored Procedures, but this is definitely much clearer than having 2 separate procedures. Hope this helps.

You can try that:
exec query1; exec query2
But be aware that the result is not combined, you just get the result of both SPs as separate result sets.

It depends on your code, you can insert the results of each SP into a table, and then UNION them together to get the single result set you are looking for - but this often can be slower if it's a lot of rows since you are making copies of the results instead of just streaming them out to the client. And it breaks the ability of the optimizer to combine things across the boundary, since it has to write them to the temporary tables.
If the procs aren't complex, I would consider making them into views or inline table-valued functions. These can be easily combined by other routines like views, functions or procedures and make things a bit more modular.

Related

How to re-use a SQL query in a PL/SQL procedure?

I am writing a PL/SQL procedure. In the body of this procedure, how can I use twice the same query without re-writing it ?
To simplify, let's say that I have this SQL query :
SELECT *
FROM mytable
WHERE age > 18
Is there a way to "store it", so I could do for example :
SELECT COUNT(*) INTO var1
FROM myQuery
I know the WITH ... AS keywords, but as I know it can be only used in the current statement, and I want to be able to call it from different statements.
Thanks !
There are various possibilities. Here are the ones I think of immediately, there are probably others:
Declare an explicit CURSOR using your query, and use that cursor multiple times in the body of your procedure.
Store the query in a string variable, and use EXECUTE IMMEDIATE to run it multiple times
Execute the query once, storing the results in a local collection (nested table, most likely), and process those stored results multiple times
Create a function that executes the query and returns its results as a nested-table type. Then SELECT FROM TABLE( my_function ) multiple times

Selecting from the result set of a DB2 stored procedure

I have a stored procedure which returns multiple records (the SP cannot be changed, I need to work with what I have). I'd like to do a DB2 select statement from Shell script that selects one record based on a combination of column data like the following:
select a.description_column from (call my_stored_proc) a where a.name_column='name_filter' and a.value_column='value_filter';
The columns description_column, name_column and value_column exist in the result set of the SP. I get a SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2 error. As I need to sort it out from a Shell script and I only have read access to the DB, I can't create additional tables for this.
You can't select from SP.
But you can from a Table-Function.
SELECT ... FROM TABLE(<table-function(param1, param2, ..., paramN))) as t WHERE ....
So, easiest way is to ask the DBA to create a table-function based in the source SP.
Good luck

Getting different values from view

I have a two tables and a view for them.
Having inline query
select * from View_tbl where sector = '04'
but when i creates stored procedure for this
create proc spTest
#sector varchar(2)
as
select * from View_tbl where sector = #sector
both returns dataset with different values.
SP Returns those columns too which are in Main tbl but not in view.
Any suggestions please
If the definition of your view has changed, you may need to recompile the stored procedure.
When you use select * in a stored procedure, this will get compiled down to an explicit list of columns. Subsequent changes to the view definition may not be reflected in the definition of the sp (depending on a few other factors and the version of SQL Server).
In general, I try to avoid select * in stored procedures and code the list of columns explicitly. This avoids the dependency on recompilation.
create proc spTest
#sector varchar(2)
as
select
col1,
col2,
col3
from
View_tbl
where
sector = #sector
My guess is that you have the SP in two places by accident (check Master) and it executing the SP in the wrong database maybe an old version of your sp is laying around...Maybe fully qualify your tables with Database as sort term test.

How to SELECT [temp table1] = [subselect 1], [temp table2] = [subselect 2] FROM [Stored Procedure]

I have a stored procedure that returns two selects, which I use in a report.
The first select is data to display in tabular format and the second are metadata to display in the report head, like showed below:
CREATE PROCEDURE dbo. GetReport
#Input INT
AS
BEGIN
--Get #Metadata
-- #Results = f(#Metadata) … compex calculation
SELECT * FROM #Results
SELECT * FROM #Metadata
END
As the sproc calculation is quite intensive, I would like to prepare the report lines as plain data (in two tables: PrecalcResults and PrecalcMetadata) for some mostly used sproc parameters overnight.
Lather I would directly select the precalculated vaues or calculate them with the sproc according to the parameters.
For maintenance reasons I would like to use the same sproc to calculate data that would be:
1. showed in the report
2. be stored in PrecalcResults and PrecalcMetadata (with the used parameters)
If I would have single select sproc I would an approach desctibed here:
Insert results of a stored procedure into a temporary table
As I have multiselect sproc I would like to do something like above but with two tables.
In .net I would do DataSet.Tables[0] and DataSet.Tables[1]..., but I want to do it in tsql, to run it in daily job.
Is this even possible in MS SQL?
I have to apologize myself, from the answer below I can see I was not very clear.
I would like to do implement this functionality as pure TSQL.
Yes, this is possible.
It's perfectly fine to return multiple result sets from a single stored procedure as you have suggested.
Your only potential issue is the limitation of a TableAdapter being able to pull both result sets from the stored procedure, but there's a very simple work-around for that issue.

SQL Server Stored Procedure - Use Row Count in Select query

My stored procedure (SQL Server 2005) returns a dataset where one field depends, among other things, on the number of rows returned by the query. I can make a simplified first query that allows me to get ##ROWCOUNT but, in that case, the procedure returns the two sets, which is not what I want.
I tried putting the first query in a WITH statement but haven't found the syntax to extract the row count and put it in a variable that I could use in the second query. An alternative would be to get ##ROWCOUNT from the first query and tell the procedure to return only the result of the second query.
There are probably better ways to do that but my expertise in SQL is quite limited...
Thanks for any help!
Is this what you're looking for? If not, could you please describe your problem in more details (perhaps, with code snippets)
alter procedure ComplicatedStoredProcedure as
begin
declare #lastQueryRowCount int
-- Storing the number of rows returned by the first query into a variable.
select #lastQueryRowCount =
-- First resultset (not seen by caller).
(select count(*) from A where ID > 100)
-- Second resultset. This will be the actual result returned from the SP.
select * from B where SomeDependentField > #lastQueryRowCount
end