.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> SQL Query >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Truncate all tables sql server?

Posted By:abhays       Posted Date: May 22, 2014    Points: 40    Category: SQL Query    URL: http://www.dotnetspark.com  

Truncate all tables sql server
 

 

 Truncate all tables sql server

 

DECLARE @tablename AS VARCHAR (1000)
 
DECLARE @sql AS VARCHAR (1000)
 
IF OBJECT_ID('tempdb.dbo.#tables') IS NOT NULL
    DROP TABLE #tables
 
SELECT *
INTO   #tables
FROM   sys.tables
 
WHILE EXISTS (SELECT *
              FROM   #tables)
    BEGIN
        SELECT @tablename = name
        FROM   #tables
        SELECT @sql = 'truncate table ' + @tablename;
        PRINT @sql
        EXECUTE (@sql)
        DELETE #tables
        WHERE  name = @tablename;
    END

This script works if the tables do not have foriegn key constrains or schema binding relations with other tables/objects in the database.


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend