日期:2014-05-17  浏览次数:20984 次

怎样查看触发器inserted表中的数据?
现在有个表,要求某个字段在表中唯一,为了前台系统提示的友好性,选择用触发器而不用唯一索引,我的触发器是这样写的:
SQL code

create trigger [dbo].[tr_m_b_material_standard_relations_i] on [dbo].[t_m_b_material_standard_relations]
for insert
as
begin
if exists(select 1 from INSERTED _a WHERE  material_id IN (SELECT material_id FROM dbo.t_m_b_material_standard_relations))
         
    begin
        select @msg='物料不允许重复!'
        raiserror(@msg,16,1)
        rollback tran
        return
    end
end



现在的问题是,我在表中插入的数据, material_id 字段不重复,触发器也会弹出“物料不允许重复”,这是为什么呢?

有没有办法查看一下inserted表里的数据呢?



------解决方案--------------------
SQL code

--for insert,此时insert的记录在表中是已经可以选出来的了
create trigger [dbo].[tr_m_b_material_standard_relations_i] on [dbo].[t_m_b_material_standard_relations]
for insert
as
declare @msg varchar(100);
if (select count(1) from inserted i,t_m_b_material_standard_relations t
    where i.material_id=t.material_id)>1
    begin
        select @msg='物料不允许重复!'
        raiserror(@msg,16,1)
        rollback tran
        return
end
go

------解决方案--------------------
SQL code

--刚才那种写法多条一起插入时有问题,这样写吧
create trigger [dbo].[tr_m_b_material_standard_relations_i] on [dbo].[t_m_b_material_standard_relations]
for insert
as
declare @msg varchar(100);
if exists (select 1 from inserted i,t_m_b_material_standard_relations t
    where i.material_id=t.material_id
    group by i.material_id
    having count(1)>1)
    begin
        select @msg='物料不允许重复!'
        raiserror(@msg,16,1)
        rollback tran
        return
end
go

------解决方案--------------------
inserted/deleted两个表存在于触发器内。所以你查不了。你可以在触发器里面select出来或者保存到一个实体表中再检查。
------解决方案--------------------
探讨
SQL code

--刚才那种写法多条一起插入时有问题,这样写吧
create trigger [dbo].[tr_m_b_material_standard_relations_i] on [dbo].[t_m_b_material_standard_relations]
for insert
as
declare @msg varchar(100);
if exists (se……