简体   繁体   中英

DATENAME and DATEPART in SQL

I'm trying to get my EntryDate column in this format 'YYYY_m' for example '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?

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.

FYI - in the future "unsuccessful" doesn't mean anything. Next time post the actual error you are receiving.

How about date_format() ?

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

This is the MySQL way. Your code looks like an attempt to do this in SQL Server.

EDIT:

The following should work in SQL Server:

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

Personally, I might use 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
  • and uses extract to pick of the part of date needed.

working fiddle http://sqlfiddle.com/#!2/63b24/8

DATEPART It is a Datetime function which extract information from date. 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. This function always returns result as varchar

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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