create table 测试1
(
编号 int identity(001,1),
单价 float,
数量 int,
总价 as 单价*数量,
生产地点 varchar(50) default'安徽省合肥'
)然后我删掉 生产地点
alter table 测试
drop column 生产地点
结果报错:
服务器: 消息 5074,级别 16,状态 1,行 1
对象 'DF__测试__生产地点__3C69FB99' 依赖于 列 '生产地点'。
服务器: 消息 4922,级别 16,状态 1,行 1
ALTER TABLE DROP COLUMN 生产地点 失败,因为有一个或多个对象访问此列。
请问是什么原因?

解决方案 »

  1.   

    create table 测试1
    (
    编号 int identity(001,1),
    单价 float,
    数量 int,
    总价 as 单价*数量,
    生产地点 varchar(50) default'安徽省合肥'  --这里用default就产生了一个约束
    )
    想要删除此列,需要先删除掉该列上面的约束
      

  2.   

    ALTER TABLE [dbo].[测试1] DROP CONSTRAINT [DF__测试__生产地点__3C69FB99]alter table 测试 drop column 生产地点
      

  3.   

    ALTER TABLE [dbo].[测试] DROP CONSTRAINT [DF__测试__生产地点__3C69FB99]alter table 测试 drop column 生产地点
      

  4.   

    1)禁止所有表约束的SQL
    select 'alter table '+name+' nocheck constraint all' from sysobjects where type='U'2)删除所有表数据的SQL
    select 'TRUNCATE TABLE '+name from sysobjects where type='U'3)恢复所有表约束的SQL
    select 'alter table '+name+' check constraint all' from sysobjects where type='U'4)删除某字段的约束
    declare @name varchar(100)
    --DF为约束名称前缀
    select @name=b.name from syscolumns a,sysobjects b where a.id=object_id('表名') and b.id=a.cdefault and a.name='字段名' and b.name like 'DF%'
    --删除约束
    alter table 表名 drop constraint @name
    --为字段添加新默认值和约束
    ALTER TABLE 表名 ADD CONSTRAINT @name  DEFAULT (0) FOR [字段名] 对字段约束进行更改
    --删除约束
    ALTER TABLE tablename
    Drop CONSTRAINT 约束名
    --修改表中已经存在的列的属性(不包括约束,但可以为主键或递增或唯一)
    ALTER TABLE tablename 
    alter column 列名 int not null
    --添加列的约束
    ALTER TABLE tablename
    ADD CONSTRAINT DF_tablename_列名 DEFAULT(0) FOR 列名
    --添加范围约束
    alter table   tablename  add  check(性别 in ('M','F'))