我正在使用此语法从Excel 2013运行SQL Server 2008存储过程。一切都在一台PC上执行,但如果我尝试在第二台PC上运行它,则会出错
OLEDB连接错误
不应该,因为我正在硬编码服务器名,用户名和密码,语法在任何PC上运行都没有?
Function RunSQLServerProc()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset
con.Open "Provider=SQLOLEDB;Data Source=Server;Initial Catalog=Database;User Id=userid;Password=password;Integrated Security=SSPI;Trusted_Connection=Yes;"
cmd.ActiveConnection = con
cmd.CommandText = "TestProc"
Set rs = cmd.Execute(, , adCmdStoredProc)
End Function
答案 0 :(得分:0)
通过VBA连接到SQL Server有两种方法
1)综合安全性= SSPI;
2)提供有效的用户名和&密码通过VBA
使用SSPI时,将使用登录用户(即Excel工作簿)的Windows登录凭据。
现在,由于您不想使用Windows凭据,因此您需要使用您指定的用户ID和密码提供SQL Server登录,并且还必须与具有您的权限的数据库中的帐户相关联需要。
答案 1 :(得分:0)
这两个样本对我来说非常合适。
Option Explicit
Sub CallSprocOne()
Dim con As Connection
Dim rst As Recordset
Dim strConn As String
Set con = New Connection
strConn = "Provider=SQLOLEDB;"
strConn = strConn & "Data Source=LAPTOP\SQL_EXPRESS;"
strConn = strConn & "Initial Catalog=Northwind;"
strConn = strConn & "Integrated Security=SSPI;"
con.Open strConn
'Put a country name in Cell E1
Set rst = con.Execute("Exec dbo.TestNewProc '" & ActiveSheet.Range("E1").Text & "'")
'The total count of records is returned to Cell A5
ActiveSheet.Range("A5").CopyFromRecordset rst
rst.Close
con.Close
End Sub
Sub CallSprocTwo()
Dim con As Connection
Dim rst As Recordset
Set con = New Connection
con.Open "Provider=SQLOLEDB;Data Source=LAPTOP\SQL_EXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;"
Set rst = con.Execute("Exec dbo.[Ten Most Expensive Products]")
'Results of SProc are returned to Cell A1
ActiveSheet.Range("A1").CopyFromRecordset rst
rst.Close
con.Close
End Sub