通过VBA从传递查询返回值

时间:2011-02-09 13:12:11

标签: sql-server-2008 ms-access stored-procedures access-vba pass-through

我有VBA代码在SQL-Server 2008中运行查询。它运行正常并显示我需要的表。执行此操作的代码在此处:

Set db = CurrentDb
Set qdf = db.QueryDefs("MyStoredProcedure")

qdf.SQL = "exec [WCNS_Ops].[dbo].MyStoredProcedure [plus a bunch of parameters]"   
DoCmd.OpenQuery "MyStoredProcedure"

显示此表:

Picture of the table the stored procedure returns

我的问题是:如何在不显示表的情况下以编程方式将这些值返回给VBA代码?

2 个答案:

答案 0 :(得分:3)

以下代码未经测试,但应该指向正确的方向:

Set db = CurrentDb

Set qdf = db.QueryDefs("MyStoredProcedure")
qdf.ReturnsRecords = True
qdf.SQL = "exec [WCNS_Ops].[dbo].MyStoredProcedure [plus a bunch of parameters]"  

With qdf.OpenRecordset(dbOpenSnapshot)  'could also be dbOpenDynaset, etc. '
    Do Until .EOF
        Debug.Print !firstid
        Debug.Print !lastid
        .MoveNext
    Loop
End With

答案 1 :(得分:1)

您需要做的就是执行查询并将其输出设置为记录集。我最喜欢这样的东西

Dim dbCon as new ADODB.Connection
Dim rst as new ADODB.Recordset
Dim cmd as new ADODB.Command

dbCon.ConnectionString=”Your Connection String”
with cmd
    .comandtype=adCmdStoredProc
    .commandtext=”Your SP name”
    .Parameters.Append .CreateParameter("@Pram1", adVarChar, adParamInput, 50, “WhatEver”)
    .ActiveConnection=dbCon
    .NamedParameters = True
    Set rst = .Execute
end with

with rst
    if .EOF=false then
        myVar=!Column1
    end if
end with

rst.close
dbcon.close
set cmd=nothing