如何通过 DAO 传递查询从存储过程检索输出值

UhC*_*lem 2 sql-server ms-access dao stored-procedures return-value

我正在将 ADP 转换为 ACCDB(链接到 SQL Server 的表/视图),并且在 DAO 传递查询方面运气很好。我陷入困境的一个领域是从存储过程中检索 OUTPUT 参数。

SP有以下参数

(@IType int, @RetVal bit OUTPUT) 
Run Code Online (Sandbox Code Playgroud)

简单来说,处理逻辑如下

IF @IType = 1
    SET @RetVal = (SELECT ... 
. . . 
Run Code Online (Sandbox Code Playgroud)

没有返回任何记录。Access VBA 过程所需的只是 RetVal。

我在网上搜索过,解决方案倾向于将值写入表或使用 ADODB。

我真的想避免修改存储过程,因为更改必须传播到多个数据库。

另外,坚持使用 DAO 传递会很好,因为我已经开始走这条路了。

有什么方法可以实现这一点吗?

Gor*_*son 5

是的,您可以创建一个使用匿名代码块来检索 OUTPUT 参数的传递查询。对于存储过程

CREATE PROCEDURE [dbo].[IsOne] 
    @IType INT = 0, 
    @RetVal BIT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    IF @IType = 1
        SET @RetVal = 1;
    ELSE
        SET @RetVal = 0;
END
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用VBA代码:

Option Compare Database
Option Explicit

Sub ptqTest()
    Dim cdb As DAO.Database
    Set cdb = CurrentDb
    Dim ptq As DAO.QueryDef
    Set ptq = cdb.CreateQueryDef("")  ' temporary pass-through query
    ptq.Connect = "ODBC;DSN=SQLmyDb"
    ptq.ReturnsRecords = True
    ptq.SQL = _
            "DECLARE @rv BIT;" & _
            "EXEC dbo.IsOne @IType = 3, @RetVal = @rv OUTPUT;" & _
            "SELECT @rv;"
    Dim rs As DAO.Recordset
    Set rs = ptq.OpenRecordset
    ' BIT value 0 will map to False in this case
    Debug.Print "stored procedure returned " & rs(0)  
    rs.Close
    Set rs = Nothing
    Set ptq = Nothing
    Set cdb = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)