select 来自#Temp table 的数据在#temp table 之后在 asp.net c# 中的另一个查询中创建

select data from #Temp table after #temp table create in another query in asp.net c#

首先,我执行创建#temp table 的过程,首先使用数据,然后在我想要#temp 之后使用连接将某些列与其他table 列。 第一个查询在第二个查询错误发生后执行(#temp 对象无效)

       if (con.State == ConnectionState.Closed)
        { con.Open(); }

        IsInTransaction = true;
        trans = con.BeginTransaction();


        da = new SqlDataAdapter("Execute SP_Statement_Temp", con);
        da.SelectCommand.Transaction = trans;
        DataTable DatTemp = new DataTable();
        da.Fill(DatTemp);
       SelectString = "Select Distinct #temp.IdentityID, TblMasterTypeOfIdentity.TypeOfIdentity,TblIdentity.IdentityName, '' As 'Opening Balance' , '' As 'Closing Balance'  from #temp inner join TblIdentity on TblIdentity.IdentityID=#temp.IdentityID inner join TblMasterTypeOfIdentity on TblMasterTypeOfIdentity.TypeOfIdentityID=#temp.TypeOfIdentityID";    
        CmdString = SelectString + " " + WhereString + " " + OrderBy;

        da = new SqlDataAdapter(CmdString, con);
        da.SelectCommand.Transaction = trans;
        DataTable datDetail = new DataTable();


        da.Fill(datDetail);
        trans.Commit();
        IsInTransaction = false;
        con.Close();

那是因为 #temp table 在创建 SP 后立即被删除。

A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process that called the stored procedure that created the table.

https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql

如果要创建临时 table 可以跨连接使用,则可以使用双哈希 (##) 而不是单哈希 (#)。这将创建一个全局临时变量,而不是局部临时变量。因此,如果您更改 Execute SP_Statement_Temp 中的 SQL 以创建一个名为 ##temp 而不是 #temp 的临时变量,您应该能够在 SQL 中使用它.

之前有人问过这个问题,例如

Local and global temporary tables in SQL Server