从PHP执行存储过程时出错

时间:2018-06-23 05:39:53

标签: php sql-server

我是MSSQL Server的新手,并且有一些开发人员创建了一个存储的proc,我所需要做的就是从我的PHP代码运行proc。 但是我正在错误以下 正式参数“ @contract_id”未声明为OUTPUT参数,但实际参数已传递至请求的输出中。

下面是我的代码

        $params['contract_id'] = '00990007';
        $params['major_version'] = '1';
        $procedure_params = array(
            array(&$params['contract_id'], SQLSRV_PARAM_OUT),
            array(&$params['major_version'], SQLSRV_PARAM_OUT)
        );

        $sql = "EXEC [MTP].[Process_07a_create_a_contract_version_wrapper] @contract_id = ?, @major_version = ?";
        $stmt = sqlsrv_prepare($conn, $sql, $procedure_params);
        if( !$stmt ) {
            die( print_r( sqlsrv_errors(), true));
        }
        if(sqlsrv_execute($stmt)){
            while($res = sqlsrv_next_result($stmt)){
                // make sure all result sets are stepped through, since the output params may not be set until this happens
            }
            // Output params are now set,

        }else{
            die( print_r( sqlsrv_errors(), true));
        }

有人可以指导我吗?

1 个答案:

答案 0 :(得分:0)

首先,使用sys.parameters检查参数的类型和顺序。然后使用结果设置参数:

<?php
...
$sql = 
    "SELECT [name], [is_output]
    FROM sys.parameters
    WHERE object_id = object_id('[MTP].[Process_07a_create_a_contract_version_wrapper]')
    ORDER BY parameter_id";
$res = sqlsrv_query($conn, $sql);
if ($res === false) {
    echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
    exit;
}
while ($row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC)) {
    echo 'Name: '.$row['name'].', ';
    echo 'Output: '.($row['is_output'] == 1 ? 'Yes' : 'No');
    echo '</br>';
}
...
?>

当@contract_id参数不是输出参数时,会引发错误消息“形式参数“ @contract_id”未声明为OUTPUT参数,但实际参数已传入请求的输出中。因此,您可以尝试使用此代码(使用您的代码):

<?php
...
$sql = "{call [MTP].[Process_07a_create_a_contract_version_wrapper](?, ?)}";
$procedure_params = array(
    array($params['contract_id'], SQLSRV_PARAM_IN),
    array(&$params['major_version'], SQLSRV_PARAM_INOUT)
);
$stmt = sqlsrv_query($conn, $sql, $procedure_params);
if( $stmt === false ) {
    echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
    exit;
}
// Output parameters are available after consuming all resultsets.
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
}
...
?>