- MS SQL 不支持
BEFORE
触发器。您应该使用INSTEAD OF
触发器。
- MS SQL 触发器是基于集合而不是基于行的触发器,因此应该考虑到这一点
话虽如此,你可以试试
CREATE TRIGGER tg_BI_Info_insert ON BI_Info
INSTEAD OF INSERT AS
BEGIN
DECLARE @max INT
SET @max = (SELECT COALESCE(MAX(id), 0) FROM BI_Info WITH (TABLOCKX, HOLDLOCK))
INSERT INTO BI_Info (id, column1, ...)
SELECT @max + ROW_NUMBER() OVER (ORDER BY (SELECT 1)), column1, ...
FROM INSERTED
END
这是SQLFiddle演示
如果您想模拟WHEN (NEW."Id" IS NULL OR NEW."Id" = 0)
允许插入显式分配的 id 的部分,那么
CREATE TRIGGER tg_BI_Info_insert ON BI_Info
INSTEAD OF INSERT AS
BEGIN
DECLARE @max INT
INSERT INTO BI_Info
SELECT *
FROM INSERTED
WHERE COALESCE(id, 0) <> 0
SET @max = (SELECT COALESCE(MAX(id), 0) FROM BI_Info WITH (TABLOCKX, HOLDLOCK))
INSERT INTO BI_Info (id, column1)
SELECT @max + ROW_NUMBER() OVER (ORDER BY (SELECT 1)), column1
FROM INSERTED
WHERE COALESCE(id, 0) = 0
END
这是该案例的SQLFiddle演示