1

我有一个声明表变量的查询。似乎 nanodbc 无法获取数据,尽管在 SQL 服务器上直接执行查询时可以正常工作。这是否意味着 nanodbc 不支持复杂的查询?

环境

  • nanodbc 版本:2.14
  • DBMS 名称/版本:MS SQL Server 2017
  • ODBC 连接字符串:
  • 操作系统和编译器:Windows、Visual C++ 2019
  • CMake 设置:

实际行为

包含表变量的 sql 查询不起作用。

预期行为

包含表变量的 sql 查询应该可以工作。

最小的工作示例

void show(nanodbc::result& results)
{
    const short columns = results.columns();
    long rows_displayed = 0;

    cout << "\nDisplaying " << results.affected_rows() << " rows "
         << "(" << results.rowset_size() << " fetched at a time):" << endl;

    // show the column names
    cout << "row\t";
    for(short i = 0; i < columns; ++i)
        cout << results.column_name(i) << "\t";
    cout << endl;

    // show the column data for each row
    while(results.next())
    {
        cout << rows_displayed++ << "\t";
        for(short col = 0; col < columns; ++col)
            cout << "(" << results.get<string>(col, "null") << ")\t";
        cout << endl;
    }
}
nanodbc::connection db_conn_ = nanodbc::connection(db_conn_string_);
execute(db_conn_, NANODBC_TEXT("DROP TABLE IF EXISTS research.dbo.nanodbc_test"));
execute(db_conn_, NANODBC_TEXT("CREATE TABLE research.dbo.nanodbc_test(Name varchar(20), Age int)"));
execute(db_conn_, NANODBC_TEXT("INSERT INTO research.dbo.nanodbc_test(Name, Age) VALUES('Bar', 20)"));
execute(db_conn_, NANODBC_TEXT("INSERT INTO research.dbo.nanodbc_test(Name, Age) VALUES('Foo', 30)"));
nanodbc::result result_working = execute( db_conn_, NANODBC_TEXT("select * from research.dbo.nanodbc_test"));
show(result_working);
//The following query does not return valid result, result_not_working contains 0 observations.
nanodbc::result result_not_working = execute(
    db_conn_,
    NANODBC_TEXT(
        "declare @names table(n varchar(20) not null primary key);"
        "   insert into @names select * from string_split('Bar,Foo', ',');"
        "   select[Name], [Age]"
        "   from research.dbo.nanodbc_test where Age in(20, 30)"
        "   and [Name] in(select n from @names)"
    )
);
show(result_not_working);

通过在下面提到的 David 和 Dan 建议的查询的开头添加“set nocount on”来解决上述问题。

我要解决的问题实际上要复杂一些。我想运行参数化查询。

string query = NANODBC_TEXT(
        "set nocount on"
        "   declare @names table(n varchar(20) not null primary key);"
        "   insert into @names select * from string_split(?, ',');"
        "   select[Name], [Age]"
        "   from research.dbo.nanodbc_test where Age in(20, 30)"
        "   and [Name] in(select n from @names)"
    );

nanodbc::statement statement = nanodbc::statement(db_conn__);
prepare(statement, query);

string names = "Bar,Foo";
//The error happens when I try to bind a string parameter.
statement.bind(0, names.c_str());

有人可以帮忙吗?谢谢。

4

0 回答 0