How to get current week dates in SQL Server?
-- Declare temporary variables @day, @today.
Declare @day INT, @today SMALLDATETIME
-- Assign values to temporary variables.
Set @today = CAST(CONVERT(VARCHAR(10), GETDATE(), 101) AS SMALLDATETIME)
-- Now see the output for @today:
Select @today as [Today]
Note: Here iām truncating the time part from current date.
Set @day = DATEPART(dw, @today)
-- Now see the output for @today:
Select @day as [Day]
Note: Here ā4ā means 4th day of current week. So it is Wednesday. But when you are euting this script, your output may or may not differ. If you got 3 as your output, means current day is Tuesday.
-- Declare temporary table '@WeekDateDay'.
Declare @WeekDateDay Table ( DayName varchar(20), Date SMALLDATETIME )
-- Inser data into '@WeekDateDay' table.
INSERT INTO @WeekDateDay
Select 'Sunday', DATEADD(dd, 1 - @day, @today)
union all
Select 'Monday',DATEADD(dd, 2 - @day, @today)
union all
Select 'Tuesday',DATEADD(dd, 3 - @day, @today)
union all
Select 'Wednesday',DATEADD(dd, 4 - @day, @today)
union all
Select 'Thursday',DATEADD(dd, 5 - @day, @today)
union all
Select 'Friday',DATEADD(dd, 6 - @day, @today)
union all
Select 'Saturday',DATEADD(dd, 7 - @day, @today)
-- Now see the output for Current Week dates.
select * from @WeekDateDay
When to use
Example 1: If you want to display current week travelers list
Query:
-- Select Current Week Travelers List.
select *
from dbo.trnxTicket
where DepartureDate in (select Date from @WeekDateDay)
Example 2: If you want to display current week interviews list
Query:
-- Select Current Week Interviewers List.
select *
from dbo.trnxInterview
where InterViewDate in (select Date from @WeekDateDay)
-
CreatedJul 10, 2013
-
UpdatedOct 03, 2020
-
Views3,368
Related Articles
Different types of variables in SQL Server
What is Cross Join in SQL Server
How delete record from parent table when there is Foreign Key relation in SQL Server
What is the differences between CHAR, NCHAR, VARCHAR and NVARCHAR in SQL Server?
How to use Delete Command in SQL Server?
How to add or remove a column from a table in SQL Server?
How to insert values into Identity Column in SQL Server?
How to get a fixed-length value in SQL Server?
What is Left Join (or) Left Outer Join in SQL Server?
What are the different types of Date formats in SQL Server?