Truncate all Tables in Database with T-SQLWhy is truncate DDL?Oracle GoldenGate add trandata errorsTruncate...

Is this apparent Class Action settlement a spam message?

How do I rename a Linux host without needing to reboot for the rename to take effect?

How does Loki do this?

How do scammers retract money, while you can’t?

How does the UK government determine the size of a mandate?

India just shot down a satellite from the ground. At what altitude range is the resulting debris field?

Why, precisely, is argon used in neutrino experiments?

How to Reset Passwords on Multiple Websites Easily?

Tiptoe or tiphoof? Adjusting words to better fit fantasy races

Avoiding estate tax by giving multiple gifts

What happens if you roll doubles 3 times then land on "Go to jail?"

What is the opposite of 'gravitas'?

Would a high gravity rocky planet be guaranteed to have an atmosphere?

Is the destination of a commercial flight important for the pilot?

What can we do to stop prior company from asking us questions?

How to pronounce the slash sign

How to check is there any negative term in a large list?

Implement the Thanos sorting algorithm

Trouble understanding the speech of overseas colleagues

Do the temporary hit points from the Battlerager barbarian's Reckless Abandon stack if I make multiple attacks on my turn?

Are student evaluations of teaching assistants read by others in the faculty?

How do I find the solutions of the following equation?

How to safely derail a train during transit?

Pole-zeros of a real-valued causal FIR system



Truncate all Tables in Database with T-SQL


Why is truncate DDL?Oracle GoldenGate add trandata errorsTruncate log file mirrored databaseTruncate/delete tables for non-owner schemaEffect of TRUNCATE TABLE different from DELETE on subsequent queriesAudit all does not capture truncateTruncate tables with dependent foreign key constraintsSQL Server TRUNCATE TABLE permissionsWill TRUNCATE stop the increase of the DB2 database size?Adding IF Exist to truncate statement while looping through DBs













-1















Is there a way to truncate all tables in a database without using sp_MSForEachTable in TSQL Language?
Background: not my call, DBA company policy does not allow sp_MSForEachTable.



EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'


Wondering if this is most efficient way, or another option available?



select 'truncate table ' + Table_Schema + '.' + Table_Name from INFORMATION_SCHEMA.tables where table_type = 'base table'


Another site recommends this:
https://www.mssqltips.com/sqlservertip/3218/truncate-all-tables-in-a-sql-server-database/



 /* TRUNCATE ALL TABLES IN A DATABASE */
DECLARE @dropAndCreateConstraintsTable TABLE
(
DropStmt VARCHAR(MAX)
,CreateStmt VARCHAR(MAX)
)
/* Gather information to drop and then recreate the current foreign key constraints */
INSERT @dropAndCreateConstraintsTable
SELECT DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
+ '].[' + ForeignKeys.ForeignTableName + '] DROP CONSTRAINT ['
+ ForeignKeys.ForeignKeyName + ']; '
,CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
+ '].[' + ForeignKeys.ForeignTableName
+ '] WITH CHECK ADD CONSTRAINT [' + ForeignKeys.ForeignKeyName
+ '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn
+ ']) REFERENCES [' + SCHEMA_NAME(sys.objects.schema_id)
+ '].[' + sys.objects.[name] + ']([' + sys.columns.[name]
+ ']); '
FROM sys.objects
INNER JOIN sys.columns
ON ( sys.columns.[object_id] = sys.objects.[object_id] )
INNER JOIN ( SELECT sys.foreign_keys.[name] AS ForeignKeyName
,SCHEMA_NAME(sys.objects.schema_id) AS ForeignTableSchema
,sys.objects.[name] AS ForeignTableName
,sys.columns.[name] AS ForeignTableColumn
,sys.foreign_keys.referenced_object_id AS referenced_object_id
,sys.foreign_key_columns.referenced_column_id AS referenced_column_id
FROM sys.foreign_keys
INNER JOIN sys.foreign_key_columns
ON ( sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.[object_id] )
INNER JOIN sys.objects
ON ( sys.objects.[object_id] = sys.foreign_keys.parent_object_id )
INNER JOIN sys.columns
ON ( sys.columns.[object_id] = sys.objects.[object_id] )
AND ( sys.columns.column_id = sys.foreign_key_columns.parent_column_id )
) ForeignKeys
ON ( ForeignKeys.referenced_object_id = sys.objects.[object_id] )
AND ( ForeignKeys.referenced_column_id = sys.columns.column_id )
WHERE ( sys.objects.[type] = 'U' )
AND ( sys.objects.[name] NOT IN ( 'sysdiagrams' ) )
/* SELECT * FROM @dropAndCreateConstraintsTable AS DACCT --Test statement*/
DECLARE @DropStatement NVARCHAR(MAX)
DECLARE @RecreateStatement NVARCHAR(MAX)
/* Drop Constraints */
DECLARE Cur1 CURSOR READ_ONLY
FOR
SELECT DropStmt
FROM @dropAndCreateConstraintsTable
OPEN Cur1
FETCH NEXT FROM Cur1 INTO @DropStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @DropStatement
EXECUTE sp_executesql @DropStatement
FETCH NEXT FROM Cur1 INTO @DropStatement
END
CLOSE Cur1
DEALLOCATE Cur1
/* Truncate all tables in the database in the dbo schema */
DECLARE @DeleteTableStatement NVARCHAR(MAX)
DECLARE Cur2 CURSOR READ_ONLY
FOR
SELECT 'TRUNCATE TABLE [dbo].[' + TABLE_NAME + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_TYPE = 'BASE TABLE'
/* Change your schema appropriately if you don't want to use dbo */
OPEN Cur2
FETCH NEXT FROM Cur2 INTO @DeleteTableStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @DeleteTableStatement
EXECUTE sp_executesql @DeleteTableStatement
FETCH NEXT FROM Cur2 INTO @DeleteTableStatement
END
CLOSE Cur2
DEALLOCATE Cur2
/* Recreate foreign key constraints */
DECLARE Cur3 CURSOR READ_ONLY
FOR
SELECT CreateStmt
FROM @dropAndCreateConstraintsTable
OPEN Cur3
FETCH NEXT FROM Cur3 INTO @RecreateStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @RecreateStatement
EXECUTE sp_executesql @RecreateStatement
FETCH NEXT FROM Cur3 INTO @RecreateStatement
END
CLOSE Cur3
DEALLOCATE Cur3
GO


This answer uses, so cannot utilize: sp_MSForEachTable



https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql










share|improve this question









New contributor




Adam Marcus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2





    wouldn't it be much easier to script the database, drop the database, and then recreate it from the script?

    – SQLRaptor
    yesterday






  • 2





    Just a note that TRUNCATE TABLE will fail if there are foreign keys referencing a table (even of there are no rows in the referencing table). A DELETE without a WHERE clause won't fail because of the presence of an FK, but referencing rows might make it fail (depending on the FK definition). I'm with SQLRaptor, having a script to re-create the database is usually a cleaner method, IMO.

    – Tibor Karaszi
    20 hours ago
















-1















Is there a way to truncate all tables in a database without using sp_MSForEachTable in TSQL Language?
Background: not my call, DBA company policy does not allow sp_MSForEachTable.



EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'


Wondering if this is most efficient way, or another option available?



select 'truncate table ' + Table_Schema + '.' + Table_Name from INFORMATION_SCHEMA.tables where table_type = 'base table'


Another site recommends this:
https://www.mssqltips.com/sqlservertip/3218/truncate-all-tables-in-a-sql-server-database/



 /* TRUNCATE ALL TABLES IN A DATABASE */
DECLARE @dropAndCreateConstraintsTable TABLE
(
DropStmt VARCHAR(MAX)
,CreateStmt VARCHAR(MAX)
)
/* Gather information to drop and then recreate the current foreign key constraints */
INSERT @dropAndCreateConstraintsTable
SELECT DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
+ '].[' + ForeignKeys.ForeignTableName + '] DROP CONSTRAINT ['
+ ForeignKeys.ForeignKeyName + ']; '
,CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
+ '].[' + ForeignKeys.ForeignTableName
+ '] WITH CHECK ADD CONSTRAINT [' + ForeignKeys.ForeignKeyName
+ '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn
+ ']) REFERENCES [' + SCHEMA_NAME(sys.objects.schema_id)
+ '].[' + sys.objects.[name] + ']([' + sys.columns.[name]
+ ']); '
FROM sys.objects
INNER JOIN sys.columns
ON ( sys.columns.[object_id] = sys.objects.[object_id] )
INNER JOIN ( SELECT sys.foreign_keys.[name] AS ForeignKeyName
,SCHEMA_NAME(sys.objects.schema_id) AS ForeignTableSchema
,sys.objects.[name] AS ForeignTableName
,sys.columns.[name] AS ForeignTableColumn
,sys.foreign_keys.referenced_object_id AS referenced_object_id
,sys.foreign_key_columns.referenced_column_id AS referenced_column_id
FROM sys.foreign_keys
INNER JOIN sys.foreign_key_columns
ON ( sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.[object_id] )
INNER JOIN sys.objects
ON ( sys.objects.[object_id] = sys.foreign_keys.parent_object_id )
INNER JOIN sys.columns
ON ( sys.columns.[object_id] = sys.objects.[object_id] )
AND ( sys.columns.column_id = sys.foreign_key_columns.parent_column_id )
) ForeignKeys
ON ( ForeignKeys.referenced_object_id = sys.objects.[object_id] )
AND ( ForeignKeys.referenced_column_id = sys.columns.column_id )
WHERE ( sys.objects.[type] = 'U' )
AND ( sys.objects.[name] NOT IN ( 'sysdiagrams' ) )
/* SELECT * FROM @dropAndCreateConstraintsTable AS DACCT --Test statement*/
DECLARE @DropStatement NVARCHAR(MAX)
DECLARE @RecreateStatement NVARCHAR(MAX)
/* Drop Constraints */
DECLARE Cur1 CURSOR READ_ONLY
FOR
SELECT DropStmt
FROM @dropAndCreateConstraintsTable
OPEN Cur1
FETCH NEXT FROM Cur1 INTO @DropStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @DropStatement
EXECUTE sp_executesql @DropStatement
FETCH NEXT FROM Cur1 INTO @DropStatement
END
CLOSE Cur1
DEALLOCATE Cur1
/* Truncate all tables in the database in the dbo schema */
DECLARE @DeleteTableStatement NVARCHAR(MAX)
DECLARE Cur2 CURSOR READ_ONLY
FOR
SELECT 'TRUNCATE TABLE [dbo].[' + TABLE_NAME + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_TYPE = 'BASE TABLE'
/* Change your schema appropriately if you don't want to use dbo */
OPEN Cur2
FETCH NEXT FROM Cur2 INTO @DeleteTableStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @DeleteTableStatement
EXECUTE sp_executesql @DeleteTableStatement
FETCH NEXT FROM Cur2 INTO @DeleteTableStatement
END
CLOSE Cur2
DEALLOCATE Cur2
/* Recreate foreign key constraints */
DECLARE Cur3 CURSOR READ_ONLY
FOR
SELECT CreateStmt
FROM @dropAndCreateConstraintsTable
OPEN Cur3
FETCH NEXT FROM Cur3 INTO @RecreateStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @RecreateStatement
EXECUTE sp_executesql @RecreateStatement
FETCH NEXT FROM Cur3 INTO @RecreateStatement
END
CLOSE Cur3
DEALLOCATE Cur3
GO


