我在表中添加了个test int not NULL的列
当删除时报错:
消息 5074,级别 16,状态 1,第 9 行
对象'DF__Name__test__0CBAE877' 依赖于 列'test'。
消息 4922,级别 16,状态 9,第 9 行
由于一个或多个对象访问此列,ALTER TABLE DROP COLUMN test 失败。请问这是为何?

解决方案 »

  1.   


    --这是因为有约束存在
    --得先去掉约束
    alter table tb drop constraint DF__Name__test__0CBAE877
      

  2.   

    首先说明我刚学,
    我当时只是这样:
    alter table *
    add
        test int NOT NULL
    创建列的,所以我也不知道怎的了就给约束了,
    还有当我创建的是null的,则可以drop掉,请问这是为何
      

  3.   

    首先说明我刚学,
    我当时只是这样:
    alter table *
    add
        test int NOT NULL
    创建列的,所以我也不知道怎的了就给约束了,
    还有当我创建的是null的,则可以drop掉,请问这是为何
      

  4.   


    --执行一下看看。
    sp_help tablename
      

  5.   


    如果只是加这一列的话,drop column 不会有问题的。
      

  6.   

    --执行一下看看。
    sp_helpconstraint tablename
      

  7.   

    create table t(i int identity,d int NOT NULL default(0)) --创建测试表
    insert t select 6 union select 2 union select 3 --插入测试数据
    select * from t --查看测试数据
    sp_helpconstraint t --本例找到DF__t__d__093F5D4E
    alter table t drop constraint DF__t__d__093F5D4E --命令成功完成
    alter table t drop column d --命令成功完成
    select * from t --查看删除列后的表
    drop table t --删除测试表
      

  8.   

    改好点:
    create table t(i int identity,d int NOT NULL default(0)) --创建测试表
    insert t select 6 union select 2 union select 3 --插入测试数据
    select * from t --查看测试数据
    sp_helpconstraint t --查找字段的约束名,本例找到DF__t__d__093F5D4E
    alter table t drop constraint DF__t__d__093F5D4E --先删除字段约束,提示:命令成功完成
    alter table t drop column d --删除字段,提示:命令成功完成
    select * from t --查看删除列后的表
    drop table t --删除测试表,测试完毕
      

  9.   


    因为在建立表的时候,字段设置了Default约束。在没有给 Default分配约束名称,
    系统会随机起个Default约束名称的。e.g:Use test
    Go
    If object_id('test') Is Not Null
    Drop Table Test
    Go
    Create Table test
    (
    id int Identity(1,1) Not Null Primary Key ,
    x nvarchar(50) Default('A'),
    y int
    )
    Go
    Select name From sys.objects Where Type='D' And parent_object_id=object_id('Test')
    /*
    name
    ---------------------
    DF__test__x__3E3D3572
    */--也可以指定给test建立Default约束名称If object_id('test1') Is Not Null
    Drop Table test1
    Go
    Create Table test1
    (
    id int Identity(1,1) Not Null Primary Key ,
    x nvarchar(50) ,
    y int
    )
    Alter Table test1 Add  Constraint DF_test1_x  Default ('A')  For x 
    Go
    Select name From sys.objects Where Type='D' And parent_object_id=object_id('test1')/*
    name
    ---------------------
    DF_test1_x
    */
      

  10.   

    先删除从表,然后在删除主表,最后把约束删除就可以了··当然你在运行一下SQL