SQL Server 2005 - Truncate All Tables

SQL Server 2005 - Truncate All Tables

Truncate All Tables - Part II by Madhivanan

  1. SET NoCount ON
  2. DECLARE @tableName varchar( 200 )
  3. SET @tableName=''
  4. WHILE EXISTS
  5. (
  6. --Find all child tables and those which have no relations
  7. SELECT T.table_name
  8. FROM INFORMATION_SCHEMA.TABLES T
  9. LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
  10. ON T.table_name = TC.table_name
  11. WHERE ( TC.constraint_Type = 'Foreign Key' OR TC.constraint_Type IS NULL )
  12. AND T.table_name NOT IN ( 'dtproperties', 'sysconstraints', 'syssegments' )
  13. AND Table_type = 'BASE TABLE'
  14. AND T.table_name > @TableName
  15. )
  16. Begin
  17. SELECT @tableName = min(T.table_name)
  18. FROM INFORMATION_SCHEMA.TABLES T
  19. LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
  20. ON T.table_name=TC.table_name
  21. WHERE ( TC.constraint_Type = 'Foreign Key' OR TC.constraint_Type IS NULL )
  22. AND T.table_name NOT IN ( 'dtproperties', 'sysconstraints', 'syssegments' )
  23. AND Table_type = 'BASE TABLE'
  24. AND T.table_name > @TableName
  25. --Truncate the table
  26. Exec( 'Truncate table '+@tableName)
  27. End
  28. SET @TableName=''
  29. WHILE EXISTS
  30. (
  31. --Find all Parent tables
  32. SELECT T.table_name
  33. FROM INFORMATION_SCHEMA.TABLES T
  34. LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
  35. ON T.table_name = TC.table_name
  36. WHERE TC.constraint_Type = 'Primary Key'
  37. AND T.table_name <> 'dtproperties'
  38. AND Table_type='BASE TABLE'
  39. AND T.table_name > @TableName
  40. )
  41. Begin
  42. SELECT @tableName = min(T.table_name)
  43. FROM INFORMATION_SCHEMA.TABLES T
  44. LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
  45. ON T.table_name=TC.table_name
  46. WHERE TC.constraint_Type = 'Primary Key'
  47. AND T.table_name <> 'dtproperties'
  48. AND Table_type = 'BASE TABLE'
  49. AND T.table_name > @TableName
  50. --Delete the table
  51. Exec( 'Delete from '+@tableName)
  52. --Reset identity column
  53. IF EXISTS
  54. (
  55. SELECT *
  56. FROM INFORMATION_SCHEMA.COLUMNS
  57. WHERE COLUMNPROPERTY(
  58. OBJECT_ID( QUOTENAME(table_schema)+ '.' + QUOTENAME(@tableName) ),
  59. column_name,'IsIdentity'
  60. ) = 1
  61. )
  62. DBCC CHECKIDENT (@tableName, RESEED, 1 )
  63. End
  64. SET NoCount OFF