我的应用程序代码中有一个无法运行的 Oracle 合并查询。但是,当我回显查询并在 sqldeveloper 中运行它时,它运行良好。奇怪的是,我只有合并查询的这个问题;使用直接插入查询,一切正常。
代码示例:
$sql = "merge into table1 c using (select '$value' as value from table1 where ROWNUM=1) cd
on (c.value = cd.value)
when matched then
update set c.col1 = '$col1val', c.col2= '$col2val'
when not matched then
insert (c.col2, c.col2, c.col3)
values ('$col1val', '$col2val', '$col3val')";
$stid = oci_parse($conn, $sql);
$result = oci_execute($stid);
//Checking to see if it ran properly
if(!$result)
{
echo "query failed: $sql";
}
echo $sql; //If I copy what gets echoed onto the screen into my db gui and run it, I get '1 row merged' with no warnings or errors
在上面的代码片段中,我总是得到“查询失败”语句。另外,当我检查数据库时,我注意到没有执行任何更新或插入。相反,如果我要将合并查询更改为直接插入查询,例如:
$sql = "insert into table1 (col1, col2, col3)
values ('$col1val', '$col2val', '$col3val')";
$stid = oci_parse($conn, $sql);
$result = oci_execute($stid);
//Checking to see if it ran properly
if(!$result)
{
echo "query failed: $sql";
}
然后它根本不会失败。我没有得到“查询失败”,我看到数据库表中的新行。
我不知道为什么这只发生在合并查询中。作为参考,我使用的是 Oracle 10g 和 PHP 5。任何帮助将不胜感激。谢谢。
** * ** * *找到答案* ** * ** *
正如 Roger 指出的那样,查询需要被绑定。这就是我解决问题的方式:
//REMOVE single quoted variable ('$var') and used binding instead (:val)
$sql = "merge into table1 c using (select :value as value from table1 where ROWNUM=1) cd
on (c.value = cd.value)
when matched then
update set c.col1 = :col1val, c.col2= :col2val
when not matched then
insert (c.col2, c.col2, c.col3)
values (:col1val, :col2val, :col3val)";
$stid = oci_parse($conn, $sql);
//BIND VALUES
oci_bind_by_name($stid, ":col1val", $col1val);
oci_bind_by_name($stid, ":col2val", $col2val);
oci_bind_by_name($stid, ":col3val", $col3val);
$result = oci_execute($stid);