sqlserver t-sql操作

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 約束名;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章