SQLRETURN core_sqlsrv_execute()

in source/shared/core_stmt.cpp [456:516]


SQLRETURN core_sqlsrv_execute( _Inout_ sqlsrv_stmt* stmt, _In_reads_bytes_(sql_len) const char* sql, _In_ int sql_len )
{
    SQLRETURN r = SQL_ERROR;

    try {

    // close the stream to release the resource
    close_active_stream( stmt );

    if( sql ) {

        sqlsrv_malloc_auto_ptr<SQLWCHAR> wsql_string;
        unsigned int wsql_len = 0;
        if( sql_len == 0 || ( sql[0] == '\0' && sql_len == 1 )) {
            wsql_string = reinterpret_cast<SQLWCHAR*>( sqlsrv_malloc( sizeof( SQLWCHAR )));
            wsql_string[0] = L'\0';
            wsql_len = 0;
        }
        else {
            SQLSRV_ENCODING encoding = (( stmt->encoding() == SQLSRV_ENCODING_DEFAULT ) ? stmt->conn->encoding() : stmt->encoding() );
            wsql_string = utf16_string_from_mbcs_string( encoding, reinterpret_cast<const char*>( sql ),
                                                         sql_len, &wsql_len );
            CHECK_CUSTOM_ERROR( wsql_string == 0, stmt, SQLSRV_ERROR_QUERY_STRING_ENCODING_TRANSLATE,
                                get_last_error_message() ) {
                throw core::CoreException();
            }
        }
        r = core::SQLExecDirectW( stmt, wsql_string );
    }
    else {
        r = core::SQLExecute( stmt );
    }

    // if data is needed (streams were bound) and they should be sent at execute time, then do so now
    if( r == SQL_NEED_DATA && stmt->send_streams_at_exec ) {
        core_sqlsrv_send_stream_packet(stmt, true);
    }

    stmt->new_result_set();
    stmt->executed = true;

    // if all the data has been sent and no data was returned then finalize the output parameters
    if( stmt->send_streams_at_exec && ( r == SQL_NO_DATA || !core_sqlsrv_has_any_result( stmt ))) {
        stmt->params_container.finalize_output_parameters();
    }

    return r;
    }
    catch( core::CoreException& e ) {

        // if the statement executed but failed in a subsequent operation before returning,
        // we need to remove all the parameters and cancel the statement
        stmt->params_container.clean_up_param_data();
        if( stmt->executed ) {
            SQLCancel( stmt->handle() );
            // stmt->executed = false; should this be reset if something fails?
        }

        throw e;
    }
}