我的任务是将新记录从 Excel 表添加到 Microsoft SQL Server 表,为此,我计划使用 ADODB 对象;但是,我的 SQL 语句没有执行,我认为这与我的连接字符串有关。
在我的代码中,我写下了我打算最终使用的SQL语句,但是当我尝试时:
sql = "SELECT * FROM [Provider=SQLOLEDB;Data Source=hpwfh-ssql01; _
Initial Catalog=HPW DataIntegrated Security=SSPI;Trusted_Connection=Yes].Hubspot_Data"
(一个简单的选择语句)它甚至不起作用。
Sub update1()
Dim cn, rs As Object, path As String, name As String, sql As String, file As String
path = "T:\Marketing\Data Analytics\Hubspot data for SQL"
name = "Hubspot_Data"
file = path & "\" & name & ".xlsx"
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.connectionstring = "Data Source=" & file & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;Readonly=false;IMEX=0"";"
.Open
End With
sql = "INSERT INTO [Provider=SQLOLEDB;Data Source=hpwfh-ssql01;Initial Catalog=Hubspot_Data;Integrated Security=SSPI;Trusted_Connection=Yes].Hubspot_Data " & _
"SELECT * FROM (SELECT * FROM [Provider=SQLOLEDB;Data Source=hpwfh-ssql01;Initial Catalog=Hubspot_Data;Integrated Security=SSPI;Trusted_Connection=Yes].Hubspot_Data" & _
"EXCEPT SELECT * FROM [hubspot-crm-exports-sql-data-20$])"
Set rs = cn.Execute(sql)
End Sub
附注:表的名称与数据库的名称相同
对于这段代码,我遇到了三个不同的错误:
Microsoft Access 数据库引擎无法找到对象“Area” 确保该对象存在并且您拼写了它的名称和路径名 正确。 (而且我没有拼错 Hubspot_Data)
外部表的格式不符合预期。
Microsoft Acess 数据库引擎无法打开或写入该文件 (我的文件路径)'\My Documents\Provider=SQLOLEDB.XLSX'。已经开通了 只能由其他用途使用,或者您需要查看和写入其权限 数据。
显然,计算机去错误的地方检索它所需的表,而我不知道哪里出了问题。感谢您的帮助。
最佳答案
首先,您需要 2 个连接 - 一个用于 SQLSvr,一个用于 Excel。 然后查询源 (Excel) 并单独插入到 SQLSvr 中。您无法将这些混合到一个查询中。
Sub SelectInsert()
Dim cn As Object, rs As Object, sql As String
Dim conSQL As Object, sInsertSQL As String
'---Connecting to the Data Source---
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.Open
End With
Set conSQL = CreateObject("ADODB.Connection")
With cn
.Provider = "SQLOLEDB"
.ConnectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
.Open
End With
'---Run the SQL SELECT Query---
sql = "SELECT * FROM [Sheet1$]"
Set rs = cn.Execute(sql)
Do 'the insert. Each rs(n) represents an Excel column.
sInsertSQL = "INSERT INTO table VALUES(" & rs(0) & ";" & rs(1) & ";" & rs(2) & ")"
conSQL.Execute sInsertSQL
rs.MoveNext
Loop Until rs.EOF
'---Clean up---
rs.Close
cn.Close
conSQL.Close
Set cn = Nothing
Set conSQL = Nothing
Set rs = Nothing
End Sub
关于sql-server - 同时使用 Excel 和 Microsoft SQL Server 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57923816/