如何从表中逐行插入数据,然后逐行插入另一个表

时间:2019-07-04 08:27:02

标签: sql-server datatables

我有两个具有自动生成的ID的表(A,B),我需要在对一个(A)进行插入时自动将该表的ID放入另一个(B.Aid)的列中

我尝试了一个触发器,一个称为过程的游标...

2 个答案:

答案 0 :(得分:1)

这可以达到目的

-- DROP TABLE A
-- DROP TABLE B

CREATE TABLE A (Id INT IDENTITY(1,1), Name VARCHAR(50))
CREATE TABLE B (Id INT IDENTITY(1,1), Name VARCHAR(50), Aid INT)
GO
CREATE TRIGGER TriggerToAddAutoIntoTableB ON A
AFTER INSERT
AS
    INSERT INTO B (Name,Aid) 
    SELECT i.Name,i.id
    FROM inserted i

GO
INSERT INTO A (Name) values ('A1')
INSERT INTO A (Name) values ('A2')
INSERT INTO A (Name) values ('A3')
GO
SELECT * FROM A
SELECT * FROM B

答案 1 :(得分:0)

使用INSERT INTO SELECT函数

INSERT INTO dbo.eexample(street, city, state, zip_code) 
SELECT
    street,
    city,
    state,
    zip_code
FROM
    dbo.anotherexample
where
 ORDER BY anotherexample.Id