我有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"
显示此表:
我的问题是:如何在不显示表的情况下以编程方式将这些值返回给VBA代码?
答案 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