From 21bb3f94668e0ffdde38132ffad03d279acf670d Mon Sep 17 00:00:00 2001 From: "Eloy Lafuente (stronk7)" Date: Thu, 31 May 2012 01:01:14 +0200 Subject: [PATCH] MDL-33434 mssql: Improve handling of returned ids on insert. This commit moves from the batch SCOPE_IDENTITY() way to return the inserted ids to the OUTPUT alternative (supported and recommended since 2005). Also the handling of possible return values is improved, with all the alternatives leading to expected results. --- lib/dml/mssql_native_moodle_database.php | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/dml/mssql_native_moodle_database.php b/lib/dml/mssql_native_moodle_database.php index f32239e6c2235..5029beb4f40c9 100644 --- a/lib/dml/mssql_native_moodle_database.php +++ b/lib/dml/mssql_native_moodle_database.php @@ -810,7 +810,7 @@ public function insert_record_raw($table, $params, $returnid=true, $bulk=false, } else { unset($params['id']); if ($returnid) { - $returning = "; SELECT SCOPE_IDENTITY()"; + $returning = "OUTPUT inserted.id"; } } @@ -822,18 +822,29 @@ public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $qms = array_fill(0, count($params), '?'); $qms = implode(',', $qms); - $sql = "INSERT INTO {" . $table . "} ($fields) VALUES($qms) $returning"; + $sql = "INSERT INTO {" . $table . "} ($fields) $returning VALUES ($qms)"; list($sql, $params, $type) = $this->fix_sql_params($sql, $params); $rawsql = $this->emulate_bound_params($sql, $params); $this->query_start($sql, $params, SQL_QUERY_INSERT); $result = mssql_query($rawsql, $this->mssql); - $this->query_end($result); + // Expected results are: + // - true: insert ok and there isn't returned information. + // - false: insert failed and there isn't returned information. + // - resource: insert executed, need to look for returned (output) + // values to know if the insert was ok or no. Posible values + // are false = failed, integer = insert ok, id returned. + $end = false; + if (is_bool($result)) { + $end = $result; + } else if (is_resource($result)) { + $end = mssql_result($result, 0, 0); // Fetch 1st column from 1st row. + } + $this->query_end($end); // End the query with the calculated $end. if ($returning !== "") { - $row = mssql_fetch_assoc($result); - $params['id'] = reset($row); + $params['id'] = $end; } $this->free_result($result);