database 清空表数据并重置 IDENTITY 列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9384776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Empty table data and reset IDENTITY columns
提问by Dr.Denis McCracleJizz
I created a database in SQL Server with a couple of tables. I ran some tests and now am ready to deploy my solution, problem is, there is all sorts of data in the tables. I want to delete every row of all the tables created with my tests and put back the primary keys to zero. I tried delete which doesn't reset the primary keys index, and drop simply destroyed the table.
我在 SQL Server 中创建了一个包含几个表的数据库。我运行了一些测试,现在准备部署我的解决方案,问题是,表中有各种各样的数据。我想删除用我的测试创建的所有表的每一行,并将主键归零。我尝试了不重置主键索引的删除,而删除只是破坏了表。
回答by Aaron Bertrand
You can try TRUNCATE TABLEwhich deletes all rows and resets identity seeds. However you will have to execute in a certain order if you have foreign keys. In which case you will need to delete from the child tables first, or drop the constraints and re-add them.
您可以尝试TRUNCATE TABLE删除所有行并重置身份种子。但是,如果您有外键,则必须按特定顺序执行。在这种情况下,您需要先从子表中删除,或者删除约束并重新添加它们。
Also note that if you are using IDENTITYyou really shouldn't expect the numbers to mean anything, or to be generated forever without gaps. You shouldn't care whether it starts at 1 vs. 22 or 65 - can you explain why the identity values need to be reset?
另请注意,如果您正在使用,IDENTITY您真的不应该期望这些数字有任何意义,或者永远没有间隙地生成。您不应该关心它是从 1 还是 22 或 65 开始 - 您能解释为什么需要重置标识值吗?
回答by Valamas
From: http://www.howtogeek.com/howto/database/reset-identity-column-value-in-sql-server/
来自:http: //www.howtogeek.com/howto/database/reset-identity-column-value-in-sql-server/
To set the value of the next ID to be 1, I can use this command:
要将下一个 ID 的值设置为 1,我可以使用以下命令:
DBCC CHECKIDENT (orders, RESEED, 0)

