在SQL Server中转换日期时间 [英] Convert datetime in sql server

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

问题描述

如何转换下面的日期时间格式

How can i convert the datetime format below

2010-10-25 11:13:36.700

进入

2010年10月25日 2010-10-25 00:00:00.000

推荐答案

要获取"2010年10月25日"

假定值以字符串形式提供,而不是DATETIME数据类型:

To get "25-Oct-2010"

Assuming the value is supplied as a string, not a DATETIME data type:

SELECT REPLACE(CONVERT(VARCHAR, CAST('2010-10-25 11:13:36.700' AS DATETIME), 106), ' ', '-')

有关其他格式,请参见 CAST/CONVERT文档,尽管您请求的其中一项需要后处理.

See the CAST/CONVERT documentation for other formats, though the one you requested requires post-processing.

效果最好的方法是使用DATEADD&DATEDIFF:

The best performing means is to use DATEADD & DATEDIFF:

SELECT DATEADD(d, DATEDIFF(dd, 0, '2010-10-25 11:13:36.700'), 0)

参考文献:

WITH sample AS (
   SELECT CAST('2010-10-25 11:13:36.700' AS DATETIME) dt)
SELECT REPLACE(CONVERT(VARCHAR, s.dt, 106), ' ', '-') AS col1,
       DATEADD(d, DATEDIFF(dd, 0, s.dt), 0) AS col2
  FROM sample s

返回:

col1          col2
-------------------------------------
25-Oct-2010   2010-10-25 00:00:00.000

附录

由于您使用的是SQL Server 2005,因此可以通过创建允许使用.NET日期格式的SQLCLR函数来简化日期格式设置.

Addendum

Being that you're on SQL Server 2005, you could make date formatting easier for yourself by creating a SQLCLR function that would allow you to use the .NET date formatting.

这篇关于在SQL Server中转换日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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