从Varchar日期开始的一年 [英] Extact year from Varchar date

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

问题描述

你好朋友我在我的表中有一个列,其中存储日期为dd / MM / yyyy formate ......在varchar中

i只想从yyyy formate中提取年份如何才能我做....给我查询。

Hello friend i have a column in my table which store date in dd/MM/yyyy formate......in varchar
i want to extract only Year from this in yyyy formate how can i do ....give me query for this.

推荐答案

我会将字符串(varchar)转换为Datetime( Google是您的朋友 [ ^ ])然后提取年份部分 [ ^ ]。
I would firast convert the string (the varchar) to Datetime (Google is your friend[^]) and then extract the YEAR part[^].


首先要做的事情:永远不要将日期存储为字符串值 - 它会使现场变得很多,比它需要的要复杂得多因为不同的系统使用不同的日期字符串表示:

First things first: never store dates as string values - it makes live a lot, lot more complex than it needs to be, because different systems use different string representations of dates:
MM/dd/yyyy
MM/dd/yy
dd/MM/yyyy
dd/MM/yy
yyyy-MM-dd
yyMMdd
dd MMM yyyy

等等。如果您将日期值存储为DateTime列,那么您的数据库始终使用的是真实日期的有效值,而不是可能是日期,可能不是,可能是'2213年2月34日',可能是'日期' 。这会让你的软件变得愚蠢!



但是......如果你不能绕过它:

Among others. If you store date values as DateTime columns, then your database is always using a valid value that is a genuine date, rather than a "might be a date, might not, might be '34th Feb 2213', might be 'the date'". This complicates your software to a stupid degree!

But...if you can't get round it:

SELECT SUBSTRING(MyDateColumnAsAString, 7, 4) FROM MyTable

但是当它在生产中崩溃时不要感到惊讶!

But don't be surprised when it crashes in production!


接受您的请求的另一种方式是:



Another way to accede to your request is:

SELECT RIGHT(thedateinstringcolumnname, 4) from tablename





但请注意OriginalGriff和CPallini的建议。



But do take note of advice from OriginalGriff and CPallini.


这篇关于从Varchar日期开始的一年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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