我为每个月创建了一个视图,但这仅适用于本月。我正试图找到一种可以让它变得动态的方法。我有这个视图,它被存储过程调用,但似乎我错过了一些东西。
这是我的视图脚本
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = 'december_permonth_view')
DROP VIEW december_permonth_view <--range from Jan to dec
GO
CREATE VIEW december_permonth_view <--range from Jan to dec
AS
SELECT *
FROM TblGPSCur
WHERE PHILTIME BETWEEN '2014-12-01 00:00:00.000' AND '2014-12-31 23:59:59.000' <--dont know how to make it dynamic
GO
现在这是我的存储过程,它调用上面提到的视图
CREATE PROCEDURE ProcessByMonth
@from_date datetime ,
@to_date datetime
AS
BEGIN
DECLARE @month AS INT
SET @month = (SELECT MONTH(GETDATE()))
SET NOCOUNT ON;
IF @month = '1'
BEGIN
SELECT * january_permonth_view
END
IF @month = '2'
BEGIN
SELECT * february_permonth_view
END
IF @month = '3'
BEGIN
SELECT * march_permonth_view
END
IF @month = '4'
BEGIN
SELECT * april_permonth_view
END
IF @month = '5'
BEGIN
SELECT * may_permonth_view
END
IF @month = '6'
BEGIN
SELECT * june_permonth_view
END
IF @month = '7'
BEGIN
SELECT * july_permonth_view
END
IF @month = '8'
BEGIN
SELECT * august_permonth_view
END
IF @month = '9'
BEGIN
SELECT * september_permonth_view
END
IF @month = '10'
BEGIN
SELECT * october_permonth_view
END
IF @month = '11'
BEGIN
SELECT * november_permonth_view
END
IF @month = '12'
BEGIN
SELECT * december_permonth_view
END
END
GO
有人可以在我出错的地方帮助我。
感谢。
答案 0 :(得分:1)
与所有这些观点的交易是什么?而不是创建太多的视图......仅仅创建一个包含日期范围的存储过程(两个date
s ... NOT datetime
s)并执行它并不简单一个select语句,用于过滤该日期范围的结果集?
create procedure ProcessByMonth
@from_date datetime ,
@to_date datetime
as
begin
select * from TblGPSCur where PHILTIME between @from_date and @to_date;
end
go
这就是你所需要的一切。无需过度设计整个事情