我将TableA和TableB放入SQL Server 2008。
TableA有一个触发器,在INSERT& UPDATE, 在触发器我插入表B所以我的问题是如何从TableB获取插入的ID? FROM INSERTED有TableA中的记录信息吗?
ALTER TRIGGER [dbo].[trg_up_move] ON [dbo].[TableA] AFTER INSERT, UPDATE
AS
BEGIN
DECLARE @idMovINS INT
DECLARE @stationINS char(8)
DECLARE @idWorkerINS INT
DECLARE @statusINS TINYINT
SELECT @idMovINS=id_mov FROM INSERTED
SELECT @stationINS=station_number FROM INSERTED
SELECT @idWorkerINS=id_worker FROM INSERTED
SELECT @statusINS=status_mov FROM INSERTED
-- CODE
-- MORE CODE
-- MUCH MORE CODE
IF @SOMEVAL='WISE DECISION'
BEGIN
DECLARE @idTableB INT
INSERT INTO TableB (FieldA,FieldB,FieldC)VALUES(@idWorkerINS,@stationINS,'More info')
--SET @idTableB=@@IDENTITY
--SET @idTableB=SCOPE_IDENTITY()
--MAKE SOME OTHER THINGS WITH @idTableB
END
END
如果我在同一会话中向tableA发送一百或一千个插入。 我可以使用@@ identity或scope_identity()(我是最后一个)来获取b insert的标识吗?并且每次触发触发时都考虑使用这两个功能中的一个以及完成所有触发器功能的时间
是多么方便和安全答案 0 :(得分:1)
触发器基于设置。因此,获得单一身份的概念是错误的。
Aka,如果你插入10行,那么"插入"表格上有10行。
以下示例显示"输出"的使用。我相信它会更好地满足您的需求。
create table PrimaryHolderTable ( i int identity (1001,2) not null primary key, j int not null unique )
create table #OutputResultsHolder ( i int not null, j int not null)
insert into PrimaryHolderTable (j)
output inserted.i, inserted.j into #OutputResultsHolder
select top 10 o.object_id from sys.objects as o order by o.object_id desc /*<< from sys.objects is there just to provide some rows */
select * from #OutputResultsHolder
drop table #OutputResultsHolder, PrimaryHolderTable;
go
create table dbo.EmployeeTable ( EmpKey int identity(1001,2) , EmpAge int not null );
create table dbo.AuditTable ( EntityKey int not null default -1 , OldValue int null, NewValue int null , Tag varchar(64) );
insert into dbo.EmployeeTable (EmpAge)
output inserted.EmpKey , null , inserted.EmpAge , 'Employee Inserted' into dbo.AuditTable ( EntityKey , OldValue , NewValue , Tag)
values( 18 );
insert into dbo.EmployeeTable (EmpAge)
output inserted.EmpKey , null , inserted.EmpAge , 'Employee Inserted' into dbo.AuditTable ( EntityKey , OldValue , NewValue , Tag)
values( 20 );
insert into dbo.EmployeeTable (EmpAge)
output inserted.EmpKey , null , inserted.EmpAge , 'Employee Inserted' into dbo.AuditTable ( EntityKey , OldValue , NewValue , Tag)
values( 22 );
update dbo.EmployeeTable
set EmpAge = EmpAge + 1
output inserted.EmpKey , deleted.EmpAge, inserted.EmpAge , 'Employee Updated' into dbo.AuditTable ( EntityKey , OldValue , NewValue , Tag)
where EmpAge <=20;
delete from dbo.EmployeeTable
output deleted.EmpKey , deleted.EmpAge, NULL , 'Employee Deleted' into dbo.AuditTable (EntityKey , OldValue , NewValue , Tag)
where EmpAge > 0; /*Test multi rows*/
select * from dbo.EmployeeTable; /* <<will be empty at this point */
select * from dbo.AuditTable;
drop table dbo.EmployeeTable, dbo.AuditTable;
go