简体   繁体   English

带有附加列的sql批量插入

[英]sql bulk insert with additional column

A csv file contains 8 columns (col1, col2, ..., col8) and the name of the file contains the date which has to be inserted into the table as well. csv文件包含8列(col1,col2,...,col8),文件名也包含必须插入表中的日期。

If the number of columns in the table and columns in the csv file are equal the following query imports all the records from the file to the table: 如果表中的列数和csv文件中的列相等,则以下查询将文件中的所有记录导入到表中:

query += "BULK INSERT real_data FROM '" + path + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')";

So far I haven't found a solution to modify the query such that the new records can contain the date extracted from the filename. 到目前为止,我还没有找到修改查询的解决方案,以便新记录可以包含从文件名中提取的日期。 Anyway I have created a function to extract the date: 无论如何我创建了一个提取日期的函数:

DateTime eventTime = extractDate(path);

and would like to insert eventTime into 9th column for each record imported from file. 并且希望将eventTime插入到从文件导入的每个记录的第9列。

Does anyone know how to modify/create query statement to import 8 columns from file and add the date as 9th column for each imported record? 有没有人知道如何修改/创建查询语句从文件导入8列,并为每个导入的记录添加日期为第9列?

Thank you! 谢谢!

You cannot add an "arbitrary column" to the data set being loaded with the BULK INSERT command. 您不能向使用BULK INSERT命令加载的数据集添加“任意列”。 (SSIS packages can do that, if you want to deal with their complexity.) (如果你想处理它们的复杂性,SSIS包可以做到这一点。)

The following trick is a bit complex, but I've used it succesfully several times: 以下技巧有点复杂,但我已多次成功使用它:

  • Determine the name of the extra column and the value to load into it (say, MyDate and 'Jan 1, 1980') 确定额外列的名称和要加载到其中的值(例如,MyDate和'Jan 1,1980')
  • Create a (temporary) default on the table based on that (ATLER TABLE MyTable add constraint DF_TempLoad default 'Jan 1, 1980' for MyDate [ check the syntax, it may be off ] 在表上创建(临时)默认值(ATLER TABLE MyTable添加约束DF_TempLoad默认'1980年1月1日'为MyDate [ 检查语法,它可能关闭 ]
  • Create a (temporary) view on the table, listing only those columns to be bulk inserted 在表上创建(临时)视图,仅列出要批量插入的列
  • Run the BULK INSERT against the view; 对视图运行BULK INSERT; the column not included in the view will be assigned the default value 未包含在视图中的列将被分配默认值
  • Drop the view 放下视图
  • Drop the default constraint. 删除默认约束。

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

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