神刀安全网

SQL Query to get Day, Month and Year from Current or any date

Introduction : In this article I am going to share the sql query to find day, month and year from the current or any date using inbuilt DATEPART() or DAY(), MONTH() and YEAR() functions. 


In previous articles i explained How to  split string from comma and get left and right part and  Concatenate rows values as a comma separated string using for xml path and stuff in sql server and  Count number of occurrences of character or word in a string in sql   and  Remove first or last character from string or column in sql server   and  Try catch to handle exception and commit/rollback transaction

Description : Many times we need to get the day, month or year part from the date. Sql server provides functions to get any part from the date/time. Here i have used DATEPART() and  DAY(), MONTH() and YEAR() functions to get any part as per requirement. Here I am using current date from demonstration purpose. just replace the GETDATE() with the actual date if you want to get day, month and year from any other date.

Implementation : Let’s write a sample query to get the desired result

Using DATEPART() to get Day, Month and Year from current date

SELECT DATEPART ( D , GETDATE ()) AS Day , DATEPART ( M , GETDATE ()) AS Month , DATENAME ( YY , GETDATE ()) AS Year

OR

SELECT DATEPART ( DD , GETDATE ()) AS Day , DATEPART ( MM , GETDATE ()) AS Month , DATENAME ( YYYY , GETDATE ()) AS Year

OR 

SELECT DATEPART ( DAY , GETDATE ()) AS Day , DATEPART ( MONTH , GETDATE ()) AS Month , DATENAME ( YEAR , GETDATE ()) AS Year

Using DAY(), MONTH() and YEAR() functions to get Day, Month and Year from current date

SELECT DAY ( GETDATE ()) AS Day , MONTH ( GETDATE ()) AS Month , YEAR ( GETDATE ()) AS Year


Result:

Day
Month
Year
12
3
2016

Now over to you:

A blog is nothing without reader’s feedback and comments. So please provide your valuable feedback so that i can make this blog better and  If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.  

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » SQL Query to get Day, Month and Year from Current or any date

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