如果只有更新是问题,是的,您可以使用“而不是更新”触发器强制执行此操作,需要注意的是您必须编写更新语句来应用更改:
create table data (id int not null, name varchar(50), postcode varchar(50), sex bit, primary key(id))
go
create trigger tg_data_before on data instead of update as
begin
set nocount on
update data
set name = coalesce(c.name, b.name),
postcode = coalesce(c.postcode, b.postcode),
sex = coalesce(c.sex, b.sex)
from data a
join deleted b on a.id = b.id
join inserted c on a.id = c.id
end
go
insert data values (1, 'sven', '1234', 0)
insert data values (2, 'lars', '2345', 0)
insert data values (3, 'foo', '3456', 1)
update data set name = null
update data set postcode = null where id = 1
update data set postcode = 'zoink' where id in (2,3)
update data set sex = 1-sex
select * from data
drop table data
但我认为最好只使用“not null”并修复客户端代码,这显然是在做错事(明确地将一个你不想为空的字段清空,或者做一个无保护的插入/合并):
create table data (id int not null, name varchar(50) not null, postcode varchar(50) not null, sex bit not null, primary key(id))