一个含有自增序列的表,使用delete跟truncate之后会有什么不同结果呢?
大概说一下,使用truncate,表中的记录全部被清除,如果向表中插入数据,那么数据的排序是从1开始的。
如果使用的是delete,那么记录的排序值不会被清除,它是一次累加上去的。下面给出一个小例子,可以参考一下
------------================================ --Author:oliver QIN --DATE:2015-12-21 --DESC:INDETITY(1,1)使用delete跟truncate后排序是怎么变化的 ---==========================================建表 if exists(select * from sysobjects where ID=OBJECT_ID(N‘TB‘) AND XTYPE=‘u‘) drop table TB CREATE TABLE TB(ID INT IDENTITY(1,1),NAME NVARCHAR(100),dtDate datetime) INSERT INTO TB SELECT ‘JACK‘,SUBSTRING(convert(varchar,dateadd(dd,-day(getdate()),getdate()),120),1,10) UNION ALL SELECT ‘TOM‘ ,SUBSTRING(convert(varchar,dateadd(dd,-day(getdate()),getdate()),120),1,10) --===============建立存储过程(delete),先判断是否存在数据,如果存在就删除,然后插入数据,看序列的变化 go IF((SELECT COUNT(*) FROM SYSOBJECTS WHERE ID=OBJECT_ID(N‘P_sample_DELETE‘) AND XTYPE=‘P‘)>0 ) DROP PROC P_sample_DELETE GO CREATE PROC P_sample_DELETE as begin if((select count(*) from TB WHERE dtDate=SUBSTRING(convert(varchar,dateadd(dd,-day(getdate()),getdate()),120),1,10))>0) begin delete from TB --WHERE dtDate=SUBSTRING(convert(varchar,dateadd(dd,-day(getdate()),getdate()),120),1,10) end INSERT INTO TB SELECT ‘JACK‘,SUBSTRING(convert(varchar,dateadd(dd,-day(getdate()),getdate()),120),1,10) UNION ALL SELECT ‘TOM‘ ,SUBSTRING(convert(varchar,dateadd(dd,-day(getdate()),getdate()),120),1,10) end GO --===============建立存储过程(truncate),先判断是否存在数据,如果存在就删除,然后插入数据,看序列的变化 IF((SELECT COUNT(*) FROM SYSOBJECTS WHERE ID=OBJECT_ID(N‘P_sample_TRUNCATE‘) AND XTYPE=‘P‘)>0 ) DROP PROC P_sample_TRUNCATE GO CREATE PROC P_sample_TRUNCATE as begin if((select count(*) from TB WHERE dtDate=SUBSTRING(convert(varchar,dateadd(dd,-day(getdate()),getdate()),120),1,10))>0) begin TRUNCATE TABLE TB end INSERT INTO TB SELECT ‘JACK‘,SUBSTRING(convert(varchar,dateadd(dd,-day(getdate()),getdate()),120),1,10) UNION ALL SELECT ‘TOM‘ ,SUBSTRING(convert(varchar,dateadd(dd,-day(getdate()),getdate()),120),1,10) end
--------------调用三次TRUNCATE EXEC P_sample_TRUNCATE EXEC P_sample_TRUNCATE EXEC P_sample_TRUNCATE
输出结果如下:
-------------调用三次DELETE EXEC P_sample_DELETE EXEC P_sample_DELETE EXEC P_sample_DELETE
输出结果如下:
时间: 2024-12-28 01:02:16