且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在sql server 2005中截断多个表

更新时间:2023-02-03 13:03:57

你可以通过多种方式实现这一目标

1.
You can do it in many ways
1.
EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'



但是你不能截断具有外键的表,所以这只有在表之间没有外键约束时才有效。无论如何你都可以禁用约束。



2.如果你知道要截断的表的特定前缀,请使用动态查询,例如emp_


but you cannot truncate tables which have foreign keys, so this will only work if there are no foreign key constraints between tables. You can disable constraint anyways.

2. use dynamic query if you know specific prefix of tables to truncate e.g emp_

SELECT 'TRUNCATE TABLE ' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'emp%'



此查询将返回表的Truncate语句,然后您可以立即运行这些查询。 (如果有外键,它也不会被截断)

3.您可以使用带有动态查询的光标来选择和截断具有上述动态查询的表格。



谢谢


this query will return Truncate statements of tables and then you can run these query at once. (again it will not truncate if having foreign key)
3. You can use cursor with dynamic query to select and truncate tables with above dynamic query.

Thanks