当前位置:Gxlcms > 数据库问题 > SQL执行并返回执行前/后结果

SQL执行并返回执行前/后结果

时间:2021-07-01 10:21:17 帮助过:21人阅读

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 @temp TableTABLE(    idint,    Provincevarchar(50),    Cityvarchar(50) )DELETEFROMTestTB OUTPUT deleted.*INTO@tempTableWHEREid>4SELECT*FROM@tempTable
-- 返回更新前的值 UPDATE ppdai_jr_shop.dbo.GeneratorUniqueNo SET suffix=suffix+2  OUTPUT Inserted.suffix WHERE prefix=‘PPDTK‘ -- 返回更新后的值 UPDATE ppdai_jr_shop.dbo.GeneratorUniqueNo SET suffix=suffix+2  OUTPUT DELETED.suffix WHERE prefix=‘PPDTK‘

SQL执行并返回执行前/后结果

标签:tab   bsp   nbsp   变量   dai   eid   declare   before   har   

人气教程排行