Nocheck FK constraint to Load /Clean Data

-- disable all constraints
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

-- delete data in all tables
EXEC sp_MSForEachTable "DELETE FROM ?"

-- enable all constraints
exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

Sometimes to populate an empty database from external data source or
debug a problem in the database I need to disable ALL triggers and
constraints.

To do so I use the following code:

sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
sp_msforeachtable "ALTER TABLE ? DISABLE TRIGGER  all"

To enable all constraints and triggers:

exec sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? ENABLE TRIGGER  all"


DATA CLEAN:

 -- delete data
 if some of the tables have identity columns we may want to reseed them
 EXEC sp_MSforeachtable "DBCC CHECKIDENT ( '?', RESEED, 0)"


 --truncate data
 identity columns will be atuto to reseed to 0


ISSUE RESOLUTION:

1. cannot 'truncate' table A even diable the constrains

Reason:

(1) table A is a parent table, has been referenced by other tables
(2) (MSDN : http://msdn.microsoft.com/en-us/library/aa260621(SQL.80).aspx)
 "You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY
constraint; instead, use DELETE statement without a WHERE clause.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger."

Solutions :

(1) use 'DELETE' without 'where-clause'

e.g :  DELETE FROM A

(2)  Drop constraint

   1. Drop the constraints
   2. Trunc the table
   3. Recreate the constraints.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值