代码之家  ›  专栏  ›  技术社区  ›  Jason Cohen

带约束的SQL Server 2000删除列

  •  4
  • Jason Cohen  · 技术社区  · 17 年前

    我有和中描述的相同的问题 this question 但是现在它是SQL Server 2005,而“接受”的答案在SQL Server 2000中不起作用。

    具体地说:我想跑步 ALTER TABLE foo DROP COLUMN bar ,失败的原因是有一个“默认约束”。也就是说,我在该列上有一个默认值,SQL Server将该值作为一个单独的约束来实现,我需要先删除它。

    问题是在创建列时没有为默认约束指定名称,因此我必须查询系统表以发现约束的(自动生成的)名称。

    在其他问题中给出的答案对我在SQL Server 2005中有效,但在SQL Server 2000中无效。我需要后者。

    [更新]我需要 查询 这可以回答问题“列的默认约束的名称是什么” bar 在表中 foo “不是人类手动找到答案的方法。

    4 回复  |  直到 17 年前
        1
  •  3
  •   bdukes Jon Skeet    17 年前

    刚刚了解引用的SQL 2005查询实际上在做什么。下面是该查询在SQL 2000中的复制

    select 
        col.name, 
        col.colorder, 
        col.cdefault, 
        OBJECTPROPERTY(col.cdefault, N'IsDefaultCnst') as is_defcnst, 
        dobj.name as def_name
    from syscolumns col 
        left outer join sysobjects dobj 
            on dobj.id = col.cdefault and dobj.type = 'D' 
    where col.id = object_id(N'dbo.table_name') 
    and dobj.name is not null
    
        2
  •  1
  •   bdukes Jon Skeet    17 年前

    要获取表的默认约束列表,请尝试此操作

    select * from sysobjects [constraint] 
     join sysobjects [table] on [constraint].parent_obj = [table].id 
    where [constraint].type = 'D'
     and [table].name = 'table_name'
    --another option: and [table].id = OBJECT_ID(N'dbo.table_name')
    
        3
  •  0
  •   DJ.    17 年前
    sp_help 'tablename'
    

    为您提供表上的大量信息-包括所有约束和约束名称

    实际上,sp_-help称之为:

    sp_helpconstraint 'tablename', nomsg
    

    默认约束将显示“列xxx的默认值”

        4
  •  0
  •   bdukes Jon Skeet    17 年前

    这一个是在bdukes提供的第一个解决方案上构造的,混合了信息“schema.columns”,似乎信息包含默认所属列的序号位置。

    SELECT name 
    FROM sysobjects [constraint] 
     JOIN sysobjects [table] on [constraint].parent_obj = [table].id
     JOIN information_schema.columns col ON [table].name = col.table_name AND [constraint].info = col.ordinal_position
    WHERE [constraint].type = 'D'
     AND [table].name = 'table_name'
     AND col.column_name = 'column_name'