【问题标题】:SQL Server Trigger update column valueSQL Server 触发器更新列值
【发布时间】:2012-03-09 22:25:18
【问题描述】:

我需要一个基本 sql 触发器的例子,现在我解释一下:

我有一个 5 列的表(column1、power、column3、column4、times)

“power”的值实时变化(是数字),他的数据类型是“real” 而“times”的数据类型是'int'

我会触发每次“功率”变为 0 时“倍”增加 1

对不起,如果我的英语不完美!希望你明白我的意思!如果有什么不清楚的地方告诉我,我会尽力解释得更好! :)

【问题讨论】:

  • 澄清一点:你的标题有“MSSQL”但你有“mysql”标签……你用的是哪个?
  • 是的,你说得对,对不起,我错误地添加了 mysql 标签,可能是打字错误 XD,顺便说一句,我正在使用 mssql。

标签: sql sql-server triggers


【解决方案1】:

一个可能的基本触发器:

create trigger MyBasicTrigger on MyBasicTable
after insert, update
as
--  Trigger rowcount should not mess with update that triggered it, search for it in documentation provided here
   set NoCount ON
-- If power is mentioned in update/insert statement at all
   if update(Power)
   begin
   -- Update times for each changed row that has value of power 0
   -- Inserted table holds new values in updated rows
   -- You didn't mention your PK column(s), so I assume the name would be "ID"
      update MyBasicTable set Times = Times + 1
      from MyBasicTable inner join inserted on MyBasicTable.ID = inserted.ID
      where Inserted.Power = 0
   end

NoCount 和 update(power) 的文档是 here

【讨论】:

  • 谢谢 Nikola,我的主键是 column2 :)
【解决方案2】:

假设column1为主键,触发器的一般形式如下:

create trigger MyPower
on MyTable
after insert, update
as
  if exists (select column1 
             from inserted i join MyTable m
             on i.column1 = m.column1
             and i.power = 0)
    update MyTable set times = times + 1 
    where exists (select column1 from inserted i 
              join MyTable m
              on i.column1 = m.column1)

【讨论】:

  • 非常感谢,但是“update MyTable set power = power + 1”不应该是“set times = times +1”?
  • 讨厌带来坏消息但count(*)总是存在的。
  • 当您学到一些东西时,这绝不是坏消息。谢谢尼古拉,我会纠正的!
猜你喜欢
  • 2011-06-03
  • 1970-01-01
  • 2014-03-26
  • 1970-01-01
  • 1970-01-01
  • 2015-01-20
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多