Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2005 在标识列上插入的触发器_Sql Server 2005 - Fatal编程技术网

Sql server 2005 在标识列上插入的触发器

Sql server 2005 在标识列上插入的触发器,sql-server-2005,Sql Server 2005,我有一个表a,其中的标识列是主键。 主键同时是指向另一个表B的外键 我正在尝试构建一个insert触发器,将表A中即将创建的标识列和另一个自定义值(例如“1”)插入到表B中 我尝试使用@@Identity,但一直遇到外键冲突。谢谢你的帮助 create TRIGGER dbo.tr ON dbo.TableA FOR INSERT AS SET NOCOUNT ON begin insert into TableB select @@identity, 1; end alex

我有一个表a,其中的标识列是主键。 主键同时是指向另一个表B的外键

我正在尝试构建一个insert触发器,将表A中即将创建的标识列和另一个自定义值(例如“1”)插入到表B中

我尝试使用@@Identity,但一直遇到外键冲突。谢谢你的帮助

create TRIGGER dbo.tr ON dbo.TableA FOR INSERT
AS 
SET NOCOUNT ON
begin
    insert into TableB
    select @@identity, 1;
end

alexolb在上面的评论中自己回答了这个问题。另一种选择是使用
IDENT_CURRENT
功能,而不是从表中选择。这种方法的缺点是,它总是比种子高一个开始,但这很容易通过将种子设置为低一个单位来弥补。我认为使用函数比使用子查询感觉更好

例如:

CREATE TABLE [tbl_TiggeredTable](
    [id] [int] identity(0,1) NOT NULL,
    [other] [varchar](max)
)

CREATE TRIGGER [trgMyTrigger] 
    ON  [tbl_TriggeredTable] 
    INSTEAD OF INSERT,UPDATE,DELETE

    SET identity_insert tbl_TriggeredTable ON
    INSERT INTO tbl_TriggeredTable (
        [id],
        [other]
    ) 
    SELECT
        -- The identity column will have a zero in the insert table when
        -- it has not been populated yet, so we need to figure it out manually
        case i.[id]
        when 0 then IDENT_CURRENT('tbl_TriggeredTable') + IDENT_INCR('tbl_TriggeredTable') 
        ELSE i.[id]
        END,
        i.[other],
    FROM inserted i
    SET identity_insert tbl_TriggeredTable OFF

END

@@IDENTITY
在这里无效。尝试插入表格B从插入的表格中选择标识列名称,1我也试过了,但有外键问题。似乎只有在插入之后才计算标识列,为了避免错误,我需要在插入之前计算标识列……您确定要查找正确表的外键吗?这应该与
BEGIN-TRAN没有什么不同;插入表a;插入表格B选择范围_标识();提交传输表A标识列是主键,同时也是指向表B的外键。因此,插入表B应在插入表A之前进行,以避免约束问题。然后需要一个INSTEAD OF触发器,而不是AFTER触发器。