我正在尝试使用phpdo访问ms sql服务器:sqlsrv或phpsqlsrv。
对于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我没有输出。
我在sqlservermanagementstudio中直接运行相同的sql代码,并且有输出。
有人能帮忙吗!是吗?
提前谢谢!

最佳答案

一个简单的解决方案是创建一个存储过程并调用它。
也可以尝试使用php_mssql.dll模块。
这里的信息:http://php.net/manual/es/book.mssql.php

10-02 00:27