我只是在PHP中为临时表尝试此查询,但在PHP中不起作用。
IF OBJECT_ID('tempdb..##t1') IS NOT NULL
DROP TABLE ##t1
select 'rec1' as col1 into ##t1;
select * from ##t1
PHP代码:
$database = new SQL_DB;
$database->query(
"
IF OBJECT_ID('tempdb..##t1') IS NOT NULL
DROP TABLE ##t1
SELECT 'rec1' as col1 into ##t1;
SELECT * FROM ##t1;
"
);
$rows = $database->resultset();
SQL_DB类(简化):
public function __construct(){
//Set DSN
$dsn = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->dbname;
//Set options
/*$options = array(
PDO::ATTR_EMULATE_PREPARES => true,
PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8
);*/
$options = array(
PDO::SQLSRV_ATTR_QUERY_TIMEOUT => $this->TIMEOUT,
PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
//Create a new PDO instance
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
// $this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
//Prepare statement
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
//Return result Set
public function resultset($in = "") {
try{
if ($in == ""){
$this->stmt->execute();
}
else{
$this->stmt->execute($in);
}
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
它在Microsost SQL Server Management Studio中可以正常工作,而我在PHP中使用过的所有其他查询也可以正常工作,因此它不是任何连接问题。
它肯定与临时表和“#”有关。
我想念什么?
更新:
如果我将查询分为两部分,它就可以正常工作:
$database = new SQL_DB;
$database->query(
"
IF OBJECT_ID('tempdb..##t1') IS NOT NULL
DROP TABLE ##t1
SELECT 'rec1' as col1 into ##t1;
"
);
$database->resultset();
$database->query(
"
SELECT * from ##t1;
"
);
$rows = $database->resultset();
答案 0 :(得分:0)
原来问题不是临时表,而是PDO对于多个结果集的工作方式。
解决方法只是更改获取结果的方式(在本例中为获取最后一个结果集):
public function lastresultset($in = "") {
try{
if ($in == ""){
$this->stmt->execute();
}
else{
$this->stmt->execute($in);
}
$result = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
while($this->stmt->nextRowset()){
$result = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
};
return $result;
}
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}