欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

数据库触发器DB2和SqlServer有哪些区别

程序员文章站 2023-02-19 22:53:40
大部分数据库语句的基本语法是相同的,但具体到的每一种数据库,又有些不一样,例如触发器,db2和sql server两种很大的不同。 例如db2的一个触发器:...

大部分数据库语句的基本语法是相同的,但具体到的每一种数据库,又有些不一样,例如触发器,db2和sql server两种很大的不同。

例如db2的一个触发器:

create trigger eas.trname  
 no cascade before insert //插入触发器 
 on eas.t_user  
 referencing new  as n_row //把新插入的数据命名为n_row 
 for each row mode db2sql //每一行插入数据都出发此操作 
begin atomic //开始 
declare u_xtfidemp1 varchar(36); //定义变量 
declare u_xtempcode1 varchar(20); 
declare u_xtempcodecount int ; 
declare u_xtfidempcount int ; 
declare u_id1 int ; 
set u_xtfidemp1=n_row.u_xtfidemp;//把新插入的数据赋值给变量 
set u_xtempcode1=n_row.u_xtempcode; 
set u_id1=n_row.u_id; 
 set u_xtempcodecount= (select count(u_xtempcode) from eas.t_user where u_xtempcode is not null and u_xtempcode=u_xtempcode1 and u_id<>u_id1); 
 set u_xtfidempcount=(select count(u_xtfidemp) from eas.t_user where u_xtfidemp is not null and u_xtfidemp=u_xtfidemp1 and u_id<>u_id1); 
 if u_xtempcodecount>0 or u_xtfidempcount>0 then 
      signal sqlstate '80000' ('eas.t_user exceeds u_xtempcode,u_xtfidemp 插入数据时有错误,有重复'); 
  end if; 
end 

在sql server中的写法为:

create trigger eas.trname  
 for insert //插入触发器 db2 写法 no cascade before insert  
 on eas.t_user  
  //sql server没有 把新插入的数据命名为n_row referencing new  as n_row 
   //sql server没有  for each row mode db2sql  
begin // sql server没有  atomic //开始 
declare @u_xtfidemp1 varchar(36); //定义变量 db2 写法 没有@ 
declare @u_xtempcode1 varchar(20); 
declare @u_xtempcodecount int ; 
declare @u_xtfidempcount int ; 
declare @u_id1 int ; 
//set u_xtfidemp1=n_row.u_xtfidemp; 
//set u_xtfidemp1=n_row.u_xtfidemp 
//set u_xtempcode1=n_row.u_xtempcode; 
 -- 从inserted临时表中获取记录值 //把新插入的数据赋值给变量 
  select @u_xtfidemp1 = u_xtfidemp, 
      @u_xtempcode1 = u_xtempcode, 
      @u_id1 = u_id  
      from inserted 
 set @u_xtempcodecount= (select count(u_xtempcode) from eas.t_user where u_xtempcode is not null and u_xtempcode=@u_xtempcode1 and u_id<>@u_id1); 
 set @>u_xtfidempcount=(select count(u_xtfidemp) from eas.t_user where u_xtfidemp is not null and u_xtfidemp=@u_xtfidemp1 and u_id<>@u_id1); 
 if@u_xtempcodecount>0 or @u_xtfidempcount>0 then 
    //  signal sqlstate '80000' ('eas.t_user exceeds u_xtempcode,u_xtfidemp 插入数据时有错误,有重复');   end if; 
end 

可以看到虽然创建触发器的基本语法是相同的,但具体细节又不一样。

1定义变量的方式不一样.

db2定义变量时,没有要求@开头,但是sql server定义时要求以@开头

2对插入的临时表叫法不一。

 db2里边叫referencing new,你可以改成其他的名称,sql server叫做inserted

3取插入的临时表数据方法不一样

 db2里边使用点的方式取值,但sql server可以使用select取值,在 db2里使用select取值就会报错。另外 db2里边似乎不能

通过select的方式赋值。

4触发器的触发的方式不太一样。

 例如 db2里可以规定是不是每一行都出发,但sql server里边没这样的功能,一次插入100条数据,也只触发一次。

5触发后的操作不一样

 同时for类型的触发器,db2在触发器里没有异常时,会插入数据或者更新数据,sql server在触发器里没有异常时,是不会插

入数据的或者更新数据,除非在触发器中写了插入或者是更新的sql。