cmd mysql 删除表_SQLServer数据库删除表的列

本文主要向大家介绍了SQLServer数据库删除表的列,通过具体的内容向大家展现,希望对大家学习SQLServer数据库有所帮助。

如果这个表的这一列有默认值约束,那么如果直接删除就会报错

这里有两个办法

1.如果创建列的时候给默认约束设置了名字,直接删除该约束

如果是系统默认命名,那么就先获取默认约束名,

删除约束后,就可以直接删除列

[sql] view plain copy

1. --创建一个带默认值列

2. alter table dbo.Student

3. add test2  int not NULL  default 0

4.

5. --尝试删除

6. alter table dbo.Student

7. drop column test2

8. -- 报错

9. -- 对象'DF__Student__test2__3A81B327' 依赖于 列'test2'。

10. -- 消息 4922,级别 16,状态 9,第 1 行

11. -- 由于一个或多个对象访问此列,ALTER TABLE DROP COLUMN test2 失败。

12.

13. -- 查询该表的所有信息

14. sp_help 'dbo.Student'

15.

16. -- 找到约束后查询

17. alter table dbo.Student

18. drop column test2

19. drop constraint DF__Student__test2__37A5467C

20.

21. -- 再次删除发现成功

22. alter table dbo.Student

23. drop column test2

2.上边的方法显然不方便

这里有一个脚本专门删除列的默认约束

[sql] view plain copy

1. --只要改两个参数

2. declare @tablename varchar(100), @columnname varchar(100), @tab varchar(100)

3. set @tablename = 'Student'  --表名(不要加多余的东西)

4. set @columnname= 'test2'    --字段名称

5.

6. declare @defname varchar(100)   --约束名称

7. declare @cmd varchar(100)   --构造的SQL语句

8. select @defname = name from sysobjects so join sysconstraints sc on so.id = sc.constid where object_name(so.parent_obj) = @tablename

9. and so.xtype = 'd' and sc.colid =(select colid from syscolumns where id = object_id(@tablename) and name = @columnname)

10. select @cmd= 'alter table '+ @tablename+ ' drop constraint '+ @defname if @cmd is null print ' no default constraint to drop'

11. exec (@cmd)

[sql] view plain copy

1. -- 直接删除列

2. alter table dbo.Student

3. drop column test2

以上就介绍了SQL Server的相关知识,希望对SQL Server有兴趣的朋友有所帮助。了解更多内容,请关注职坐标数据库SQL Server频道!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值