Cenário:
Vamos pensar em um banco de dados que usamos para nosso processo de ETL e chamamos esse banco de dados de teste. Queremos truncar todas as tabelas de manhã para que possam ser usadas no processo diário. Uma vez que a maneira é escrever nossa instrução Truncate para cada tabela, mas as tabelas podem ser descartadas ou novas tabelas também podem ser criadas. Queremos escrever uma consulta que possa ser usada para truncar todas as tabelas de um banco de dados e não precisamos reescrever nossas instruções de truncamento.Se as tabelas não tiverem Chave Primária - Chave Estrangeira relacionamento, podemos usar Truncar. Mas muitas vezes temos tabelas que são referenciadas por outras tabelas. Não podemos usar a instrução Truncate para essas tabelas. A única maneira de truncar essas tabelas é descartar a restrição de chave estrangeira antes de truncar e, em seguida, truncar e recriar o relacionamento depois disso.
O código abaixo pode ser usado para truncar todas as tabelas do banco de dados. Se as Tabelas tiverem o relacionamento Pk-Fk, o script descartará as restrições de chave estrangeira primeiro e, em seguida, truncará essas tabelas e, finalmente, recriará as restrições de chave estrangeira.
Antes de executar abaixo do script, verifique se você está apontando para banco de dados e servidor corretos! Tudo de bom com Truncando todas as tabelas de um banco de dados SQL Server.
-- Drop Temp Tables if Exists
IF OBJECT_ID('tempdb..#DropConstraint') IS NOT NULL
DROP TABLE #DropConstraint
IF OBJECT_ID('tempdb..#CreateConstraint') IS NOT NULL
DROP TABLE #CreateConstraint
IF OBJECT_ID('tempdb..#TempTruncateTables') IS NOT NULL
DROP TABLE #TempTruncateTables
-- Drop Constraint Script Save in #DropConstraint Temp Table
SELECT 'ALTER TABLE ' + '['
+ Schema_name(o.schema_id) + '].['
+ OBJECT_NAME(FK.parent_object_id) + ']'
+ ' DROP CONSTRAINT ' + '[' + FK.name + ']' AS DropConstraintQuery
INTO #DropConstraint
FROM sys.foreign_keys AS FK
INNER JOIN sys.foreign_key_columns AS FKC
ON FK.OBJECT_ID = FKC.constraint_object_id
INNER JOIN sys.objects O
ON O.OBJECT_ID = FKC.parent_object_id
-- Create Constraint Script Save in #CreateConstraint Temp Table
SELECT 'ALTER TABLE ' + '['
+ Schema_name(o.schema_id) + '].' + '['
+ OBJECT_NAME(FK.parent_object_id) + ']'
+ ' ADD CONSTRAINT ' + '[' + FK.name
+ '] Foreign Key (['
+ (SELECT name
FROM sys.columns c
WHERE c.OBJECT_ID = FKC.parent_object_id
AND c.column_id = FKC.parent_column_id)
+ ']) REFERENCES ' + '['
+ Schema_name(o.schema_id) + '].['
+ (SELECT name
FROM sys.objects o
WHERE OBJECT_ID = FKC.referenced_object_id)
+ '] (['
+ (SELECT name
FROM sys.columns c
WHERE c.OBJECT_ID = FKC.referenced_object_id
AND c.column_id = FKC.referenced_column_id)
+ '])' AS CreateConstraintQuery
INTO #CreateConstraint
FROM sys.foreign_keys AS FK
INNER JOIN sys.foreign_key_columns AS FKC
ON FK.OBJECT_ID = FKC.constraint_object_id
INNER JOIN sys.objects o
ON FKC.parent_object_id = o.OBJECT_ID
-- Build Truncate Statement for all the tables and save into #TempTruncateTables
SELECT 'Truncate table ' + Schema_name(schema_id)
+ '.' + name AS TruncateTableQuery
INTO #TempTruncateTables
FROM sys.tables
WHERE TYPE = 'U'
AND is_ms_shipped = 0
GO
-- Drop Constraints
DECLARE @DropConstraintQuery AS VARCHAR(4000)
DECLARE DropConstraintCur CURSOR FOR
SELECT DropConstraintQuery
FROM #DropConstraint
OPEN DropConstraintCur
FETCH Next FROM DropConstraintCur
INTO @DropConstraintQuery
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @SQL VARCHAR(MAX)=NULL
SET @SQL=@DropConstraintQuery
EXEC (@SQL)
PRINT ' Query ::' + @DropConstraintQuery
+ 'Completed'
FETCH Next FROM DropConstraintCur INTO @DropConstraintQuery
END
CLOSE DropConstraintCur
DEALLOCATE DropConstraintCur
GO-- Truncate tables
DECLARE @TempTruncateTablesCur AS VARCHAR(4000)
DECLARE TempTruncateTablesCur CURSOR FOR
SELECT TruncateTableQuery
FROM #TempTruncateTables
OPEN TempTruncateTablesCur
FETCH Next FROM TempTruncateTablesCur
INTO @TempTruncateTablesCur
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @SQL VARCHAR(MAX)=NULL
SET @SQL=@TempTruncateTablesCur
EXEC (@SQL)
PRINT ' Query ::' + @TempTruncateTablesCur
+ 'Completed'
FETCH Next FROM TempTruncateTablesCur INTO @TempTruncateTablesCur
END
CLOSE TempTruncateTablesCur
DEALLOCATE TempTruncateTablesCur
GO
-- Create Constraint After Truncate
DECLARE @CreateConstraintQuery AS VARCHAR(4000)
DECLARE CreateConstraintQueryCur CURSOR FOR
SELECT CreateConstraintQuery
FROM #CreateConstraint
OPEN CreateConstraintQueryCur
FETCH Next FROM CreateConstraintQueryCur
INTO @CreateConstraintQuery
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @SQL VARCHAR(MAX)=NULL
SET @SQL=@CreateConstraintQuery
EXEC (@SQL)
PRINT ' Query ::' + @CreateConstraintQuery
+ 'Completed'
FETCH Next FROM CreateConstraintQueryCur INTO @CreateConstraintQuery
END
CLOSE CreateConstraintQueryCur
DEALLOCATE CreateConstraintQueryCur
GO
Things we covered in this Post
How to drop temp table if exists in SQL Server
How to use system tables to get Primary key and foreign key Constraint
How to use Cursors in SQL Server
How to Drop Foreign Key Constraints dynamically and Recreate them
How to Truncate all tables in SQL Server Database
How to use Dynamic SQL in TSQL
How to use Variables in TSQL