How to combine 2 results from SQL procedure - sql

I wrote a SQL query, it is 300+ line and I made this as a procedure.
I want to run two times this procedure with different parameters and then want to see all result in one table.
For example:
exec sp_xxxxx 4652,'2022-02-07 00:00:00.000',1
// Returns 2 columns, number of rows can vary
exec sp_xxxxx 4652,'2022-02-14 00:00:00.000',1
// Returns 2 columns, number of rows can vary
I run these together, then I hope to get a result of 4 columns
// 4 column,number of rows can vary
I tried openrowset but SQL blocked.
How can I do this, I would be very happy if you can help.

There's not enough information to provide a demonstrable solution, but the approach should be:
Create temp table #T1(col1, col2)
Create temp table #T2(col1, col2)
Insert into #T1(col1, col2) exec proc
Insert into #T2(col1, col2) exec proc
select t1.col1, t1.col2, t2.col1, t2.col2
from #T1 inner/left/full join #T2 on<criteria>
Also note that prefixing procedures with "sp" is not recommended, this is reserved by MS and indicates a Special Procedure. Choose a different prefix - or no prefix.

Start with creating a table type than matches the output of your procedure.
For example:
CREATE TYPE XxxxxTblType AS TABLE(
Col1 varchar(10) not null,
Col2 decimal(8,2) not null
);
This table type could also be used by your procedure.
Then use a variable with that table type to collect the results from the procedures. Then create a temporary table from that table variable.
declare #Xxxxx XxxxxTblType;
insert into #Xxxxx exec sp_xxxxx 4652,'2022-02-07 00:00:00.000',1;
insert into #Xxxxx exec sp_xxxxx 4652,'2022-02-14 00:00:00.000',1;
select * into #tmpXxxxx from #Xxxxx;
Now you can query the temporary table.
select * from #tmpXxxxx;

Related

How to limit results of Stored procedure for MS-SQl

Problem is...I will be provided with a command to execute a procedure...like EXEC SAMPLE_PROCEDURE_NAME, I cannot modify or pass count/number to that procedure
Right now, on execution, the procedure is returning all the rows. I want to limit the number of rows that I receive back
Below are a few things I have tried (Procedure name = Demo4)
This one failed
select top 10 * FROM (EXEC Demo4)
This one failed too
;WITH Results_CTE AS
(
EXEC Demo4
)
select top 10 *
FROM Results_CTE
This one failed too
DECLARE #tmpNewValue TABLE (*)
INSERT INTO #tmpNewValue
EXEC Demo4
select top 10 * FROM #tmpNewValue
I would really appreciate if someone can help on this.
You need to specify the columns in the result set to put them in a table. So:
declare #tmpNewValue table (
col1 type1,
col2 type2,
. . .
);
Then you can insert the rows:
INSERT INTO #tmpNewValue
EXEC Demo4;
And return 10 arbitrary rows:
select top 10 *
from #tmpNewValue;
You need an ORDER BY to get ten specific rows (like "first" whatever that means).
If you want them in insertion order and have no other method, then you can use an identity column in your table:
declare #tmpNewValue table (
id int identity(1, 1),
col1 type1,
col2 type2,
. . .
);
insert into #tmpNewValue (col1, col2, . . . ) -- no `id` column here
exec Demo4;
Then:
select top (10) *
from #tmpNewValue
order by id;
I should add that I strongly discourage returning result sets like this. Stored procedures should not be viewed as queryable objects. Code can break just because someone makes a small modification to the stored procedure -- like adding debugging or auditing code.
There are other ways to handle these situations:
If multiple rows are not needed, then OUTPUT parameters can be used.
In many cases, the stored procedure can be written as a user-defined function.
You can pass in a table variable to return a table (although that requires a user-defined type).
You can limit the rows from the stored procedures just by setting the row count before running the the stored procedure and releasing it later as below
Solution: SET ROWCOUNT 50; EXEC Demo4; SET ROWCOUNT 0;
Description: Running SET ROWCOUNT 50; would limit the result of any query including stored procedures. then you execute the stored procedure as EXEC Demo4; to release the connection from limiting the rows to 50 you have to set it to Zero as SET ROWCOUNT 0;

Insert into table from stored procedure with different versions

There is a stored procedure sp and a table variable #tbl
Insert into #tbl
Exec sp
Above works fine initially.
We changed the stored procedure output and added additional output columns. The insert statement above fails with 2nd version of the stored procedure.
The above SQL needs to work with version 1 of sp and version 2 of sp
What can be done?
SQL Server doesn't provide the option to specify the column names while doing the insert from sp output
The only way to do it is to use the EXECUTE WITH RESULT SETS to determine the exact columns to return from the stored procedure. This will give you the option to specify the column names to insert into the table variable from the stored procedure output.
Insert into #tbl(col1, col2, col3) EXECUTE sp
WITH RESULT SETS (
(col1 INT,
col2 INT,
col3 nvarchar(50))
)
For more information, see here.

How do I grab multiple outputs from a stored procedure into temp table

My stored procedure returns me two outputs. I want to use one of them in another stored procedure. So trying to grab the second output in a temp table. but since the structure of both the outputs are different, there fore I always get "Column name or number of supplied values does not match table definition."
Even if I change the order of the output(first output second and second output first), it is not working.
I am establishing a brand new application and I need to use the stored procedure again an d again in another stored procedures. If I face this type of situation, probably I need to rewrite lot of code.
There is a very nice questions, but this covers only one output.
Insert results of a stored procedure into a temporary table
thanks
You can't, not without modifying the stored procedure.
In SQL Server, you can only insert the first result set of a stored procedure into another table, via INSERT...EXEC. Column count and positions must match exactly, and INSERT...EXEC cannot be nested, ie you cannot insert from proc1 into a table in proc2, and then insert from proc2 into a table in proc3. So INSERT...EXEC is an altogether unsatisfying solution.
The workaround is modify the procedure to insert results into temporary tables defined in the calling scope, eg:
create proc get_some_data as
insert #temp1 (col1, col2) select col1, col2 from table1
insert #temp2 (colA, colB) select colA, colB from table2
go
create table #temp1 (col1 int, col2 int)
create table #temp2 (colA int, colB int)
exec get_some_data
select * from #temp1
select * from #temp2
drop table #temp1
drop table #temp2
go
If you can't modify the procedure, you are out of luck. CORRECTION: as HABO kindly pointed out, you could use the CLR to iterate the result sets. See link below for details. Not too bad if you know what you are doing, and have no other choice.
For more details on sharing data between stored procedures, see this very comprehensive article by Erland Sommarskog: http://www.sommarskog.se/share_data.html

SQL Select SUM(col) from exec stored_proc?

Is there an easy way in SQL Server (2010) to exec a stored procedure (that returns a table) and sum a column in one (or a few) statements?
eg
SELECT SUM(column) FROM exec proc_GetSomeStuff 'param1', 'param2'
Don't have a server handy to test with, but try this:
declare #temp table(col1 int)
insert into #temp(col1)
exec proc_GetSomeStuff 'param1', 'param2'
select sum(col1) from #temp
Make sure your table variable (or temp table) has the same schema as the results of the stored procedure. If you know that there will be a significant number of rows coming back from the SP, then a temporary table might be a better option. (I'm not sure if table variables can be flushed out to disk if they get too big)

Insert into Table select result set from stored procedure but column count is not same

I need something like that which is of course not working.
insert into Table1
(
Id,
Value
)
select Id, value from
(
exec MySPReturning10Columns
)
I wanted to populate Table1 from result set returned by MySPReturning10Columns. Here the SP is returning 10 columns and the table has just 2 columns.
The following way works as long as table and result set from SP have same number of columns but in my case they are not same.
INSERT INTO TableWith2Columns
EXEC usp_MySPReturning2Columns;
Also, I want to avoid adding "." as linked server just to make openquery and openrowset work anyhow.
Is there a way not to have define table strucutre in temp table (all columns with datatypes and lenght)? Something like CTE.
You could use a temporary table as a go-between:
insert into #TempTable exec MySP
insert into Table1 (id, value) select id, value from #TempTable
You could solve the problem in two steps by doing the insert from the stored procedure into a temporary table, then do the insert selecting just the columns you want from the temporary table.
Information on temporary tables: http://www.sqlteam.com/article/temporary-tables
-- Well, declare a temp table or a table var, depending on the number of rows expected
-- from the SP. This table will be basically the result set of your SP.
DECLARE #spResult AS TABLE
(
ID INT,
VALUE FLOAT,
....
);
-- Get the result set of the SP into the temp table.
INSERT #spResult EXEC STORED_PROC;
-- Now you can query the SP's result set for ID and Value;
INSERT Table1 (ID, VALUE)
SELECT ID, VALUE FROM #spResult;
You dont need to create a temporary table, you can do it with single query by creating temporary view like this
with tempView as EXEC MySPReturning10Columns insert into Table1 select id, value from tempView
The temporary view disappears as soon as the statement finishes execution