尝试为表创建触发器

时间:2015-03-11 16:48:34

标签: sql-server sql-server-2008 triggers

我有一个由{4>组成的表[dbo].[main]

  • MovieGenre
  • MusicGenre
  • PodcastGenre
  • CombinedColumn

我想创建一个触发器,如果​​在MovieGenrePodcastGenreMusicGenre中插入了任何内容,它也会插入CombinedColumn

CREATE TRIGGER trgAfterInsert ON [dbo].[Main]
FOR INSERT
AS
???
GO

2 个答案:

答案 0 :(得分:0)

- dbo.main`需要一个关键列(让我们说它的标识列'id1')      CREATE TRIGGER trgAfterInsert         ON [dbo]。[主要]         FOR INSERT AS              声明@allcols varchar(500)

         declare @key1 int

         set @key1 = ident_current('dbo.main')

         select  @allcols = MovieGenre+' '+ PodcastGenre+' '+ MusicGenre from inserted

 update dbo.main set CombindedColumn= @allcols where id1  = @key1

答案 1 :(得分:0)

好的,这将一个接一个地向Combined Column添加值。 "堆叠"他们如你所愿:

CREATE TRIGGER trgAfterInsert on dbo.main
AFTER INSERT
AS
    INSERT INTO yourTable(CombinedColumn)
    SELECT MovieGenre
    FROM inserted
    UNION ALL
    SELECT PodcastGenre
    FROM inserted
    UNION ALL
    SELECT MusicGenre
    FROM inserted
GO