Sql server 2008 通过VBA从传递查询返回值
我有VBA代码在SQLServer2008中运行查询。它运行良好,并显示我需要的表格。执行此操作的代码如下所示:Sql server 2008 通过VBA从传递查询返回值,sql-server-2008,ms-access,stored-procedures,vba,pass-through,Sql Server 2008,Ms Access,Stored Procedures,Vba,Pass Through,我有VBA代码在SQLServer2008中运行查询。它运行良好,并显示我需要的表格。执行此操作的代码如下所示: Set db = CurrentDb Set qdf = db.QueryDefs("MyStoredProcedure") qdf.SQL = "exec [WCNS_Ops].[dbo].MyStoredProcedure [plus a bunch of parameters]" DoCmd.OpenQuery "MyStoredProcedure" 其中显示此表:
Set db = CurrentDb
Set qdf = db.QueryDefs("MyStoredProcedure")
qdf.SQL = "exec [WCNS_Ops].[dbo].MyStoredProcedure [plus a bunch of parameters]"
DoCmd.OpenQuery "MyStoredProcedure"
其中显示此表:
我的问题是:如何在不显示表格的情况下以编程方式将这些值返回到VBA代码?以下代码未经测试,但应该为您指出正确的方向:
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
您只需执行查询并将其输出设置为记录集。从我的头顶上掉下来像这样的东西
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
工作得很好。非常感谢你。