0

我有一个插入触发器来插入表的主键(varchar)。我想获取最后插入的主键值。这是我的插入触发器

   ALTER TRIGGER dbo.equipment_insert_pk 
     ON  dbo.Equipment 
     INSTEAD OF INSERT
AS 
BEGIN
    SET NOCOUNT ON;
    declare @id int;
    declare @cat varchar(2);
    select @cat=CategoryID from INSERTED;
    select @id=cast(max(right(EquipmentID,4)) as int) from Equipment where CategoryID=@cat;
    set @id=isnull(@id,0)+1;
    -- Insert statements for trigger here
    insert into Equipment
    select CategoryID+right('0000'+cast(@id as varchar(4)),4)
    ,CategoryID
    ,Location
    ,Detail
    ,'../BarcodeImage/'+CategoryID+right('0000'+cast(@id as varchar(4)),4)+'.jpeg'  from INSERTED;

END

我试图编写一个函数来获取最后插入的主键值,但它似乎不起作用..因为触发器之外没有“插入”的范围。帮助我..我在触发器中尝试了这段代码,输出子句没有结果所以远的..

insert into Equipment 
    output INSERTED.EquipmentID into @Temp_Tbl
    select CategoryID+right('0000'+cast(@id as varchar(4)),4)
    ,CategoryID
    ,Location
    ,Detail
    ,'../BarcodeImage/'+CategoryID+right('0000'+cast(@id as varchar(4)),4)+'.jpeg'  from INSERTED;

有什么帮助吗??

4

1 回答 1

1

行。几周前我遇到了同样的问题。

我尝试了许多不同的方法 - 无济于事。长话短说 - 我最终添加了一个类型为UNIQUEIDENTIFIER(guid)的新列

因此,使用您的示例-假设有一个名为guidindbo.Equipment

大致来说,这是你如何做到的:

insert into Equipment 
    output INSERTED.EquipmentID, INSERTED.guid into @Temp_Tbl
    select CategoryID+right('0000'+cast(@id as varchar(4)),4)
    ,CategoryID
    ,Location
    ,Detail
    ,'../BarcodeImage/'+CategoryID+right('0000'+cast(@id as varchar(4)),4)+'.jpeg'
    ,NEWID() -- new column

来自插入;

然后您可以查询dbo.Equipment使用@Temp_Tbl.guid以获取插入的ID。例如:

SELECT EquipmentID FROM dbo.Equipment e WHERE EXISTS (SELECT * FROM @Temp_Tbl tt WHERE tt.guid = e.guid)

于 2012-04-18T14:36:14.397 回答