Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Month from Calendar Week (SQL Server)

I have the following problem:

In Microsoft's SQL Server, I have a table where a year and a calendar week (starting with Monday) is stored. Now, I want to write a function which returns the month in which this calendar week starts (i.e. if the Monday is the 31th of July, it should return "7"). I haven't found a built-in function to achieve this task and I have no idea to implement this easily. So I hope for your help and ideas!

Thanks in advance, Melvin

like image 786
Melvin Smith Avatar asked Apr 17 '26 22:04

Melvin Smith


1 Answers

Query

DECLARE @WEEK INT;
DECLARE @YEAR INT;
SET @week = 3
SET @year = 2014

SELECT DATEPART(MM,CAST(CONVERT(CHAR(3),
                 DATEADD(WW,@WEEK - 1,
                 CONVERT(datetime,'01/01/'+CONVERT(char(4),@Year)))
                 ,100)+ ' 1900' AS DATETIME)) AS [MONTH]

Result

╔═══════╗
║ MONTH ║
╠═══════╣
║     1 ║
╚═══════╝
like image 108
M.Ali Avatar answered Apr 19 '26 12:04

M.Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!