3

我有一个预言机触发器:

CREATE OR REPLACE TRIGGER  "BI_Info" 
BEFORE INSERT ON "Info" FOR EACH ROW
 WHEN (NEW."Id" IS NULL OR NEW."Id" = 0) BEGIN
    SELECT NVL(MAX("Id")+1, 1) INTO :NEW."Id" FROM "Info";
END;

现在我想将它转换为 ms sql 触发器。

我知道 [Id] [int] IDENTITY(1,1) 可以类似地实现这个触发器

但我不希望 Id 自动添加一个。

谢谢。

4

1 回答 1

1
  1. MS SQL 不支持BEFORE触​​发器。您应该使用INSTEAD OF触发器。
  2. 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演示

于 2013-07-18T04:16:15.477 回答