如何使用PHP从MS SQL存储过程获取输出值?

时间:2014-11-13 13:33:30

标签: php sql-server stored-procedures sqlsrv

我的MS SQL服务器上有以下存储过程:

CREATE PROCEDURE checkFollowing 
(
    @myMemberID INT,
    @otherMemberID INT
)
AS
BEGIN

IF EXISTS (SELECT 1 FROM Followers WHERE follower = @myMemberID AND followed = @otherMemberID)
    RETURN 1
ELSE
    RETURN 0    
END 
GO

在我的PHP代码中,到目前为止,我有这种方法:

function iAmFollowing($mymemberID, $otherMemberID) {
    $query = "EXEC checkFollowing @myMemberID = ?, @otherMemberID = ?";
    $stmt = sqlsrv_query($this->con, $query, array(&$mymemberID, &$otherMemberID));
    $result = sqlsrv_fetch_array($stmt);

    return $result[0];
}

正如我现在意识到的那样,我无法使用sqlsrv_fetch_array()命令获取返回值。但我似乎无法弄清楚如何使用PHP获取outpur值。 有人知道如何实现这个目标吗?

任何帮助都会得到很好的赞赏。

CREATE PROCEDURE checkFollowing 
(
    @myMemberID INT,
    @otherMemberID INT
)
AS
BEGIN

IF EXISTS (SELECT 1 FROM Followers WHERE follower = @myMemberID AND followed = @otherMemberID)
    SELECT 1 AS 'output'
ELSE
    SELECT 0 AS 'output'    
END 
GO

PHP代码应该几乎相同。只需将返回值更改为:    $结果[ '输出'];

1 个答案:

答案 0 :(得分:0)

在SP的参数列表中声明OUTPUT parameterOUTPUT parameter将数据返回给调用应用程序。查看此 Link 了解更多信息

CREATE PROCEDURE checkFollowing 
(
    @myMemberID INT,
    @otherMemberID INT,
    @output INT OUTPUT
)
AS
BEGIN

IF EXISTS (SELECT 1 FROM Followers WHERE follower = @myMemberID AND followed = @otherMemberID)
    SELECT @output= 1
ELSE
    SELECT @output= 0    
END 
GO

更新:

调用SP并存储输出。试试这样的事情

DECLARE @appout int; -- variable to hold the data returned by SP.

EXEC checkFollowing 10,20, @output = @appout OUTPUT; -- This is how i will call a SP.

@appout - will hold the data returned by the procedure.