Insert into table from stored proc - sql

I am trying to use a stored procedure that contains two different cursors as table input like such:
INSERT INTO table1 EXEC * FROM tblDailySales
The stored proc contains two cursors - I did not run just using.
I get the following error:
A cursor with the name 'csrDistricts' does not exist.
I also, get this error
An INSERT EXEC statement cannot be nested
The stored proc contains no EXEC that I can see.
What kind of stored proc other than simple SELECT can be used as source for table?

Is table1 already defined? If so all you should have to do is
INSERT INTO table1
EXEC storedProcedureName
Now, the trick is, the stored procedure will only be able to return one result set and insert into the table.
If you need to insert two different result sets, you'll have to gather then in two different stored procedures, then run two INSERT statements.
If you must do them at once, you'll need to do the insert from within the stored procedure.

Related

I want to Execute stored procedure into temporary table but it gives me an error You must specify a table where to make the selection

This my code where i want to insert the result of my stored procedure into #TempTable
SELECT * INTO #Tempannuelguiftrecap
EXECUTE PSGetDetailMensuelPPM #Year,#Mois
You can't SELECT from a Stored Procedure. Something like SELECT * FROM EXECUTE dbo.MySP isn't going to work.
You can still INSERT the data from a Stored Procedure into a table, however, you must first define the table, and then INSERT the data. This is Pseudo-SQL as we have no definitions of your objects, however, this should get you on the right path:
CREATE TABLE #MyTempTable({Column1} {Data Type}[,
{Other Column(s)} {Column DataType(s)} ..... ]);
INSERT INTO #MyTempTable ({Columns List})
EXECUTE dbo.MyStoredProcedure #MyParam;

Is it possible to retrieve Selected Columns from Stored Procedure?

I have a stored procedure which returns a few columns from a SELECT. Now I need to grab 2 columns out of those columns in my new stored procedure and use them.. I am trying to do this using EXEC method. Is it possible to do this?
Ex : Original stored procedure:
CREATE PROCEDURE myBaseProcedure
#stId INT
AS
BEGIN
SELECT Name,
Address,
StudentId,
Grade
FROM Student
WHERE StudentId = #stId
END
New stored procedure:
CREATE PROCEDURE myNextProcedure
BEGIN
EXEC myBaseProcedure 19 -- Here I need to grab only StudentId and Name??
END
Given that you cannot dump to a temp table or table variable since the base stored procedure might sometimes add columns, there are three approaches that would do this:
You can effectively SELECT from a stored procedure using either OPENROWSET or OPENQUERY
You can use SQLCLR to create a table-valued function that executes the procedure, returns a struct of just the fields that you want, which will be the only fields that you read or "get" from the SqlDataReader.
You can use SQLCLR to create a stored procedure that executes the procedure to get a SqlDataReader, and instead of returning the SqlDataReader to SqlContext.Pipe.Send(), you would use SendResultsStart, SendResultsRow, and SendResultsEnd. You would create a SqlDataRecord of just the fields you wanted, and those would also be the only fields that you read or "get" from the SqlDataReader. While this still leaves you with a stored procedure, the filtering of the fields is done within the CLR-based proc so the output is guaranteed to be just the fields you want, regardless of how the result set structure of the base stored procedure changes. In this way you could create a local temp table to dump the results to, which would be better for JOINing to other tables. This method also allows for you to pass in a list of fields to the CLR-based stored procedure that would be parsed and used as the fields to dynamically construct the SqlDataRecord with as well as to dynamically determine which fields to get from the SqlDataReader. That would be a little more complicated but also quite a bit more flexible :).
You don't need to create a new stored procedure for this, you can integrate the stored proc call in a simple query using OpenQuery or use a temporary table.
Using OPENQUERY
SELECT Name,
Address
FROM OPENQUERY(ServerName, 'EXEC myBaseProcedure 19')
-- WHERE your_field = expected_value --> if you need to add filters
Using Temp table
Declare #MyTempTable Table (columns definitions)
Insert #MyTempTable Exec myBaseProcedure 19
Select Name,
Address
FROM #MyTempTable

Is there a way to pass temporary tables across the stored procedures

