2016-11-10 61 views
0

我在循環遍歷包含TRelationCode的表的代碼時遇到了問題。當它找到它時,必須從它獲取RelationCode,然後將其轉換爲新的RelationCode並將其更新爲新的。循環訪問表並查詢每個有TRelationcode的文件

要創建新的RelationCode,我創建了一個叫做MakeRelationCode(OldRelation)的函數。我有這個代碼循環表:

但現在我需要更新舊代碼到新的。

回答

1

我更喜歡簡單的SQL命令和一點vb邏輯,因此我跳過了SqlDataAdapter部分。這隻會降低性能,並且只有在網格中顯示某些內容並希望雙向綁定時才需要。

以下代碼未經測試並輸入盲,請檢查輸入錯誤等。 我將所有內容都放在一個方法中。

Dim tableNames As New List(Of String) 
'Key: Old code, Value: New code' 
Dim trelationcodes As New Dictionary(Of String, String) 

Using conn As New SqlClient.SqlConnection("YourConnectionString") 'Change connection string to your needs' 
    Dim qTableNames = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.columns WHERE COLUMN_NAME = 'TRelationcode'" 
    conn.Open() 

    'Get table names with TRelationcode column' 
    Using commTableNames As New SqlClient.SqlCommand(qTableNames, conn) 
     Dim dataReader = commTableNames.ExecuteReader() 
     While dataReader.Read() 
      tableNames.Add(dataReader.GetString(0)) 
     End While 
    End Using 

    'Select all distinct old TRelationcode which will be updated' 
    Dim qTrelationcodesOld = "SELECT DISTINCT TRelationcode FROM {0}" 
    For Each tableName In tableNames 
     'Get all old TRelationcodes from table found previuosly' 
     Using commTrelationcodesOld As New SqlClient.SqlCommand() 
      commTrelationcodesOld.Connection = conn 
      commTrelationcodesOld.CommandText = String.Format(qTrelationcodesOld, tableName) 
      Dim dataReader = commTrelationcodesOld.ExecuteReader() 
      While dataReader.Read() 
       Dim code = dataReader.GetString(0) 
       If Not trelationcodes.ContainsKey(code) Then 
        trelationcodes.Add(code, "") 'Value will be set later' 
       End If 
      End While 
     End Using 

     'Get new TRelationcodes' 
     For Each tRelCodeOld In trelationcodes.Keys 
      trelationcodes(tRelCodeOld) = MakeRelationCode(tRelCodeOld) 
     Next 

     'Set new TRelationcodes' 
     Dim uTRelationcode = "UPDATE {0} SET TRelationcode = @newCode WHERE TRelationcode = @oldCode" 
     For Each tRelCodes In trelationcodes 
      Using commTrelationcodesNew As New SqlClient.SqlCommand() 
       commTrelationcodesNew.Connection = conn 
       commTrelationcodesNew.CommandText = String.Format(uTRelationcode, tableName) 
       commTrelationcodesNew.Parameters.Add("@oldCode", SqlDbType.VarChar).Value = tRelCodes.Key 'Varchar correct?' 
       commTrelationcodesNew.Parameters.Add("@newCode", SqlDbType.VarChar).Value = tRelCodes.Value 'Varchar correct?' 
       commTrelationcodesNew.ExecuteNonQuery() 
      End Using 
     Next 
    Next 
End Using 

該代碼遠離最佳狀態,例如,我跳過了異常處理。
最關心的部分是你的MakeRelationCode函數。如果裏面的邏輯可以用存儲過程中的T-SQL編寫,那麼整體編碼也將被簡化。

+0

雖然性能不是問題,否則我不會像這樣構建它。因爲它是一次性的東西:) –

+0

如果它是一次性的事情,你應該在T-SQL中做。這很容易。但是你可以試試我的代碼:) –

相關問題