问题
I have managed to update an SQL table and record by using this SQL string
"UPDATE Breach_Test_Key SET [VAL_BREACH_REASON] = 'SOME BREACH REASON' WHERE [ID] = 1"
Two things I am trying to achieve and that is:
- Update two specific columns in the SQL Table, how do I define two columns in the SET?
- I also need to update all records that are in a table in Excel back into an SQL table (which will all exist in the SQL table).
The ID field will always match as the data is from this table.
Please could someone guide me through the SQL structure for this please?
Thank you @MatteoNNZ for help with part 1, this is the code I am now using to update multiple columns
uSQL = "UPDATE Breach_Test_Key SET [VAL_BREACH_REASON] = 'SOME BREACH REASON1',[VAL_BREACH_DETAIL] = 'SOME BREACH DETAIL1' WHERE [ID] = 1"
So for part two, I haven't actually got anything sufficient to post but where I have specified a value in the string I would rather it be dynamic to loop through the excel table/column. Any pointers?
回答1:
Ok so I got the results I wanted. The records are being updated as expected using a loop option in the vba. It may not be the prettiest way of doing what I was trying to achieve but it works.
If anyone would like to suggest improvements then I am all ears. But here is my final macro:
Private Sub UpdateTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim strWard As String
Dim strDate As Date
Dim strUser As String
'=====USER NAME VBA================
Set WSHnet = CreateObject("WScript.Network")
UserName = WSHnet.UserName
UserDomain = WSHnet.UserDomain
Set objUser = GetObject("WinNT://" & UserDomain & "/" & UserName & ",user")
UserFullName = objUser.FullName
'===================================
'strDate is a stamp of the date and time when the update button was pressed
strDate = Format(Now(), "dd/mm/yyyy hh:mm:ss")
'User is the username of the person logged into the PC the report is updated from
strUser = UserFullName
'Set Connection string
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=ServerName; " & _
"Initial Catalog=dbName;" & _
**USER DETAILS HERE**
'Connect and Run the SQL statement to update the reords.
cnn.Open cnnstr
Dim row As Range
For Each row In [tbl_data].Rows
uSQL = "UPDATE Breach_Test_Key SET [VAL_BREACH_REASON] = '" & (row.Columns(row.ListObject.ListColumns("VAL_BREACH_REASON").Index).Value) & _
"' ,[VAL_BREACH_DETAIL] = ' " & (row.Columns(row.ListObject.ListColumns("VAL_BREACH_DETAIL").Index).Value) & _
"' WHERE [ID] = '" & (row.Columns(row.ListObject.ListColumns("ID").Index).Value) & "'"
'Debug.Print uSQL
cnn.Execute uSQL
Next
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
来源:https://stackoverflow.com/questions/29299444/excel-vba-ado-update-sql-table-record