Index: adodb-mssql.inc.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/adodb/drivers/adodb-mssql.inc.php,v
retrieving revision 1.24
diff -u -r1.24 adodb-mssql.inc.php
--- adodb-mssql.inc.php	2 May 2008 22:50:24 -0000	1.24
+++ adodb-mssql.inc.php	18 May 2008 01:01:30 -0000
@@ -152,7 +152,11 @@
 	// 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 @@
 		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 @@
 			# 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 @@
 			$decl = $this->qstr($decl);
 			if ($this->debug) ADOConnection::outp("<font size=-1>sp_executesql N{$sql[1]},N$decl,$params</font>");
 			$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 @@
 http://www.databasejournal.com/scripts/article.php/1440551
 */
 
-?>
\ No newline at end of file
+?>
