2016-09-02 36 views
1

我有一個Excel工作簿與下面的代碼 -插入新記錄只到SQL表使用VBA

Sub Button1_Click() 
    Dim conn As New ADODB.Connection 
    Dim iRowNo As Integer 
    Dim sFirstName, sLastName As String 

    With Sheets("Sheet1") 

     'Open a connection to SQL Server 
     conn.Open "Provider=SQLOLEDB;" & _ 
      "Data Source=server1;" & _ 
      "Initial Catalog=table1;" & _ 
      "User ID=user1; Password=pass1" 

     'Skip the header row 
     iRowNo = 2 

     'Loop until empty cell in CustomerId 
     Do Until .Cells(iRowNo, 1) = "" 
      sFirstName = .Cells(iRowNo, 1) 
      sLastName = .Cells(iRowNo, 2) 

      'Generate and execute sql statement 
      ' to import the excel rows to SQL Server table 
      conn.Execute "Insert into dbo.Customers (FirstName, LastName) " & _ 
         "values ('" & sFirstName & "', '" & sLastName & "')" 

      iRowNo = iRowNo + 1 
     Loop 

     MsgBox "Customers imported." 

     conn.Close 
     Set conn = Nothing 

    End With 

End Sub 

這打開了我的數據庫的連接,從規定的列輸入值。

主鍵是數據庫上的增量鍵。問題是它會複製所有值。

我想將新的數據行添加到Excel工作表中,並只插入那些不存在的行。

我試過不同的方法('合併','如果存在',如果不存在'等),但我不能正確的。

該解決方案必須通過VBA。使用SSMS建立鏈接不是一種選擇。

我明白,它可能會使用臨時表,然後觸發執行合併的過程,但我想看看作爲最後的手段。還沒有讀過它(使我通過我的MS SQL聖經書的方式),但我希望它不是必要的。

---從@卡納安的回答更新---

VBA的新的部分 -

conn.Execute "IF EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" &  sFirstName & "' and LastName = '" & sLastName & "') " & _ 
      "THEN UPDATE dbo.customers SET WHERE Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' " & _ 
      "ELSE INSERT INTO dbo.Customers (FirstName, LastName) " & _ 
      "VALUES ('" & sFirstName & "', '" & sLastName & "')" 

這將返回錯誤「不正確的語法關鍵字接近 '那麼'。

回答

4

SQL查詢是不完全正確 - SQL IF中沒有THEN

此外,如果它確實存在,則不需要執行任何操作,因此只要不存在即可使用。

"IF NOT EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _ 
     "INSERT INTO dbo.Customers (FirstName, LastName) " & _ 
     "VALUES ('" & sFirstName & "', '" & sLastName & "')" 
+0

這就是現貨。 Thankyou BeanFrog。我之前曾試過IF NOT EXISTS,但我顯然沒有把它做對。我當然沒有使用'選擇1'部分。你能告訴我SELECT 1是如何工作的嗎? – Jamsandwich

+0

這只是一個常規選擇語句,但不是任何列,而是選擇數字1。所有這一切都是爲了防止獲取所有列詳細信息的開銷,當您需要知道的只是'此行是否存在'而不是'此行中的內容'。 – BeanFrog

+0

太棒了。再次感謝。一旦最終開始專門研究SQL,這將很好地幫助我。 – Jamsandwich

0

可以使用SQL查詢這樣的:

IF Exists (Select 1 from dbo.customers where Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' THEN Update dbo.customers set --other columns where Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' 
ELSE Insert into dbo.Customers (FirstName, LastName) " & _ 
        "values ('" & sFirstName & "', '" & sLastName & "')" 

不知道的語法Excel和C#中,你可以糾正類似這樣的查詢

+0

hi @Kannan,我已將此添加到我的代碼並更新了我的問題。你知道我爲什麼會得到我提到的錯誤嗎?看起來你錯過了第一行的右括號。我想我把它加在正確的地方。 – Jamsandwich

+0

另外,我不太清楚如何輸入set命令。我假設「 - 其他列」是評論部分?所以我把它拿出來了。 – Jamsandwich

1

這應該爲你做。

Sub Button_Click() 
'TRUSTED CONNECTION 
    On Error GoTo errH 

    Dim con As New ADODB.Connection 
    Dim rs As New ADODB.Recordset 
    Dim strPath As String 
    Dim intImportRow As Integer 
    Dim strFirstName, strLastName As String 

    Dim server, username, password, table, database As String 


    With Sheets("Sheet1") 

      server = .TextBox1.Text 
      table = .TextBox4.Text 
      database = .TextBox5.Text 


      If con.State <> 1 Then 

       con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;" 
       'con.Open 

      End If 
      'this is the TRUSTED connection string 

      Set rs.ActiveConnection = con 

      'delete all records first if checkbox checked 
      If .CheckBox1 Then 
       con.Execute "delete from tbl_demo" 
      End If 

      'set first row with records to import 
      'you could also just loop thru a range if you want. 
      intImportRow = 10 

      Do Until .Cells(intImportRow, 1) = "" 
       strFirstName = .Cells(intImportRow, 1) 
       strLastName = .Cells(intImportRow, 2) 

       'insert row into database 
       con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')" 

       intImportRow = intImportRow + 1 
      Loop 

      MsgBox "Done importing", vbInformation 

      con.Close 
      Set con = Nothing 

    End With 

Exit Sub 

errH: 
    MsgBox Err.Description 
End Sub 

添加一個參考: Microsoft ActiveX數據對象2.8庫

僅供參考,我的表如下。

enter image description here