如何使TRIGGER到我的表SQL

时间:2013-01-31 06:48:29

标签: sql sql-server sql-server-2005

我有这张桌子:

 CREATE TABLE [Alerts]
(
  [Timestamp] datetime,
  [Status] int
)

INSERT INTO [Alerts] ([Timestamp], [Status])
  VALUES
    ('2013-1-1 00:00:00', 1),
    ('2013-1-1 00:00:05', 1),
    ('2013-1-1 00:00:10', 2),
    ('2013-1-1 00:00:15', 2),
    ('2013-1-1 00:00:20', 0),
    ('2013-1-1 00:00:25', 1),
    ('2013-1-1 00:00:30', 1),
    ('2013-1-1 00:00:32', 2),
    ('2013-1-1 00:00:35', 2),
    ('2013-1-1 00:00:40', 0),
    ('2013-1-1 00:00:45', 0),
    ('2013-1-1 00:00:50', 0) 



我如何通过以下代码触发:

SELECT
  MIN ([main].[Start]) AS [STOP_Begin],
  [main].[End] AS [STOP_End],
  DATEDIFF(s, MIN([main].[Start]), [main].[End]) AS [Interval_Second]
FROM
(
  SELECT
    [starts].[Start],
    MIN([ends].[Timestamp]) AS [End]
  FROM
  (
    SELECT
      [Timestamp] AS [Start]
    FROM [Alerts]
    WHERE [Status] = 0
  ) AS [starts] LEFT JOIN [Alerts] AS [ends]
  ON  [starts].[Start] < [ends].[Timestamp]
  AND [ends].[Status] <> 0
  GROUP BY
    [starts].[Start]
) AS [main]
GROUP BY
  [main].[End]
ORDER BY 1


所以每次我在表[警报]中添加新输入时,
它会自动更改新表。
我应该制作新桌子还是怎样?
请看这LINK

像我的选择代码那样执行相同操作的触发器代码,只需说新表名 newtable 所以每次添加新输入时都不需要使用我的选择代码

1 个答案:

答案 0 :(得分:0)

要实际回答您的问题,假设您已准备好此表:

CREATE TABLE NewTable 
(   Stop_Begin      DATETIME,
    Stop_End        DATETIME,
    Interval_Second INT
);

您可以创建一个触发器,每次将记录添加到警报时刷新此表:

CREATE TRIGGER Alerts_Insert ON Alerts
FOR INSERT
AS
    TRUNCATE TABLE NewTable;

    INSERT NewTable
    SELECT  MIN ([main].[Start]) AS [STOP_Begin],
            [main].[End] AS [STOP_End],
            DATEDIFF(s, MIN([main].[Start]), [main].[End]) AS [Interval_Second]
    FROM    (   SELECT  [starts].[Start],
                        MIN([ends].[Timestamp]) AS [End]
                FROM    (   SELECT  [Timestamp] AS [Start]
                            FROM    [Alerts]
                            WHERE   [Status] = 0
                        ) AS [starts] 
                        LEFT JOIN [Alerts] AS [ends]
                            ON  [starts].[Start] < [ends].[Timestamp]
                            AND [ends].[Status] <> 0
                GROUP BY [starts].[Start]
            ) AS [main]
    GROUP BY [main].[End]
    ORDER BY 1; 

<强> SQL Fiddle for Trigger

这几乎肯定是糟糕的设计,除非您从NewTable中选择Alerts 更频繁地插入NewTable,选择查询不是即时的。在99%的情况下,更实际的方法是将CREATE VIEW dbo.NewTable AS SELECT MIN ([main].[Start]) AS [STOP_Begin], [main].[End] AS [STOP_End], DATEDIFF(s, MIN([main].[Start]), [main].[End]) AS [Interval_Second] FROM ( SELECT [starts].[Start], MIN([ends].[Timestamp]) AS [End] FROM ( SELECT [Timestamp] AS [Start] FROM [Alerts] WHERE [Status] = 0 ) AS [starts] LEFT JOIN [Alerts] AS [ends] ON [starts].[Start] < [ends].[Timestamp] AND [ends].[Status] <> 0 GROUP BY [starts].[Start] ) AS [main] GROUP BY [main].[End] ORDER BY 1; 视为一种观点:

NewTable

<强> SQL Fiddle for View

比较两个SQL Fiddles,您可以看到右侧的SQL保持不变,结果相同。但是,该视图避免了必须维护Alerts以减少插入{{1}}的开销,减少出错的地方。