2014-10-17 80 views
4

有沒有辦法從C#「Microsoft SQL Exception」中獲取確切的「約束名稱」\「索引名稱」,錯誤編號爲2601或2627,但沒有解析文本「消息屬性」?如何從SQLException獲取確切的「約束名稱」

例如:

catch (SqlException e) 
{ 
    switch (e.Number) 
    { 
     case 2601: 
     /* Here i want to know the constraint name in case i have 
      more than one on a specific table, so i will be able to 
      display the correct error message to the user. 

      For example: 

      case IX_Username: 
      throw new Exception("Username duplication") 
      case IX_PhoneNumber: 
      throw new Exception("PhoneNumber duplication") 

     */ 
     break; 
     default: 
     throw; 
    } 
} 
+1

可悲得解析...... – 2014-10-17 12:13:29

+1

是沒可能執行一個查詢,以重複檢查,而不是訴諸違反約束? – user1620220 2014-10-17 12:35:25

+0

User1620220,它可能,但據我瞭解,由於「競爭條件」問題和偏好,在高數據庫負載情況下不會很好。 – Omtechguy 2014-10-17 12:41:17

回答

2

對約束使用命名約定這些名字總是包含下劃線像FK_XxxUQ_Xxx然後使用正則表達式來分析錯誤的名字,像這樣

var match = Regex.Matches("Foreign key FK_Xxx violation.", @"\b\w*_\w*\b") 
     .Cast<Match>().FirstOrDefault(); 
    return match != null ? match.Value : null; 
0

有沒有辦法得到確切的 「約束名」 \ 「目錄名稱」 從C# 「微軟SQL異常」,錯誤號2601或2627,但沒有 解析「消息屬性」的文本?

不,沒有這樣的方式。

+0

那麼你能否建議最好的方法來處理非常負載的數據庫,每秒有很多查詢的錯誤? Pleae take進入賬戶的「種族條件」問題。 – Omtechguy 2014-10-17 12:42:33