Learning While Aging

Syntax error converting datetime from character string in XML

If you use XML string as parameter to update your SQL database table as I discussed in my last post, if the server is SQL Server 2000 and the XML string contains a datetime string, you will get a SQL error as this:

Syntax error converting datetime from character string

Cause:

When generating XML string from DataTable object, all DateTime values are converted into strings in ISO 8601 format. However, ISO 8601 format is support only in SQL Server 2005 or higher.

Resolution:

If upgrading SQL Server 2000 to 2005 or higher is not an option, then you will have to manually convert the ISO 8601 formatted datetime strings into the regular datetime strings before passing on to your SQL Server 2000.

Here is the code snippet I used to convert ISO 8601 datetime string to the regular datetime string:

Code Snippet
  1. protected string FormatXMLDateTimeString(string xmlString, string nodeName)
  2. {
  3.     XmlDocument doc = new XmlDocument();
  4.     doc.LoadXml(xmlString);
  5.     XmlNodeList nodes = doc.SelectNodes(nodeName);
  6.     foreach (XmlNode node in nodes[0].ChildNodes)
  7.     {
  8.         if (node.Name.IndexOf("DateTime") != -1) // best way is to use regular expression
  9.         {
  10.             node.InnerXml = DateTime.Parse(node.InnerXml).ToString();
  11.         }
  12.         if (node.InnerXml == "false")  // SQL Server 2000 cannot convert true/false to bit
  13.         {
  14.             node.InnerXml = "0";
  15.         }
  16.         if (node.InnerXml == "true")
  17.         {
  18.             node.InnerXml = "1";
  19.         }
  20.     }
  21.     StringWriter sw = new StringWriter();
  22.     XmlTextWriter xtw = new XmlTextWriter(sw);
  23.     doc.WriteTo(xtw);
  24.     xtw.Close();
  25.     return sw.ToString();
  26. }

Also, as mentioned in the comments in the code snippet, SQL Server 2000 cannot convert true/false to database bit type, so you will need to manually convert them to 1 (true) and 0 (false), otherwise, you will get a SQL error as follows:

Syntax error converting the nvarchar value 'false' to a column of data type bit.

Hope this will help someone.