SQL - 从日期时间字段中仅选择“年份”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32924209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:04:56  来源:igfitidea点击:

SQL - Select only 'Year' from DateTime field

sqlselectsql-server-2012

提问by kekimian

My DB is an SQL Server 2012. I try to select only the year from my datetime filed. The date format is dd/mm/yyyy 00:00:00. Here is my queries:

我的数据库是 SQL Server 2012。我尝试仅从我提交的日期时间中选择年份。日期格式为 dd/mm/yyyy 00:00:00。这是我的查询:

SELECT 
       ,YEAR(DateTime)
FROM MayTable

But when I run my queries I get this error:

但是,当我运行查询时,出现此错误:

Conversion failed when converting date and/or time from character string.

从字符串转换日期和/或时间时转换失败。

回答by Martin Smith

You should store this information in a column of appropriate datatype in the first place.

您应该首先将此信息存储在适当数据类型的列中。

But if I understand your comment correctly this is not a table of your own design. You can use

但是,如果我正确理解您的评论,这不是您自己设计的表格。您可以使用

SELECT CAST(SUBSTRING(DateTime, 7, 4) AS INT)
FROM   MyTable; 

Or

或者

SET DATEFORMAT DMY;

SELECT YEAR(DateTime)
FROM   MyTable; 

回答by sumanth

Another process to select year from DateTime data type is

从 DateTime 数据类型中选择年份的另一个过程是

select datepart(yyyy,ColumnName) from table

for more details visit this link

有关更多详细信息,请访问此 链接