This answer uses, so cannot utilize: sp_MSForEachTable



https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql










share|improve this question









New contributor




Adam Marcus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2





    wouldn't it be much easier to script the database, drop the database, and then recreate it from the script?

    – SQLRaptor
    yesterday






  • 2





    Just a note that TRUNCATE TABLE will fail if there are foreign keys referencing a table (even of there are no rows in the referencing table). A DELETE without a WHERE clause won't fail because of the presence of an FK, but referencing rows might make it fail (depending on the FK definition). I'm with SQLRaptor, having a script to re-create the database is usually a cleaner method, IMO.

    – Tibor Karaszi
    20 hours ago














-1












-1








-1








Is there a way to truncate all tables in a database without using sp_MSForEachTable in TSQL Language?
Background: not my call, DBA company policy does not allow sp_MSForEachTable.



EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'


Wondering if this is most efficient way, or another option available?



select 'truncate table ' + Table_Schema + '.' + Table_Name from INFORMATION_SCHEMA.tables where table_type = 'base table'


Another site recommends this:
https://www.mssqltips.com/sqlservertip/3218/truncate-all-tables-in-a-sql-server-database/



 /* TRUNCATE ALL TABLES IN A DATABASE */
DECLARE @dropAndCreateConstraintsTable TABLE
(
DropStmt VARCHAR(MAX)
,CreateStmt VARCHAR(MAX)
)
/* Gather information to drop and then recreate the current foreign key constraints */
INSERT @dropAndCreateConstraintsTable
SELECT DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
+ '].[' + ForeignKeys.ForeignTableName + '] DROP CONSTRAINT ['
+ ForeignKeys.ForeignKeyName + ']; '
,CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
+ '].[' + ForeignKeys.ForeignTableName
+ '] WITH CHECK ADD CONSTRAINT [' + ForeignKeys.ForeignKeyName
+ '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn
+ ']) REFERENCES [' + SCHEMA_NAME(sys.objects.schema_id)
+ '].[' + sys.objects.[name] + ']([' + sys.columns.[name]
+ ']); '
FROM sys.objects
INNER JOIN sys.columns
ON ( sys.columns.[object_id] = sys.objects.[object_id] )
INNER JOIN ( SELECT sys.foreign_keys.[name] AS ForeignKeyName
,SCHEMA_NAME(sys.objects.schema_id) AS ForeignTableSchema
,sys.objects.[name] AS ForeignTableName
,sys.columns.[name] AS ForeignTableColumn
,sys.foreign_keys.referenced_object_id AS referenced_object_id
,sys.foreign_key_columns.referenced_column_id AS referenced_column_id
FROM sys.foreign_keys
INNER JOIN sys.foreign_key_columns
ON ( sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.[object_id] )
INNER JOIN sys.objects
ON ( sys.objects.[object_id] = sys.foreign_keys.parent_object_id )
INNER JOIN sys.columns
ON ( sys.columns.[object_id] = sys.objects.[object_id] )
AND ( sys.columns.column_id = sys.foreign_key_columns.parent_column_id )
) ForeignKeys
ON ( ForeignKeys.referenced_object_id = sys.objects.[object_id] )
AND ( ForeignKeys.referenced_column_id = sys.columns.column_id )
WHERE ( sys.objects.[type] = 'U' )
AND ( sys.objects.[name] NOT IN ( 'sysdiagrams' ) )
/* SELECT * FROM @dropAndCreateConstraintsTable AS DACCT --Test statement*/
DECLARE @DropStatement NVARCHAR(MAX)
DECLARE @RecreateStatement NVARCHAR(MAX)
/* Drop Constraints */
DECLARE Cur1 CURSOR READ_ONLY
FOR
SELECT DropStmt
FROM @dropAndCreateConstraintsTable
OPEN Cur1
FETCH NEXT FROM Cur1 INTO @DropStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @DropStatement
EXECUTE sp_executesql @DropStatement
FETCH NEXT FROM Cur1 INTO @DropStatement
END
CLOSE Cur1
DEALLOCATE Cur1
/* Truncate all tables in the database in the dbo schema */
DECLARE @DeleteTableStatement NVARCHAR(MAX)
DECLARE Cur2 CURSOR READ_ONLY
FOR
SELECT 'TRUNCATE TABLE [dbo].[' + TABLE_NAME + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_TYPE = 'BASE TABLE'
/* Change your schema appropriately if you don't want to use dbo */
OPEN Cur2
FETCH NEXT FROM Cur2 INTO @DeleteTableStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @DeleteTableStatement
EXECUTE sp_executesql @DeleteTableStatement
FETCH NEXT FROM Cur2 INTO @DeleteTableStatement
END
CLOSE Cur2
DEALLOCATE Cur2
/* Recreate foreign key constraints */
DECLARE Cur3 CURSOR READ_ONLY
FOR
SELECT CreateStmt
FROM @dropAndCreateConstraintsTable
OPEN Cur3
FETCH NEXT FROM Cur3 INTO @RecreateStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @RecreateStatement
EXECUTE sp_executesql @RecreateStatement
FETCH NEXT FROM Cur3 INTO @RecreateStatement
END
CLOSE Cur3
DEALLOCATE Cur3
GO


