【问题标题】:select data from #Temp table after #temp table create in another query in asp.net c#在asp.net c#的另一个查询中创建#temp表后从#Temp表中选择数据
【发布时间】:2018-08-27 08:57:10
【问题描述】:

首先,我首先执行使用数据创建#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();

【问题讨论】:

标签: c# asp.net sql-server ado.net


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    Local and global temporary tables in SQL Server

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 2012-03-26
      相关资源
      最近更新 更多