SQL触发器更新和插入

时间:2015-01-03 19:09:32

标签: sql sql-server stored-procedures triggers

我有三个表OUTPUTINVENTORYPRODUCT

Create Table OUTPUT(){
       OUTPUTID int indentity, -- output ID
       PRODUCTID varchar(10),
       QUANTUM int,
}
Create Table INVENTORY(){
       INVENTORYID int indentity, -- inventory ID
       QUANTUM int,
       QUANTUMOUT int, -- quantum out
}
Create Table PRODUCT(){
       PRODUCTID varchar(10),
}       

我创建了以下触发器:

create trigger [dbo].[trig_OUTPUT]
on [dbo].[OUTPUT]
after insert,update
as
begin
 Set nocount on;

    UPDATE INVENTORY 
    set INVENTORY.QUANTUMOUT = OUT.QUANTUM 
    from OUTPUT 
    inner join PRODUCT    on OUTPUT.PRODUCTID = PRODUCT.PRODUCTID 
    inner join INVENTORY  on PRODUCT.PRODUCT = INVENTORY.PRODUCT

end

和存储过程

CREATE procedure [dbo].[spud_addOUTPUT]
@productID varchar(10),
@quantum int
AS

 declare @quantumtemp int

  set @quantumtemp = (select QUANTUM from INVENTORY where INVENTORY.PRODUCTID = @productID)

if(@quantumtemp> @quantum or ISNULL(@quantumtemp,'0')='0')
 begin
    INSERT OUTPUT(PRODUCTID,QUANTUM) values(@productID,@quantum)
 end
else
  begin
    print 'do not insert quantum out greater quantum in inventory'
  end

但是,存储过程仅适用于第一个,然后我调用存储过程。它没有更新QUANTUMOUT

中的列INVENTORY

1 个答案:

答案 0 :(得分:0)

不知道你在这里使用了什么逻辑,但我修复了语法错误,

永远不要将sql server关键字用于您的对象名称,如果您确实有任何关键字命名的对象,请始终使用方括号[]

<强>触发

create trigger [dbo].[trig_OUTPUT]
on [dbo].[OUTPUT]
after insert,update
as
begin
 Set nocount on;

    UPDATE INVENTORY 
    set INVENTORY.QUANTUMOUT = [OUTPUT].QUANTUM   --<-- this should be OUTPUT
    from [OUTPUT] 
    inner join PRODUCT    on [OUTPUT].PRODUCTID = PRODUCT.PRODUCTID 
    inner join INVENTORY  on PRODUCT.PRODUCT = INVENTORY.PRODUCT

end

<强>程序

CREATE procedure [dbo].[spud_addOUTPUT]
@productID varchar(10),
@quantum int
AS
BEGIN
  SET NOCOUNT ON;
 declare @quantumtemp int

SELECT TOP 1 @quantumtemp = QUANTUM from INVENTORY where PRODUCTID = @productID

if(@quantumtemp> @quantum or ISNULL(@quantumtemp,'0')='0')
 begin
    INSERT INTO dbo.[OUTPUT](PRODUCTID,QUANTUM) 
    values(@productID,@quantum)
 end
else
  begin
    print 'do not insert quantum out greater quantum in inventory'
  end
END