Error while converting XML date data to SQL column data.

Gani_tpt 1,261 Reputation points

I am trying to insert XML date data to SQL table.

my XML field is "DateRelieved" and its XML element value is "2022-02-25T00:00:00.000Z"

My SQL Table column name is "DateRelieved" and its data type is DateTime.

while processing the code through .net getting below error.

'The given value of type String from the data source cannot be converted to type datetime of the specified target column.'

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
9,162 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,617 questions
{count} votes

Accepted answer
  1. Jack J Jun 22,306 Reputation points Microsoft Vendor

    @Gani_tpt , based on my test, I find that I can still convert your xml value to DateTime field by your code.

    I used the following database design:

    Also, I used the folllowing code:

            DataSet dataSet = new DataSet();  
            string connstr = @"connstr";  
            SqlConnection connection = new SqlConnection(connstr);  
            SqlBulkCopy copy = new SqlBulkCopy(connection);  
            copy.DestinationTableName = "Employee";  
            copy.ColumnMappings.Add("EmpRetired", "EmpRetired");  
            copy.ColumnMappings.Add("CurrentStatus", "CurrentStatus");  
            copy.ColumnMappings.Add("DateRelieved", "DateRelieved");  
            copy.ColumnMappings.Add("EmpId", "EmpId");  
            copy.ColumnMappings.Add("SearchRes_Id", "SearchRes_Id");  

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 30,441 Reputation points

    Have you tried to convert, something like this?

    static void Main(string[] args)
        XElement element = new("DateRelieved", "2022-02-25T00:00:00.000Z");
        DateTime parsed = (DateTime)element;
  2. Olaf Helper 27,301 Reputation points

    SqlBCopy1.ColumnMappings.Add(col1.ColumnName, col1.ColumnName);

    Why do you think there is just one table/+1 column.
    I see the relation SearchRes => Employee => 3 properties.