This answer uses, so cannot utilize: sp_MSForEachTable



https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql










share|improve this question









New contributor




Adam Marcus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












Is there a way to truncate all tables in a database without using sp_MSForEachTable in TSQL Language?
Background: not my call, DBA company policy does not allow sp_MSForEachTable.



EXEC sp_MSForEachTable 'TRUNCATE TABLE ?'


Wondering if this is most efficient way, or another option available?



select 'truncate table ' + Table_Schema + '.' + Table_Name from INFORMATION_SCHEMA.tables where table_type = 'base table'


Another site recommends this:
https://www.mssqltips.com/sqlservertip/3218/truncate-all-tables-in-a-sql-server-database/



 /* TRUNCATE ALL TABLES IN A DATABASE */
DECLARE @dropAndCreateConstraintsTable TABLE
(
DropStmt VARCHAR(MAX)
,CreateStmt VARCHAR(MAX)
)
/* Gather information to drop and then recreate the current foreign key constraints */
INSERT @dropAndCreateConstraintsTable
SELECT DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
+ '].[' + ForeignKeys.ForeignTableName + '] DROP CONSTRAINT ['
+ ForeignKeys.ForeignKeyName + ']; '
,CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
+ '].[' + ForeignKeys.ForeignTableName
+ '] WITH CHECK ADD CONSTRAINT [' + ForeignKeys.ForeignKeyName
+ '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn
+ ']) REFERENCES [' + SCHEMA_NAME(sys.objects.schema_id)
+ '].[' + sys.objects.[name] + ']([' + sys.columns.[name]
+ ']); '
FROM sys.objects
INNER JOIN sys.columns
ON ( sys.columns.[object_id] = sys.objects.[object_id] )
INNER JOIN ( SELECT sys.foreign_keys.[name] AS ForeignKeyName
,SCHEMA_NAME(sys.objects.schema_id) AS ForeignTableSchema
,sys.objects.[name] AS ForeignTableName
,sys.columns.[name] AS ForeignTableColumn
,sys.foreign_keys.referenced_object_id AS referenced_object_id
,sys.foreign_key_columns.referenced_column_id AS referenced_column_id
FROM sys.foreign_keys
INNER JOIN sys.foreign_key_columns
ON ( sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.[object_id] )
INNER JOIN sys.objects
ON ( sys.objects.[object_id] = sys.foreign_keys.parent_object_id )
INNER JOIN sys.columns
ON ( sys.columns.[object_id] = sys.objects.[object_id] )
AND ( sys.columns.column_id = sys.foreign_key_columns.parent_column_id )
) ForeignKeys
ON ( ForeignKeys.referenced_object_id = sys.objects.[object_id] )
AND ( ForeignKeys.referenced_column_id = sys.columns.column_id )
WHERE ( sys.objects.[type] = 'U' )
AND ( sys.objects.[name] NOT IN ( 'sysdiagrams' ) )
/* SELECT * FROM @dropAndCreateConstraintsTable AS DACCT --Test statement*/
DECLARE @DropStatement NVARCHAR(MAX)
DECLARE @RecreateStatement NVARCHAR(MAX)
/* Drop Constraints */
DECLARE Cur1 CURSOR READ_ONLY
FOR
SELECT DropStmt
FROM @dropAndCreateConstraintsTable
OPEN Cur1
FETCH NEXT FROM Cur1 INTO @DropStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @DropStatement
EXECUTE sp_executesql @DropStatement
FETCH NEXT FROM Cur1 INTO @DropStatement
END
CLOSE Cur1
DEALLOCATE Cur1
/* Truncate all tables in the database in the dbo schema */
DECLARE @DeleteTableStatement NVARCHAR(MAX)
DECLARE Cur2 CURSOR READ_ONLY
FOR
SELECT 'TRUNCATE TABLE [dbo].[' + TABLE_NAME + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_TYPE = 'BASE TABLE'
/* Change your schema appropriately if you don't want to use dbo */
OPEN Cur2
FETCH NEXT FROM Cur2 INTO @DeleteTableStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @DeleteTableStatement
EXECUTE sp_executesql @DeleteTableStatement
FETCH NEXT FROM Cur2 INTO @DeleteTableStatement
END
CLOSE Cur2
DEALLOCATE Cur2
/* Recreate foreign key constraints */
DECLARE Cur3 CURSOR READ_ONLY
FOR
SELECT CreateStmt
FROM @dropAndCreateConstraintsTable
OPEN Cur3
FETCH NEXT FROM Cur3 INTO @RecreateStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Executing ' + @RecreateStatement
EXECUTE sp_executesql @RecreateStatement
FETCH NEXT FROM Cur3 INTO @RecreateStatement
END
CLOSE Cur3
DEALLOCATE Cur3
GO


