【问题标题】:Returning a value from a PDO SQL Server transaction从 PDO SQL Server 事务返回值
【发布时间】:2016-03-18 05:01:50
【问题描述】:

我通过PDO 传递一个大小合适的SQL 服务器TRANSACTION,格式如下:

$sql = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
       BEGIN TRANSACTION;
       DECLARE @id [int];
           //Check whether specific record exists with a SELECT
           //If it doesn't, create records on two tables
           //Check whether record exists again with another sSELECT (it will now) and assign the selected ID to @id
           //Update records on the two tables where ID = @id
       COMMIT TRANSACTION;";

这很好用,我可以愉快地UPSERT 一整天。但是,我想检索 @id 的值以更新调用对象以供以后使用,理想情况下不需要编写另一个单独的选择查询,并且无法找到可靠的获取方法。

fetch() 在不需要 INSERTs 时将其带回(即记录存在,因此仅调用 UPDATEs),但在调用 INSERTs 时不会。

【问题讨论】:

标签: php sql-server pdo


【解决方案1】:

事实证明,经过大量实验,问题出在第一个SELECT 语句 - 当记录存在时,它返回一个值,而当记录不存在时,它不存在。添加第二个SELECT 最初似乎没有帮助,因为它是一个单独的结果行。因此,解决方案是在获取数组的内容之前将结果集提前 1。

工作查询格式:

$sql = "SET NOCOUNT ON
            SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
            BEGIN TRANSACTION;
                DECLARE @id int;
                //Check whether specific record exists with a SELECT
                //If it doesn't, create records on two tables
                //Check whether record exists again with another SELECT (it will now) and assign the selected ID to @id
                //Update records on the two tables where ID = @id
                SELECT @id AS testID
            COMMIT TRANSACTION;";
 $stmt = $this->_db->prepare($sql);
 $stmt->execute();
 $stmt->nextRowset();
 $result = $stmt->fetch(PDO::FETCH_ASSOC);
 $testID = $result['testID'];
 return $testID;

【讨论】:

    猜你喜欢
    • 2011-12-10
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2010-09-21
    相关资源
    最近更新 更多