2

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

就像根据成员类型字段一样,我想生成成员 ID,即 PK。

例如,如果新记录的成员类型为 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
4

2 回答 2

0

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

于 2012-05-17T13:58:15.773 回答
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
于 2012-05-22T08:53:58.453 回答