[英]what is the correct way to format a datetime in SQL server datetime field
I have a dateTime object in C# and i want to do an insert into SQL Server datetime field. 我在C#中有一个dateTime对象,我想插入SQL Server datetime字段。 What is the correct format for this? 这是什么格式?
The correct way to do this is by using a parameterised query, not text formatting. 执行此操作的正确方法是使用参数化查询, 而不是文本格式。 Then you can just use a strongly-typed SqlDbType.DateTime
parameter. 然后你可以使用强类型的SqlDbType.DateTime
参数。
(If you absolutely must use text formatting to do this - and I strongly recommend against it - then something like yyyyMMdd HH:mm:ss
should do the trick.) (如果你绝对必须使用文本格式来执行此操作 - 我强烈建议不要这样做 - 那么yyyyMMdd HH:mm:ss
应该可以解决问题。)
To expand on @Luke's answer I came across this bug just the other day. 为了扩展@Luke的答案,我前几天遇到了这个bug。
The yyyy-MM-dd HH:mm:ss
format has a locale/language issue on SQL Server 2005 (an example is French), but is fixed in SQL 2008: yyyy-MM-dd HH:mm:ss
格式在SQL Server 2005上有一个语言环境/语言问题(例如法语),但在SQL 2008中修复了:
So, do NOT use this format: yyyy-MM-dd HH:mm:ss
(space separator). 所以,不要使用这种格式: yyyy-MM-dd HH:mm:ss
(空格分隔符)。
Only use: yyyy-MM-ddTHH:mm:ss
("T" separator) or yyyyMMdd HH:mm:ss
(no dash delimiters) 仅使用: yyyy-MM-ddTHH:mm:ss
(“T”分隔符)或yyyyMMdd HH:mm:ss
(无破折号分隔符)
Important if you're generating scripts that include datetime
constants. 如果要生成包含datetime
常量的脚本,则很重要。
See Jamie Thomson's article on SQL Blog 请参阅Jamie Thomson关于SQL博客的文章
use SET DATEFORMAT 使用SET DATEFORMAT
a sample took from here 从这里取样
SET NOCOUNT ON
CREATE TABLE X(EXAMPLE INT, D SMALLDATETIME)
-- EXAMPLE 1
SET DATEFORMAT MDY
INSERT INTO X VALUES (1, '10/30/56')
-- EXAMPLE 2
SET DATEFORMAT YDM
INSERT INTO X VALUES (2, '56/31/10')
-- EXAMPLE 3
SET DATEFORMAT YMD
INSERT INTO X VALUES (3, '56/10/31')
SELECT * FROM X
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.