简体   繁体   English

在SQL Server中上传CSV文件而不清空数据库中的表

[英]Upload csv files in sql server without emptying the table in the database

I want to upload csv files in sql server database. 我想在sql server数据库中上传csv文件。 I want to upload data one after the other without emptying the table before inserting....How can i modify that code to achieve that... 我要一个接一个地上传数据,而不要在插入之前清空表。...如何修改该代码以实现该目标...

Thanks. 谢谢。

$deleterecords = "TRUNCATE TABLE csvTable"; //empty the table of its current records
$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query($conn, $deleterecords, $params, $options ); 
//$stmt=odbc_exec($conn,$deleterecords);




//Upload File
if (isset($_POST['submit'])) {
    if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
        echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
        echo "<h2>Displaying contents:</h2>";
        readfile($_FILES['filename']['tmp_name']);
    }

    //Import uploaded file to Database
    $handle = fopen($_FILES['filename']['tmp_name'], "r");

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $import="INSERT into csvTable(Name,city) values('$data[0]','$data[1]')";
        $params = array();
        $options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
        $stmt = sqlsrv_query($conn, $import, $params, $options ); 
        //$stmt=odbc_exec($conn,$import);
    }

    fclose($handle);

    print "Import done";

I think, that this is the actual problem 我认为这是实际问题

now i want the data to remain in the table and the next insert to go just below the data already inserted in the table 现在我希望数据保留在表中,并且下一次插入要恰好位于表中已插入数据的下方

A SQL-Server table does not have any implicit order! SQL-Server表没有任何隐式顺序!

There is no just below the data ... 数据下方没有...

What happens, if you just do not delete the old data? 如果您只是不删除旧数据,会发生什么情况? Am I right, that your actual problem is: How can I know which records are newly inserted? 我是对的,您的实际问题是: 我怎么知道哪些记录是新插入的?

You might 你可能

  • add a column ImportID INT IDENTITY which will ensure a running number. 添加一列ImportID INT IDENTITY ,以确保运行编号。 If you use ORDER BY ImportID in your queries, you'll get new data just below old data 如果在查询中使用ORDER BY ImportID ,则会在旧数据的下方获得新数据
  • add a column to your target table and pass in a mark (sessionID, datetime, whatever) to allow groupings later on 在目标表中添加一列,并传递一个标记(sessionID,日期时间等),以便以后进行分组
  • add a column with a DEFAULT CONSTRAINT to set the current time to allow groupings on this (only if there are no parallel inserts possible!) 添加带有DEFAULT CONSTRAINT的列以设置当前时间以允许对此分组(仅当不可能并行插入时!)
  • use a staging table to first store your values in an emptied table (as before) and move your data into the real data with a stored procedure (with any additional logic you like) 使用临时表首先将值存储在清空表中(如前所述),然后使用存储过程将数据移动到真实数据中(使用您喜欢的任何其他逻辑)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM