从Access VBA运行存储过程

时间:2017-03-15 18:44:33

标签: vba ms-access sql-server-2008-r2 ms-access-2013

我一直收到错误

  

从字符串转换日期和/或时间时转换失败。

这是我使用的vba以及我的sql server存储过程语法。为了让这次成功运行,我应该改变什么?

Private Sub btnRunStoredProc_Click()
Dim cmd As ADODB.Command, startdate As String, enddate As String
    Set cmd = New ADODB.Command
    startdate = "'" & Me.txtStartDate & "'"
    enddate = "'" & Me.txtEndDate & "'"
    cmd.ActiveConnection = "Provider=sqloledb;Server=Server;Database=DB;Trusted_Connection=yes;"
    cmd.CommandType = adCmdStoredProc
    cmd.CommandText = "runstoredproc"
    cmd.Parameters.Append cmd.CreateParameter("@startdate", adVarChar, adParamInput, 255, startdate)
    cmd.Parameters.Append cmd.CreateParameter("@enddate", adVarChar, adParamInput, 255, enddate)
    cmd.Execute
End Sub


ALTER Procedure [dbo].[runstoredproc]
(
       @startdate varchar(100)
       ,@enddate varchar(100) 
)
As

Select * from helper where hiredate between @startdate And @enddate

2 个答案:

答案 0 :(得分:2)

考虑使用Format()将MS Access日期转换为字符串,因为连接引号不起作用。此外,使用CONVERT()将varchar字符串转换为SQL Server中的日期。格式YYYY-MM-DD用于不依赖于放置月份和日期的文化设置。

<强> VBA

Private Sub btnRunStoredProc_Click()
    Dim cmd As ADODB.Command, startdate As String, enddate As String

    Set cmd = New ADODB.Command

    startdate = Format(Me.txtStartDate, "YYYY-MM-DD")
    enddate = Format(Me.txtEndDate, "YYYY-MM-DD")

    With cmd
       .ActiveConnection = "Provider=sqloledb;Server=Server;Database=DB;Trusted_Connection=yes;"
       .CommandType = adCmdStoredProc
       .CommandText = "runstoredproc"
       .Parameters.Append .CreateParameter("@startdate", adVarChar, adParamInput, 255, startdate)
       .Parameters.Append .CreateParameter("@enddate", adVarChar, adParamInput, 255, enddate)
       .Execute
    End With

    Set cmd = Nothing
End Sub

<强> TSQL

ALTER Procedure [dbo].[runstoredproc]
(
       @startdate varchar(100)
       ,@enddate varchar(100) 
)
As

SELECT * FROM [helper]
WHERE hiredate BETWEEN CONVERT(DATE, @startdate) AND CONVERT(DATE, @enddate)

答案 1 :(得分:0)

您的参数不能是日期/时间数据类型的任何原因?您的hiredate列的数据类型是什么?这一直对我有用:

Private Sub btnRunStoredProc_Click()
Dim cmd As ADODB.Command, startdate As Date, enddate As Date
    Set cmd = New ADODB.Command
    startdate = CVDate(Me.txtStartDate)
    enddate = CVDate(Me.txtEndDate)
    cmd.ActiveConnection = "Provider=sqloledb;Server=Server;Database=DB;Trusted_Connection=yes;"
    cmd.CommandType = adCmdStoredProc
    cmd.CommandText = "runstoredproc"
    cmd.Parameters.Append cmd.CreateParameter("@startdate", adDBTimeStamp, adParamInput, , startdate)
    cmd.Parameters.Append cmd.CreateParameter("@enddate", adDBTimeStamp, adParamInput, , enddate)
    cmd.Execute
End Sub


ALTER Procedure [dbo].[runstoredproc]
(
       @startdate datetime
       ,@enddate datetime 
)
As

Select * from helper where hiredate between @startdate And @enddate