diff --git a/sqlsrv/database.inc b/sqlsrv/database.inc
index 9bbf857..c84d877 100755
--- a/sqlsrv/database.inc
+++ b/sqlsrv/database.inc
@@ -202,7 +202,18 @@ class DatabaseConnection_sqlsrv extends DatabaseConnection {
     $query = $this->addRangeToQuery($query, $from, $count);
     return $this->query($query, $args, $options);
   }
-
+  
+  /**
+   * Generates a temporary table name.
+   *
+   * @return
+   *   A table name.
+   */
+  protected function generateTemporaryTableName() {
+    $s = strtoupper(md5(uniqid(rand(),true))); 
+    return "db_temp_" . $this->temporaryNameIndex++ . '_' . $s;
+  }
+  
   /**
    * Override of DatabaseConnection::queryTemporary().
    *
@@ -211,15 +222,16 @@ class DatabaseConnection_sqlsrv extends DatabaseConnection {
   public function queryTemporary($query, array $args = array(), array $options = array()) {
     // Generate a new temporary table name and protect it from prefixing.
     // SQL Server requires that temporary tables to be non-qualified.
-    $tablename = '#' . $this->generateTemporaryTableName();
+    $tablename = '##' . $this->generateTemporaryTableName();
     $prefixes = $this->prefixes;
     $prefixes[$tablename] = '';
     $this->setPrefix($prefixes);
 
     // Replace SELECT xxx FROM table by SELECT xxx INTO #table FROM table.
-    $query = preg_replace('/^SELECT(.*?)FROM/i', 'SELECT$1 INTO ' . $tablename . ' FROM', $query);
+    $query = preg_replace('/^SELECT(.*?)FROM/is', 'SELECT$1 INTO ' . $tablename . ' FROM', $query);
 
     $this->query($query, $args, $options);
+    
     return $tablename;
   }
 
@@ -434,7 +446,7 @@ class DatabaseConnection_sqlsrv extends DatabaseConnection {
       return $cache->data;
     }
     // Rescue the # prefix from the escaping.
-    $result = ($table[0] == '#' ? '#' : '') . preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
+    $result = ($table[0] == '#' ? '#' : '') . ((isset($table[1]) && $table[1] == '#') ? '#' : '') . preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
     fastcache::cache_set($table, $result, 'schema_escapeTable');
     return $result;
   }
