T-SQL provides a lot of functions; for each of them see the doc (google TSQL functionname).
Here is an example that should get you going.
Warning: I explicitly set
DATEFIRST
as per your requirement; it is essential for obtaining the results you want.
Without it, it is also possible but more complex (requires either modulo arithmtic or some case constructs), I would not go for that.
You can run the below code inside Visual Studio (using menu Tools/SQL Server)
DECLARE @mydate DATE = DATEFROMPARTS(2022,1,1);
DECLARE @startdate DATE;
DECLARE @enddate DATE;
DECLARE @wd INT;
DECLARE @wk INT;
DECLARE @dd INT = 1;
SET DATEFIRST 6;
PRINT @@DATEFIRST
PRINT ' '
WHILE @dd < 40
BEGIN
SET @wd=DATEPART(weekday, @mydate)
SET @startdate = DATEADD(day, 1-@wd, @mydate)
SET @enddate = DATEADD(day, 7-@wd, @mydate)
SET @wk = DATEPART(week, @mydate)
PRINT convert(varchar(10),@mydate)+' start='+convert(varchar(10),@startdate)+' end='+convert(varchar(10),@enddate)+' week='+convert(varchar(2),@wk)
PRINT ' '
SET @mydate = DATEADD(day, 1, @mydate)
SET @dd = @dd + 1;
END;
The results would look like this:
6
2022-01-01 start=2022-01-01 end=2022-01-07 week=1
2022-01-02 start=2022-01-01 end=2022-01-07 week=1
2022-01-03 start=2022-01-01 end=2022-01-07 week=1
2022-01-04 start=2022-01-01 end=2022-01-07 week=1
2022-01-05 start=2022-01-01 end=2022-01-07 week=1
2022-01-06 start=2022-01-01 end=2022-01-07 week=1
2022-01-07 start=2022-01-01 end=2022-01-07 week=1
2022-01-08 start=2022-01-08 end=2022-01-14 week=2
2022-01-09 start=2022-01-08 end=2022-01-14 week=2
...
Finally you can convert such code to a single-line SQL e.g.
SET DATEFIRST 6; DECLARE @mydate DATE = DATEFROMPARTS(2022,1,12); DECLARE @wd INT=DATEPART(weekday, @mydate); SELECT DATEADD(day, 1-@wd, @mydate) as startdate,
DATEADD(day, 7-@wd, @mydate) as enddate, DATEPART(week, @mydate) as week