2012-10-30 60 views
2

我寫了一個C#代碼轉移使用SMO兩個遠程服務器之間的表在目標服務器已經存在,我想知道的是,反正是有檢查表中已經存在具有確切架構,列名稱,數據類型,約束和一切的目標服務器。然後,我不必每次都刪除現有的表並創建新的表。C#SMO-檢查,如果該表在

+0

我有一個類似的問題比較簡單的方法: http://stackoverflow.com/a/25273567/2188550 – Ivanzinho

回答

1

嘗試這一塊代碼段:

Server srv1 = new Server("<server_location>"); 
srv1.ConnectionContext.LoginSecure = false; 
srv1.ConnectionContext.Login = "<username>"; 
srv1.ConnectionContext.Password = "<password>"; 
srv1.ConnectionContext.Connect(); 
Database sourceDb = srv1.Databases["<database_name>"]; 
Table sourceTbl = sourceDb.Tables["<table_name>"]; 

Server srv2 = new Server("<server_location>"); 
srv2.ConnectionContext.LoginSecure = false; 
srv2.ConnectionContext.Login = "<username>"; 
srv2.ConnectionContext.Password = "<password>"; 
srv2.ConnectionContext.Connect(); 
Database destinationDb = srv1.Databases["<database name>"]; 
Table destinationTbl = sourceDb.Tables["<table_name>"]; 

var isMatched = CompareTables(sourceTbl, destinationTbl);  

比較方法:

bool CompareTables(Table source, Table destination) 
{ 
    // Column count doesn't match 
    if (!source.Columns.Count.Equals(destination.Columns.Count)) 
     return false; 

    // Assuming the order of the Columns are same in both the Tables 
    for (int i = 0; i < source.Columns.Count; i++) 
     if (!source.Columns[i].Equals(destination.Columns[i])) 
      return false; 

    // Constraints count doesn't match 
    if (!source.Checks.Count.Equals(destination.Checks.Count)) 
     return false; 

    // Assuming the order of the Contraints are same in both the Tables 
    for (int i = 0; i < source.Checks.Count; i++) 
     if (!source.Checks[i].Equals(destination.Checks[i])) 
      return false; 

    return true; 
} 
+0

這不會檢查是否存在相同名稱和模式的表。我想要列,數據類型和約束 – Ejaz

+0

仍然沒有幫助我的約束 – Ejaz

+0

現在檢查我的答案。我現在已經在我身邊測試了這段代碼。乾杯! –