【问题标题】:Update or insert from csv into sql server从 csv 更新或插入 sql server
【发布时间】:2014-01-03 14:15:12
【问题描述】:

我有一个包含用户信息的 CSV 文件,比如说

first_name;last_name;user_id;full_name

列分隔符为;,行终止符为\n

我需要做的是插入或更新到users 表中。唯一键是user_id:如果这个user_id的记录已经存在,我需要更新,如果没有我需要插入。

但是,有一些问题阻止我使用管理工作室数据导入或bulk insert

首先,users 表中有更多字段(不仅仅是 4 个),csv 文件中的列顺序与表中的列顺序不对应。所以我需要能够指定文件中的哪一列转到表中的哪一列。

其次,需要填写一些额外的字段。例如,users.email = users.user_id。这是另一个障碍 - 尽管对于新插入的行 users.email = users.user_idusers.email 将来可能会发生变化,所以我不能只插入 user_id 然后运行 ​​update [users] set [email] = [user_id]

【问题讨论】:

  • 您是否尝试过使用导入数据向导?听起来你可能需要一个两阶段的过程
  • 您可以做的一件事是将所有数据导入临时表,然后使用新的临时表将insert/update 导入目标表。另请查看thisthis 文章
  • @Yakyb 在导入数据向导中我无法填写其他字段。或者我可以吗?
  • @huMptyduMpty,我可以在这里使用#temp 表吗? bulk insert 从 csv 中写入,然后编写像 if exists(... where user_id=...) then (update ...) else (insert ... ) 这样的脚本,然后编写 #drop temp。对吗?
  • @xaxa:对不起,我的意思不是#temp。数据库中用于此导入的临时物理表。之后可以删除!

标签: sql-server


【解决方案1】:

使用 fgetcsv

两个冒号的例子:

<?php
$row = 0;
$update = "";
//separator of column
$separator = ";";

//creates two variables containing the index columns to read / modify
$idx_nom = 0;
$idx_rubrique = 1;

//Open file writing
if (($handle = fopen("test.csv", "r")) !== FALSE) 
{

   //we travel the file line by line, storing the data in a table
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) 
    {
       //can not control that the second line if the first contains the column headers
       if ($row != 0)
       {
          //conditions of one column 
          if (stristr($data[$idx_nom], 'chemise'))
          {
             $data[$idx_rubrique] = 1;
          }
           else if (stristr($data[$idx_nom], 'costume'))
          {
             $data[$idx_rubrique] = 2;
          }
           else if (stristr($data[$idx_nom], 'cravate'))
          {
             $data[$idx_rubrique] = 3;
          }
      }

      $update   .= implode($separator,$data)."\r\n";
      $row++;
   }

    fclose($handle);
}

//update from csv
$ouvre=fopen("test.csv","w+");
fwrite($ouvre,$update);
fclose($ouvre);
?>

【讨论】:

    猜你喜欢
    • 2021-04-29
    • 2020-11-21
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 2013-10-08
    • 1970-01-01
    • 2011-04-16
    相关资源
    最近更新 更多