哪些设置提供SQL Server默认的datetime格式? [英] Which settings provide SQL Server default datetime format?

查看:407
本文介绍了哪些设置提供SQL Server默认的datetime格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有这样的表:



表名DateTimeFormatCheck>





我使用下面的查询来插入:

 插入到[dbo]。[DateTimeFormatCheck]([DateTimeCheck])值('11 / 19/2014 1:29 PM ')

它插入日期像 2014-11-19 13:29:00.000 ,但是我的插入格式( M / d / yyyy h:m tt )不是这样的。



现在我想知道 SQL Server如何检测我提供的字符串日期格式?为什么总是提供这种格式yyyy -MM-dd HH:mm:ss插入后



谢谢

解决方案

不要这样做不要使用字符串而不是日期,并且不要使用文化特定的日期或日期时间格式,这是灾难的秘诀。



SQL Server没有日期格式,只是格式用于将字符串转换为字符串和从字符串转换日期。其中一个是默认的,由服务器的归类控制。您不能假设也不应该依赖于特定的排序规则,因此您应尽可能避免转换。此外,传递字符串值可能会阻止SQL Server在日期列上使用索引,因为它必须将字符串转换为底层列类型。



它更容易和更安全将日期作为日期类型的变量或参数传递。您避免了这种方式的整个转换,避免SQL注入攻击。



没有理由将字符串而不是日期传递到服务器。所有SQL Server客户端(包括ADO.NET)允许您执行参数化查询。 ORM(如NHibernate和Entity Framework)也为日期类型的列生成参数化查询。



无论何时需要创建字符串文字,请使用不变格式,如 20140913 2012-11-07T18:26:20



你可以在撰写国际T-SQL语句中阅读更多信息


Say, I have a table like this :

Table name "DateTimeFormatCheck" >

I used below query to insert :

Insert into [dbo].[DateTimeFormatCheck] ([DateTimeCheck]) values('11/19/2014 1:29 PM')

It inserted date like 2014-11-19 13:29:00.000 , but my insertion format(M/d/yyyy h:m tt) is not like it.

Now i want to know How SQL Server detect my string date format that i provide ? and Why it always provide this format yyyy-MM-dd HH:mm:ss after insertion?

Thanks

解决方案

Don't do that! Don't use strings instead of dates and don't use a culture-specific date or datetime format, it's a recipe for disaster.

SQL Server doesn't have a "date format", just formats it uses to convert dates to and from strings. One of them is the default, controlled by the server's collation. You can neither assume nor should you depend on a specific collation, so you should avoid conversions whenever possible. Moreover, passing a string value can prevent SQL Server from using indexes on date columns because it would have to convert the string to the underlying column type.

It's far easier and safer to pass dates as date-typed variables or parameters. You avoid the entire conversion mess this way, to and from and avoid SQL injection attacks.

There's no reason to pass strings instead of dates to the server. All SQL Server clients (including ADO.NET) allow you to execute parameterized queries. ORMs like NHibernate and Entity Framework also generate parameterized queries for date-typed columns.

Whenever you need to create a string literal, use one of the invariant formats like 20140913 or 2012-11-07T18:26:20

You can read more about it at Writing International T-SQL Statements

这篇关于哪些设置提供SQL Server默认的datetime格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