如何将datetime插入time(0)字段

l--*_*''' 2 c# sql sql-server sql-server-2008

我正在做一个批量插入:

// Get the data into the DataTable
//dtData = GetData(...);

// Create an object of SqlBulkCopy
SqlBulkCopy objSBC = new SqlBulkCopy(connection);
// Specify the destination table
objSBC.BulkCopyTimeout = 0;
objSBC.BatchSize = 10000;
objSBC.DestinationTableName = "QuickLabDump";
// Write the data to the SQL Server

objSBC.WriteToServer(QuickLabDump);
Run Code Online (Sandbox Code Playgroud)

我插入的数据表看起来像这样:

QuickLabDump = new DataTable();

QuickLabDump.Columns.Add("Time Collected", typeof(TimeSpan));
QuickLabDump.Columns.Add("Time Entered", typeof(TimeSpan));
QuickLabDump.Columns.Add("Time Completed", typeof(TimeSpan));
QuickLabDump.Columns.Add("Test Time", typeof(TimeSpan));

QuickLabDump.Columns.Add("Date Collected", typeof(DateTime));
QuickLabDump.Columns.Add("Date Entered", typeof(DateTime));
QuickLabDump.Columns.Add("Date Completed", typeof(DateTime));
QuickLabDump.Columns.Add("Test Date", typeof(DateTime));
......
Run Code Online (Sandbox Code Playgroud)

当我从c#(上面的代码)运行批量插入时,我收到以下错误:

The given value of type DateTime from the data source cannot be converted to type time of the specified target column.
Run Code Online (Sandbox Code Playgroud)

我认为问题是我插入typeof(DateTime)到sql server 2008表中time(0)

这是我插入的数据示例:

6:50:00 AM
6:50:00 AM
6:50:00 AM
10:36:00 AM
4:45:00 PM
7:39:00 PM
Run Code Online (Sandbox Code Playgroud)

问题:如何正确定义数据表列,以便将上述时间值插入time(0)列中?

以下是时间(0)字段中数据库表中已存在的值:

14:57:00
14:58:00
14:58:00
14:57:00
10:49:00
13:31:00
14:02:00
14:13:00
14:20:00
14:56:00
15:00:00
Run Code Online (Sandbox Code Playgroud)

这就是我将数据添加到DataTable:

 public DataTable dt;
        public ReadFileIntoDataTable(string inputfile)
        {
            using (GenericParserAdapter parser = new GenericParserAdapter())
            {
                parser.SetDataSource(inputfile);

                char[] delimiters = new char[] { ',' };
                parser.ColumnDelimiter = delimiters[0];
                parser.FirstRowHasHeader = true;
                //parser.SkipDataRows = 10;
                parser.MaxBufferSize = 4096;
                //parser.MaxRows = 500;
                parser.TextQualifier = '\"';

                dt = parser.GetDataTable();   


            }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

TimeSpan而不是DateTime.你可以得到一个TimeSpan 一个DateTime使用DateTime.TimeOfDay.

有关更多类型映射信息,请参阅MSDN上的" SQL Server数据类型映射"页面.

  • @АртёмЦарионов:如果每次有人来到Stack Overflow时我都有一英镑绝对*确定*问题不在X点,但事实证明是在那里,我会变得富有.但是,嘿,不要让我的建议以更加经验的方式进行(以自己的方式测试每一步,一次只有一个字段)会妨碍我. (2认同)