2014-12-29 36 views
1

我想問一下使用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 

是否有任何方法來維護我的臨時表基於這個序列。

+0

取而代之的是臨時​​表,您可以創建一個實際的表,你再落? SQL服務器臨時表是會話範圍(http://stackoverflow.com/questions/892351/sql-server-2005-and-temporary-table-scope),我不確定VB.net會話如何處理會話;你取決於那些不應該如此工作的東西。 –

+0

由於各列不同,因此無法創建實際表格。這意味着,每當我完成創建時,我都需要刪除此臨時表。 – Musikero31

+1

臨時表的作用域僅爲創建它的當前會話,如果您的代碼正在與數據庫建立兩個單獨的連接,則在一個會話中創建的臨時表將不會在其他會話中可見。爲了迴應你的陳述「每次完成時我都需要刪除這張臨時表」,最好的做法是當你完成它們時,你還要刪除臨時表,因爲它們將存在於tempdb中,即使它們已經消失超出範圍,只有當sql服務器需要該臨時表所佔用的空間時,纔會放棄它們。 –

回答

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