Search code examples
sqlsql-serverdatepart

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.


Solution

  • 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), '-', '_')