从 SQL 中的无格式文本解析日期 [英] Parse a date from unformatted text in SQL

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

问题描述

我试图找出一种优雅的方法来从包含YYYYMMDD"这样的数据的文本列中获取日期……所以我们可能会看到20060508"作为列中的一个值,我想要能够从查询返回作为日期(2006 年 5 月 8 日).

I'm trying to figure out an elegant way to get a date from a text column that has data like this "YYYYMMDD"...so we might see "20060508" as a value in the column, which I would like to be able to return from a query as a date (May 8, 2006).

如果有足够的时间,我相信我可以一起破解一些东西,但我想到的方法似乎很笨拙,我怀疑有一种方法可以在单个查询中优雅地完成.

I'm sure I can hack something together given enough time, but the approaches I'm thinking of seem pretty kludgy, and I suspect there's a way this can be elegantly done in a single query.

有什么建议吗?

推荐答案

这已经是一个有效的日期 - ISO-8601 格式 - 只需使用:

This is already a valid date - ISO-8601 format - just use:

SELECT CAST('20060508' AS DATETIME)

或者:

SELECT CONVERT(DATETIME, '20060508', 112)

那应该没问题!

为了显示2006 年 5 月 8 日",使用日期转换样式 107 再次转换为 varchar:

In order to get your "May 08, 2006" display, do another convert into varchar, using the date convert style 107:

SELECT CONVERT(VARCHAR(25), CAST('2006-05-08' AS DATETIME), 107)

请参阅此处,了解有关投射和;在 MS SQL 中转换

See here for more information on casting & converting in MS SQL

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

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