[SQL]删除约束

时间:2021-12-12 21:14:14
DECLARE @ConstraintName nvarchar(200);

SELECT @ConstraintName = Name
FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (
SELECT column_id
FROM SYS.COLUMNS
WHERE NAME = N'__ColumnName__'
AND object_id = OBJECT_ID(N'__TableName__')
);
IF @ConstraintName IS NOT NULL
BEGIN
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName);
END

另一方法(修改字段类型)

IF EXISTS(SELECT name FROM SYSOBJECTS WHERE name = '__TableName__' AND xtype='U')
BEGIN
DECLARE @name VARCHAR(100) = (
SELECT TOP 1 name
FROM SYSOBJECTS
WHERE name LIKE 'DF\_\_%' ESCAPE '\' AND xtype='D' AND id=(SELECT TOP 1 cdefault FROM SYSCOLUMNS WHERE id=OBJECT_ID('__TableName__') AND name='__ColumnName__')
); IF(@name IS NOT NULL)
BEGIN
EXEC('ALTER TABLE [DBO].[__TableName__] DROP CONSTRAINT ' + @name);
EXEC('ALTER TABLE [DBO].[__TableName__] ALTER COLUMN [__ColumnName__] TEXT NULL');
END;
ELSE
BEGIN
ALTER TABLE [DBO].[__TableName__] ALTER COLUMN [__ColumnName__] TEXT NULL;
END;
END;

PS:将__TableName__和__ColumnName__替换你的表名和字段名