【问题标题】:T-SQL: DROP Table cascade constraints equivalent?T-SQL:DROP 表级联约束等效?
【发布时间】:2011-01-15 21:04:35
【问题描述】:

在 oracle 中,我可以发出 DROP TABLE ... 级联约束,它不会抱怨 FK 等。

T-SQL 中是否有等价物?

【问题讨论】:

    标签: tsql cascade


    【解决方案1】:

    对于那些希望获得更普遍适用的答案的人

    这将找到约束,删除它,然后是列

    感谢 Tim Lentine How to find the name of a default constraint 为开始投票。

    Declare @sql VarChar(255)
    Declare @tableName Varchar(255)
    Declare @columnName VarChar(255)
    Select @tableName = 'MyTableName'
    Select @columnName = 'MyColumnName'
    select @sql = o.[name] from sysobjects o 
    inner join syscolumns c
    on o.id = c.cdefault
    inner join sysobjects t
    on c.id = t.id
    where o.xtype = 'd'
    and t.name = @tableName
    and c.name = @columnName
    
    if @sql is not null
    begin
      select @sql = 'Alter Table ' + @tableName + ' Drop Constraint ' + @sql + ' Alter Table ' + @tablename + ' Drop Column ' + @columnName
      exec(@sql)
    end
    

    【讨论】:

      【解决方案2】:

      不,在 SSMS 中右键单击表格,然后选择“将表格作为脚本”,然后选择“拖放到”,然后选择“新窗口”、“文件...”或“剪贴板”,它会生成一个脚本,该脚本将包括所有必要的 FK 等。

      【讨论】:

      • 那只生成了 'drop table [table]' 。您必须确保在启用脚本相关元素的选项中它可以工作
      • 如果您需要生成一个其他人可以使用的脚本,这也不是一个可行的解决方案,因为不能保证约束名称在多个系统中都是相同的。
      猜你喜欢
      • 2015-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 2014-01-17
      • 2013-10-06
      • 2011-02-24
      相关资源
      最近更新 更多