Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
declare @table varchar(100)
declare NfrTable_cursor cursor
for
select  tableDetails from #temporaryTable
open NfrTable_cursor
fetch next from NfrTable_cursor into @table
WHILE @@FETCH_STATUS = 0
BEGIN

exec('select top 1 1 as found from ' + @table)
If @@RowCount > 0
begin
exec ('truncate table ' + @table)
end
fetch next from NfrTable_cursor into @table
end
close NfrTable_cursor
deallocate NfrTable_cursor


I am getting error as :

"Cannot truncate table 'BragDetail' because it is being referenced by a FOREIGN KEY constraint."



--How can I achieve this inside a cursor where the table name is dynamic.
-- I referred some sites,,but it is suggesting to drop the constraint,truncate and recreate the constraint.. but I am not sure how to do inside a cursor. Please help me in this.
Posted

You can truncate the table after turning off the foreign key constraint.
For e.g ALTER TABLE myTable NOCHECK CONSTRAINT myConstraint

Then enable the check constraint again.

However, note that you are actually corrupting your data by letting foreign key data lying around in another table.
 
Share this answer
 
Comments
anurag19289 29-Jul-14 5:31am    
Hi Abhinav,
quick question... How will I know myConstraint when I am looping inside cursor for a particular table ?
Abhinav S 29-Jul-14 5:43am    
http://bhaveshgpatel.wordpress.com/2009/11/04/sql-server-list-all-constraints-of-database-or-table/
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
EXEC sp_MSForEachTable "DELETE FROM ?"
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

declare @table varchar(100)
declare NfrTable_cursor cursor
for
select TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'dbo'
and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME
open NfrTable_cursor
fetch next from NfrTable_cursor into @table
WHILE @@FETCH_STATUS = 0
BEGIN
 DBCC CHECKIDENT (@table, reseed, 0); 
fetch next from NfrTable_cursor into @table
end
close NfrTable_cursor
deallocate NfrTable_cursor
 
Share this answer
 

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