Sql server 如何在第一个表中插入行的基础上在另一个表中插入行
如果表A中发生任何插入,那么我需要将最后插入的行插入表B 如何使用@@rowcount执行此操作 我正在尝试下面的代码Sql server 如何在第一个表中插入行的基础上在另一个表中插入行,sql-server,sql-server-2008,Sql Server,Sql Server 2008,如果表A中发生任何插入,那么我需要将最后插入的行插入表B 如何使用@@rowcount执行此操作 我正在尝试下面的代码 create table table1 ( id int identity(1,1), column1 nvarchar ) create table table2 ( id int identity(1,1), column1 nvarchar ) Create procedure insert1 @column1 nvarchar AS De
create table table1
(
id int identity(1,1),
column1 nvarchar
)
create table table2
(
id int identity(1,1),
column1 nvarchar
)
Create procedure insert1
@column1 nvarchar
AS
Declare @t int,@column2 nvarchar
insert into table1 values(@column1)
select * from table1
set @t= (Select @@IDENTITY from table1)
Insert into table2 values (@t)
请让我知道如何通过触发器执行相同的操作。您可以编写如下触发器:
CREATE TRIGGER trgTableAInsert
ON dbo.Table1
FOR INSERT
AS
INSERT INTO dbo.Table2(Column1)
SELECT Column1
FROM Inserted
注意事项:
- 每个语句调用一次触发器,例如,如果您的
语句插入10行,则触发器调用一次,并且INSERT
包含新插入的10行(是否将所有10行插入Inserted
?)表B
- 我建议在表上始终使用模式前缀(dbo.部分)
- 我建议始终在
和插入
语句中明确指定列的列表-不要忽略它们!(或者,当其中一个表突然更改时,您可能会遇到混乱且难以调试的问题)选择