我有一个包含用户信息的CSV文件
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_id,users.email将来可能会改变,所以我不能只插入user_id然后运行update [users] set [email] = [user_id]。
发布于 2013-12-16 17:09:37
使用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);
?>https://stackoverflow.com/questions/20606687
复制相似问题