如何动态创建视图以根据会计年度(财政年度)获取数据。
让我们看一下示例数据,其中 im 具有示例数据。
Declare @t table(StartDate date )
insert into @t values('04/01/2012'),
('01/01/2012'),
('09/15/2013'),
('04/01/2014'),
('01/01/2015'),
('09/15/2015'),
('04/01/2016'),
('01/01/2017'),
('09/15/2016')
举个例子,如果我今天运行了我需要从 2016 年 3 月到 2017 年 4 月获取的视图。如果我在 2017 年 5 月运行视图,我需要获取从 2017 年 3 月到 2017 年 5 月的数据。我可以在 Sql 服务器脚本或存储过程中解决它,但我如何在动态视图或视图中实现相同的结果。建议我 !
我的脚本
DECLARE @STARTDATE DATETIME, @ENDDATE DATETIME,@CURR_DATE DATETIME
SET @CURR_DATE='2016-06-01'
IF MONTH(@CURR_DATE) IN (1,2,3)
BEGIN
SET @STARTDATE= CAST( CAST(YEAR(@CURR_DATE)-1 AS VARCHAR)+'/04/01' AS DATE)
SET @ENDDATE= CAST( CAST(YEAR(@CURR_DATE) AS VARCHAR)+'/03/31' AS DATE)
END
ELSE
BEGIN
SET @STARTDATE= CAST( CAST(YEAR(@CURR_DATE) AS VARCHAR)+'/04/01' AS DATE)
SET @ENDDATE= CAST( CAST(YEAR(@CURR_DATE)+1 AS VARCHAR)+'/03/31' AS DATE)
END
select * from @t
where StartDate between
@STARTDATE AND @ENDDATE
order by year (StartDate)
它为财政年度(2016-2017)提供了我想要的数据但是我如何使用它并创建一个视图
select t.*,getdate()
from @t t
where year(startdate) * 100 + month(startdate) >=
case
when month(getdate()) in (1,2,3) then (year(getdate()) * 100) + 3 - 100
else (year(getdate()) * 100) + 3
end
您可以在视图中将cte
与基于当前日期(GETDATE()
)的日期一起使用:
;WITH cte AS (
SELECT CASE WHEN MONTH(GETDATE()) IN (1,2,3) THEN CAST( CAST(YEAR(GETDATE())-1 AS VARCHAR)+'/04/01' AS DATE) ELSE CAST( CAST(YEAR(GETDATE()) AS VARCHAR)+'/04/01' AS DATE) END AS StartDate,
CASE WHEN MONTH(GETDATE()) IN (1,2,3) THEN CAST( CAST(YEAR(GETDATE()) AS VARCHAR)+'/03/31' AS DATE) ELSE CAST( CAST(YEAR(GETDATE())+1 AS VARCHAR)+'/03/31' AS DATE) END AS EndDate
)
SELECT t.*
FROM YourTable t
INNER JOIN cte c
ON t.StartDate between c.StartDate AND c.EndDate
ORDER BY year(t.StartDate)
如果您已经在脚本\存储过程中计算了代码,则可以在表值用户定义函数中重用此类代码。
这样,您将能够像查询视图一样查询 UDF。
你可以尝试这样的事情:
select t.*
from @t t
cross join (
select startdate = case
when MONTH(@CURR_DATE) IN (1,2,3)
then CAST( CAST(YEAR(@CURR_DATE)-1 AS VARCHAR)+'/04/01' AS DATE)
else CAST( CAST(YEAR(@CURR_DATE) AS VARCHAR)+'/04/01' AS DATE)
end) s
cross join (
select enddate = case
when MONTH(@CURR_DATE) IN (1,2,3)
then CAST( CAST(YEAR(@CURR_DATE) AS VARCHAR)+'/03/31' AS DATE)
else CAST( CAST(YEAR(@CURR_DATE)+1 AS VARCHAR)+'/03/31' AS DATE)
end) e
where t.StartDate between s.startdate and e.enddate
order by year (t.StartDate)