SQL基本操作

来源:互联网 发布:喜欢熟女 知乎 编辑:程序博客网 时间:2024/06/03 15:41

 --创建数据库
create database cwh
on primary 
(
 name ='数据文件',
 filename='e:\data\data.mdf',
 size=20MB,
 maxsize=50MB,
 filegrowth=2MB
)
log on
(
 name ='日志文件',
 filename='e:data\data.ldf',
 size=10MB,
 maxsize=25MB,
 filegrowth=10%
)

--创建表
create table T_cwh
(
id int identity(1,1) primary key,
name varchar(20) not null,
password varchar(30)
)

--检索表
select * from T_cwh
select * from T_stu
select * from T_teacher

--删除表
drop table T_cwh  //删除定义和内容,并且释放空间
truncate table T_teacher  //只删除内容,并且释放空间
delete from T_stu  //只删除内容,但不释放空间(空间释放不释放可以重id自增长可以看出)
truncate table T_stu
drop table T_stu

--删除表中的某一行
delete from T_teacher where sdf=7

--单行插入数据
insert into T_teacher(name,sex,password) values('孔子','男','999' )

--从旧表挑选列插入要将创建的新表
select name,password  into T_stu from T_cwh

--给将要创建的新表加入标识
select identity(int,1,1) as id into T_stu 

--从旧表中挑选没有标识的列加入将要创建的新表,并添加带有标识的id列
select T_cwh.name,T_cwh.password, identity(int,1,1) as id into T_stu from T_cwh

--从一个旧表挑选列嵌入另一个表中(相同内容不会覆盖)
insert into T_stu  (name,password) select name,password from T_cwh

--更新数据(一列或某几行行几列)
update T_Teacher set password='567' where sdf=3 

--添加一列
alter table T_stu add grade varchar(30)  null 
--报错
alter table T_stu add crouse varchar(30)  not null
    ALTER TABLE 只允许添加满足下述条件的列
  1. 列可以包含 Null 值;
  2. 或者列具有指定的 DEFAULT 定义;或者要添加的列是标识列或时间戳列;
  3. 如果前几个条件均未满足,则表必须为空以允许添加此列。
  4. 不能将列“crouse添加到非空表“T_stu中,因为它不满足上述条件
--更改列的类型varchar->int
alter table T_stu add age varchar(10) null
alter table T_stu alter column age int

--删除列
alter table T_stu drop column age

--主键约束
alter table T_stu add constraint  _first primary key ( id)

--唯一键约束
alter table T_cwh add constraint  _only unique (id)

--默认键约束 
alter table T_stu add constraint  _same default ('一年级') for grade

--检查约束
alter table T_stu add constraint  _check check(age<40 and age>16)

--外键约束
alter table T_stu add constraint _wai foreign key (name) references T_cwh (id)

--删除约束
alter table T_stu drop constraint _same



0 0
原创粉丝点击