This answer uses, so cannot utilize: sp_MSForEachTable



https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql







sql-server sql-server-2016 ddl truncate






share|improve this question









New contributor




Adam Marcus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Adam Marcus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 26 mins ago







Adam Marcus













New contributor




Adam Marcus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









Adam MarcusAdam Marcus

12




12




New contributor




Adam Marcus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Adam Marcus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Adam Marcus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 2





    wouldn't it be much easier to script the database, drop the database, and then recreate it from the script?

    – SQLRaptor
    yesterday






  • 2





    Just a note that TRUNCATE TABLE will fail if there are foreign keys referencing a table (even of there are no rows in the referencing table). A DELETE without a WHERE clause won't fail because of the presence of an FK, but referencing rows might make it fail (depending on the FK definition). I'm with SQLRaptor, having a script to re-create the database is usually a cleaner method, IMO.

    – Tibor Karaszi
    20 hours ago














  • 2





    wouldn't it be much easier to script the database, drop the database, and then recreate it from the script?

    – SQLRaptor
    yesterday






  • 2





    Just a note that TRUNCATE TABLE will fail if there are foreign keys referencing a table (even of there are no rows in the referencing table). A DELETE without a WHERE clause won't fail because of the presence of an FK, but referencing rows might make it fail (depending on the FK definition). I'm with SQLRaptor, having a script to re-create the database is usually a cleaner method, IMO.

    – Tibor Karaszi
    20 hours ago








2




2





wouldn't it be much easier to script the database, drop the database, and then recreate it from the script?

– SQLRaptor
yesterday





wouldn't it be much easier to script the database, drop the database, and then recreate it from the script?

– SQLRaptor
yesterday




2




2





Just a note that TRUNCATE TABLE will fail if there are foreign keys referencing a table (even of there are no rows in the referencing table). A DELETE without a WHERE clause won't fail because of the presence of an FK, but referencing rows might make it fail (depending on the FK definition). I'm with SQLRaptor, having a script to re-create the database is usually a cleaner method, IMO.

– Tibor Karaszi
20 hours ago





