作为一个新手,我创造了一些没有明确名称的外键.
然后我创建了SQL生成的疯狂名字之类的FK__Machines__IdArt__760D22A7
.猜猜它们将在不同的服务器上生成不同的名称.
是否有任何好的函数可以删除未命名的FK约束作为参数传递表和相关字段?
要在列上删除单个未命名的默认约束,请使用以下代码:
DECLARE @ConstraintName VARCHAR(256) SET @ConstraintName = ( SELECT obj.name FROM sys.columns col LEFT OUTER JOIN sys.objects obj ON obj.object_id = col.default_object_id AND obj.type = 'F' WHERE col.object_id = OBJECT_ID('TableName') AND obj.name IS NOT NULL AND col.name = 'ColunmName' ) IF(@ConstraintName IS NOT NULL) BEGIN EXEC ('ALTER TABLE [TableName] DROP CONSTRAINT ['+@ConstraintName+']') END
如果你想为默认列做这个,这可能比原始问题更常见,我相信很多人会从Google搜索中找到这个,然后只需更改一行:
obj.type = 'F'
至
obj.type = 'D'
没有内置的过程来完成此任务,但您可以使用information_schema视图中的信息构建自己的过程.
基于表的例子
Create Proc dropFK(@TableName sysname) as Begin Declare @FK sysname Declare @SQL nvarchar(4000) Declare crsFK cursor for select tu.Constraint_Name from information_schema.constraint_table_usage TU LEFT JOIN SYSOBJECTS SO ON TU.Constraint_NAME = SO.NAME where xtype = 'F' and Table_Name = @TableName open crsFK fetch next from crsFK into @FK While (@@Fetch_Status = 0) Begin Set @SQL = 'Alter table ' + @TableName + ' Drop Constraint ' + @FK Print 'Dropping ' + @FK exec sp_executesql @SQL fetch next from crsFK into @FK End Close crsFK Deallocate crsFK End