conversion of a varchar data type to a datetime data type resulted in an out-of-range value

后端 未结 7 2411
梦毁少年i
梦毁少年i 2020-11-27 06:33

I have the following piece of inline SQL that I run from a C# windows service:

UPDATE table_name SET 
    status_cd = \'2\', 
    sdate = CAST(\'03/28/2011 1         


        
7条回答
  •  粉色の甜心
    2020-11-27 07:29

    I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.

    You better execute set datetime (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
    Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.

    To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').

    For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)

提交回复
热议问题