From f4607d530975f0bdde7c4b4ac66a92636bcf6be9 Mon Sep 17 00:00:00 2001 From: stronk7 Date: Sun, 18 May 2008 01:06:08 +0000 Subject: [PATCH] Fix MSSQL Insert_ID() to work when inserting using placeholders. MDL-14886 --- lib/adodb/drivers/adodb-mssql.inc.php | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/adodb/drivers/adodb-mssql.inc.php b/lib/adodb/drivers/adodb-mssql.inc.php index 2048f5fcf2..96e029ec12 100644 --- a/lib/adodb/drivers/adodb-mssql.inc.php +++ b/lib/adodb/drivers/adodb-mssql.inc.php @@ -152,7 +152,11 @@ class ADODB_mssql extends ADOConnection { // the same scope. A scope is a module -- a stored procedure, trigger, // function, or batch. Thus, two statements are in the same scope if // they are in the same stored procedure, function, or batch. + if ($this->lastInsID !== false) { + return $this->lastInsID; // InsID from sp_executesql call + } else { return $this->GetOne($this->identitySQL); + } } function _affectedrows() @@ -539,7 +543,7 @@ order by constraint_name, referenced_table_name, keyno"; for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) { $sql2 .= '@P'.($i-1) . $sqlarr[$i]; } - return array($sql,$this->qstr($sql2),$max); + return array($sql,$this->qstr($sql2),$max,$sql2); } function PrepareSP($sql) @@ -663,6 +667,11 @@ order by constraint_name, referenced_table_name, keyno"; # bind input params with sp_executesql: # see http://www.quest-pipelines.com/newsletter-v3/0402_F.htm # works only with sql server 7 and newer + $getIdentity = false; + if (!is_array($sql) && preg_match('/^\\s*insert/i', $sql)) { + $getIdentity = true; + $sql .= (preg_match('/;\\s*$/i', $sql) ? ' ' : '; ') . $this->identitySQL; + } if (!is_array($sql)) $sql = $this->Prepare($sql); $params = ''; $decl = ''; @@ -702,13 +711,20 @@ order by constraint_name, referenced_table_name, keyno"; $decl = $this->qstr($decl); if ($this->debug) ADOConnection::outp("sp_executesql N{$sql[1]},N$decl,$params"); $rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params", $this->_connectionID); + if ($getIdentity) { + $arr = @mssql_fetch_row($rez); + $this->lastInsID = isset($arr[0]) ? $arr[0] : false; + @mssql_data_seek($rez, 0); + } } else if (is_array($sql)) { # PrepareSP() $rez = mssql_execute($sql[1]); + $this->lastInsID = false; } else { $rez = mssql_query($sql,$this->_connectionID); + $this->lastInsID = false; } return $rez; } @@ -1035,4 +1051,4 @@ order by constraint_name, ordinal_position http://www.databasejournal.com/scripts/article.php/1440551 */ -?> \ No newline at end of file +?> -- 2.39.5