Just a note that TRUNCATE TABLE will fail if there are foreign keys referencing a table (even of there are no rows in the referencing table). A DELETE without a WHERE clause won't fail because of the presence of an FK, but referencing rows might make it fail (depending on the FK definition). I'm with SQLRaptor, having a script to re-create the database is usually a cleaner method, IMO.

– Tibor Karaszi
20 hours ago










2 Answers
2






active

oldest

votes


















0














I'm not sure why you would want to truncate all tables in a database, but, there are several ways to do this. You can use a cursor to loop through sys.tables or INFORMATION_SCHEMA.TABLES:



DECLARE @SqlCmd NVARCHAR(MAX)

DECLARE C1 CURSOR FOR
SELECT N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

OPEN C1

FETCH NEXT FROM C1 INTO @SqlCmd

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @SqlCmd
-- EXEC sp_executesql @SqlCmd

FETCH NEXT FROM C1 INTO @SqlCmd
END

CLOSE C1
DEALLOCATE C1


Or you could use the COALESCE method to produce a combined string:



DECLARE @SqlCmd NVARCHAR(MAX)

SELECT @SqlCmd = COALESCE(@SqlCmd + CHAR(10), '') + N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

PRINT @SqlCmd


In these examples, you can either copy the printed statements and run them or use sp_executesql to execute the commands directly.



As highlighted by George Palacios, this solution does not handle Foreign Keys. There is a solution for generating commands to drop and recreate foreign keys here which would work in well.






share|improve this answer





















  • 2





    This won't deal with FKs just as a heads up so may fail.

    – George.Palacios
    18 hours ago











  • @George.Palacios good point, I've added a link to a suitable solution for this, which doesn't use sp_msforeachtable.

    – HandyD
    3 hours ago











  • doesn't my second solution above in my question handle foreign keys? just wanted to go to stack, to see if there is better answer mssqltips.com/sqlservertip/3218/…

    – Adam Marcus
    27 mins ago



















0














This is a slight frame challenge, but it has been mentioned twice in the comments, and seems likely to be the most reasonable approach to solving this problem.



Instead of truncating all of the tables, script out the database schema.




  • Right click the database

  • Tasks

  • Generate Scripts

  • Choose "Script entire database and all database objects"


    • if you prefer, you can also select specific objects if you want to skip database users (for instance)



  • Continue through the wizard to save the script to a file


    • Review the "advanced" options as some items, like triggers, are not scripted by default




Then you can drop the database, and recreate it from that script with 0 rows in all the tables. This has the advantage of not generating a lot of log file activity, and not having to deal with foreign keys and other dependencies.






share|improve this answer
























  • well I am trying to conduct this with T-SQL and scripting, not interactive GUI,

    – Adam Marcus
    26 mins ago











Your Answer








StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "182"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






Adam Marcus is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f233202%2ftruncate-all-tables-in-database-with-t-sql%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I'm not sure why you would want to truncate all tables in a database, but, there are several ways to do this. You can use a cursor to loop through sys.tables or INFORMATION_SCHEMA.TABLES:



DECLARE @SqlCmd NVARCHAR(MAX)

DECLARE C1 CURSOR FOR
SELECT N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

OPEN C1

FETCH NEXT FROM C1 INTO @SqlCmd

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @SqlCmd
-- EXEC sp_executesql @SqlCmd

FETCH NEXT FROM C1 INTO @SqlCmd
END

CLOSE C1
DEALLOCATE C1


Or you could use the COALESCE method to produce a combined string:



DECLARE @SqlCmd NVARCHAR(MAX)

SELECT @SqlCmd = COALESCE(@SqlCmd + CHAR(10), '') + N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

PRINT @SqlCmd


In these examples, you can either copy the printed statements and run them or use sp_executesql to execute the commands directly.



As highlighted by George Palacios, this solution does not handle Foreign Keys. There is a solution for generating commands to drop and recreate foreign keys here which would work in well.






share|improve this answer





















  • 2





    This won't deal with FKs just as a heads up so may fail.

    – George.Palacios
    18 hours ago











  • @George.Palacios good point, I've added a link to a suitable solution for this, which doesn't use sp_msforeachtable.

    – HandyD
    3 hours ago











  • doesn't my second solution above in my question handle foreign keys? just wanted to go to stack, to see if there is better answer mssqltips.com/sqlservertip/3218/…

    – Adam Marcus
    27 mins ago
















0














I'm not sure why you would want to truncate all tables in a database, but, there are several ways to do this. You can use a cursor to loop through sys.tables or INFORMATION_SCHEMA.TABLES:



DECLARE @SqlCmd NVARCHAR(MAX)

DECLARE C1 CURSOR FOR
SELECT N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

OPEN C1

FETCH NEXT FROM C1 INTO @SqlCmd

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @SqlCmd
-- EXEC sp_executesql @SqlCmd

