首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从csv更新或插入到sql server

从csv更新或插入到sql server
EN

Stack Overflow用户
提问于 2013-12-16 16:52:30
回答 1查看 468关注 0票数 0

我有一个包含用户信息的CSV文件

代码语言:javascript
复制
first_name;last_name;user_id;full_name

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

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

但是,有一些问题阻碍了我使用management studio data-import或bulk insert

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

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

EN

回答 1

Stack Overflow用户

发布于 2013-12-16 17:09:37

使用fgetcsv

带有两个柱号的示例:

代码语言:javascript
复制
<?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);
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20606687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档