在一个表中插入数据时,在第二个表中填充自动数据

时间:2015-04-23 06:03:07

标签: sql sql-server

我有两个表Table1Table2,表格结构为

Table1          
Primary Key | Name      

Table2          
Primary Key |  Table1_Id_pk |  Status - true/false value    

当我将数据插入Table2时,我想自动从table1 Table2中传输Status In [52]: print open('aa1.csv').read() Date,Open,High,Low,Close,Total Volume 1999-11-18,29,32,26,30,10000 1999-11-20,30,33,27,31,9000 1999-11-22,31,34,28,32,8000 In [53]: print open('aa2.csv').read() Date,Open,High,Low,Close,Total Volume 1999-11-18,50,51,49,50,9000 1999-11-19,50,52,48,50,8000 1999-11-21,50,53,47,50,7000 的数据。

2 个答案:

答案 0 :(得分:0)

您可以创建AFTER INSERT trigger

CREATE TRIGGER DataMigration
ON Table2
AFTER INSERT
AS
BEGIN

    INSERT INTO Table1
    SELECT *
    FROM TAble2
    WHERe Status = 'false'

END
GO

答案 1 :(得分:0)

检查此示例,使用@@identity获取插入的row-id并将该id用于子表。

declare @t1 table (pk int identity(1,1) not null , name varchar(50) )
declare @t2 table (pk int identity(1,1) not null , t1pk int, status bit )
declare @new_table1Id int

insert into @t1 values( 'ajay')

set @new_table1Id = @@IDENTITY -This gives you last inserted id of @t1
insert into @t2 values( @new_table1Id , 0)

select * from @t1
select * from @t2

@@IDENTITY official documentation