SQL 无法在列中插入转换后的日期时间

SQL Unable to Insert Converted DateTime in Column

我很困惑为什么我无法将转换后的日期值插入到我的 table 列中,而它的输出是相同的。

错误:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Conversion failed when converting date and/or time from character string

成功(硬编码日期时间):

cmd.CommandText = @"INSERT INTO [TestDB].[Cat1].[Table1] (CreatedOn) 
                    VALUES ('2019-08-22 23:59:59.000')";

失败(转换后的日期时间):

cmd.CommandText = @"INSERT INTO [TestDB].[Cat1].[Table1] (CreatedOn) 
                    VALUES ('@CreatedOn')";

//value below has the same output as above (2019-08-22 23:59:59.000)
cmd.Parameters.AddWithValue("@CreatedOn", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

//below failed too
cmd.Parameters.AddWithValue("@CreatedOn", DateTime.Now);

列类型:

'2019-08-22 23:59:59.000'datetime 数据类型 明确(它与新的日期和时间数据类型)。例如,如果您是英国人,那么以下操作将失败:

SET LANGUAGE BRITISH;
SELECT CONVERT(datetime,'2019-08-22 23:59:59.000');

这是因为SQL服务器读取格式为yyyy-dd-MM的日期,一年中没有22个月。如前所述,它适用于较新的数据类型,或者如果您是美国人(但您应该 编写与语言无关的代码):

SET LANGUAGE BRITISH; --English
SELECT CONVERT(datetime2(3),'2019-08-22 23:59:59.000');
SELECT CONVERT(datetimeoffset(0),'2019-08-22 23:59:59.000');

SET LANGUAGE ENGLISH; --American. Confusing, right? :)
SELECT CONVERT(datetime,'2019-08-22 23:59:59.000');

一种方法是使用明确的格式,它不受数据类型或语言的影响:

SET LANGUAGE BRITISH;
SELECT CONVERT(datetime,'2019-08-22T23:59:59.000');

否则你可以告诉 SQL 服务器 style 值(在本例中 121):

SET LANGUAGE BRITISH;
SELECT CONVERT(datetime,'2019-08-22 23:59:59.000',121);