北滘,石家庄中美经贸,语言栏没有了怎么办
本文以一个简单实例为大家介绍了sql中truncate和delete的区别,帮助大家理解,具体内容如下
---创建表table1 if object_id('table1','u') is not null drop table table1 go create table table1 (id int not null, foid int not null) go --插入测试数据 insert into table1 values(1,101),(2,102),(3,103),(4,104) go ---创建表table2 if object_id('table2','u') is not null drop table table2 go create table table2 ( foid int not null) go --插入测试数据 insert into table2 values(101),(102),(103),(104) go select * from table1 go select * from table2 go
在table1表中创建触发器,当表中的数据被删除时同时删除table2表中对应的foid
create trigger tg_table1 on table1 after delete as begin delete from ta from table2 ta inner join deleted tb on ta.foid=tb.foid end go
---测试delete删除操作 delete from table1 where id=1 go ---执行触发器成功,table2表中的foid=101的数据也被删除 select * from table1 go select * from table2
---测试truncate删除操作 truncate table table1 go ---table2中的数据没有被删除 select * from table1 go select * from table2
---查看truncate和delete的日志记录情况 checkpoint go select * from fn_dblog(null,null) go delete from table2 where foid=102 go select * from fn_dblog(null,null)
在第四行记录有一个lop_delete_rows,lcx_heap的删除操作日志记录
----truncate日志记录 checkpoint go select * from fn_dblog(null,null) go truncate table table2 go select * from fn_dblog(null,null) go
truncate操作没有记录删除日志操作
主要的原因是因为truncate操作不会激活触发器,因为truncate操作不会记录各行的日志删除操作,所以当你需要删除一张表的数据时你需要考虑是否应该如有记录日志删除操作,而不是根据个人的习惯来操作。
以上就是本文的全部内容,希望对大家区分sql中truncate和delete的使用方法有所帮助。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
数据库SQL---数据库、基本表、视图、索引的定义、修改、删除
在 Azure CentOS VM 中配置 SQL Server 2019 AG - (上)
在 Azure CentOS VM 中配置 SQL Server 2019 AG - (下)
网友评论