Wednesday, December 23, 2009

How to truncate database tables in SQL Server?

Suppose you have created a database containing three tables with no foreign key constraints. Now simply execute the following commands:

TRUNCATE TABLE [dbo].[table1]
TRUNCATE TABLE [dbo].[table2]
TRUNCATE TABLE [dbo].[table3]

that's it.

But what if some of your tables have foreign key constraints? Don't worry there is a solution as follows.Suppose table1 and table2 have foreign key constraints with reference to table1. Now follow the following steps:

1. ALTER TABLES-[Drop Foreign Key Constraints]

ALTER TABLE [dbo].[table2] DROP CONSTRAINT FKtable2
ALTER TABLE [dbo].[table3] DROP CONSTRAINT FKtable3

2. TRUNCATE TABLES

TRUNCATE TABLE [dbo].[table1]
TRUNCATE TABLE [dbo].[table2]
TRUNCATE TABLE [dbo].[table3]


3. ALTER TABLES-[Add Foreign Key Constraints]

ALTER TABLE [dbo].[table2] ADD CONSTRAINT FKtable2 FOREIGN KEY (Id) REFERENCES [dbo].[table1] (Id)

ALTER TABLE [dbo].[table3] ADD CONSTRAINT FKtable3 FOREIGN KEY (Id) REFERENCES [dbo].[table1] (Id)

that's it.

1 comment:

  1. Hello friend,
    I am now following your blog on Google.
    Please visit and follow my blog :
    multibrand.blogspot.com

    ReplyDelete

Related Posts with Thumbnails