上一个例子http://www.cnblogs.com/insus/articles/1921391.html中,触发器写得有点不好,因为没有考虑到主键值是自动增长的,如果出现有记录被删除了,这个[Num]字段值就不能顺序排列了,会出现空缺。因此需要修改一下这个触发器(TRIGGER),
代码
IF
EXISTS
(
SELECT
[
name
]
FROM
sysobjects
WHERE
[
name
]
=
'
tri_OrderDemo_Insert
'
AND
TYPE
=
'
TR
'
)
DROP TRIGGER [ dbo ] . [ tri_OrderDemo_Insert ]
GO
CREATE TRIGGER [ dbo ] . [ tri_OrderDemo_Insert ] ON [ dbo ] . [ OrderDemo ]
AFTER INSERT
AS
DECLARE @PK INT , @DummyKey INT
SELECT @PK = [ OrderDemoId ] FROM inserted
-- 如果是第一笔记录插入,字段[Num]的值,就是等于主键值
IF @PK = 1
SET @DummyKey = @PK
ELSE
BEGIN
-- 如果非是第一笔记录插入,需要找出最大值添加1即是最新记录字段[Num]的值。
SELECT @DummyKey = MAX ( [ Num ] ) FROM [ dbo ] . [ OrderDemo ]
SET @DummyKey = @DummyKey + 1
END
UPDATE [ dbo ] . [ OrderDemo ] SET [ Num ] = @DummyKey WHERE [ OrderDemoId ] = @PK
DROP TRIGGER [ dbo ] . [ tri_OrderDemo_Insert ]
GO
CREATE TRIGGER [ dbo ] . [ tri_OrderDemo_Insert ] ON [ dbo ] . [ OrderDemo ]
AFTER INSERT
AS
DECLARE @PK INT , @DummyKey INT
SELECT @PK = [ OrderDemoId ] FROM inserted
-- 如果是第一笔记录插入,字段[Num]的值,就是等于主键值
IF @PK = 1
SET @DummyKey = @PK
ELSE
BEGIN
-- 如果非是第一笔记录插入,需要找出最大值添加1即是最新记录字段[Num]的值。
SELECT @DummyKey = MAX ( [ Num ] ) FROM [ dbo ] . [ OrderDemo ]
SET @DummyKey = @DummyKey + 1
END
UPDATE [ dbo ] . [ OrderDemo ] SET [ Num ] = @DummyKey WHERE [ OrderDemoId ] = @PK