Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何在一个表中阻止错误的插入和更新?_Sql_Sql Server_Sql Server 2005 - Fatal编程技术网

Sql 如何在一个表中阻止错误的插入和更新?

Sql 如何在一个表中阻止错误的插入和更新?,sql,sql-server,sql-server-2005,Sql,Sql Server,Sql Server 2005,情况如下。我有一张这样的桌子: Col1 Col2 Col3 Col4 Col5 Col6 a b c 1 e 1 a b c 3 l 1 a b c 1 e 0 a b f 1 f 1 我的想法是,我不能更新现有数据或添加新行 哪一个有组合a b c 1?1. 如果有,我必须阻止在最后一列中添加1 已经是1-3的组合了,但我仍然可以 在第6列中添加与0相同的组合 除

情况如下。我有一张这样的桌子:

Col1 Col2 Col3 Col4 Col5 Col6
a    b    c     1   e     1
a    b    c     3   l     1
a    b    c     1   e     0
a    b    f     1   f     1
我的想法是,我不能更新现有数据或添加新行 哪一个有组合a b c 1?1. 如果有,我必须阻止在最后一列中添加1 已经是1-3的组合了,但我仍然可以
在第6列中添加与0相同的组合

除非我误解了您的需求,否则我认为您希望在除col5之外的所有列中都有一个唯一的约束

Alter Table Foo
ADD CONSTRAINT ak_orf UNIQUE 
(Col1, Col2 ,Col3 ,Col4 ,Col6),

对于更复杂的逻辑,可以使用触发器:触发器在指定的时间触发插入、更新、删除-在使用word For之前或之后

您的示例-不允许插入给定列组合的触发器:

create table MyTable (
    Col1 char, Col2 char, Col3 char, Col4 int, Col5 char, Col6 int
);

insert into MyTable (Col1, Col2, Col3, Col4, Col5, Col6)
values ('a', 'b', 'c', 1, 'e', '1');
insert into MyTable (Col1, Col2, Col3, Col4, Col5, Col6)
values ('a', 'b', 'f', 1, 'e', '1');

create trigger [dbo].[trigger_MyTable] on MyTable for insert as
begin
    if 0 < (select count(*) from inserted where 
        Col1='a' and Col2='b' and Col3='c' and Col4=1 and Col6=1)
    begin
        raiserror 50009 'wrong insert, no way!'
        rollback transaction
        return
    end
end;

-- now it fails
insert into MyTable (Col1, Col2, Col3, Col4, Col5, Col6)
values ('a', 'b', 'c', 1, 'e', '1');
当然,您可以为update use inserted table或delete use deleted table创建触发器。 您可以执行其他操作,例如在另一个表中插入另一行


也可以试试MSDN:

您是说不允许重复行,还是说比这更复杂?