简体   繁体   中英

Temporary table in stored procedure

I have a stored procedure that executes variously dynamic sql statements. In reality this Stored procedure will be fired from SSIS with various parameters. So there will be a lot of parallel executions.

This stored procedure uses temp tables during execution. I create the tables manually with a Select .. into statement and drop them at the end.

During parallel executions, the process ends up in error because of execution 2 is trying to create or use the same temp table as execution 1. This is giving errors..

I tried to resolve this using table variables. However this does not work in dynamic SQL. ( How to use table variable in a dynamic sql statement? )

I tried to resolve this using local temp table. However SSIS and Stored Procedures using local temp tables is not a great marriage. I have never found a good working solution so far.. http://consultingblogs.emc.com/jamiethomson/archive/2006/12/20/SSIS_3A00_-Using-stored-procedures-inside-an-OLE-DB-Source-component.aspx

I have an idea of how to create a temp table with the name of a GUID. And then use this so that it is unique in the Stored Procedure execution. However this would really make my dynamic SQL code much more difficult to maintain.

Does anyone see other options or am I over-complicating things? Is there a more viable solution?

You can create the temp table as

Create table #tmp_execute ( id int, name varchar(50), ....... )

then, execute the dynamic query

insert into #tmp_execute select .... from tbl_Sample

If you are require to execute the dynamic columns, you can use ' alter table #tmp_execute add your_column int' with conditional statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM