我试图通过使用SQL Server Express 2008中的函数来提高查询可读性。 下面是我正在尝试执行的一个示例。使用函数改进SQL查询
我有一个表,我们存储最大温度每一天的时间阅读,然后我想选择所有天凡8-10AM之间的最高温度比之间的最高温度更大12-2PM
因此,这里是如何像:
DECLARE @TableA TABLE ([Date] DATE, [Time] TIME(0), HighTemp DECIMAL(6,2));
INSERT @TableA VALUES
('2011-09-10','08:00:00',38.15),
('2011-09-10','09:00:00',38.32),
('2011-09-10','10:00:00',38.17),
('2011-09-10','11:00:00',38.10),
('2011-09-10','12:00:00',38.05),
('2011-09-10','13:00:00',38.15),
('2011-09-10','14:00:00',38.30),
('2011-09-11','08:00:00',38.12),
('2011-09-11','09:00:00',38.09),
('2011-09-11','10:00:00',38.07),
('2011-09-11','11:00:00',38.15),
('2011-09-11','12:00:00',38.13),
('2011-09-11','13:00:00',38.11),
('2011-09-11','14:00:00',38.10),
('2011-09-12','08:00:00',38.30),
('2011-09-12','09:00:00',38.33),
('2011-09-12','10:00:00',38.35),
('2011-09-12','11:00:00',38.30),
('2011-09-12','12:00:00',38.25),
('2011-09-12','13:00:00',38.23),
('2011-09-12','14:00:00',38.20)
select distinct [DATE] from @TableA maintbl
where
-- Select the high temp between 08:00:00-10:00:00
(select MAX(HighTemp) from @TableA tmptbl where tmptbl.Time >= '08:00:00' and tmptbl.Time <= '10:00:00' and maintbl.Date = tmptbl.Date)
>
-- Select the high between 12:00:00-14:00:00
(select MAX(HighTemp) from @TableA tmptbl where tmptbl.Time >= '12:00:00' and tmptbl.Time <= '14:00:00' and maintbl.Date = tmptbl.Date)
查询运行良好(快)和上面的查询结果应该是: 2011-09-10 2011-09-12
现在,我试图简化查询Ÿ通过使用检索某一天和时间段的最大tempreture的功能,所以查询更容易阅读,就像这样:
select distinct [DATE] from @TableA maintbl
where GetPeriodHigh(maintbl.Date, '08:00:00', '10:00:00') > GetPeriodHigh(maintbl.Date, '12:00:00', '14:00:00')
而且功能就像这样:
CREATE FUNCTION [dbo].[GetPeriodHigh]
(
@Date date,
@From time,
@To time
)
RETURNS decimal(6,2)
AS
BEGIN
declare @res decimal(6,2)
select @res = MAX(high) from MyTable
where Time >= @from and Time <= @to and Date = @Date
return @res
END
问题是运行查询使用该函数需要LONG时间,实际上我从来没有看到它完成,看起来像是在某种无限循环...
任何想法,为什么是这样的,而且有什么我可以为了简化我的查询吗?
Thx。
你有在桌子上有什么指标,多少次测量,你每天? –