在sql中复制数据时添加列

发布于 2024-08-20 14:12:27 字数 828 浏览 3 评论 0原文

我正在使用 SqlBulkCopy 将一些记录从一个表批量插入到另一个表中。该查询使用 SqlDataReader 来获取数据。表之间最重要的一个区别(除了在映射中处理的列顺序之外)是目标表具有一个需要添加当前日期的日期列。该日期不在源表中。我怎样才能将其添加到当前运行良好的进程中?

当前的工作代码如下所示:

SqlCommand cmd = new SqlCommand("SELECT * from dbo.source", cn);
            SqlDataReader rdr = cmd.ExecuteReader();                

            using (SqlBulkCopy copy = new SqlBulkCopy(cn))
            {
                copy.ColumnMappings.Add(0, 0);
                copy.ColumnMappings.Add(1, 2);
                copy.ColumnMappings.Add(3, 3);
                copy.ColumnMappings.Add(2, 4);
                copy.ColumnMappings.Add(5, 5);
                copy.ColumnMappings.Add(14, 6);
                copy.DestinationTableName = "destination";
                copy.WriteToServer(rdr);
            }

数据库是 sql 2008 ENT。

I'm using SqlBulkCopy to bulk insert some records from one table into another table. The query is using a SqlDataReader to get the data. The one difference that matters (besides column order which is handled in the mappings) between the tables is that the destination table has a date column into which the current date needs to be added. This date is not in the source table. How can I add this into the current process which is working fine minus this?

Current working code looks like this:

SqlCommand cmd = new SqlCommand("SELECT * from dbo.source", cn);
            SqlDataReader rdr = cmd.ExecuteReader();                

            using (SqlBulkCopy copy = new SqlBulkCopy(cn))
            {
                copy.ColumnMappings.Add(0, 0);
                copy.ColumnMappings.Add(1, 2);
                copy.ColumnMappings.Add(3, 3);
                copy.ColumnMappings.Add(2, 4);
                copy.ColumnMappings.Add(5, 5);
                copy.ColumnMappings.Add(14, 6);
                copy.DestinationTableName = "destination";
                copy.WriteToServer(rdr);
            }

The DB is sql 2008 ENT.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静水深流 2024-08-27 14:12:27

您可以将其添加为由您的 SELECT 返回:

SELECT *, GETDATE() AS CurrentDate from dbo.source

然后为其添加另一个 ColumnMapping 。

You could just add it to be returned by your SELECT:

SELECT *, GETDATE() AS CurrentDate from dbo.source

And then just add another ColumnMapping for it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文