1.创建表
如果表存在可以先删除再创建,具体看实际情况
go
if OBJECT_ID(N'k_emp',N'U') is not null
drop table k_emp
go
create table k_emp(
id bigint primary key,
post_id bigint,
code varchar(32) not null,
name nvarchar(30) not null,
born date,
sex char(1) not null,
del_flag char(1) default '0' not null)
2.判断表是否存在
方法一
if exists(select top 1 * from sysObjects where Id=OBJECT_ID(N'k_emp') and xtype='U')
print '表k_emp存在'
else
print '表k_emp不存在'
方法二
if OBJECT_ID(N'k_emp',N'U') is not null
print '表k_emp存在!'
else
print '表k_emp不存在!'
3.修改表的字段
新增字段
alter table 表名 add 字段名 type not null default 0
修改字段名(注意可能影响存储过程)
exec sp_rename 'k_emp.sex','sexs'
修改字段类型
alter table 表名 alter column 字段名 type not null
删除字段
alter table 表名 drop column 字段名;
修改字段默认值
alter table 表名 add default (0) for 字段名 with values
4.修改表的约束
添加主键约束
alter table 表名 add constraint 主键名 primary key (字段)
删除主键约束
alter table 表名 drop constraint 主键名
添加外键约束
alter table 从表 add constraint 外键名 foreign key(外键字段) references 主表(主键)
删除外键约束
alter table 从表 drop constraint 外键约束名
5.修改表的索引
添加唯一约束
alter table 表名 add unique (字段)
删除唯一约束
alter table 表名 drop constraint 约束名;