[英]How do you UPDATE SQL Table from Excel Table using VBA JOIN
我已通讀Stackoverflow 14814098 帖子,並想知道 (2) 件事。
您能否通過使用引用 Excel 表的更新語句創建字符串來從 Excel 更新 MS SQL 表。 下面是我的意思 VBA 中的粗略想法。
如果將 SQL 語句添加到服務器,如何使用 VBA 從 Excel 調用它?
背景:我正在嘗試從 MS SQL 服務器中提取一個表,將結果作為 Excel 表加載到 Excel 表中,我可以在其中退出表並更新所有更改回服務器表。
Sub UpdateSqlWithExcelTableJoin()
Dim cmd As ADODB.Command
Dim strSQL As String
Set cnn = New ADODB.Connection
cnn.ConnectionString = "DRIVER=SQL Server;SERVER=MYSERVERNAME;DATABASE=MYDATABASENAME;Trusted_Connection=Yes"
Set cmd = New ADODB.Command
cnn.Open
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdText
Call setString2
cmd.CommandText = strSQLUpdate
cmd.Execute
cnn.Close
Set cmd = Nothing
Set cnn = Nothing
End Sub
Sub setString2()
strSQLUpdate = _
"Update test.profile " & vbNewLine & _
"Set test.profile.Field = ExcelTable.Field " & vbNewLine & _
" test.profile.Profile_Name = ExcelTable.Profile_Name " & vbNewLine & _
"From test.profile " & vbNewLine & _
"INNER JOIN OPENROWSET('MICROSOFT.JET.OLEDB.4.0', 'Excel 8.0;Database=C:\Users\USERNAME\ONEDRIVE - FOLDER\SQL_VBA_b.xlsm;', 'Select ID, Profile_Name' " & vbNewLine & _
"From '[Sheet3$]') As ExcelTable " & vbNewLine & _
"ON test.profile.ID = ExcelTable.ID " & vbNewLine & _
"WHERE (test.profile.ID = ExcelTable.ID " & vbNewLine & _
" AND test.profile.Profile_Name = ExcelTable.Profile_Name)"
Debug.Print strSQLUpdate
End Sub
我總是發現通過 MS-Access 連接運行它比直接連接到 SQL 服務器更容易。
Update
SQLServerTable Set
SQLServerColumn =
ExcelColumn From
SQLServerTable S
Inner Join
ExcelTable E
Where
sqlServerkey =
ExcelKey這比直接嘗試更靈活,因為如果更新關系變得更復雜,您始終可以將 FROM 子句編碼為 Access 保存的查詢,這是在 ODBC 中進行嵌套查詢的唯一好方法(使用其他查詢的查詢從)。
您不能在 position 處使用 select 它總是會占用整張紙。
此外,您在 Field 之后缺少逗號
Update test.profile
Set test.profile.Field = ExcelTable.Field,
test.profile.Profile_Name = ExcelTable.Profile_Name
From test.profile
INNER JOIN OPENROWSET('MICROSOFT.JET.OLEDB.4.0', 'Excel 8.0;Database=C:\Users\USERNAME\ONEDRIVE - FOLDER\SQL_VBA_b.xlsm;', [Sheet3$]) As ExcelTable
ON test.profile.ID = ExcelTable.ID
WHERE (test.profile.ID = ExcelTable.ID
AND test.profile.Profile_Name = ExcelTable.Profile_Name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.