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.什么是触发器?
触发器是与表相关联的数据库对象,当为表执行定义的动作时,它将被激活。当我们运行以下语句时,可以执行该触发器:
- 插
- 更新
- 删除
并且可以在事件之前或之后调用它。
句法 –
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. |
断言不能修改数据,并且不链接到数据库中的任何特定表或事件,但是触发器具有更强大的功能,因为它们可以检查条件,还可以修改数据库内部表中的数据,这与断言不同。