从 PDO SQL Server 事务返回值


Returning a value from a PDO SQL Server transaction

我正在通过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时不会。

经过大量实验,事实证明,问题出在第一个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;