stored procedures and temp tables - sql

I have to create a 10 stored procedure as follows:
In stored procedure # 1 I create temp table 1 and this temp table is used in stored procedure 2 to create another temp table and this new tem table is used in another STORED PROCEDURE and so on.
I am not sure how to create these stored procedure, because for these stored procedure I need to have temporary tables present in temdb.
Any help

Can you user Global Temporary Tables?
SELECT * INTO ##Users FROM UserTable
The Global temp tables will remain in tempdb until deleted and can be used across different stored procs.

Assuming you want to name the table (or some of its columns) that's about to be created based on the data present in the temp table, you might want to resort to dynamic SQL, since you can't use variables like this:
declare #foo varchar(50)
select #foo = tableName from #tempTable
create table #foo (fooColumn int)
But before you even think of using dynamic SQL, you've got to ask yourself whether you really need this solution.

Related

Reduce duplication of creation of SQL temp tables

I have multiple (more than 12) SQL Stored Procedures that setup the same set of temp tables at the start of each procedure. When one of these tables needs modified I need to go make a change in each of those Stored Procedures to match. The temp tables are expected to exist by other stored procedures later in the process. I have no ability to change the process or the flow of these stored procedures or the fact of using these as temp tables, I am coming at it from a DRY approach and looking for a way to consolidate the creation of these shared temp tables into a reusable piece of code so that when changes are needed I can do it in 1 file and reduce the amount of duplication happening today.
Example of the stored procedure
CREATE OR ALTER PROCEDURE [dbo].[procedureName]
#inputs ...
AS
BEGIN
DROP TABLE IF EXISTS #Table1
CREATE TABLE #Table1 (...)
DROP TABLE IF EXISTS #Table2
CREATE TABLE #Table2 (...)
...
DROP TABLE IF EXISTS #Table10
CREATE TABLE #Table10 (...)
...
INSERT INTO #Table5
SELECT * FROM data
...
END

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.

Stored Procedure - Outputing a temp table

I have a stored procedure that creates multiple temp tables and uses them to output a variable. I want to test the data inside of my temp tables before moving forward. Is there a way to view my temp tables or at least output them from the stored procedure so that I can use them somewhere else?
Currently I have:
CREATE PROCEDURE Top10_SP_getMeasure007
(
in :division char(2),
in :startdate date,
in :enddate date,
out :QualifyingModels int
);
I was thinking the out variable could be the temp table.
According to documentation, temp tables within Stored Procedures are only accessible outside the stored procedure if the temp table is a Global Temp Table.
You cannot pass the temp table as an OUT parameter. You might be able to print (display) the data in your temp table within the procedure but that would take more effort.
My suggestion would be to pull the temp table portion out of the procedure and run it in the PCC.

SQL - Need to run stored proc with ~100 different params, what's the best way to do this?

Assuming I have a table with one field called ID that stores 100 different integer values. I can select all of these rows simply by doing select id from example_table
I then have a stored procedure that I need to execute for each of these id's (as the sole parameter) and then select specific columns from (the stored procedure returns more data then I need). Besides executing the stored procedure 100 separate times into a temporary table and then selecting data from this table - how else could I do this?
You can pass table parameter to the procedure.
Check http://www.techrepublic.com/blog/datacenter/passing-table-valued-parameters-in-sql-server-2008/168
Update
CREATE TYPE LIST_OF_ID TABLE (ID INT);
go
CREATE PROCEDURE PROC1(#ids LIST_OF_ID READONLY)
....

Using Stored Procedure into Select (T-SQL)

I need to access the result of a stored procedure within a select statement, i.e.:
SELECT * FROM [dbo].[sp_sample]
in SQL_Server 2005.
This isn't possible. You would have to create a temporary table to store the results.
Create Table #tmp
(
...
)
Insert into #tmp
Exec dbo.StoredProcedure
The table structure must match the output of the Stored Procedure.
#Barry is right you need to create a temp table and insert into it first, then join that table in your select.
However, there are numerous ways for sharing data between stored procedures, see this excellent article: How to Share Data Between Stored Procedures by Erland Sommarskog
One method that may work for you is to "share" a temp table. The #temp table is created in the Parent procedure and can be used by the Child: http://www.sommarskog.se/share_data.html#temptables