我有一个插入触发器来插入表的主键(varchar)。我想要获取最后插入的主键值。 这些是我的INSERT触发器获取最后一个主键 - 非身份 - 使用触发器插入
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 [email protected];
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
我试着写一个函数来获取最后插入的主键值,但它似乎没有work..because没有“插入”外trigger.Help我余地。 。 我试图触发在此代码输出条款没有结果至今..
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;
任何帮助?
可以使用一个'OUTPUT'子句外部的触发的捕获插入的值(一个或多个)。旁白:触发器在一组行上操作。你的触发器代码假设插入了一行。 – HABO 2012-04-18 14:25:53
你的PK是一个UNIQUEIDENTIFIER,默认为NEWID()?如果是这样,为什么不先生成NEWID(),将它存储在INSTEAD OF触发器中的变量中,然后手动插入该值? – 2012-04-18 14:46:21
我在这里发现了一个问题:'select @ cat = INSERTED中的CategoryID;'。我认为如果有人使用相同的语句插入两行不同的'CategoryID'值,那么这段代码将无法正常工作:'INSERT INTO dbo.Equipment(...,CategoryID,...)VALUES(..., 1,...),(...,2,...);' – 2012-04-18 15:23:53