I have 2 tables:
- It's regular table that contain information about calendar dates
- It's WITH comon table that contains other calendar dates with parameters that user can pick by himself.
My task is to create view that will show those two tables in one table.
First table is regular it's named CalendarDates so it's simple. It contains normal columns like: day, month, quarter, year, formatedfulldate etc. Second table:
DECLARE @Year INT
DECLARE @Month INT
DECLARE @FullDate DATE = DATEFROMPARTS(@Year, @Month, 1);
WITH FullDate
AS (
SELECT cast(DATEADD(yy, DATEDIFF(yy, 0, @FullDate), 0) AS DATE) AS FirstDayInCurrentYear
,cast(DATEADD(dd, - 1, DATEADD(yy, DATEDIFF(yy, 0, @FullDate) + 1, 0)) AS DATE) AS LastDayInCurrentYear
,cast(DATEADD(month, DATEDIFF(month, 0, @FullDate), 0) AS DATE) AS FirstDayInCurrentMonth
,cast(EOMONTH(@FullDate) AS DATE) AS LastDayInCurrentMonth
)
Select * from FullDate
I can Join them doing:
Select * FROM FullDate
JOIN CalendarDates cal ON @FullDate = cal.formatedfulldate
But before this I have to do second table query with declaring parameters.
I need to create one view that will merge two tables and show resault depend from user paramters: @Year INT and @Month INT
I know that View can not contain parameters so I tried with function. It's blocked me on that part:
DECLARE @FullDate DATE = DATEFROMPARTS(@Year, @Month, 1);
There is code of function:
CREATE FUNCTION vv_FullDate
(
@Year INT ,@Month INT, @FullDate DATE = DATEFROMPARTS(@Year, @Month, 1)
)
returns table
AS RETURN
WITH FullDate
AS (
SELECT cast(DATEADD(yy, DATEDIFF(yy, 0, @FullDate), 0) AS DATE) AS FirstDayInCurrentYear
,cast(DATEADD(dd, - 1, DATEADD(yy, DATEDIFF(yy, 0, @FullDate) + 1, 0)) AS DATE) AS LastDayInCurrentYear
,cast(DATEADD(month, DATEDIFF(month, 0, @FullDate), 0) AS DATE) AS FirstDayInCurrentMonth
,cast(EOMONTH(@FullDate) AS DATE) AS LastDayInCurrentMonth
)
If anyone can help with this or know better way please let me know. Thanks