FETCH NEXT FROM C1 INTO @SqlCmd
END

CLOSE C1
DEALLOCATE C1


Or you could use the COALESCE method to produce a combined string:



DECLARE @SqlCmd NVARCHAR(MAX)

SELECT @SqlCmd = COALESCE(@SqlCmd + CHAR(10), '') + N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

PRINT @SqlCmd


In these examples, you can either copy the printed statements and run them or use sp_executesql to execute the commands directly.



As highlighted by George Palacios, this solution does not handle Foreign Keys. There is a solution for generating commands to drop and recreate foreign keys here which would work in well.






share|improve this answer





















  • 2





    This won't deal with FKs just as a heads up so may fail.

    – George.Palacios
    18 hours ago











  • @George.Palacios good point, I've added a link to a suitable solution for this, which doesn't use sp_msforeachtable.

    – HandyD
    3 hours ago











  • doesn't my second solution above in my question handle foreign keys? just wanted to go to stack, to see if there is better answer mssqltips.com/sqlservertip/3218/…

    – Adam Marcus
    27 mins ago














0












0








0







I'm not sure why you would want to truncate all tables in a database, but, there are several ways to do this. You can use a cursor to loop through sys.tables or INFORMATION_SCHEMA.TABLES:



DECLARE @SqlCmd NVARCHAR(MAX)

DECLARE C1 CURSOR FOR
SELECT N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

OPEN C1

FETCH NEXT FROM C1 INTO @SqlCmd

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @SqlCmd
-- EXEC sp_executesql @SqlCmd

FETCH NEXT FROM C1 INTO @SqlCmd
END

CLOSE C1
DEALLOCATE C1


Or you could use the COALESCE method to produce a combined string:



DECLARE @SqlCmd NVARCHAR(MAX)

SELECT @SqlCmd = COALESCE(@SqlCmd + CHAR(10), '') + N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

PRINT @SqlCmd


In these examples, you can either copy the printed statements and run them or use sp_executesql to execute the commands directly.



As highlighted by George Palacios, this solution does not handle Foreign Keys. There is a solution for generating commands to drop and recreate foreign keys here which would work in well.






share|improve this answer















I'm not sure why you would want to truncate all tables in a database, but, there are several ways to do this. You can use a cursor to loop through sys.tables or INFORMATION_SCHEMA.TABLES:



DECLARE @SqlCmd NVARCHAR(MAX)

DECLARE C1 CURSOR FOR
SELECT N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

OPEN C1

FETCH NEXT FROM C1 INTO @SqlCmd

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @SqlCmd
-- EXEC sp_executesql @SqlCmd

FETCH NEXT FROM C1 INTO @SqlCmd
END

CLOSE C1
DEALLOCATE C1


Or you could use the COALESCE method to produce a combined string:



DECLARE @SqlCmd NVARCHAR(MAX)

SELECT @SqlCmd = COALESCE(@SqlCmd + CHAR(10), '') + N'TRUNCATE TABLE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ';'
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.[name] <> 'sysdiagrams'
AND t.is_ms_shipped = 0

PRINT @SqlCmd


In these examples, you can either copy the printed statements and run them or use sp_executesql to execute the commands directly.



As highlighted by George Palacios, this solution does not handle Foreign Keys. There is a solution for generating commands to drop and recreate foreign keys here which would work in well.







share|improve this answer














share|improve this answer



share|improve this answer








edited 3 hours ago

























answered 22 hours ago









HandyDHandyD

1,335212




1,335212








  • 2





    This won't deal with FKs just as a heads up so may fail.

    – George.Palacios
    18 hours ago











  • @George.Palacios good point, I've added a link to a suitable solution for this, which doesn't use sp_msforeachtable.

    – HandyD
    3 hours ago











  • doesn't my second solution above in my question handle foreign keys? just wanted to go to stack, to see if there is better answer mssqltips.com/sqlservertip/3218/…

    – Adam Marcus
    27 mins ago














  • 2





    This won't deal with FKs just as a heads up so may fail.

    – George.Palacios
    18 hours ago











  • @George.Palacios good point, I've added a link to a suitable solution for this, which doesn't use sp_msforeachtable.

    – HandyD
    3 hours ago











  • doesn't my second solution above in my question handle foreign keys? just wanted to go to stack, to see if there is better answer mssqltips.com/sqlservertip/3218/…

    – Adam Marcus
    27 mins ago








2




2





This won't deal with FKs just as a heads up so may fail.

– George.Palacios
18 hours ago





This won't deal with FKs just as a heads up so may fail.

– George.Palacios
18 hours ago













@George.Palacios good point, I've added a link to a suitable solution for this, which doesn't use sp_msforeachtable.

