php pdo mssql声明插入选择

时间:2018-01-22 15:53:08

标签: php sql-server pdo sqlsrv

我正在尝试使用PHP PDO访问MS SQL服务器:SQLSRV或PHP SQLSRV。

对于PHP PDO:SQLSRV,我正在使用此代码:

<?php

    try {
        $db = new PDO("sqlsrv:Server=sql_server;Database=database", "username", "password");
        $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

        $test = $db->prepare('declare @t2 code.instancereferencestable;
                              insert into @t2 select top 10 [Instance Reference] from imported.instance where [Instance Type] = \'CENAS\' and [Instance Reference] = \'CENAS.8000\' order by [Instance (Id)] desc;
                              select * from transformed.attribute_instance_extended_from_references(@t2)');
        $test->execute();
        $test->fetch(PDO::FETCH_OBJ);

        echo "Connected!". "\n";
    }
    catch(Exception $e) {
            echo "Error: " . $e->getMessage() . "\n";
    }

?>

对于PHP SQLSRV,我正在使用此代码:

<?php

    $serverName = "sql_server";
    $connectionOptions = array(
        "Database" => "database",
        "Uid" => "username",
        "PWD" => "password"
    );

    $conn = sqlsrv_connect($serverName, $connectionOptions);
    if ( $conn ) {
        echo "Connection established.".PHP_EOL;

        $sql = ("declare @t2 code.instancereferencestable;
                insert into @t2 select top 10 [Instance Reference] from imported.instance where [Instance Type] = 'CENAS' and [Instance Reference] = 'CENAS.8000' order by [Instance (Id)] desc;
                select * from transformed.attribute_instance_extended_from_references(@t2);");

        $stmt = sqlsrv_query($conn, $sql);
        if ( $stmt === false ) {
               die( print_r( sqlsrv_errors(), true));
        } else {
            $row = sqlsrv_fetch_array($stmt); 
            print_r ($row);
        }

    } else {
            echo "Connection could not be established.".PHP_EOL;
            die( print_r( sqlsrv_errors(), true)).PHP_EOL;
    }

?>  

我从PHP PDO获得的输出:SQLSRV是: 错误:SQLSTATE [IMSSP]:查询的活动结果不包含任何字段。

从PHP SQLSRV我没有输出。

我直接在SQL Server Management Studio中运行相同的SQL代码,然后输出。

任何人都可以帮忙!? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

一个简单的解决方案可能是创建一个存储过程并调用它。

您也可以尝试使用php_mssql.dll模块。 信息在这里:http://php.net/manual/es/book.mssql.php