Search code examples
c++sqlcsql-serverodbc

Calling stored procedure with string output parameter


I want to call a stored procedure in SQL Server 2022 database with string output parameter using ODBC API. Numeric output parameters work fine, but the string ones I can not get to work.

Stored procedure:

CREATE PROCEDURE TestStoredProcedure(@inParam VARCHAR(MAX), @outParam VARCHAR(MAX) OUTPUT) AS
BEGIN
  SET @outParam = @inParam;
END;

Application code snippet (error checking omitted):

char* pStr = "{call TestStoredProcedure(?, ?)}";
SQLPrepare(hstmt, pStr, (SQLINTEGER)strlen(pStr));

char inParam[10] = "1234";
char outParam[10] = "";

SQLBindParameter(hstmt,
            (SQLUSMALLINT)1,
            SQL_PARAM_INPUT,
            SQL_C_CHAR,
            SQL_LONGVARCHAR,
            (SQLUINTEGER)strlen(inParam),
            0,
            (SQLPOINTER)inParam,
            sizeof(inParam),
            0);

SQLBindParameter(hstmt,
            (SQLUSMALLINT)2,
            SQL_PARAM_OUTPUT,
            SQL_C_CHAR,
            SQL_LONGVARCHAR,
            (SQLUINTEGER)sizeof(outParam),
            0,
            (SQLPOINTER)outParam,
            sizeof(outParam),
            0);

SQLExecute(hstmt); // error

The error is:

[Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Invalid parameter 4 (''): Data type 0x23 is a deprecated large object, or LOB, but is marked as output parameter. Deprecated types are not supported as output parameters. Use current large object types instead.

I tried with VARCHAR(5), CHAR(5), NVARCHAR(MAX), but nothing seems to work.

What should be the parameter types in order for this to work and what exactly is the Invalid parameter 4 ('')?


Solution

  • The output character has to be SQL_VARCHAR, not SQL_LONGVARCHAR:

    SQLBindParameter(hstmt,
                (SQLUSMALLINT)2,
                SQL_PARAM_OUTPUT,
                SQL_C_CHAR,
                SQL_VARCHAR,
                (SQLUINTEGER)sizeof(outParam),
                0,
                (SQLPOINTER)outParam,
                sizeof(outParam),
                0);