yyyy-mm-dd hh:mm:ss.sss 到 SQL Server 过程中的 ddmmyy [英] yyyy-mm-dd hh:mm:ss.sss to ddmmyy in SQL Server procedures

查看:41
本文介绍了yyyy-mm-dd hh:mm:ss.sss 到 SQL Server 过程中的 ddmmyy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 SQL Server 存储过程中将 yyyy-mm-dd hh:mm:ss.sss 转换为 ddmmyy,但无法做到.有人可以解决这个问题吗?

I am trying to convert yyyy-mm-dd hh:mm:ss.sss to ddmmyy in a SQL Server stored procedure, but can't do it. Can someone sort this thing out?

还需要 (27-Apr-18) 这种格式吗?

and also need (27-Apr-18) in this format also ?

推荐答案

更新

一旦您拥有 Date 数据类型的值,要获得 dd-MMM-yy 格式,您还可以使用 convert和<代码>替换:

Once you have your value as a Date data type, to get to dd-MMM-yy format you can also use a combination of convert and replace:

DECLARE @Date as datetime = GETDATE();

SELECT  @Date As Original, 
        REPLACE(CONVERT(char(9), @Date, 6), ' ', '-') As Result

将返回:

Original                Result
01.05.2018 08:08:29     01-May-18

注意:由于所需的结果格式从 mmddyyy 更改为 ddmmyy,我已经更新了我的答案 - 我所做的只是转换样式 - 从 1 到 3.

Note: I've updated my answer due to the desired result format change from mmddyyy to ddmmyy - All I've changed was the convert style - from 1 to 3.

原答案

如果您的原始值是 DateTime 类型,则它没有显示值.您只需要使用 convert替换:

If your original value is of type DateTime it has no display value. All you need to use is convert and replace:

DECLARE @Date as datetime = GETDATE();

SELECT  @Date As Original, 
        REPLACE(CONVERT(char(8), @Date, 3), '/', '') As Result

Original                Result
26.04.2018 06:56:19     042618

如果您的原始值是字符串类型,您首先将其转换为datetime,然后再转换回具有所需显示格式的字符串:

If your original value is a string type, you first convert it to datetime and then convert back to a string with the desired display format:

DECLARE @StringDate as char(23) = '2018-04-26 07:55:43.003'

SELECT @StringDate As Original,  
       REPLACE(CONVERT(char(8), CONVERT(datetime, @StringDate, 120), 3), '/', '') As Result

Original                    Result
2018-04-26 07:55:43.003     042618

在 Sql Server 2012 或更高版本中,您可以使用 Formatdatetime 转换为您想要的任何字符串表示形式,但 Formatconvertreplace,所以如果你在大表上使用它,你应该考虑使用旧的 convert 代替.
有关详细信息,请阅读 Aaron Bertrand 的 FORMAT() 很好,但是……

In Sql Server 2012 or higher you can use Format to convert the datetime to whatever string representation you want, but Format is slower than convert and replace, so if you are using it on a large table, you should consider using the good old convert instead.
For more information, read Aaron Bertrand's FORMAT() is nice and all, but…

这篇关于yyyy-mm-dd hh:mm:ss.sss 到 SQL Server 过程中的 ddmmyy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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