Reduce duplication of creation of SQL temp tables - sql

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

Related

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.

How to fill a temp table from stored procedure without knowing it's schema in SQL Server

I have a question here regarding filling temp table from stored procedures in SQL Server.
When we already have table schema of a table we can fill it from stored procedure as:
Create #tempTable (Id int, Value varchar(50))
Insert into #tempTable
exec GetValues
Where GetValues returns the same schema as declared for #tempTable.
Here is another case when we fill a temp table from another table
Select colA,colB into #tempTableA from SomeTable
Here we don't need to know the schema of #tempTableA, it will be same as based on selected columns from table SomeTable.
My question is: how can we fill a #temptable without knowing it's schema, from a stored procedure? As we do when filling a temp table from some other table.
SELECT * INTO #tmpTable FROM OPENQUERY(YOURSERVERNAME, 'EXEC test.dbo.prc_test 1');
Insert results of a stored procedure into a temporary table

stored procedures and temp tables

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.

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

Can I have index created on temp tables (#temp) which are created dynamically in a stored procedure?

I am creating temp tables (#temp_table) in my stored procedure. It is a huge table with large data. Then I am creating a index in the storeed procedure as it is required for faster query to the temp table. But when I execute the stored procedure, the index is not used. The index is not being created when the stored procedure is executed.
Pseudo code
CREATE PROC abcdefg
AS
...
SELECT col_a, col_b, col_c....
INTO #temp_table
FROM .....
WHERE ....
...
CREATE INDEX abc_idx ON #temp_table (col_a)
...
SELECT col_a FROM #temp_table WITH (INDEX (abc_idx))
...
GO
When I try to execute the stored proc, it is not recognizing the index. How can I fix this problem?
This usually happens because the access plans for the temp tables have been generated before the indexes ever existed.
Fortunately, you can use table-level constraints to get around this problem. Since the indexes to support UNIQUE and PRIMARY KEY constraints are defined at the same time as the temp table, the optimizer will always be able to use these indexes.
Reference: Optimizing Performance / Indexes on Temp Tables
I tried the code you suggested using Sql Server 2005
ALTER PROCEDURE Test
AS
BEGIN
CREATE TABLE #Test (
ID INT,
Code VARCHAR(20)
)
CREATE INDEX test_ind ON #Test (Code)
INSERT INTO #Test (ID,Code) SELECT ID, Code FROM MyTable
SELECT Code
FROM #Test WITH(INDEX(test_ind))
DROP TABLE #Test
END
When running the
EXEC Test
Command with Include Actual Execution Plan, it does show that the index was used.