即使连接未关闭,Temp table 也不存在

Temp table does not exists even if connection is not closed

我有以下代码:

using (var connection = new SqlConnection(constr))
{
    connection.Open();

    var createTempTables = new SqlCommand("[dbo].[p_CreateTempTable]", connection)
    {
        CommandType = CommandType.StoredProcedure
    };

    createTempTables.Parameters.Add(new SqlParameter("@Id", 2));
    createTempTables.ExecuteNonQuery();

    var actualCommand = new SqlCommand("[dbo].[p_Test]", connection)
    {
        CommandType = CommandType.StoredProcedure
    };

    var dt = new DataTable();

    dt.Load(actualCommand.ExecuteReader());
}

基本上,[dbo].[p_CreateTempTable] 从 table 中选择与 ID 输入匹配的行作为参数。然后,[dbo].[p_Test] 只选择温度 table。据我了解,只要连接未关闭,temp table 就应该持续存在,但我总是收到一个异常,提示我的 temp table 不存在。为什么这不起作用?

注意:如果我改用在 C# 中创建临时文件 table 的文本命令,则程序运行时不会出现任何问题。然而,我想避免这样做,因为在创建临时文件时会有更多验证 table 并且由于应用程序是 WinForms,我想避免每次逻辑更改时都重新编译。

这里的基本问题是,在 SQL 服务器临时 table 中,生命周期绑定到创建它们的批处理和//或会话上下文。

这意味着,如果您在存储过程中创建一个临时 table,那么只有在该存储过程退出之前才能看到该临时 table(如此有效,只能由其他存储存储过程调用的过程)。这是因为存储过程本身是一个批处理上下文,所以如果它创建一个临时 table,那么它就会绑定到该存储过程的批处理上下文。

只有两种解决方法,但都不太方便:

  1. 使用直接命令(即不在存储过程中)在 session-level 处创建临时 tables,这意味着您必须包含命令在您的客户端代码(或配置设置)中。或者

  2. 改用全局温度 tables。全局 temp tables 并不真正像普通 temp tables 那样工作,它们将在批次和会话中持续存在,直到您明确删除它们,因此您可以在存储过程中创建它们并且它们将持续存在。但是,现在您必须担心与常规 table 相同的事情:如果 table 已经存在怎么办?如果不止一个用户同时运行这个存储过程怎么办?与常规 tables 相比的唯一优势是创建和删除它们需要较少的权限。