2013-12-12 60 views
1

我試圖通過具有多個插入語句的SQL文件循環。我想檢查每個單獨的語句,因爲有可能有重複的主鍵。以編程方式使用C#完成此任務的最佳方式是什麼?使用C遍歷多個SQL插入語句循環使用#

對於重複項,我需要跳過該查詢並將密鑰(代碼)添加到Excel文件中。 SQL查詢的

例子:

INSERT [dbo].[JuryInstructions] ([Code], [Description], [InstructionText], [EnterUserID], [EnterDate], [UpdateUserID], [UpdateDate], [Type], [InstructionNumber]) VALUES (N'1000A', N'GENERAL INSTRUCTIONS', N'', N'I', NULL) 
INSERT [dbo].[JuryInstructions] ([Code], [Description], [InstructionText], [Type], [InstructionNumber]) VALUES (N'1001', N'Introduction', N'', N'I', NULL) 
+0

因此您試圖讀取包含SQL語句而不僅僅是數據元素的文本文件?我的理解是否正確? –

+2

我們需要一個文件內容的樣本 –

+0

我給出了一個sql語句形式的查詢語句(Washington_Insert_Statements.sql)。 – Katherine

回答

1

好的。我迅速將一塊簡單的代碼黑入其中,這些代碼應該爲您提供構建解決方案的基礎。有更高級的方法來做到這一點,但我儘可能保持簡單。你應該可以通過一點工作來構建一個你想要的解決方案。如果有什麼不清楚的地方,請隨時問我。

 //open the text file for reading 
     using (TextReader tr = new StreamReader("Filepath")) 
     { 
      try 
      { 
       // read line from text file 
       string query = tr.ReadLine(); 
       // split the string on the commas to make it easier to find the key value 
       string[] queryArray = query.Split(','); 
       int beginingOfKeyIndex = queryArray[8].IndexOf('\'') + 1; // add one because we don't want the ' 
       // get the key value from the correct array element 
       string keyValue = queryArray[8].Substring(beginingOfKeyIndex, queryArray.Length - beginingOfKeyIndex); 
      } 
      catch (IOException) 
      { 
       // we get here when it tries to read beyond end of file or there is some other issue. 
       throw; 
      } 
     } 
0

我沒有時間來寫的正則表達式解析出關鍵字段(也就是不知道你的樣品SQL是關鍵字段,字段)。

下面是一些代碼,讓你開始:

 try 
     { 
      Hashtable htKeys = new Hashtable(); 
      List<string> sqlToExecute = new List<string>();   

      IEnumerable<string> lines = File.ReadLines("path-to-your-file.sql"); 
      foreach (string line in lines) 
      { 
       // parse out key field here 
       string keyfield = RegExToFindYourValue(line); 

       if (!htKeys.ContainsKey(keyfield)) 
       { 
        sqlToExecute.Add(line);    
        htKeys.Add(keyfield, line); 
       } 
       else 
       { 
        // duplicate key, handle here. 
       } 
      } 

     } 
     catch (Exception e) 
     { 
      Console.WriteLine("The file could not be read:"); 
      Console.WriteLine(e.Message); 
     } 
1

到目前爲止,最簡單的方法就是打擊你的數據庫服務器單獨運行的每個插入語句。如果有關主鍵違規的錯誤返回,則將該特定行存儲在日誌文件中。

+0

我將需要爲多個服務器執行此操作,並且大約有一千個查詢語句,因此不起作用。 – Katherine

+0

一千個查詢語句真的沒有那麼多.. – NotMe

+0

在多臺服務器上,這是很多我沒有的時間。另外,如果我可以通過編程的方式來完成,我可以在其他項目中使用它。 – Katherine