1

我正在处理的数据库具有以下插入触发器。问题是触发器不适用于多行插入。当我尝试一次插入多行时,我收到以下消息。

消息 512,级别 16,状态 1,过程 _ti_UD06,第 8 行
子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。我认为问题在于以下语句,当插入多行时,它将返回多个值。

如何使此插入触发器适用于多行?

IF(SELECT PROGRESS_RECID FROM inserted) IS NULL 

表中有 2 列,PROGRESS_RECIDPROGRESS_RECID_IDENT_

我认为这PROGRESS_RECID_IDENT_IdentitySQL Server 的一列。由PROGRESS_RECID_INDENTPROGRESS 服务器使用。

如果插入了新记录,触发器会检查是否PROGRESS_RECID为空,并将其设置为inserted.Identity

ALTER trigger [dbo].[_ti_UD06] ON [dbo].[UD06] for insert as
begin
if  ( select PROGRESS_RECID from inserted) is NULL
    begin
        update t set PROGRESS_RECID = i.IDENTITYCOL
        from UD06 t JOIN INSERTED i ON
        t.PROGRESS_RECID_IDENT_ = i.PROGRESS_RECID_IDENT_
        select convert (bigint, @@identity)
    end
end

这是表定义

CREATE TABLE [dbo].[UD06](
[Company] [nvarchar](8) NULL,
[Key1] [nvarchar](50) NOT NULL,
[Key2] [nvarchar](50) NULL,
[Key3] [nvarchar](50) NULL,
[Key5] [nvarchar](50) NULL,
[Character01] [nvarchar](max) NULL,
[Character02] [nvarchar](max) NULL,
[Character03] [nvarchar](max) NULL,
[Character04] [nvarchar](max) NULL,
[Character05] [nvarchar](max) NULL,
[Character06] [nvarchar](max) NULL,
[Character07] [nvarchar](max) NULL,
[Character08] [nvarchar](max) NULL,
[Character09] [nvarchar](max) NULL,
[Character10] [nvarchar](max) NULL,
[SysRowID] [nvarchar](36) NULL,
[SysRevID] [int] NULL,
[BitFlag] [int] NULL,
[GlobalUD06] [tinyint] NULL,
[GlobalLock] [tinyint] NULL,
[PROGRESS_RECID] [bigint] NULL,
[PROGRESS_RECID_IDENT_] [bigint] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
4

1 回答 1

1

我认为你已经很接近了:

ALTER trigger [dbo].[_ti_UD06] ON [dbo].[UD06] for insert as
begin

    UPDATE t 
    SET    PROGRESS_RECID = t.PROGRESS_RECID_IDENT_  --not "IDENTITYCOL"
    FROM   UD06 t 
    JOIN   inserted i ON  t.PROGRESS_RECID_IDENT_ = i.PROGRESS_RECID_IDENT_
    WHERE  i.PROGRESS_RECID is Null

    -- Not sure what this bit is for?  I doubt it's a good idea though...
    select convert (bigint, @@identity)

end
于 2013-04-28T21:45:51.467 回答