首页 > 解决方案 > 如何将存储过程的返回值与 Poco 绑定?

问题描述

最初的目标

我需要在 SQL Server 中调用存储过程,并有办法从我的调用 C++ 代码中确定过程中的状态代码,以了解它们是否成功。我用Poco C++ Libraries做到这一点。

失败的方法

我试图从过程中返回状态代码,但找不到将返回值成功绑定到我的局部变量的方法。

我用

问题示例

我创建了两个存储过程:

create procedure test1
as
    declare @result int;
    set @result = 5;
    return @result;
go
create procedure test2
as
    declare @result int;
    set @result = 5;
    select 'Hello World!' as message;
    return @result;
go

并在 Micorsoft 的 SQL Server Management Studio (SSMS) 中使用以下 SQL 行对其进行了测试

declare @result1 int;
exec @result1 = test1;
select @result1;
declare @result2 int;
exec @result2 = test2;
select @result2;

SSMS 在第一个示例中打印 5 和“Hello World!” 如预期的那样,在第二个示例中紧随其后的是 5。

但是,当我使用 Poco 运行以下两个示例时,我得到了不同的结果。

Poco::Data::Statement statement( session );
std::int32_t result1 = -1;
statement << "exec ? = test1", out( result1 ), now;
Poco::Data::Statement statement( session );
std::int32_t result2 = -1;
statement << "exec ? = test2", out( result2 ), now;

test1中,我成功地将result1变量更新为返回代码 ( 5 ),但在test2中,result2保持其初始值-1

有人可以解释一下如何成功地将存储过程的返回码与 Poco 绑定吗?还是我错过了一些关于 SQL/ODBC 的琐碎事情?

更新 1

我重复了上面的例子,但是在存储过程中使用了输出参数,例如

create procedure test2B(@result int out)

并用

statement << "exec test2B @result = ?", out( result2B ), now;

与使用返回值时的行为完全相同。

更新 2

使用ODBC 过程调用转义序列 {call myproc(?)}时,只要过程不包含事务,我就能够返回输出参数。

create procedure test2B( @result int out )
as
    set @result = 5;
    select 'Hello World!' as message;
go

statement << "{call test2B(?)}", out(result2B), now; // Succeeds
create procedure test3( @result int out )
as
    set @result = 5;
    begin transaction;
    select 'Hello World!' as message;
    commit transaction;
go
statement << "{call test3(?)}", out(result3), now; // Fails

到目前为止,我唯一的工作策略是将结果列附加到我的结果集中。

Poco 文档: Poco::Data::Session , Poco::Data::Statement

标签: sql-serverstored-proceduresodbcpoco-libraries

解决方案


推荐阅读