SQL Server触发器更新列值

SQL Server触发器更新列值

问题描述:

我需要基本的SQL触发的一个例子,现在我来解释一下:SQL Server触发器更新列值

我有5列(列1,电力,栏3,column4,次)

值表(是数字),他的数据类型是'真实' 而“times”的数据类型是'int'

我会触发每次“power”变为0次'增加1

对不起,如果我的英语不完善牛逼!并希望你明白我的意思!如果有什么不清楚的话告诉我,我会尽力解释更好! :)

+2

澄清一点:您的标题有“MSSQL”,但您有“mysql”标签......您正在使用哪个标签? – 2012-03-09 22:33:38

+0

是的,你说的对不起,我错误地添加mysql标记也许是一个打字错误XD,顺便说一句我使用的是mssql。 – LdB 2012-03-09 22:40:53

假设列1是主键,触发的一般形式如下:

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) 
+0

非常感谢,但 “更新MyTable设置功率=功率+ 1”不应该是“设置时间=次+1”? – LdB 2012-03-09 22:57:14

+0

对不起,我误解了它并将修改答案。 – 2012-03-09 23:13:45

+0

讨厌带坏消息但数数(*)始终存在。 – 2012-03-09 23:27:15

一个可能的基本触发:

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和更新(功率)是here

+0

谢谢尼古拉,我的主键是第2列:) – LdB 2012-03-09 23:06:28