多线程中的临时表
我有一个多线程应用程序。
每个线程执行存储过程,我在其中创建本地临时表。 临时表的名称相同:#TempTable
当线程操作此#TempTable
时,线程之间发生冲突,
如何制作#TempTable
code> 对于每个具有相同名称的线程?
I have a multithread application.
Each thread executes store procedures in which I create a local temporary table.
The name of the temporary table is the same : #TempTable
I have a conflict between thread when they manipulate this #TempTable
How can I make a #TempTable
for each thread with the same name ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要确保每个线程都在与连接池不同的连接中运行(因此它位于不同的会话中)。
临时表仅在其自己的会话中可见。
来自 MSDN:
You need to ensure each thread is running in a different connection from the connectio npool (so it is in a different session).
Temp tables are only visible in their own session.
From MSDN:
只要多个线程使用单独的连接(我真的希望它们是这样,否则多线程可能没有任何好处,或者代码中隐藏着大量的竞争条件),它们都应该有自己的临时表副本。你不应该做任何其他事情。
So long as the multiple threads are using separate connections (which I really hope they are, otherwise there's probably no benefit to multithreading, or you have a massive race condition hiding in your code), they should all have their own copies of the temp table. You shouldn't have to do anything else.
#TempTable 临时表 应该仅对当前 SQL Server 会话/连接可用,因此如果您希望每个进程都有一个单独的#TempTable,只需为每个进程使用单独的连接即可。
如果这不可行,您可以使用表变量,它在某种程度上是常规表和变量之间的交叉 - 像这样:
但是,如果您希望所有进程都使用同一个表,只需用双散列命名它(# #TempTable),然后它就可以全局访问。
The #TempTable temporary table should only be available to the current SQL server session/connection, so if you want each process to have a separate #TempTable, just use separate connections for each.
If that is not feasible, you can use table variables, which are somewhat of a cross between regular tables and variables - like this:
If however, you want all processes to use the one and same table, just name it with double hash (##TempTable) and then it will be accessible globally.