我有一个表格可以记录我们的应用程序中的警报,如下所示,我们会报告这些警报。但是,有时候,由于某种原因,我们可能会忽略一些警报或一组警报,例如,运行测试,或者有人忘记在该时间段内关闭警报。
我想创建一个配置表,例如,ChartId,StartTime和EndTime,以及一个Active位(即,使用此规则或不使用)。
以下脚本大部分都有效,除非我在给定ChartId的@ReportAlarmOverride表中有多行...说我们要忽略下午2:00 - 下午3:00对ChartId = 1的警报然后再从下午4点到下午5点。
DECLARE @ReportAlarmOverride TABLE
(
ReportAlarmOverrideId INT IDENTITY(1,1),
ChartId INT,
Active BIT,
StartTime DATETIME,
EndTime DATETIME,
LastModifiedTime DATETIME DEFAULT GETDATE()
)
INSERT INTO @ReportAlarmOverride
SELECT 1, 1, GETDATE() - 1, NULL, NULL UNION
SELECT 3, 1, GETDATE() - 1, GETDATE(), NULL UNION
SELECT 5, 1, GETDATE() - 3, NULL, NULL UNION
SELECT 7, 1, GETDATE() - 1, NULL, GETDATE() --UNION
--SELECT 3, 1, '2012-11-12 16:09:20', '2012-11-12 16:09:21', NULL --Adding this row makes SELECT below stop working
SELECT Alarm.AlarmTime, AlarmOverride.StartTime, AlarmOverride.EndTime, *
FROM dbo.AlarmLogSummary Alarm
JOIN dbo.AlarmConfiguration AlarmConfig ON Alarm.AlarmConfigurationId = AlarmConfig.AlarmConfigurationId
LEFT JOIN @ReportAlarmOverride AlarmOverride ON AlarmConfig.ChartId = AlarmOverride.ChartId
WHERE Alarm.AlarmTime > GETDATE() - 2
AND ((AlarmOverride.Active = 1 AND Alarm.AlarmTime NOT BETWEEN AlarmOverride.StartTime AND ISNULL(AlarmOverride.EndTime, GETDATE()))
OR Active = 0)
答案 0 :(得分:3)
尝试将此逻辑放在WHERE子句中,而不是加入@ReportAlarmOverride表,如下所示:
DECLARE @ReportAlarmOverride TABLE
(
ReportAlarmOverrideId INT IDENTITY(1,1),
ChartId INT,
Active BIT,
StartTime DATETIME,
EndTime DATETIME,
LastModifiedTime DATETIME DEFAULT GETDATE()
)
INSERT INTO @ReportAlarmOverride
SELECT 1, 1, GETDATE() - 1, NULL, NULL UNION
SELECT 3, 1, GETDATE() - 1, GETDATE(), NULL UNION
SELECT 5, 1, GETDATE() - 3, NULL, NULL UNION
SELECT 7, 1, GETDATE() - 1, NULL, GETDATE() --UNION
--SELECT 3, 1, '2012-11-12 16:09:20', '2012-11-12 16:09:21', NULL --Adding this row makes SELECT below stop working
SELECT Alarm.AlarmTime, *
FROM dbo.AlarmLogSummary Alarm
JOIN dbo.AlarmConfiguration AlarmConfig ON Alarm.AlarmConfigurationId = AlarmConfig.AlarmConfigurationId
WHERE Alarm.AlarmTime > GETDATE() - 2
AND NOT EXISTS(SELECT 1 FROM @ReportAlarmOverride Override
WHERE Override.ChartId = AlarmConfig.ChartId
AND Override.Active = 1
AND Alarm.AlarmTime BETWEEN Override.StartTime AND ISNULL(Override.EndTime, GETDATE())
唯一的问题是您将无法在查询中返回覆盖数据。我希望不需要它。