我的查询生成ORA-00933错误,为什么会这样?

时间:2014-07-04 13:36:46

标签: php sql oracle

我使用php生成这样的oracle查询:

...

$sql = sprintf("INSERT INTO $table_name %s %s ON DUPLICATE KEY UPDATE ", 
            $this->prepare_insert_sql("", $fields, false), 
            $this->prepare_insert_sql(" VALUES ", $values, true));
    for ($index = 0; $index < count($fields); $index++) {
        if ($index > 0) {
            $sql .= ", ";
        }
        $sql .= $fields[$index] . "='" . $values[$index] . "'";
    }
...

结果查询是:

INSERT INTO TBL_CONFIG(KEY,VALUE) 
VALUES ('1_default_meter_type_for_device_type_1','822') 
ON DUPLICATE KEY 
UPDATE KEY='1_default_meter_type_for_device_type_1', VALUE='822'

它给出了ORA-00933错误。

我真的无法找到错误。任何提示都表示赞赏。

3 个答案:

答案 0 :(得分:1)

根据您发布的代码KEY是一个保留字,因此您需要使用""双引号转义它,如下所示

INSERT INTO TBL_CONFIG("KEY",VALUE) 
VALUES ('1_default_meter_type_for_device_type_1','822') 
ON DUPLICATE KEY 
UPDATE "KEY"='1_default_meter_type_for_device_type_1', VALUE='822'

修改

完全糊涂了。甲骨文没有ON Dulicate Key Update。您必须使用Fred-ii评论的MERGE语句。

答案 1 :(得分:1)

使用merge代替insert into

MERGE INTO TBL_CONFIG USING DUAL ON (KEY ='1_default_meter_type_for_device_type_1')
WHEN MATCHED THEN UPDATE SET VALUE = '822'
WHEN NOT MATCHED THEN INSERT (KEY, VALUE) VALUES ('1_default_meter_type_for_device_type_1', '822')

答案 2 :(得分:0)

试试这个:

$sql = sprintf(
    "INSERT INTO $table_name %s %s ON DUPLICATE KEY UPDATE ",
    $this->prepare_insert_sql("", $fields, false),
    $this->prepare_insert_sql(" VALUES ", $values, true)
);

for($index = 0; $index < count($fields); $index++) {
    if($index > 0) {
        $sql .= ", ";
    }

    // added " before and after field name
    $sql .= '"' . $fields[$index] . '"=\'' . $values[$index] . "'";
}