对于例子http://www.cnblogs.com/insus/articles/1921465.html写的触发器有bug,当使用http://www.cnblogs.com/insus/articles/1921618.html例子中的INSERT VALUES的语法头两种插入记录时,[Num]字段只做更第一笔,其他[Num]值均为NULL,
解决办法,只好修改触发器,代码如下,
代码
SET
ANSI_NULLS
ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [ dbo ] . [ tri_OrderDemo_Insert ] ON [ dbo ] . [ OrderDemo ]
AFTER INSERT
AS
-- 创建一个临时表
IF OBJECT_ID ( ' tempdb.dbo.#T ' ) IS NOT NULL DROP TABLE dbo.#T
-- 把所有添加记录都插入这个临时表中
SELECT * INTO dbo.#T FROM inserted
-- 宣告变量@MinKey为每次插入记录最初主键,@MaxKey为最后一个主键,@NumValue为[Num]字段值
DECLARE @MinKey INT , @MaxKey INT , @NumValue INT
-- 在临时表中找到最小主键和最大主键
SELECT @MinKey = MIN ( [ OrderDemoId ] ), @MaxKey = MAX ( [ OrderDemoId ] ) FROM dbo.#T
-- 如果是第一次有记录插入表
IF ( @MinKey = 1 )
-- [Num]字段值等于主键值
SET @NumValue = @MinKey
ELSE
BEGIN
-- 如果表[OrderDemo]已经有记录存在,找到最大值的从字段[Num]
SELECT @NumValue = MAX ( [ Num ] ) FROM [ dbo ] . [ OrderDemo ]
-- 并加上1
SET @NumValue = @NumValue + 1
END
-- 循环插入的记录
WHILE @MinKey <= @MaxKey
BEGIN
-- 更新新插入记录的[Num]字段值。
UPDATE [ dbo ] . [ OrderDemo ] SET [ Num ] = @NumValue WHERE [ OrderDemoId ] = @MinKey
SET @MinKey = @MinKey + 1
SET @NumValue = @NumValue + 1
END
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [ dbo ] . [ tri_OrderDemo_Insert ] ON [ dbo ] . [ OrderDemo ]
AFTER INSERT
AS
-- 创建一个临时表
IF OBJECT_ID ( ' tempdb.dbo.#T ' ) IS NOT NULL DROP TABLE dbo.#T
-- 把所有添加记录都插入这个临时表中
SELECT * INTO dbo.#T FROM inserted
-- 宣告变量@MinKey为每次插入记录最初主键,@MaxKey为最后一个主键,@NumValue为[Num]字段值
DECLARE @MinKey INT , @MaxKey INT , @NumValue INT
-- 在临时表中找到最小主键和最大主键
SELECT @MinKey = MIN ( [ OrderDemoId ] ), @MaxKey = MAX ( [ OrderDemoId ] ) FROM dbo.#T
-- 如果是第一次有记录插入表
IF ( @MinKey = 1 )
-- [Num]字段值等于主键值
SET @NumValue = @MinKey
ELSE
BEGIN
-- 如果表[OrderDemo]已经有记录存在,找到最大值的从字段[Num]
SELECT @NumValue = MAX ( [ Num ] ) FROM [ dbo ] . [ OrderDemo ]
-- 并加上1
SET @NumValue = @NumValue + 1
END
-- 循环插入的记录
WHILE @MinKey <= @MaxKey
BEGIN
-- 更新新插入记录的[Num]字段值。
UPDATE [ dbo ] . [ OrderDemo ] SET [ Num ] = @NumValue WHERE [ OrderDemoId ] = @MinKey
SET @MinKey = @MinKey + 1
SET @NumValue = @NumValue + 1
END