sql-server - 如何将存储过程的返回值与 Poco 绑定?
问题描述
最初的目标
我需要在 SQL Server 中调用存储过程,并有办法从我的调用 C++ 代码中确定过程中的状态代码,以了解它们是否成功。我用Poco C++ Libraries做到这一点。
失败的方法
我试图从过程中返回状态代码,但找不到将返回值成功绑定到我的局部变量的方法。
我用
- 微软 SQL 服务器 2019
- Poco 版本:带有 ODBC 连接的 1.9.4
- ODBC 驱动程序:SQL Server Native Client 11.0
问题示例
我创建了两个存储过程:
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
解决方案
推荐阅读
- html - 你如何减少段落之间的空间
- reactjs - React fetch - 根据用户角色获取字段
- php - Laravel Voyager Breadcrumb 子域问题
- android - 无法在 Android Studio 4.0 中创建活动,没有创建文件,没有错误
- reactjs - 如何在使用 Enzyme 测试 React 组件时设置状态
- r - 在 dplyr 中创建具有动态位置数的滞后/领先变量
- spring-boot - 如何遍历 Web 应用程序中的文件
- apache-zeppelin - 启动 Zeppelin 失败
- c++ - 在 Linux 中存储语言环境名称的缓冲区大小应该是多少?
- javascript - CentOS 7 中 curl 请求得到的响应不同