sql语句基础

来源:互联网 发布:autocut下料软件 编辑:程序博客网 时间:2024/05/20 04:30
//DDL 数据定义语言
//建表,设置主键、外键、列属性(非空,唯一,约束等)、默认值修改表结构
//增加字段,删除字段,修改字段,建立索引,创建视图
//DDL语句学习
1  创建  删除数据库
create database taikang;
drop database taikang;
2 备份sqlserver数据库
---创建备份数据的device
exec sp_addumpdevice 'disk','taikangBack','G:\taikang.dat'
---开始备份语句
backup database taikang to taikangBack


use taikang;


3---创建新表
create table personInfo(
id int not null primary key,  //创建时设定主键,非空
name varchar(50),
sex varchar(10)
)
---根据旧表创建新表
oracle写法
A:
create table personInfo_new1 like personInfo
B:
create table personInfo_new2 as select id, name from personInfo definition only


sql server 写法
select * into personInfo_new1 from personInfo


---建表时添加约束
create table deptInfo(
deptId int constraint dept_deptId primary key, --主键
deptName varchar(50) constraint dept_deptName not null,--非空
deptAddr varchar(50) constraint dept_deptAddr unique,--唯一
deptPersonNum int constraint dept_personNum check(deptPersonNum > 0),--核查
deptType int constraint dept_deptType references jobType(id)--外键
)
--identity(1, 1)  自增1
---4 删除表
drop table personInfo_new1


create table jobType(
id int not null,
jobtype varchar(50)
)
---5增加表列
alter table personInfo add typeid int not null default(1)
---删除表列 如果有默认值或是其他约束,需要先去掉约束,找到约束命,删掉,约束名为错误中提到过的
alter table personInfo drop constraint DF__personInf__typei__07020F21
alter table personInfo drop constraint NotNull
alter table personInfo drop column typeid


alter table personInfo add testNum int not null default(2)
alter table personInfo drop constraint DF__personInf__testN__117F9D94
alter table personInfo drop column testNum


---6设置主外键(增加约束)
---第一个PrimaryKey为约束的名字,方便管理,删除,如下变的删除,第二个是设置的主键列
alter table jobType add constraint PrimaryKey Primary Key(id)
---两个主键时
alter table jobType add constraint PrimaryKey Primary Key(id, jobtype)
---删除主键  根据约束名来删除主键,约束删除,并不代表字段被删除了,注意
alter table jobType drop constraint PrimaryKey


---创建外键
alter table personInfo add constraint ForeignKey_id foreign key(typeid) references jobType(id)
---删除外键
alter table personInfo drop constraint ForeignKey_id


---7增删索引  一个表只能有一个聚簇索引(索引顺序是数据的物理存储数据)
create index name_index on personInfo(name) 
create unique CLUSTERED  index id_index on personInfo(id)


---若建立的列中有了重复的数据,以上可能报错,可以这样
create index name_index on personInfo(name) with allow_dup_row
---删除索引
drop index personInfo.name_index


---8修改字段属性
---A 更改字段类型长度
alter table personInfo alter column name varchar(55)
---B修改字段类型 拥有约束的时候,不能更改
alter table personInfo alter column testNum varchar(20)
alter table personInfo alter column testNum int


---C 添加null约束
--alter table personInfo alter column testNum int not null default(3)




---9创建视图view