SQL Server trigger before insert or update depend on value

时间:2015-06-30 13:26:29

标签: sql-server database sql-server-2008 triggers

Is it possible to check a column value, then before insert or update change other records value?

I'll explain more: I have table as below:

CREATE DATABASE pics
GO

CREATE TABLE tel
(
    [id] [bigint] IDENTITY(1,1) NOT NULL,
    [name] [nvarchar](10) NULL,
    [number] [nvarchar](10) NULL,
    [active] [bit]                                  
)

I need to know active tel number, I need if current record (insert or update) is True in active column, other records active column set to False,

I mean when

  1. insert or update a record and
  2. current record active value is True

then set all other records active column to False.

Is it possible?

2 个答案:

答案 0 :(得分:1)

I am not sure did i understand you well, but if you want to do some checks before some record is inserted into table by using trigger then you can use Instead of trigger type.

Behavior and syntax is similar to after trigger, the main difference is that you can say instead of inserting this row => do this... and with after trigger logic is insert row => do this....

答案 1 :(得分:1)

Please check following SQL trigger

select * from tel
/*
insert into tel select 'kodyaz','123456789',1
insert into tel select 'eralper','45688',1
insert into tel select 'sql','7955528',1
insert into tel values ('SQLServer','0152222',1),('SQL2016','20162016',1)
*/
go
create trigger tr_tel_active on tel after update, insert
as
begin
    if exists (
        select * from inserted where active = 1
    )
    update tel 
    set active = 0
    where 
        id not in (
            select id from inserted where active = 1
        ) and active = 1
end
go

Please note that the most common error made by developers about triggers is that we always think each insert or update statement will work only for one record. This is not true. For example, one of my insert statements creates 2 rows at the same time.

What this trigger does is that: It updates all active rows to deactive statement if at least there is one active row is inserted or updated

Please test before deploying to productive