【问题标题】:tsql trigger for copy older data before update更新前复制旧数据的 tsql 触发器
【发布时间】:2021-05-06 18:41:56
【问题描述】:

我需要帮助来创建触发器,我有一个包含此表的数据库:test01(id, name, id_parent)

CREATE TABLE [dbo].[test01](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](64) NOT NULL,
 CONSTRAINT [PK_test01] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)

执行更新时,我需要将更新行复制到同一个表中。

更新前的示例数据

id,  name, id_parent
1 , 'bob', null
2 , 'jak', null

如果我发送:

更新 test01 set name='newbob' where id=1

我需要这个结果

id,  name,    id_parent
1 , 'newbob', null    <---- updated row
2 , 'jak',    null
3 , 'bob',    1       <---- copy of previous row with id_parent referenced to the updated row

我需要帮助来为此创建触发器。

我的非工作版本:

CREATE TRIGGER testtrg 
   ON  test01
   INSTEAD OF UPDATE
AS 
BEGIN
    SET NOCOUNT ON;

    insert into test01 
    select * from inserted

END
GO

【问题讨论】:

  • inserted 包含您插入的数据(提示在名称中;))。如果您想要以前在表中的数据,您需要deleted 伪表。

标签: tsql triggers


【解决方案1】:

它有效。您需要将 id 映射到 id_parent 列

drop table test01
CREATE TABLE [dbo].[test01](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](64) NOT NULL,
    [id_parent][int] NULL,

 CONSTRAINT [PK_test01] PRIMARY KEY CLUSTERED 
(
   [id] ASC
));

insert into test01   (name,id_parent)
values('bob', null),('jak', null)
select * from test01

CREATE TRIGGER testtrg 
ON  test01
INSTEAD OF UPDATE
AS 
BEGIN
   SET NOCOUNT ON;

   insert into test01(name,id_parent) 
   select name,id from inserted

END

update test01 set name='bob2' where id=1
select * from test01

输出:

id  name    id_parent
1   bob NULL
2   jak NULL
3   bob2    1

【讨论】:

    猜你喜欢
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2016-11-03
    相关资源
    最近更新 更多