1
0
mirror of https://github.com/vrana/adminer.git synced 2025-08-11 17:14:07 +02:00

MS SQL: Import all CSV rows with one command

This commit is contained in:
Jakub Vrana
2025-02-26 22:27:43 +01:00
parent e8fa48a257
commit e075f4bd8b
2 changed files with 14 additions and 12 deletions

View File

@@ -187,29 +187,31 @@ if (isset($_GET["mssql"])) {
function insertUpdate($table, $rows, $primary) {
$fields = fields($table);
queries("SET IDENTITY_INSERT " . table($table) . " ON");
$values = array();
foreach ($rows as $set) {
$update = array();
$where = array();
$columns = "c" . implode(", c", range(1, count($set)));
$c = 0;
foreach ($set as $key => $val) {
$c++;
$name = idf_unescape($key);
if (!$fields[$name]["auto_increment"]) {
$update[] = "$key = $val";
$update[] = "$key = c$c";
}
if (isset($primary[$name])) {
$where[] = "$key = $val";
$where[] = "$key = c$c";
}
}
//! can use only one query for all rows
if (!queries("MERGE " . table($table) . " USING (VALUES(" . implode(", ", $set) . ")) AS source (c" . implode(", c", range(1, count($set))) . ") ON " . implode(" AND ", $where) //! source, c1 - possible conflict
. " WHEN MATCHED THEN UPDATE SET " . implode(", ", $update)
. " WHEN NOT MATCHED THEN INSERT (" . implode(", ", array_keys($set)) . ") VALUES (" . implode(", ", $set) . ");" // ; is mandatory
)) {
return false;
}
$values[] = "(" . implode(", ", $set) . ")";
}
queries("SET IDENTITY_INSERT " . table($table) . " ON");
$return = queries("MERGE " . table($table) . " USING (VALUES\n\t" . implode(",\n\t", $values) . "\n) AS source ($columns) ON " . implode(" AND ", $where) //! source, c1 - possible conflict
. "\nWHEN MATCHED THEN UPDATE SET " . implode(", ", $update)
. "\nWHEN NOT MATCHED THEN INSERT (" . implode(", ", array_keys($set)) . ") VALUES ($columns);" // ; is mandatory
);
queries("SET IDENTITY_INSERT " . table($table) . " OFF");
return true;
return $return;
}
function begin() {

View File

@@ -205,7 +205,7 @@ if ($_POST && !$error) {
}
$result = (!$rows || $driver->insertUpdate($TABLE, $rows, $primary));
if ($result) {
$result = $driver->commit();
$driver->commit();
}
queries_redirect(remove_from_uri("page"), lang('%d row(s) have been imported.', $affected), $result);
$driver->rollback(); // after queries_redirect() to not overwrite error