这种技术主要是用到了inserted和deleted虚拟表,这两张表相信大家都很熟悉。以前我们主要是在触发器中使用。
我们先来复习下这两个表:
Inserted和Deleted这两个表是逻辑表,并且这两个表是由系统管理的,存储在内存中,不是存储在数据库中,因此,不允许用户直接对其修改。
这两个表的结构与被该触发器作用的表在相同的表结构。这两个表是动态驻留在内存中的,当触发器工作完成,它们也被删除。
接下来,看看我们的事例,其实使用起来很简单,但也很实用。他除了用上面的两张表外,还使用了output参数。
create table TestTB
(
id int identity(1,1) primary key not null,
Province varchar(50) null,
City varchar(50) null
)
1、插入数据,并返回插入的数据:
insert into TestTB(Province,City)
output inserted.Province, inserted.City
values ('广东','深圳')
2、同理,删除数据也是一样的,只不过是使用deleted表罢了
delete from TestTB
output deleted.*
where id=1
3、两个结合一起:返回更新前和更新后的数据:
update TestTB set Province = '湖南',City='郴州'
output '我来自(更新前)'+ DELETED.Province+DELETED.City as [Before] ,'我来自(更新后)' + Inserted.Province+Inserted.City as [After]
where id=1
4、还可以将返回的结果保存在表变量中,这在删除数据,并把删除的数据插入到历史表时很实用
declare @tempTable table(
id int,
Province varchar(50),
City varchar(50)
)
delete from TestTB output deleted.* into @tempTable
where id > 4
select * from @tempTable