SQL Server 日期格式函数 [英] SQL Server date format function

查看:22
本文介绍了SQL Server 日期格式函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SELECT CONVERT(VARCHAR(10), GETDATE(), 105)  

此查询返回 [DD-MM-YYYY] 中的日期格式为 varchar.我需要 sql server 中日期时间数据类型的相同格式.请帮帮我

This query return the date in the [DD-MM-YYYY] format as varchar. I need the same format in datetime datatype in sql server. Pls help me out

推荐答案

在 SQL Server 中,DATETIME 数据类型存储为 2 个 4 字节整数,因此没有像这样的特定格式.

In SQL Server, a DATETIME datatype is stored as 2 4-byte integers so as such doesn't have a particular formatting like this.

如果要以特定格式返回日期,则需要使用指定的适当格式标识符将其转换为 VARCHAR.

If you want to return the date in a specific format, you need to CONVERT it to VARCHAR with the appropriate format identifier specified.

如果您在 VARCHAR 中有一个日期时间,并且想将它存储在 SQL Server 的 DATETIME 字段中,那么您应该确保将该值以始终可以安全解释的格式传递给 SQL.例如dd/mm/YYYY 格式不安全,因为取决于设置,它可以在进入时被视为 mm/dd/yyyy.安全格式是:

If you have a datetime in a VARCHAR and want to store that in a DATETIME field in SQL Server, then you should make sure you pass that value to SQL in a format that will always be safely interpreted. e.g. dd/mm/YYYY format is not safe as depending on settings, it could be treated as mm/dd/yyyy when it goes in. Safe formats are:

yyyyMMdd
yyyy-MM-ddThh:mi:ss.mmm

例如

INSERT MyTable (DateField) VALUES ('01/10/2010') -- dd/MM/yyyy not safe
INSERT MyTable (DateField) VALUES ('20101001') -- yyyyMMdd safe

更新:
当您选择一个 DATETIME 字段(GETDATE()、字段、变量....)时,您在 SSMS 中看到的是一个格式化的值,因为这对您有用,而不是显示它是实际的内部 8 字节表示.

Update:
When you SELECT a DATETIME field (GETDATE(), field, variable....) what you see in SSMS is a formatted value as this is what is useful to you, instead of it showing it's actual internal 8byte representation.

这篇关于SQL Server 日期格式函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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