0

我有一个数据库表,其中包含通过从日志文件导入插入的新记录。我想写一个在输入特定新字段时发送警报的作业。到目前为止,我一直在检查该字段中唯一条目的数量,当它增加设定值时,我会收到警报。问题是每次我需要返回并更新查询中的计数。所以只是想知道是否有另一种方法可以做到这一点。

Declare @count as int 
select @count = count(clientkey) from QueryData group by clientkey
If @@ROWCOUNT > 18

EXEC msdb.dbo.sp_send_dbmail @profile_name='DB Admin',
    @recipients = 'joe@mail.com',
    @copy_recipients = 'pete@mail.com',
    @subject = 'GPDB Warning',
    @body = 'A new clientkey is being used in the QueryData table'

感谢任何回应

编辑:

桌子

CREATE TABLE [dbo].[QueryData](
[ImportDate] [datetime] NULL,
[clientKey] [nvarchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[QueryTerms] [nvarchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[UpdatedDate] [datetime] NULL,
[LastSearchDate] [datetime] NULL,
[QueryActivity]  AS (datediff(day,[UpdatedDate],[LastSearchDate])) PERSISTED,
[ImportMethod] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PowerField] [nvarchar](5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
 ) ON [PRIMARY]

因此,当导入发生时,importdate 会更新,并且 updatedDate 字段也会更新。clientKey 字段是我关心的一个字段,一个 clientkey 可以有多行,但我需要知道何时插入尚未插入的新密钥。

4

1 回答 1

1

您可以使用而不是触发器来执行此操作。唯一的并发症是您必须重复INSERT...

CREATE TRIGGER dbo.QueryData_NewClientKey
ON dbo.QueryData
INSTEAD OF INSERT
AS
BEGIN
  IF EXISTS (SELECT 1 FROM inserted AS i
    LEFT OUTER JOIN dbo.QueryData AS q
    ON i.clientkey = q.clientkey
    WHERE q.clientkey IS NULL
  )
  BEGIN
    -- send your e-mail here
  END

  INSERT dbo.QueryData(column1, columns2, etc.)
    SELECT column1, column2, etc. FROM inserted;
END
GO

使用后触发器,您需要能够区分刚刚插入到表中的行和之前存在的行,因此逻辑稍微复杂一些。假设您在表上有一个主键,您可以说:

CREATE TRIGGER dbo.QueryData_NewClientKey
ON dbo.QueryData
FOR INSERT
AS
BEGIN
  IF EXISTS (SELECT 1 FROM dbo.QueryData AS new_data
    INNER JOIN inserted AS i
    ON new_data.key = i.key
    LEFT OUTER JOIN dbo.QueryData AS old_data
    ON i.clientkey = old_data.clientkey
    AND i.key <> old_data.key
    WHERE old_data.key IS NULL
  )
  BEGIN
    -- send your e-mail
  END
END
GO
于 2012-07-05T14:02:24.707 回答