简体   繁体   English

存储过程中的临时表

[英]Temporary table in stored procedure

I have a stored procedure that executes variously dynamic sql statements. 我有一个执行各种动态sql语句的存储过程。 In reality this Stored procedure will be fired from SSIS with various parameters. 实际上,将使用各种参数从SSIS触发此存储过程。 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. 我使用Select .. into语句手动创建表,并将它们放在最后。

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.. 在并行执行期间,由于执行2试图创建或使用与执行1相同的临时表,因此该过程最终会出错。

I tried to resolve this using table variables. 我试图使用表变量来解决这个问题。 However this does not work in dynamic SQL. 但是,这在动态SQL中不起作用。 ( How to use table variable in a dynamic sql statement? ) 如何在动态SQL语句中使用表变量?

I tried to resolve this using local temp table. 我尝试使用本地临时表解决此问题。 However SSIS and Stored Procedures using local temp tables is not a great marriage. 但是,使用本地临时表的SSIS和存储过程并不是很好的结合。 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 到目前为止,我还没有找到一个好的工作解决方案。.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. 我有一个关于如何使用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. 但是,这确实会使我的动态SQL代码难以维护。

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), ....... ) 创建表#tmp_execute(id int,名称varchar(50),.......)

then, execute the dynamic query 然后,执行动态查询

insert into #tmp_execute select .... from tbl_Sample 从tbl_Sample插入#tmp_execute select ....

If you are require to execute the dynamic columns, you can use ' alter table #tmp_execute add your_column int' with conditional statement. 如果需要执行动态列,则可以在条件语句中使用'alter table #tmp_execute add your_column int'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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