I have 4 stored procedures. I need to take the result of the first stored procedure (2 temp tables) and pass it into the second stored procedure. These temp tables need to be used in the from clause in the second stored procedure.
Similarity the third and fourth stored procedures need results from the previous stored procedures.
is there a way to pass temporary tables across the stored procedures?
Regarding this comment, "it was 1 Sp but we broke it into 4 so its easier to alter if needed", I suggest that you break it up even more. In other words, implement encapsulation.
Have a separate stored procedure for each time you want to select data from the actual tables. Do not populate temp tables in these procedures, just return the data.
Then write a stored procedure that creates and populates temp tables from the procs mentioned above, and does the necessary processing.
Here is a simple example:
create procedure GetData1
select Field1, Field2
from blah, blah, blah
create procedure AssembleAllData
create table #temp1 (Field1, Field2)
insert into #temp1
exec GetData1
select Field1, Field2, etc
from #temp1 join anActualTable etc
drop table #temp1
In your current SP1, you can create temporary table pass the name to the second stored procedure like below
SP1 code
IF OBJECT_ID('tempdb.dbo.#TempTable1') IS NOT NULL
DROP TABLE #TempTable1
EXEC SP2 N'#TempTable1'
Inside the SP2 you can insert the values into #TempTable1 which will be available to the calling SP
SP2 code
CREATE procedure [dbo].[SP2]
#outTempTable NVARCHAR(128)
AS
IF #outTempTable IS NOT NULL AND LEN(#outTempTable) > 0
BEGIN
EXEC ( 'INSERT INTO ' + #outTempTable + ' SELECT * FROM TableA' )
END
Your question sounds more like an answer than a question. Just do as you described.
You don't need to pass the data in the temp tables from one procedure to the next. The data is just there. In one procedure you write to the temp table and in the next procedure you read from the temp table.
I would also not create temp tables dynamically, just create them and let them wait for data. This assumes that the temp table data is local to a session (in oracle this is the case and in a way the reason why temp tables exist).
Also I would opt against passing table names between procedures. There is almost always a better way and it is a no-no anyways. If you are under the impression that you need variable temp table names, then you really want to add another column to the temp tables (you may even call it "temp_table_name", though it almost certainly means something different). Then you can pass the "temp_table_name" around and the selects would need a where temp_table_name = ... and the inserts would have to populate this extra column.

Catch/Work with/Handle multiple datasets in a Stored Procedure from another Stored Procedure

Is it possible to work with the returned datasets from a stored procedure? Basically I have a stored procedure (lets call it SP_1) and it calls another stored procedure (lets call it SP_2). SP_2 has 5 or so select statements. What I want to do is handle each select statement within SP_1. Basically to manipulate the data or whatever, but I do not know how to get it.
Let me show what im doing and that may make things clearer
CREATE PROCEDURE [dbo].[usp_1]
AS
exec usp_2
//How do I store the multiple select statements results in this stored proc?
In order to work, all the SELECTs within SP_2 will need to return the same number of compatible columns. If one returns 2 columns, another returns 5, and another returns 10, then it won't work.
If each SELECT does return the same number of columns, and the datatypes are consistent then you should be good to go using this approach in SP_1
CREATE TABLE #test (Col1 VARCHAR(10), Col2 VARCHAR(10))
INSERT #test
EXECUTE SP2 -- all resultsets return 2 VARCHAR columns
-- Now use #test which should contain all the combined results from SP2
However, if they all return different columns then you can't do it. You'd need to break each individual select into it's own sproc and call each one independently. SP2 would change to call those sub sprocs too.

Stored Procedure returning Multiple resultset

One Stored procedure returning multiple result sets and I need only the last result set, How do I achieve this without changing original procedure. am using the last reulst set in further processing in other Stored procedure.
if you are "filling" a dataset in c#, very simple, just use:
datasetobj.Tables[datasetobj.Tables.Count-1].Table
to get the DataTable
if doing this within sql procedures (i.e. one procedure calling another that returns multiple), best solution would be to use output variables. concept:
procedure1 returns multiple resultsets
when calling:
declare #table1 table (), #table2 table ()
exec procedure1 out #table1, out #table2