临时表的寿命

时间:2014-12-29 01:48:16

标签: sql-server vb.net temp-tables

我想问一下使用Windows应用程序创建的临时表的生命周期是什么?我打算隔离临时表的创建。但在此代码段的某处,我无法获取我选择的表格。以下是要解释的代码段

Public Sub CreateTempTableWithData(ByVal tableName As String, ByVal connectionString As String, ByVal startDate As DateTime,
                                    ByVal endDate As DateTime, ByVal startSerialNo As String, ByVal endSerialNo As String,
                                    ByVal refTable As String, ByVal refKey As String, ByVal transferStatus As String)
    Dim dal As New DataTransferDal

    Dim tableSchemaList As New List(Of TableSchema)
    Dim sqlQuery As String
    Try
        ' 1. create temporary table
        sqlQuery = FormTempTable(tableName, connectionString, tableSchemaList)

        dal.ExecuteQuery(sqlQuery, connectionString)

        ' 2. populate temporary table
        sqlQuery = PopulateTempTable(tableName, refTable, startDate, endDate, startSerialNo, endSerialNo,
                                        refKey, tableSchemaList, transferStatus)
        ' Unable to retrieve my temp table
        dal.ExecuteQuery(sqlQuery, connectionString)     
    Catch dbEx As DbLoggingException
        ExceptionLogger.ErrorLogging(LoggingType.SQLException, dbEx)
    Catch ex As Exception
        ExceptionLogger.ErrorLogging(LoggingType.General, ex)
    End Try

End Sub

有没有办法根据这个顺序维护我的临时表。

1 个答案:

答案 0 :(得分:0)

临时表仅存在于创建的会话中。我在过去注意到ExecuteQuery调用往往在他们自己的会话中运行(尝试连续调用ExecuteQuery('SELECT @@SPID',connectionString))。该表可能仍在tempdb中,但其他会话不允许访问它。

对于您的情况,最好将创建和填充语句加入一个ExecuteQuery调用:

Try
    ' 1. create temporary table
    sqlQuery = FormTempTable(tableName, connectionString, tableSchemaList)

    ' 2. populate temporary table
    sqlQuery += ";" + PopulateTempTable(tableName, refTable, startDate, endDate, startSerialNo, endSerialNo,
                                    refKey, tableSchemaList, transferStatus)

    dal.ExecuteQuery(sqlQuery, connectionString)     
Catch dbEx As DbLoggingException
    ExceptionLogger.ErrorLogging(LoggingType.SQLException, dbEx)
Catch ex As Exception
    ExceptionLogger.ErrorLogging(LoggingType.General, ex)
End Try
相关问题