SQL中TRUNCATE和DELETE的区别是什么?
如果你的答案是针对特定平台的,请注明。
SQL中TRUNCATE和DELETE的区别是什么?
如果你的答案是针对特定平台的,请注明。
当前回答
一眨眼的功夫就不能做DDL。
其他回答
删除
DELETE是一个DML命令 DELETE可以回退 Delete =仅删除-因此可以回滚 在DELETE中,可以使用WHERE子句编写条件 语法- Delete from [Table] where [Condition]
截断
TRUNCATE是一个DDL命令 不能在TRUNCATE中回滚,TRUNCATE将永久删除该记录 Truncate = Delete+Commit -这样我们就不能回滚 不能在TRUNCATE中使用条件(WHERE子句) 语法- Truncate table [table]
详情请浏览
http://www.zilckh.com/what-is-the-difference-between-truncate-and-delete/
这两个操作的另一个区别是,如果表包含一个标识列,则在TRUNCATE下该列的计数器将重置1(或为该列定义的种子值)。DELETE没有这种影响。
TRUNCATE是DDL语句,而DELETE是DML语句。以下是两者的区别:
As TRUNCATE is a DDL (Data definition language) statement it does not require a commit to make the changes permanent. And this is the reason why rows deleted by truncate could not be rollbacked. On the other hand DELETE is a DML (Data manipulation language) statement hence requires explicit commit to make its effect permanent. TRUNCATE always removes all the rows from a table, leaving the table empty and the table structure intact whereas DELETE may remove conditionally if the where clause is used. The rows deleted by TRUNCATE TABLE statement cannot be restored and you can not specify the where clause in the TRUNCATE statement. TRUNCATE statements does not fire triggers as opposed of on delete trigger on DELETE statement
这里有一个非常好的与主题相关的链接。
如果将TRUNCATE包装在事务中,则可以回滚。
请参阅下面的两个参考资料并自行测试:-
http://blog.sqlauthority.com/2007/12/26/sql-server-truncate-cant-be-rolled-back-using-log-files-after-transaction-session-is-closed/
http://sqlblog.com/blogs/kalen_delaney/archive/2010/10/12/tsql-tuesday-11-rolling-back-truncate-table.aspx
截断与删除是SQL面试中最臭名昭著的问题之一。一定要向面试官解释清楚,否则可能会让你丢掉这份工作。问题是没有多少人意识到这一点,所以如果你告诉他们YES Truncate可以回滚,他们很可能会认为答案是错误的。
微软sql server的另一个不同之处在于,使用delete,你可以使用output语句来跟踪哪些记录被删除了,例如:
delete from [SomeTable]
output deleted.Id, deleted.Name
你不能用truncate这样做。