多线程中的临时表

发布于 2024-10-08 02:33:47 字数 193 浏览 0 评论 0原文

我有一个多线程应用程序。

每个线程执行存储过程,我在其中创建本地临时表。 临时表的名称相同:#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

执妄 2024-10-15 02:33:47

您需要确保每个线程都在与连接池不同的连接中运行(因此它位于不同的会话中)。

临时表仅在其自己的会话中可见。

来自 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:

Local temporary tables are visible only in the current session

〃安静 2024-10-15 02:33:47

只要多个线程使用单独的连接(我真的希望它们是这样,否则多线程可能没有任何好处,或者代码中隐藏着大量的竞争条件),它们都应该有自己的临时表副本。你不应该做任何其他事情。

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.

寂寞笑我太脆弱 2024-10-15 02:33:47

#TempTable 临时表 应该仅对当前 SQL Server 会话/连接可用,因此如果您希望每个进程都有一个单独的#TempTable,只需为每个进程使用单独的连接即可。
如果这不可行,您可以使用表变量,它在某种程度上是常规表和变量之间的交叉 - 像这样:

DECLARE @TableVar TABLE (
  IDColumn int,
  NameColumn varchar(max))

INSERT INTO @TableVar (IDColumn, NameColumn)
SELECT  ID, Name
FROM    RealTable
WHERE   .....

但是,如果您希望所有进程都使用同一个表,只需用双散列命名它(# #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:

DECLARE @TableVar TABLE (
  IDColumn int,
  NameColumn varchar(max))

INSERT INTO @TableVar (IDColumn, NameColumn)
SELECT  ID, Name
FROM    RealTable
WHERE   .....

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文