当前位置:网站首页>The difference between delete and truncate in SQL Server
The difference between delete and truncate in SQL Server
2021-02-23 17:47:53 【Manong translation station】
DELETE and TRUNCATE The difference between sentences is one of the most common questions in job interviews . Both statements can remove data from a table . However , There are also differences .
This article will focus on these differences , It is illustrated by examples .
TRUNCATE |
DELETE |
Delete all records from the table . We can't use WHERE Delete specific records |
Delete all records , And can be used WHERE Delete specific records . |
Don't trigger DELETE trigger . |
Trigger DELETE trigger |
Reset identity column |
Do not reset the identity column |
Because there are very few logs , So it's faster . |
Because a table scan was performed , To calculate the number of rows to delete , And delete the rows one by one , So it's going to be slower . Changes are recorded in the transaction log . |
Using row level locks |
Using table level locks |
need ALTER TABLE jurisdiction |
You need a watch DELETE jurisdiction |
For demonstration purposes , I created a project called studentDB Table of . besides , Two more tables were created ,tblSchool and tblStudent, And insert some records into these two tables .
The following statement creates tblStudent surface :
CREATE TABLE [dbo].[tblStudent](
[ID] [int] IDENTITY(1,1) NOT NULL,
[student_name] [varchar](250) NOT NULL,
[student_code] [varchar](5) NOT NULL,
[student_grade] [char](2) NOT NULL,
[SchoolID] [int] NOT NULL,
CONSTRAINT [PK_tblStudent] PRIMARY KEY CLUSTERED
( [ID] ASC))
GO
ALTER TABLE [dbo].[tblStudent] WITH CHECK ADD CONSTRAINT [FK_tblStudent_tblSchool] FOREIGN KEY([SchoolID])
REFERENCES [dbo].[tblSchool] ([School_ID])
GO
ALTER TABLE [dbo].[tblStudent] CHECK CONSTRAINT [FK_tblStudent_tblSchool]
GO
The following statement creates tblSchool surface :
CREATE TABLE [dbo].[tblSchool](
[School_ID] [int] IDENTITY(1,1) NOT NULL,
[School_Name] [varchar](500) NULL,
[City] [varchar](50) NULL,
CONSTRAINT [PK_tblSchool] PRIMARY KEY CLUSTERED
([School_ID] ASC)) ON [PRIMARY]
GO
Insert data into tblStudent In the table :
insert into [dbo].[tblStudent] ([student_name],[student_code],[student_grade],[SchoolID])
values
('Nisarg Upadhyay','ST001','A',1),
('Nirali Upadhyay','ST002','B',1),
('Dixit Upadhyay','ST003','A',1),
('Bharti Upadhyay','ST004','C',2),
('Nimesh Patel','ST005','C',2),
('Raghav Dave','ST006','A',1)
Go
Insert data into tblSchool In the table :
insert into [dbo].[tblSchool] ([school_name], [city])
values
('Nalanda School','Mehsana'),
('Sarvajanik School','Mehsana')
Now? , Let's look at the difference between the two .
1. Delete data
DELETE The function of the command is to remove a specific / All records .TRUNCATE Statement to delete all data .
-
DELETE
To use DELETE Delete specific records , You can use... In queries WHERE Clause . Let's say we want to go from tblstudent Delete some students from the table , The student's code is ST002. stay DELETE Add the following condition to the statement :
Delete from tblstudent where student_code='ST002'
After execution , Only one record in the table will be deleted . Once the record is deleted , function select Query and view data :
-
TRUNCATE
stay truncate in , add to WHERE Clause is impossible . The following query was deleted tblStudent All records in the table :
Truncate table tblStudent
2. trigger
When we run DELETE When the sentence is ,SQL Would call DELETE trigger .
I am already in tblStudent A new one named trgdeleteStudent The trigger of . When the tblstudent Table execution DELETE When the sentence is , The trigger will be in tblDeletedStudent Insert a record in the table .
establish tbldeletedStudent Of T-SQL The code is as follows :
CREATE TABLE [dbo].[tblDelatedStudents]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Student_Code] [varchar](10) NULL,
CONSTRAINT [PK_tblDelatedStudents] PRIMARY KEY CLUSTERED ([ID] ASC)
)
The following code creates the trigger :
create TRIGGER trgdeleteStudent on [tblStudent]
FOR DELETE
AS
INSERT INTO [dbo].[tblDelatedStudents](student_code)
SELECT student_code
FROM DELETED;
GO
Run the following query to delete students ST0001 The record of :
delete from tblstudent where student_code='ST001'
Execute the following query command to verify :
select * from [dbo].[tblDelatedStudents]
As you can see in the screenshot above , A record is added to tblDelatedStudents In the table .
Now? , Let's run TRUNCATE TABLE Statement to delete tblstudent Table data :
Truncate table [dbo].[tblDelatedStudents]
By inquiring tblDeletedStudent To verify the data :
select * from [dbo].[tblDelatedStudents]
As you can see ,tblDeletedStudent There are no records inserted in the table . therefore ,trgdeletestudent The trigger is not triggered .
3. Reset identity column
When executed DELETE When the sentence is , The identity column is not reset to the initial value . about TRUNCATE sentence , The identity column will be reset .
-
DELETE
perform DELETE Statement delete tblStudent Table data :
delete from tblStudent where student_code='ST004'
then , Perform the following insert sentence , To watch tblStudent Add records :
insert into [dbo].[tblStudent] ([student_name],[student_code],[student_grade],[SchoolID])
values
('Ramesh Upadhyay','ST007','B',2)
Go
Execute the following query command to view tblStudent The data of :
select * from [dbo].[tblStudent]
The initial identity column value plus 1.
-
TRUNCATE
Perform the following TRUNCATE Statement delete tblStudent Table data :
Truncate table [dbo].[tblStudents]
After deleting data , Insert records into the table :
insert into [dbo].[tblStudent] ([student_name],[student_code],[student_grade],[SchoolID])
values
('Nisarg Upadhyay','ST001','A',1),
('Nirali Upadhyay','ST002','B',1),
('Dixit Upadhyay','ST003','A',1),
('Bharti Upadhyay','ST004','C',2),
('Nimesh Patel','ST005','C',2),
('Raghav Dave','ST006','A',1)
Go
Execute the following query command to view tblStudent The data of :
select * from [dbo].[tblStudent]
in summary , The identity column has been reset .
4. jurisdiction
To use DELETE Statement delete data , Must have... On the table DELETE jurisdiction . To use TRUNCATE TABLE Statement delete data , We need to ALTER TABLE jurisdiction .
-
DELETE
I've created one called testuser1 Users of , And in tblStudent The delete permission is assigned to the table .
We delete student_code=ST001 Student records of :
use StudentDB
go
delete from tblstudent where student_code='ST001'
Then check tblStudent The data of :
It does delete records from the table .
-
TRUNCATE
Now? , function TRUNCATE Delete data :
use StudentDB
go
truncate table tblstudent
The query returned the following error :
Msg 1088, Level 16, State 7, Line 3
Cannot find the object "tblstudent" because it does not exist or you do not have permissions
To correct the problem , We have to allocate ALTER TABLE jurisdiction . Perform the following query , grant tblStudent Table access :
grant ALTER on tblstudent to testuser1
Re execution truncate:
use StudentDB
go
truncate table tblstudent
give the result as follows :
The data in the table is deleted .
This article explains DELETE Statement and TRUNCATE The difference between . We pointed out the common differences , It is illustrated by an example .
Link to the original text :https://codingsight.com/difference-between-delete-and-truncate-table-in-sql-server/
版权声明
本文为[Manong translation station]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/02/20210223174446240a.html
边栏推荐
- A small intelligent robot: help us automatically pull people, automatically verify payment, automatically transfer payment to personal bank card
- [4 / 25] enable template method pattern in page objects
- [5 / 25] chain of responsibility pattern
- 在Visual Studio中创建一个新的ASP.NET项目
- PAT_甲级_1108 Finding Average
- Create a new one in Visual Studio ASP.NET project
- PAT_ Grade A_ 1108 Finding Average
- NTP时间同步服务器(时钟服务器)如何助力桥梁监控系统的?
- How does NTP time synchronization server (clock server) help the development of bridge monitoring system?
- 正则表达式:备忘录
猜你喜欢
-
Regular expressions: memos
-
FIL将为新一代币王
-
Fil will be a new token King
-
PAT_甲级_1109 Group Photo
-
PAT_ Grade A_ 1109 Group Photo
-
location.host和location.hostname区别
-
大专文凭,干过工地;奋斗了六年成为阿里资深架构师,现年薪百万!
-
location.host and location.hostname difference
-
College diploma, worked in construction site; worked hard for six years to become a senior architect of Ali, with a salary of one million!
-
【亲测有效】Win10家庭版Microsoft Edge页面出现乱码的两种解决方案及gpedit.msc命令无法使用的解决策略
随机推荐
- Two solutions and solutions of garbled code on Microsoft edge page of win10 Home Edition gpedit.msc Solutions to the problem that commands cannot be used
- PAT_甲级_1110 Complete Binary Tree
- PAT_ Grade A_ 1110 Complete Binary Tree
- 实际工作中到底如何开展性能测试????
- How to carry out performance test in actual work????
- UNI-APP 记录
- Uni-app record
- PostgreSQL
- PostgreSQL
- 【STM32F407】第5章 RL-USB移植(MDK AC6)
- 单机最快MQ—Disruptor
- PAT_甲级_1111 Online Map
- [stm32f407] Chapter 5 rl-usb porting (MDK AC6)
- Single fastest MQ - disruptor
- PAT_ Grade A_ 1111 Online Map
- 如何避免微服务设计中的耦合问题
- How to avoid coupling problem in microservice design
- 51信用卡股价年初至今上浮5倍,引入银行背景高管担任行政总裁
- 51 the share price of credit card has risen five times since the beginning of the year, and senior executives with bank background have been introduced as the chief executive
- prometheus监控之进程监控(process-exporter)
- 华为轮值董事长胡厚崑:技术创新的同时要避免社会发展的分化
- 疫情推动“宅经济”,企业防御DDoS更加不能松懈
- 二分图最小点覆盖构造方案+König定理证明
- Anno&Viper -分布式锁服务端怎么实现
- 解决Win7 X64由于百联控件造成的蓝屏问题 (PassGuard_X64.sys)
- Process exporter of Prometheus monitoring
- 浅谈 Vite 2.0 原理,依赖预编译,插件机制是如何兼容 Rollup 的?
- Hu houkun, Huawei's rotating Chairman: avoid the differentiation of social development while making technological innovation
- The epidemic situation promotes "residential economy", and enterprises' defense against DDoS cannot be relaxed
- Construction scheme of minimum point cover of bipartite graph + proof of K ü nig theorem
- npm install 版本号^的坑
- Activity显示界面背后的故事:一文让你理清View的那些复杂关系
- Android面试官:Window连环十二问你顶得住吗?(快扶我起来,我还能问)
- 开发一个小程序,最好先做好课前工作
- SQL Server中DELETE和TRUNCATE的区别
- Simar 的 参考书
- 【招聘】分布式存储架构师 40K-80K*14薪
- How to implement anno & Viper - distributed lock server
- Solve the blue screen problem of win7 x64 caused by Bailian control (PassGuard)_ X64.sys)
- Talk about the vite 2.0 principle, dependence precompile, how is plug-in mechanism compatible with rollup?