Laravel 多结果集查询生成器

Laravel multi result set query builder

我有一个 MSSQL 存储过程:

BEGIN
    SET NOCOUNT ON;
    SELECT [ID],
           [Type],
           [message]
    FROM [ir.pay].[dbo].[notifications]
    WHERE ReciverID = @userID;
    SELECT ID AS id,
           Website AS website,
           Status AS status
    FROM dbo.Customers
    WHERE UserID = @userID;
END;

我正在用我的 laravel 应用程序执行此操作:

DB::connection('sqlsrv')->select('EXEC StoredProcedureName  @userID=1');

它只是 returns 我第一个 SELECT 查询结果。

如何获得两个结果集?

你需要union:

SELECT [ID], [Type], [message]
FROM [ir.pay].[dbo].[notifications]
WHERE ReciverID = @userID 
UNION ALL
SELECT ID, Website, Status
FROM dbo.Customers
WHERE UserID = @userID;

你可以利用DB::statement();

要创建存储过程,您可以像这样创建。 例如

DB::statement('
BEGIN
    SET NOCOUNT ON;
    SELECT [ID],
           [Type],
           [message]
    FROM [ir.pay].[dbo].[notifications]
    WHERE ReciverID = @userID;
    SELECT ID AS id,
           Website AS website,
           Status AS status
    FROM dbo.Customers
    WHERE UserID = @userID;
END;

');

对于 运行 存储过程,您可以

DB::connection('sqlsrv')->statement('EXEC StoredProcedureName  @userID=1');

希望对您有所帮助。

我认为你的存储过程returns不止一个结果集,所以你必须移动到下一个结果集。我不熟悉 Laravel,但我认为您使用 SQLSRV 驱动程序 PHP。所以,在这种情况下,我使用 sqlsrv_next_result()PDOStatement::nextRowset()。在Laravel中找到合适的方法并检查。

通过编写波纹管函数解决:

function get_multi_result_set($conn, $statement)
{
    $results = [];
    $pdo = DB::connection($conn)->getPdo();
    $result = $pdo->prepare($statement);
    $result->execute();
    do {
        $resultSet = [];
        foreach ($result->fetchall(PDO::FETCH_ASSOC) as $res) {
            array_push($resultSet, $res);
        }
        array_push($results, $resultSet);
    } while ($result->nextRowset());

    return $results;
}