I have a php script that inserts data from a csv file into an Oracle table :
$handle = fopen('file.txt', "r");
for($i =1;($data = fgetcsv($handle, 10000, ";")) !== FALSE; $i++) {
// The query uses placeholders for data
$sql = "INSERT INTO table
(col1,col2,col3,col4)
VALUES
(:val1,:val2,:val3,:val4)";
$sth = $conn->prepare($sql);
// The data is bound to the placeholders
$sth->bindParam(':val1', $data[0]);
$sth->bindParam(':val2', $data[1]);
$sth->bindParam(':val3', $data[2]);
$sth->bindParam(':val4', $data[3]);
// The row is actually inserted here
$sth->execute();
$sth->closeCursor();
Now i'm trying to replace the insert with a merge so I can do an isert only if the data does not exist already.
I took a look at some SO questions and the Oracle documentation, but still can't figure that out (without using procedures, whice is all i found...)
can you please help ?
In your case, if you only want to do an INSERT
then you don't need to use MERGE
. If you have proper constraints defined on the table , then you don't have to worry about validating the existing rows in the table.
Anyway, as per your comments to the question, you want to use MERGE . So, here are few examples of the [optional] MATCHED and NOT MATCHED clauses valid for releases 10g and up:
Both clauses present
MERGE INTO test1 a
USING (SELECT :val1,:val2,:val3,:val4 FROM DUAL) b
ON (a.key = b.key) -- put the required join key
WHEN MATCHED THEN
UPDATE SET a.col = b.col
WHEN NOT MATCHED THEN
INSERT (col1,col2,col3,col4)
VALUES (b.object_id, b.status);
No matched clause, insert only
MERGE INTO test1 a
USING (SELECT :val1,:val2,:val3,:val4 FROM DUAL) b
ON (a.key = b.key) -- put the required join key
WHEN NOT MATCHED THEN
INSERT (col1,col2,col3,col4)
VALUES (b.object_id, b.status);
No not-matched clause, update only
MERGE INTO test1 a
USING (SELECT :val1,:val2,:val3,:val4 FROM DUAL) b
ON (a.key = b.key) -- put the required join key
WHEN MATCHED THEN
UPDATE SET a.col = b.col;
See some usage examples here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.