sql server触发自定义PK

时间:2012-05-17 12:29:02

标签: sql-server-2008 triggers

我想通过触发器生成PK,因为它是自定义PK。

就像取决于成员类型字段一样,我想生成PK的成员ID。

e.g。如果新记录的成员类型是DGIA,那么成员ID将是DGIA1,DGIA2,DGIA3 ......等等......如果成员类型是DGIL,那么成员ID将是DGIL1,DGIL2,DGIL3 ......等等。 ..

那么,如何为同一个写入触发器......我已经尝试过以下但它仅适用于第一条记录。

ALTER TRIGGER [dbo].[next_member_id] ON  [dbo].[DAD_MEMBERSHIP] AFTER INSERT
AS 
BEGIN

DECLARE @COUNT INT
SET @COUNT=0;

SELECT @COUNT=ISNULL(MAX(CAST(SUBSTRING(DAD_MEMBERSHIP.MEMBER_ID,5,15) AS INT)),0)+1 FROM DAD_MEMBERSHIP where DAD_MEMBERSHIP.MEMBER_TYPE = DAD_MEMBERSHIP.MEMBER_TYPE

update DAD_MEMBERSHIP set DAD_MEMBERSHIP.MEMBER_ID = DAD_MEMBERSHIP.MEMBER_TYPE + CONVERT(varchar,@COUNT)
from DAD_MEMBERSHIP inner join inserted on DAD_MEMBERSHIP.MEMBER_TYPE = inserted.MEMBER_TYPE

END

2 个答案:

答案 0 :(得分:0)

触发器按批次记录操作,您无法分配标量变量并期望它适用于多个记录。您需要将整个过程重新考虑为基于集合的过程。

答案 1 :(得分:0)

我使用以下触发器解决了问题

ALTER TRIGGER [dbo].[next_member_id] 
   ON  [dbo].[DAD_MEMBERSHIP] 
   AFTER INSERT
AS 
BEGIN

DECLARE @COUNT INT
SET @COUNT=0;

DECLARE @STR VARCHAR(5)
SET @STR=''

select @STR=i.MEMBER_TYPE from inserted i;  

SELECT @COUNT=ISNULL(MAX(CAST(SUBSTRING(DAD_MEMBERSHIP.MEMBER_ID,5,15) AS INT)),0)+1 
from DAD_MEMBERSHIP where MEMBER_TYPE=@STR

update DAD_MEMBERSHIP set DAD_MEMBERSHIP.MEMBER_ID = @STR + CONVERT(varchar,@COUNT)
from DAD_MEMBERSHIP inner join inserted i on i.MEMBER_TYPE=DAD_MEMBERSHIP.MEMBER_TYPE where DAD_MEMBERSHIP.MEMBER_ID is null



END