我有一个简单的表AMC_GW_TESTTABLE
,其中有两列, name nvarchar(20)和 phone nvarchar(12)。我还有一个带有两个变量的简单存储过程。
create procedure AMC_GW_TESTSP (@name nvarchar(20),
@phone nvarchar(12)) as
insert into AMC_GW_Testtable (name,phone)
values (@name, @Phone)
我已经能够在Excel中获得一个按钮来创建命令:
exec dbo.amc_gw_testsp 'fred' '620-555-1212'
但它没有执行它。我将它复制到我的SSMS中并完全像它并执行它并且它工作正常。有什么想法吗?
VBA代码
Sub Button1_Click()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim connStr As String
Dim param As ADODB.Parameter
Dim param2 As ADODB.Parameter
connStr = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;" _
& "Initial Catalog=am_app);Data Source=bcu-sql-01"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandType = adCmdStoredProc
.CommandText = "AMC_GW_TESTSP"
Set param = .CreateParameter("@name", adVarChar, adParamInput, 20, "Christopher")
.Parameters.Append param
Set param2 = .CreateParameter("@phone", adVarChar, adParamInput, 12, "0123456789")
.Parameters.Append param
.Execute
End With
conn.Close
Set cmd = Nothing
Set conn = Nothing
End Sub
答案 0 :(得分:0)
我希望我没有用VBA代码请求吓唬你
让您了解应该拥有的内容:
Sub Button1_Click()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim connStr As String
Dim param As ADODB.Parameter
Dim param2 As ADODB.Parameter
connStr = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;" & _
"Initial Catalog=dbname;Data Source=servername"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandType = adCmdStoredProc
.CommandText = "AMC_GW_TESTSP"
Set param = .CreateParameter("@name", adVarChar, adParamInput, 20, "Christopher")
.Parameters.Append param
Set param2 = .CreateParameter("@phone", adVarChar, adParamInput, 12, "0123456789")
.Parameters.Append param
.Execute
End With
conn.Close
Set cmd = Nothing
Set conn = Nothing
End Sub
你必须改变的事情。首先是连接字符串(connStr)。您将需要提供数据库名称来代替dbname和server来代替servername。此字符串也假设您正在为SQL Server使用Windows身份验证。如果不是,则需要删除Integrated Security = SSPI;并在其位置提供用户ID = myUser;密码= myPassword;。 接下来,您将注意到.CreateParameter函数中的最后一个参数是固定字符串(“Christopher”和“0123456789”)。在您的情况下,它们应该是从电子表格中的单元格中获取的变量。请确保这些字符串不包含“;”在尝试执行之前。
我希望这会有所帮助,但如果有什么不明确的话,请随时与我联系!
PS您需要确保在“工具参考”下,选中了最高版本的Microsoft ActiveX数据对象库(我的是6.1,但2.0或更高版本肯定有效)。