将新值输入某个列时的操作

时间:2012-07-05 13:48:52

标签: sql-server-2008

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

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可以有多行但我需要知道何时插入了尚未插入的新密钥。

1 个答案:

答案 0 :(得分: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

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

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