1.创建数据库:
Create database databasename
2.删除数据库:
drop database databasename 注意:删除数据库后无法通过日志恢复
3.修改数据库名
EXEC sp_renamedb ‘原数据库名’,‘修改后的数据库名’;
EXEC sp_renamedb ‘Student’,‘Stu’;
1.创建表
1>create table tabname
2>使用旧表创建新表
create table tab_new like tab_old
2.删除表
create table tabname
3.修改表名
EXEC sp_renamedb ‘原表名’,‘修改后表名’;
EXEC sp_renamedb ‘table’,‘tab’;
1.创建视图
create view viewname
2.删除视图
create view viewname
1.创建索引
1>创建普通索引
alter table tab_name add index idxname (column_list)
create index idxname on tab_name(column_list)
2>创建unique索引
create UNIQUE index idxname on tab_name(column_list)
alter table tab_name add unique (column_list)
3>创建primary key索引
alter table tab_name add PRIMARY KEY (column_list)
注意:不能用create index语句创建PRIMARY KEY索引。
2.删除索引
drop index idxname
注意:索引不可更改。如果要更改索引,必须先删除然后再重新创建
SQL数据库的增删改查:
增:
1.insert [into] <表名> (列名) values (列值)
insert into Student(“学号”,“姓名”,“性别”,“成绩”)
values(“1001”,“张三”,“女”,“98”)
2.select <新建表列名> into <新建表名> from <原表名>
select ‘姓名’,‘职工编号’,‘年龄’ into Teacher from Student
注意:新表是执行查询语句的时候创建的
删:
1.delete from <表名> [where <删除条件>]
delete from Student where 学号=‘1001’
2.truncate table <表名>
turncate table Student
改:
update <表名> set <列名=更新值> [where <更新条件>]
update Student set 学号=1002 where 姓名= ‘小张’
查:
select <列名> from <表名> [where <查询条件表达试>] [order by <排序的列名>[asc或desc]]
普通查询:
- select * from student
2.select * from student where 学号=‘1001’
模糊查询:
1.用like实现模糊查询
1>%:表示任意0个或者多个字符。可匹配任意长度和类型的字符。有些情况若是中文,请用两个百分号(%%)表示;
select * from Teacher where name like ‘%刘%’
select * from Teacher where ID like ‘10%’
2>:表示任意单个字符。可匹配任意单个字符。一般情况下,用它来限定表达式的字符串长度;
select * from Student where name like '刘’
3>[ ]:表示括号内所列字符中的一个。指定一个范围,所匹配的对象为范围内的任意一个。
select * from Student where name like ‘[周吴郑王]三’
4>[^ ]:表示不在括号所列内的单个字符。取值与[ ]相同。所匹配的对象为范围外的任意一个。
select * from Student where ID like ‘100[^5-7]’
2.用between实现范围内的查询
select * from Teacher where age between 30 and 55
3.用in实现列举内的查询
select * from Teacher where age in (‘36’,‘40’,‘45’)
分组查询:
1.用group by实现分组查询
一般情况下,group by 是和聚合函数配合使用的。
注意:在select后面的所有列中,没有使用聚合函数的列,必须出现在group by 后面
select A,count(B) as quantity from table group by A
2.用having子句实现分组筛选
having作用是筛选满足条件的组,即分组后过滤数据,条件中一般会包含聚组函数,使用having条件显示特定的组,同时也可用多个分组标准实现分组。
select A count(B) from table group by A having count(B)<6