– HandyD
3 hours ago





@George.Palacios good point, I've added a link to a suitable solution for this, which doesn't use sp_msforeachtable.

– HandyD
3 hours ago













doesn't my second solution above in my question handle foreign keys? just wanted to go to stack, to see if there is better answer mssqltips.com/sqlservertip/3218/…

– Adam Marcus
27 mins ago





doesn't my second solution above in my question handle foreign keys? just wanted to go to stack, to see if there is better answer mssqltips.com/sqlservertip/3218/…

– Adam Marcus
27 mins ago













0














This is a slight frame challenge, but it has been mentioned twice in the comments, and seems likely to be the most reasonable approach to solving this problem.



Instead of truncating all of the tables, script out the database schema.




  • Right click the database

  • Tasks

  • Generate Scripts

  • Choose "Script entire database and all database objects"


    • if you prefer, you can also select specific objects if you want to skip database users (for instance)



  • Continue through the wizard to save the script to a file


    • Review the "advanced" options as some items, like triggers, are not scripted by default




Then you can drop the database, and recreate it from that script with 0 rows in all the tables. This has the advantage of not generating a lot of log file activity, and not having to deal with foreign keys and other dependencies.






share|improve this answer
























  • well I am trying to conduct this with T-SQL and scripting, not interactive GUI,

    – Adam Marcus
    26 mins ago
















0














This is a slight frame challenge, but it has been mentioned twice in the comments, and seems likely to be the most reasonable approach to solving this problem.



Instead of truncating all of the tables, script out the database schema.




  • Right click the database

  • Tasks

  • Generate Scripts

  • Choose "Script entire database and all database objects"


    • if you prefer, you can also select specific objects if you want to skip database users (for instance)



  • Continue through the wizard to save the script to a file


    • Review the "advanced" options as some items, like triggers, are not scripted by default




Then you can drop the database, and recreate it from that script with 0 rows in all the tables. This has the advantage of not generating a lot of log file activity, and not having to deal with foreign keys and other dependencies.






share|improve this answer
























  • well I am trying to conduct this with T-SQL and scripting, not interactive GUI,

    – Adam Marcus
    26 mins ago














0












0








0







This is a slight frame challenge, but it has been mentioned twice in the comments, and seems likely to be the most reasonable approach to solving this problem.



Instead of truncating all of the tables, script out the database schema.




  • Right click the database

  • Tasks

  • Generate Scripts

  • Choose "Script entire database and all database objects"


    • if you prefer, you can also select specific objects if you want to skip database users (for instance)



  • Continue through the wizard to save the script to a file


    • Review the "advanced" options as some items, like triggers, are not scripted by default




Then you can drop the database, and recreate it from that script with 0 rows in all the tables. This has the advantage of not generating a lot of log file activity, and not having to deal with foreign keys and other dependencies.






share|improve this answer













This is a slight frame challenge, but it has been mentioned twice in the comments, and seems likely to be the most reasonable approach to solving this problem.



Instead of truncating all of the tables, script out the database schema.




  • Right click the database

  • Tasks

  • Generate Scripts

  • Choose "Script entire database and all database objects"


    • if you prefer, you can also select specific objects if you want to skip database users (for instance)



  • Continue through the wizard to save the script to a file


    • Review the "advanced" options as some items, like triggers, are not scripted by default




Then you can drop the database, and recreate it from that script with 0 rows in all the tables. This has the advantage of not generating a lot of log file activity, and not having to deal with foreign keys and other dependencies.







share|improve this answer












share|improve this answer



share|improve this answer










answered 3 hours ago









Josh DarnellJosh Darnell

7,22522141




7,22522141













  • well I am trying to conduct this with T-SQL and scripting, not interactive GUI,

    – Adam Marcus
    26 mins ago



















  • well I am trying to conduct this with T-SQL and scripting, not interactive GUI,

    – Adam Marcus
    26 mins ago

















well I am trying to conduct this with T-SQL and scripting, not interactive GUI,

– Adam Marcus
26 mins ago





well I am trying to conduct this with T-SQL and scripting, not interactive GUI,

– Adam Marcus
26 mins ago










Adam Marcus is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















Adam Marcus is a new contributor. Be nice, and check out our Code of Conduct.













Adam Marcus is a new contributor. Be nice, and check out our Code of Conduct.












Adam Marcus is a new contributor. Be nice, and check out our Code of Conduct.
















Thanks for contributing an answer to Database Administrators Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f233202%2ftruncate-all-tables-in-database-with-t-sql%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Anexo:Material bélico de la Fuerza Aérea de Chile Índice Aeronaves Defensa...

Always On Availability groups resolving state after failover - Remote harden of transaction...

update json value to null Announcing the arrival of Valued Associate #679: Cesar Manara ...