Sql Server 增加字段、修改字段、修改类型、修改默认值

1、修改字段名:
     alter table 表名 rename column A to B                  (不可用:rename 附近有语法错误)
         exec sp_rename 'table.oldcolumn','newcolumn'     (可用)
 例:  exec sp_rename 'Person.A','B'             

2、修改字段类型:
  alter table 表名 alter column 字段名 type not null
      注意:如果字段有默认值,则需要先删除字段的约束,在添加新的字段类型

     1.) sp_helpconstraint 表名           获取表有哪些字段有约束,
 例:    sp_helpconstraint person (查看person表里面有那些约束)

     2.)alter table 表名drop constraint 约束名    删除约束,
 例:   alter table person drop constraint DF__Person__A__605D434C (删除person表里的DF__Person__A__605D434C约束)

     3.)alter table 表名 alter column 字段名 type not null  修改字段类型:
 例:   alter table person alter column A int  null

3、修改字段默认值
   alter table 表名 add default (0) for 字段名 with values
 例:alter table person add default (1) for A with values
  注意:如果字段有默认值,则需要先删除字段的约束,在添加新的默认值,( 见修改字段类型)

4、增加字段:
    alter table 表名 add 字段名 type not null default 0
 例: alter table person add "BB" varchar(20) not null  default('b')

5、删除字段:
  alter table 表名 drop column 字段名;
例:alter table person drop column "BB"
  注意:如果字段有默认值,则需要先删除字段的约束,在添加新的默认值,( 见修改字段类型)

你可能感兴趣的:(SQL,使用)