如何在sql批量复制中插入具有特定值的列
我正在使用 C# 中的 sql 批量复制使用 excel 中的值填充表。
DataTable dt = new DataTable();
string line = null;
int i = 0;
using (StreamReader sr = File.OpenText(@"c:\temp\table1.csv"))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
dt.Rows.Add(row);
}
}
}
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsoleApplication3.Properties.Settings.daasConnectionString"].ConnectionString))
{
cn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(cn))
{
copy.ColumnMappings.Add(0, 0);
copy.ColumnMappings.Add(1, 1);
copy.ColumnMappings.Add(2, 2);
copy.ColumnMappings.Add(3, 3);
copy.ColumnMappings.Add(4, 4);
copy.DestinationTableName = "Censis";
copy.WriteToServer(dt);
}
}
在上面的代码中,我将 Excel 中的记录插入到表中。但是,我在 Censis 表中多了一列“ProcessID”。对于每次运行,我需要生成一个 GUID 并用它填充此列。
当我使用为该运行的所有行生成的 GUID 进行如上所述的批量复制时,任何人都可以帮助我如何填充 ProcessID 列吗?
I am populating a table with the values in excel using sql bulk copy in c#.
DataTable dt = new DataTable();
string line = null;
int i = 0;
using (StreamReader sr = File.OpenText(@"c:\temp\table1.csv"))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
dt.Rows.Add(row);
}
}
}
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConsoleApplication3.Properties.Settings.daasConnectionString"].ConnectionString))
{
cn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(cn))
{
copy.ColumnMappings.Add(0, 0);
copy.ColumnMappings.Add(1, 1);
copy.ColumnMappings.Add(2, 2);
copy.ColumnMappings.Add(3, 3);
copy.ColumnMappings.Add(4, 4);
copy.DestinationTableName = "Censis";
copy.WriteToServer(dt);
}
}
In the above code, I am inserting the records from excel into the table. But, I have one more column "ProcessID" in the Censis table. For each time run, I need to generate a GUID and populate this column with this.
Can any one help me how to populate the ProcessID column when I do bulk copy as above with a generated GUID for all the rows for that run?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您插入数据库时,请使用函数
newsequentialid
When you do your insert into the database use the function
newsequentialid
谢谢乔恩。但是,我找到了我的问题的答案。我可以用这样的东西。我可以将具有默认值的新 DataColumn 添加到用于批量复制的数据表中。
Thanks JonH. But, I found an answer for my problem. I can use something like this. I can add a new DataColumn with a default value to the datatable which I use for bulk copy.