我有一个插入触发器来插入表的主键(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;
任何帮助??
答案 0 :(得分:1)
确定。几个星期前我碰到了同样的问题。
我尝试了很多不同的方法 - 无济于事。长话短说 - 我最后添加了一个类型为UNIQUEIDENTIFIER
(guid)
所以要使用你的例子 - 假设在guid
dbo.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
来自INSERTED;
然后,您可以使用dbo.Equipment
查询@Temp_Tbl.guid
以获取插入的ID。
例如:
SELECT EquipmentID FROM dbo.Equipment e WHERE EXISTS (SELECT * FROM @Temp_Tbl tt WHERE tt.guid = e.guid)