📜  DBMS 中断言和触发器的区别

📅  最后修改于: 2021-09-28 10:54:44             🧑  作者: Mango

1. 什么是断言?
当一个约束涉及 2 个(或)多个表时,表约束机制有时很困难,结果可能不会如预期的那样。为了涵盖这种情况,SQL 支持创建断言,这些断言是不只与一个表相关联的约束。并且断言语句应确保数据库中始终存在某个条件。每当在相应的表中进行修改时,DBMS 总是检查断言。

句法 –

CREATE ASSERTION  [ assertion_name ]
CHECK ( [ condition ] );

例子 –

CREATE TABLE sailors (sid int,sname varchar(20), rating int,primary key(sid),
CHECK(rating >= 1 AND rating <=10)
CHECK((select count(s.sid) from sailors s) + (select count(b.bid)from boats b)<100) ); 

在上面的例子中,我们强制执行 CHECK 约束,船和水手的数量应该小于 100。所以这里我们可以同时检查两个平板电脑的约束。

2. 什么是触发器?
触发器是与表关联的数据库对象,当为表执行定义的动作时,它会被激活。 当我们运行以下语句时,触发器可以被执行:

  1. 插入
  2. 更新
  3. 删除

它可以在事件之前或之后被调用。

句法 –

create trigger [trigger_name]       
[before | after]          
{insert | update | delete} 
on [table_name]  
[for each row]    
[trigger_body]  

例子 –

create trigger t1  before  UPDATE on sailors
for each row
begin
   if new.age>60 then
      set new.age=old.age;
   else
      set new.age=new.age;
   end if;
end;
$ 

在上面的例子中,我们在更新之前创建触发器。所以,如果新的年龄大于 60 我们不应该更新,否则我们应该更新。我们可以使用“$”符号调用这个触发器。

断言和触发器的区别:

S.No Assertions Triggers
1. We can use Assertions when we know that the given particular condition is always true. We can use Triggers even particular condition may or may not be true.
2. When the SQL condition is not met then there are chances to an entire table or even Database to get locked up. Triggers can catch errors if the condition of the query is not true.
3. Assertions are not linked to specific table or event. It performs task specified or defined by the user. It helps in maintaining the integrity constraints in the database tables, especially when the primary key and foreign key constraint are not defined.
4. Assertions do not maintain any track of changes made in table. Triggers maintain track of all changes occurred in table.
5. Assertions have small syntax compared to Triggers. They have large Syntax to indicate each and every specific of the created trigger.
6. Modern databases do not use Assertions. Triggers are very well used in modern databses.

断言不能修改数据,并且它们不链接到数据库中的任何特定表或事件,但触发器更强大,因为它们可以检查条件并修改数据库内表中的数据,这与断言不同。