how to extract only the year from the date in sql server 2008?

前端 未结 9 2354
遥遥无期
遥遥无期 2020-12-15 02:09

In sql server 2008, how to extract only the year from the date. In DB I have a column for date, from that I need to extract the year. Is there any function for that?

相关标签:
9条回答
  • 2020-12-15 02:43
    select year(current_timestamp)
    

    SQLFiddle demo

    0 讨论(0)
  • 2020-12-15 02:44
    year(table_column)
    

    Example:

    select * from mytable where year(transaction_day)='2013' 
    
    0 讨论(0)
  • 2020-12-15 02:47

    Simply use

    SELECT DATEPART(YEAR, SomeDateColumn)

    It will return the portion of a DATETIME type that corresponds to the option you specify. SO DATEPART(YEAR, GETDATE()) would return the current year.

    Can pass other time formatters instead of YEAR like

    • DAY
    • MONTH
    • SECOND
    • MILLISECOND
    • ...etc.
    0 讨论(0)
  • DATEPART(yyyy, date_column) could be used to extract year. In general, DATEPART function is used to extract specific portions of a date value.

    0 讨论(0)
  • year(@date)
    year(getdate())
    year('20120101')
    
    update table
    set column = year(date_column)
    whre ....
    

    or if you need it in another table

     update t
       set column = year(t1.date_column)
         from table_source t1
         join table_target t on (join condition)
        where ....
    
    0 讨论(0)
  • 2020-12-15 03:01

    SQL Server Script

    declare @iDate datetime
    set @iDate=GETDATE()
    
    print year(@iDate) -- for Year
    
    print month(@iDate) -- for Month
    
    print day(@iDate) -- for Day
    
    0 讨论(0)
提交回复
热议问题