SQL Server通过存储过程将表返回到MS Access

时间:2017-04-11 14:08:23

标签: sql-server vba stored-procedures access-vba ms-access-2010

我正在尝试将表格返回到具有50多列的MS Access,并且行数可以在0到5000之间变化。对于每种情况,可以有多个记录和车辆类型。

我可以执行存储过程并且工作正常。我无法将数据返回MS Access。

存储过程代码:

ALTER PROCEDURE [dbo].[pJDB_Export] 
    (@dteFrom int, 
     @dteTo int,
     @Veh nvarchar(80))
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @stWhere VARCHAR(200)

    SELECT DISTINCT [Case] 
    INTO #tmp 
    FROM data 
    WHERE [VEHICLE TYPE] = @Veh 
      AND (CY BETWEEN @dteFrom AND @dteTo)

    SELECT DISTINCT * 
    FROM dbo.vdata_Export_V3_3_2 v
    INNER JOIN #tmp t ON v.[CASE] = t.[CASE] 

MS Access代码:

Function Exec_pJDB_export(sqlConn as string)
    Dim conn As ADODB.Connection
    Dim cmd As ADODB.Command

    Dim iFrom, iTo As Integer
    Dim stv As String
    iFrom = 1999
    iTo = 2002
    stv = "1 TO 2 TON TRUCKS (COMMERCIAL)"
    Set conn = New ADODB.Connection

    conn.Open "DSN=Cars"
    conn.ConnectionString = sqlConn
    Set cmd = New ADODB.Command
    cmd.ActiveConnection = conn
    cmd.CommandType = adCmdStoredProc
    cmd.CommandText = "pJDB_export"

    cmd.Parameters.Append cmd.CreateParameter("@dteFrom", adInteger, adParamInput, , iFrom)
    cmd.Parameters.Append cmd.CreateParameter("@dteTo", adInteger, adParamInput, , iTo)
    cmd.Parameters.Append cmd.CreateParameter("@vehicle", adVarChar, adParamInput, 80, stv)

    cmd.Execute
    conn.Close

End Function

1 个答案:

答案 0 :(得分:1)

execute method返回recordset object。这个对象包含您的记录。这是一个例子:

Function Exec_pJDB_export(sqlConn As String)
    Dim conn As ADODB.Connection
    Dim cmd As ADODB.Command
    Dim rs As ADODB.Recordset               ' ADO recordset object, for accessing records.

    Dim iFrom, iTo As Integer
    Dim stv As String
    iFrom = 1999
    iTo = 2002
    stv = "1 TO 2 TON TRUCKS (COMMERCIAL)"
    Set conn = New ADODB.Connection

    conn.Open "DSN=Cars"
    conn.ConnectionString = sqlConn
    Set cmd = New ADODB.Command
    cmd.ActiveConnection = conn
    cmd.CommandType = adCmdStoredProc
    cmd.CommandText = "pJDB_export"

    cmd.Parameters.Append cmd.CreateParameter("@dteFrom", adInteger, adParamInput, , iFrom)
    cmd.Parameters.Append cmd.CreateParameter("@dteTo", adInteger, adParamInput, , iTo)
    cmd.Parameters.Append cmd.CreateParameter("@vehicle", adVarChar, adParamInput, 80, stv)

    ' This line has changed.
    Set rs = cmd.Execute()


    ' Loops over the records.
    Do Until rs.EOF

        ' Display the contents of column one to the user.
        MsgBox rs.Fields(0).Value

        rs.MoveNext
    Loop



    rs.Close
    conn.Close
End Function

快速概述:

  1. EOF代表文件结尾。查看所有记录时都是如此。
  2. 别忘了给MoveNext打电话,否则do循环会永远继续!
  3. 如果您愿意,可以将rs.Fields(0).Value行更改为rs.Fields("YourFieldName").Value。我发现通过名称而不是位置来引用字段更容易。