您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

SQL Server 2005 返回修改后的数据

2025/7/17 12:33:33发布28次查看
今天在公司看到同事写了个sql2005的新特性的文章,觉得很实用,在这里和大家分享下。原著作权不属于我。 这种技术主要是用到了inserted和deleted虚拟表,这两张表相信大家都很熟悉。以前我们主要是在触发器中使用。 我们先来复习下这两个表: inserted和dele
今天在公司看到同事写了个sql2005的新特性的文章,觉得很实用,在这里和大家分享下。原著作权不属于我。
这种技术主要是用到了inserted和deleted虚拟表,这两张表相信大家都很熟悉。以前我们主要是在触发器中使用。
我们先来复习下这两个表:
inserted和deleted这两个表是逻辑表,并且这两个表是由系统管理的,存储在内存中,不是存储在数据库中,因此,不允许用户直接对其修改。
这两个表的结构与被该触发器作用的表在相同的表结构。这两个表是动态驻留在内存中的,当触发器工作完成,它们也被删除。
接下来,看看我们的事例,其实使用起来很简单,但也很实用。他除了用上面的两张表外,还使用了output参数。
创建表:
if exists (select * from sys.objects where object_id = object_id(n'[testtb]') and type in (n'u'))
drop table testtb
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
希望大家灵活应该!
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product