如何通过 DAO 传递查询从存储过程中检索输出值
How to retrieve an output value from a stored procedure via DAO pass-through query
我正在将 ADP 转换为 ACCDB(tables/views 链接到 SQL 服务器),并且在 DAO 传递查询方面运气不错。我遇到困难的一个方面是从存储过程中检索 OUTPUT 参数。
SP有以下参数
(@IType int, @RetVal bit OUTPUT)
并且,简单来说就是下面的处理逻辑
IF @IType = 1
SET @RetVal = (SELECT ...
. . .
没有返回任何记录。 Access VBA 过程所需要的只是 RetVal。
我在网上搜索过,解决方案倾向于将值写入 table,或者使用 ADODB。
我真的想避免修改存储过程,因为更改必须传播到多个数据库。
此外,坚持使用 DAO 传递会很好,因为我已经开始沿着这条路走下去了。
有什么方法可以实现吗?
是的,您可以创建使用匿名代码块 的传递查询来检索 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
您可以像这样使用 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
我正在将 ADP 转换为 ACCDB(tables/views 链接到 SQL 服务器),并且在 DAO 传递查询方面运气不错。我遇到困难的一个方面是从存储过程中检索 OUTPUT 参数。
SP有以下参数
(@IType int, @RetVal bit OUTPUT)
并且,简单来说就是下面的处理逻辑
IF @IType = 1
SET @RetVal = (SELECT ...
. . .
没有返回任何记录。 Access VBA 过程所需要的只是 RetVal。
我在网上搜索过,解决方案倾向于将值写入 table,或者使用 ADODB。
我真的想避免修改存储过程,因为更改必须传播到多个数据库。
此外,坚持使用 DAO 传递会很好,因为我已经开始沿着这条路走下去了。
有什么方法可以实现吗?
是的,您可以创建使用匿名代码块 的传递查询来检索 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
您可以像这样使用 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