繁体   English   中英

在SQL Server中更新表的属性时触发?

[英]Trigger on update of an attribute of a table in SQL Server?

我创建了计算机审核应用程序。 当我运行我的应用程序时,它在浏览器上显示计算机附件,例如computerName,osVersion,lastAudit,模型,totalMemory,处理器,userName。

我在SQL Server 2008中用一个表Computers创建了一个数据库。 将值插入该表后,我需要更新列中的表值。 为了尝试这一点,我使用了触发器。 但是,我不完全了解触发器如何工作。

有人可以告诉我如何做到这一点。

我的表包含以下列:

id, computerName, osVersion, lastAudit, model, totalMemory, processor, userName

我知道这段代码中有什么错误或遗漏,但我无法完成。 请在这方面帮助我。

  CREATE TRIGGER update_trigger
  ON computers
  AFTER UPDATE
   AS 
   BEGIN
declare @id as int
declare @computerName as varchar(100)
declare @osVersion as varchar(100)
declare @lastAudit as datetime
declare @model as varchar(100)
declare @totalMemory float
declare @processor as varchar(100)
declare @userName as varchar(100)
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
if update(id)
BEGIN
    insert into computers values(@id,@computerName,@osVersion,@lastAudit,@model,
                            @totalMemory,@processor,@userName,'Update')

SET NOCOUNT ON;

    END
    GO

如果要在插入新行时(或更新时?不是很清楚...)简单地更新现有表的一列或多列,请尝试这样的触发器:

CREATE TRIGGER trigUpdateTable
ON dbo.Computers
AFTER INSERT  -- or AFTER UPATE or AFTER INSERT, UPDATE
AS 
BEGIN
  -- do whatever you want to do on INSERT and/or UPDATE
  UPDATE 
      dbo.Computers
  SET 
      LastAudit = GETDATE()
  FROM 
      dbo.Computers c
  INNER JOIN 
      Inserted i ON c.id = i.id

需要记住的非常重要的一点: 不会针对受影响的每一行调用SQL Server触发器-而是针对每个语句,并且如果INSERTUPDATE语句影响多行,则在Inserted伪表中将有多个条目,您需要能够在触发条件中处理该事实

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM