将数据从另一列读取到SQL中的当前表

时间:2016-09-01 10:36:53

标签: sql-server

我有这些表格:

CREATE TABLE [dbo].[FileISOManagers]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [LineId] [int] NOT NULL,
    [Revision] [nvarchar](max) NULL,
    [FileName] [nvarchar](max) NULL,
    [UserId] [int] NOT NULL,
    [SubmitDateTime] [datetime] NOT NULL
)

CREATE TABLE [dbo].[Lines]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [LineNumber] [nvarchar](max) NULL,
    [DocumentNumber] [nvarchar](max) NULL,
    [Revision] [nvarchar](max) NULL
)

每一行都有多个修订版,因此我只需要自动在revision表的FileISOManagers列的Revision表中插入最后一个lines列值。我想在SQL Server中执行此操作。有没有解决办法呢?我应该使用触发器吗?

enter image description here

修改

enter image description here

2 个答案:

答案 0 :(得分:1)

 -- Create trigger on table FileISOManagers for Insert statement
CREATE TRIGGER trgAfterInsert on FileISOManagers
FOR INSERT
AS declare @Revision varchar(100);
select @Revision=i.Revision from inserted i;
set @action='Inserted Record -- After Insert Trigger.'; insert into Lines(Revision)
values (@Revision);
PRINT 'AFTER INSERT trigger fired.

答案 1 :(得分:0)

可以使用连接和别名来完成。

实施例

INSERT INTO FileISOManagers (Revision ..columns)
 SELECT *
  FROM Lines ls
 WHERE NOT EXISTS
(
  SELECT * 
    FROM FileISOManagers
   WHERE LineId = ls.id       
) order by ls.id desc