繁体   English   中英

在ASP.NET C中的另一个查询中创建#temp表之后,从#Temp表中选择数据

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

首先,我首先执行创建带有数据的#temp表的过程,然后我要#temp与其他表列使用联接的某些列。 在第二次查询发生错误(#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表在创建SP后立即被删除。

存储过程完成后,将自动删除在存储过程中创建的本地临时表。 该表可以由创建表的存储过程执行的任何嵌套存储过程引用。 调用创建表的存储过程的进程无法引用该表。

https://docs.microsoft.com/zh-cn/sql/t-sql/statements/create-table-transact-sql

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

这已经被问过了,参见例如

SQL Server中的本地和全局临时表

暂无
暂无

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

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