简体   繁体   English

SQL中的DATENAME和DATEPART

[英]DATENAME and DATEPART in SQL

I'm trying to get my EntryDate column in this format 'YYYY_m' for example '2013_04'. 我正在尝试以“ YYYY_m”格式获取我的EntryDate列,例如“ 2013_04”。

This code has been unsuccessful 该代码未成功

DATENAME (YYYY, EntryDate) + '_' + DATEPART (M, EntryDate) 

Attempts using DATEFORMAT have also been unsuccessful, stating there was syntax error at ',' after the M. What code would work instead? 使用DATEFORMAT的尝试也没有成功,指出在M之后的','处存在语法错误。什么代码可以代替呢?

Thank you. 谢谢。

select DATENAME (YYYY, EntryDate) 
      + '_' 
      + right('0' + convert(varchar(2),datepart (MM, EntryDate)), 2)

You have to convert the result of DATEPART() to a character string in order for the + to perform an append. 您必须将DATEPART()的结果转换为字符串,才能使+执行附加操作。

FYI - in the future "unsuccessful" doesn't mean anything. 仅供参考-将来,“不成功”并不意味着任何事情。 Next time post the actual error you are receiving. 下次发布您收到的实际错误。

How about date_format() ? date_format()怎么样?

select date_format(EntryDate, '%&Y_%m')

This is the MySQL way. 这是MySQL的方式。 Your code looks like an attempt to do this in SQL Server. 您的代码看起来像是在SQL Server中执行此操作的尝试。

EDIT: 编辑:

The following should work in SQL Server: 以下应在SQL Server中工作:

select DATENAME(year, EntryDate) + '_' + RIGHT('00' + DATEPART(month, EntryDate), 2)

Personally, I might use convert() : 就个人而言,我可能会使用convert()

select replace(convert(varchar(7), EntryDate, 121), '-', '_')

For example: 例如:

SELECT concat(EXTRACT(YEAR FROM '2015/1/1'), '_', 
         LPAD(extract(month from '2014/1/1'),2,'0')) AS OrderYear

This uses 这使用

  • concat to combine strings 结合字符串
  • lpad to place a leading 0 if month is one digit 如果月份是一位数字,则lpad放置前导0
  • and uses extract to pick of the part of date needed. 并使用摘录选择所需日期的一部分。

working fiddle http://sqlfiddle.com/#!2/63b24/8 工作小提琴http://sqlfiddle.com/#!2/63b24/8

DATEPART It is a Datetime function which extract information from date. DATEPART这是一个Datetime函数,用于从日期中提取信息。 This function always returns result as integer type. 此函数始终以整数类型返回结果。

SELECT DATEPART(month, '2009-01-01 00:00:00:000') as month
it is return "1" as an integer:

DATENAME It is also another Datetime function which to extract information from date. DATENAME这也是另一个Datetime函数,用于从日期中提取信息。 This function always returns result as varchar 此函数始终以varchar返回结果

SELECT DATENAME(month, '2009-01-01 00:00:00:000')  as month
it is return "January". 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM