I been practicing queries, and my current scenario is to find the nearest Saturday for a given date. After i got the logic down, i came up with a, whats looks like a long and messy query. And I was wondering if there is a way to simplify this. Here's my query
DECLARE @DATE DATE
SET @DATE ='2013-09-13'
IF DATENAME(DW,@DATE) = 'SUNDAY'
BEGIN
SELECT DATEADD(DAY,-1,@DATE) AS DATE, 'IS THE NEAREST SATURDAY'
END
ELSE IF DATENAME(DW,@DATE) = 'MONDAY'
BEGIN
SELECT DATEADD(DAY,-2,@DATE) AS DATE, 'IS THE NEAREST SATURDAY'
END
ELSE IF DATENAME(DW,@DATE) = 'TUESDAY'
BEGIN
SELECT DATEADD(DAY,-3,@DATE) AS DATE, 'IS THE NEAREST SATURDAY'
END
ELSE IF DATENAME(DW,@DATE) = 'WEDNESDAY'
BEGIN
SELECT DATEADD(DAY,3,@DATE) AS DATE, 'IS THE NEAREST SATURDAY'
END
ELSE IF DATENAME(DW,@DATE) = 'THURSDAY'
BEGIN
SELECT DATEADD(DAY,2,@DATE) AS DATE, 'IS THE NEAREST SATURDAY'
END
ELSE IF DATENAME(DW,@DATE) = 'FRIDAY'
BEGIN
SELECT DATEADD(DAY,1,@DATE) AS DATE, 'IS THE NEAREST SATURDAY'
END
ELSE IF DATENAME(DW,@DATE) = 'SATURDAY'
BEGIN
SELECT CONVERT(NVARCHAR,@DATE) + ' IS SATURDAY' AS DATE_DOW
END
As we can see the query is long and runs multiple IFs to look for TRUE condition. Please don't write the query, just hints. I would like to work on the query myself.