Thursday, March 1, 2012

How to get week number from a date in SQL Server

As a developer i beleive that most of the times we need to built our query based on date column. Some times we need to get or find out the week number from a given date. Sql server provides us such an easy way to find out the week number from a date. The function is DATEPART. By using DATEPART function we can calculate week number easily. Please follow my example code to achieve the expected result.

Sample Output:
TSQL_DATEPART Function Example


To run the example find the following code:
CREATE TABLE [dbo].[Employee]
(
 [ID] [int] NULL,
 [Name] [varchar](200) NULL,
 [JoiningDate] [smalldatetime] NULL
)

INSERT INTO EMPLOYEE VALUES(1,'Shawpnendu','Jan 01, 2012')
INSERT INTO EMPLOYEE VALUES(2,'Bimalandu','Jan 10, 2012')
INSERT INTO EMPLOYEE VALUES(3,'Purnendu','Jan 20, 2012')
INSERT INTO EMPLOYEE VALUES(4,'Amalendu','Jan 30, 2012')
INSERT INTO EMPLOYEE VALUES(5,'Chadbindu','Feb 05, 2012')

SELECT *,DATEPART(wk,JoiningDate) [Week Number] FROM EMPLOYEE

Hope now you can retrieve week number from a given date using DATEPART TSQL function.

No comments:

Post a Comment

Write your Comment: