当前位置: 代码迷 >> Sql Server >> 为什么小弟我这里用if来判断会有异常
  详细解决方案

为什么小弟我这里用if来判断会有异常

热度:13   发布时间:2016-04-27 12:28:27.0
为什么我这里用if来判断会有错误
触发器如下:
CREATE TRIGGER addpd ON aapd
for INSERT
as
declare @i int
declare @j int
set @i=(select count(*) from inserted where fsort=2)
set @j=(select count(*) from inserted where fsort=3)
if @i>0
begin
insert into aapy(djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh) select djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh 
from inserted where fsort=1
insert into aapymx(djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh) select djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh 
from inserted where fsort=2
end
if @j>0
begin
insert into aapk(djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh) select djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh 
from inserted where fsort=1
insert into aapkmx(djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh) select djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh 
from inserted where fsort=3
end

假如有四条记录要插入aapd表中:
fid djbh djbs rq bm ywy spid dw pihao fqty fsort dj_sort fxh
1 1 w 2012-06-01 销售部 张三 '' '' '' 0 1 1 ''
2 1 '' '' '' '' 123 个 888 2 2 1 ''
3 1 '' '' '' '' 124 个 888 3 2 2 ''
3 1 '' '' '' '' 125 个 888 5 3 3 ''

触发器执行后,发现结果为:只把fsort=2的记录插入到了aapymx中,把fsort=3的记录插入到aapkmx中。而应该把fsort=1的这条记录分别插入aapy和aapk表无效,没有插入。

请问是何原因导致。
多谢!




------解决方案--------------------
根據你寫改裝:
SQL code
asbegininsert into aapymx(djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh) select djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh from inserted where fsort=2if @@Rowcount>0insert into aapy(djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh) select djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh from inserted where fsort=1insert into aapkmx(djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh) select djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh from inserted where fsort=3if @@Rowcount>0insert into aapy(djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh) select djbh,djbs,rq,bm,ywy,spid,dw,pihao,fqty,fsort,dj_sort,fxh from inserted where fsort=1end
  相关解决方案