SQL Server 禁用外键约束和启用外键约束及删除表数据

--禁止约束
DECLARE DEL_CONSTRAINT CURSOR FOR
	SELECT 'ALTER TABLE '+OBJECT_NAME(PARENT_OBJ)+' NOCHECK CONSTRAINT '+NAME+';'
	FROM SYSOBJECTS A LEFT OUTER JOIN SYSCOMMENTS B ON A.ID = B.ID
	WHERE A.XTYPE = 'F' AND A.PARENT_OBJ IN (SELECT ID FROM SYSOBJECTS WHERE name LIKE 'Test%')
OPEN DEL_CONSTRAINT
DECLARE @DEL_CONSTRAINT VARCHAR(8000)
FETCH NEXT FROM DEL_CONSTRAINT INTO @DEL_CONSTRAINT
WHILE (@@fetch_status = 0)
	BEGIN
		PRINT @DEL_CONSTRAINT
		EXEC(@DEL_CONSTRAINT)
		FETCH NEXT FROM DEL_CONSTRAINT INTO @DEL_CONSTRAINT
	END
CLOSE DEL_CONSTRAINT
DEALLOCATE DEL_CONSTRAINT
GO
--删除表数据
DECLARE DEL_TABLES CURSOR FOR
	SELECT 'DELETE TABLE dbo.'+ NAME
	FROM SYSOBJECTS WHERE XTYPE = 'U' AND NAME LIKE 'Test%'
OPEN DEL_TABLES
DECLARE @DEL_TABLES VARCHAR(8000)
FETCH NEXT FROM DEL_TABLES INTO @DEL_TABLES
WHILE (@@fetch_status = 0)
	BEGIN
		PRINT @DEL_TABLES
		EXEC (@DEL_TABLES)
		FETCH NEXT FROM DEL_TABLES INTO @DEL_TABLES
	END
CLOSE DEL_TABLES
DEALLOCATE DEL_TABLES
GO
--启动约束
DECLARE DEL_CONSTRAINT CURSOR FOR
	SELECT 'ALTER TABLE '+OBJECT_NAME(PARENT_OBJ)+' CHECK CONSTRAINT '+NAME+';'
	FROM SYSOBJECTS A LEFT OUTER JOIN SYSCOMMENTS B ON A.ID = B.ID
	WHERE A.XTYPE = 'F' AND A.PARENT_OBJ IN (SELECT ID FROM SYSOBJECTS WHERE name LIKE 'Test%')
OPEN DEL_CONSTRAINT
DECLARE @DEL_CONSTRAINT VARCHAR(8000)
FETCH NEXT FROM DEL_CONSTRAINT INTO @DEL_CONSTRAINT
WHILE (@@fetch_status = 0)
	BEGIN
		PRINT @DEL_CONSTRAINT
		EXEC(@DEL_CONSTRAINT)
		FETCH NEXT FROM DEL_CONSTRAINT INTO @DEL_CONSTRAINT
	END
CLOSE DEL_CONSTRAINT
DEALLOCATE DEL_CONSTRAINT
GO


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值