简体   繁体   English

SQL Server触发器更新列值

[英]SQL Server Trigger update column value

i need an example of basic sql trigger, now i explain: 我需要一个基本的SQL触发器示例,现在我解释一下:

I Have a table with 5 columns(column1, power, column3, column4, times) 我有一个包含5列的表格(column1,power,column3,column4,times)

the value of "power" change in real time (Are numbers), and his datatype is 'real' while the datatype of "times" is 'int' “ power”的值实时变化(Are数字),其数据类型为“ real”,而“ times”的数据类型为“ int”

i would a trigger that everytime "power" go to 0 'times' increase by 1 我会触发一次,每次“力量”变为0,“次数”增加1

sorry if my english isn't perfect! 对不起,如果我的英语不完美! and hope you understood what i mean!if something isn't clear tell me and i will try to explain better! 希望您理解我的意思!如果不清楚,请告诉我,我会尽力解释! :) :)

A possible basic trigger: 可能的基本触发条件:

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

Documentation for NoCount and update(power) is here . NoCount和update(power)的文档在此处

Assuming column1 is the primary key, the general form of the trigger is as follows: 假设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)

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

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