简体   繁体   中英

php - how execute a sqlsrv stored procedure

I have a successful connection to SQL Server using SQLSRV in my PHP script:

$name = 'SERVERNAME';
$db  = 'DBNAME';
$par = array("Database"=>$db);

$conn = sqlsrv_connect($name, $par);

Also I have the following T-SQL script:

Declare @dt datetime;
SET @dt = GETDATE();
EXEC oik..SrezLTGES @Cat = 'Ë', @Ids = '140539,140540,140589,150395,180395,180396,180445',@Time = @dt

The procedure parameters are:

在此处输入图像描述

I don't know how to execute this query in PHP. Any ideas?

A possible approach here is to parameterize the statement and use sqlsrv_query() . As is mentioned in the documentation , the sqlsrv_query function is well-suited for one-time queries and should be the default choice to execute queries unless special circumstances apply and sqlsrv_query function does both statement preparation and statement execution, and can be used to execute parameterized queries .

The stored procedure has varchar parameters (and I'm almost sure, that you are using a cyrillic collation), so you may need to use the appropriate encoding ( "CharacterSet" => "UTF-8" or "CharacterSet" => SQLSRV_ENC_CHAR in the connection options) and/or character set conversion on the parameters values (with iconv() for example). Reading UTF-8 all the way through is a good starting point.

If the stored procedure returns data, you may try to use sqlsrv_fetch_array() to retrieve the returned data. You may also use SET NOCOUNT ON to prevent SQL Server from passing the count of the affected rows as part of the result set.

The following example, based on your code, is a possible solution to your problem:

<?php
// Connection
$server   = "SERVERNAME";
$database = "DBNAME";
$cinfo = array(
    "CharacterSet" => "UTF-8",
    "Database" => $database
);
$con = sqlsrv_connect($server, $cinfo);
if ($con === false) {
    echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
    exit;
}

// Statement
$sql = "
    SET NOCOUNT ON;
    DECLARE @dt datetime;
    SET @dt = GETDATE();
    EXEC oik..SrezLTGES 
        @Cat = ?, 
        @Ids = ?, 
        @Time = @dt,
        @TimeIsSummer = 1,
        @ShowSystemTime = 1
";      
$params = array("Ë", "140539,140540,140589,150395,180395,180396,180445");
$stmt = sqlsrv_query($con, $sql, $params);
if ($stmt === false) {
    echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
    exit;
}

// Data
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
   echo print_r($row, true);
}

// End
sqlsrv_free_stmt($stmt);
sqlsrv_close($con);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM