Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i am using sql server 2005 and in my database i have more than 100 tables. now i want to truncate some selected table like 50 table using single sql query. i know it is possible and i do not know how to write query. please any one can help me..?
Posted
Comments
/\jmot 28-Feb-15 1:55am    
how do you want to specify the selected 50 table from your database??
50 table list as a parameter or by using prefix???

1 solution

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

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_
SQL
SELECT 'TRUNCATE TABLE ' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'emp%'

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
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900