日期:2014-05-18  浏览次数:20386 次

触发器问题,急急急!
我写了一个触发器,主要是为了实现,把移动号插到tb_sys_sendmsg_bak 里面,同时要把phone和msg插到SendMsg_Result_Table里,但是每次批量插入的时候都是在SendMsg_Result_Table里面插了1条,不知道为什么,以下是代码,请各位大侠帮忙!
create TRIGGER [Tr_SensMsg_Insert1] ON dbo.Send_Temp_Table 
INSTEAD OF INSERT 
AS
declare @phone varchar(21),@msg varchar(160),@MsgID int
select @msg=SendMsg, @phone=DestAddr from INSERTED  
where left(DestAddr,3) in ( '134 ', '135 ', '136 ', '137 ', '138 ', '139 ', '158 ', '159 ','150')
insert into tb_sys_sendmsg_bak (MessageText,PhoneNumber,flag)select SendMsg,DestAddr,'0' from INSERTED  
where left(DestAddr,3) in ( '134 ', '135 ', '136 ', '137 ', '138 ', '139 ', '158 ', '159 ','150')

insert into Send_Temp_Table select * from INSERTED where left(DestAddr,3) not in ( '134 ', '135 ', '136 ', '137 ', '138 ', '139 ', '158 ', '159 ','150')

if exists(select * from SendMsg_Result_Table)
begin
select @msgid= max(msgid) 
  from SendMsg_Result_Table 
   
set @msgid = @msgid+1
end
else
begin
set @msgid = 1
end

if @msgid is not null and @phone is not null
begin
insert into SendMsg_Result_Table(msgid,DestAddr,SendMsg,sendtime,SendResult) values (@msgid,@phone,@msg,getdate(),'发送成功!')
end
end


------解决方案--------------------
触发器里用变量不支持批量,只有用游标一个个赋值给变量插入数据

------解决方案--------------------
INSTEAD OF INSERT --这个触发器的类型,楼主要搞明白:
指定执行触发器而不是执行触发 SQL 语句,从而替代触发语句的操作。

------解决方案--------------------
SQL code
create TRIGGER [Tr_SensMsg_Insert1] ON dbo.Send_Temp_Table   
INSTEAD OF INSERT 
AS
insert  into  tb_sys_sendmsg_bak (MessageText,PhoneNumber,flag)
select 
SendMsg,DestAddr, '0 '
from 
INSERTED 
where 
left(DestAddr,3)  in  (  '134  ',  '135  ',  '136  ',  '137  ',  '138  ',  '139  ',  '158  ',  '159  ', '150 ')

insert  into  Send_Temp_Table 
select 
*
from 
INSERTED
where 
left(DestAddr,3) not  in  (  '134  ',  '135  ',  '136  ',  '137  ',  '138  ',  '139  ',  '158  ',  '159  ', '150 ')


declare @phone varchar(21),@msg varchar(160),@MsgID int
declare Test cursor for
select  SendMsg, DestAddr  from  INSERTED 
where  left(DestAddr,3)  in  (  '134  ',  '135  ',  '136  ',  '137  ',  '138  ',  '139  ',  '158  ',  '159  ', '150 ')
open Test
fetch next from test into  @msg,@phone
while @@fetch_status=0
begin

if exists(select * from SendMsg_Result_Table)
  begin
  select  @msgid= max(msgid) 
          from  SendMsg_Result_Table 
         
    set  @msgid = @msgid+1
  end
else
  begin
set @msgid = 1
  end
if @msgid is not null and @phone is not null
begin
insert into Se