DDL和DML语句
数据定义语言(DDL)用来定义和管理SQL数据库中所有的对象,最基本的功能是创建和维护数据库和数据表结构
1.创建和维护数据库
创建数据库语法
create database database_name
删除数据库语法
drop database database_name
2.创建和维护数据表结构
(1)创建数据表语法
create table table_name(
字段名1,数据类型[列级别约束条件][默认值],
字段名2,数据类型[列级别约束条件][默认值],
......
)
举例创建一个学生表
create table Student(
stuid int identity(1,1) primary key ----主键,自增
name varchar(50),
stuaddress varchar(50) default '武汉' ---默认值
)
(2)新增字段语法
alter table 表名 add 字段名 数据类型
举例
alter table Student add score int
(3)删除字段语法
alter table 表名 drop column 字段名
例如
alter table Student drop column score
(4)修改字段名语法
alter table 表名 rename column 旧字段名 to 新字段名
例如
alter table Student rename column name to Stuname
(5)修改字段类型语法
alter table 表名 alter column 字段名 数据类型
举例
alter table Student alter column stuaddress varchar(50)
2.使用DML(数据操作语言)对数据库的数据进行增,删,改,查
(1)新增数据内容语法
insert [into] table_name[(字段列表)] values (值列表)
举例
insert into person(name,age,address)
values('bier',19,'湖南')
(2)更新表记录语法
update table_name set 字段名1=值1,字段名2=值2,...字段名n=值n
[where 条件表达式]
举例
update person set age=age+1 where name='bier'
(3)删除表记录语法
delete from table_name [where 条件表达式]
Select 基本查询语法(全)
select 字段列表 from table_name [where 条件表达式] [gruop by 字段列表] having 条件
order by 字段列表 (ASC)/Desc
语法说明
1.必须的子句只有select子句和from 子句
2.where子句是对查询的结果进行过滤
3.group by子句根据指定列进行分组,having子句是将分组后的结果进行过滤
4.order by子句用来对查询数据的结果进行排序,默认是升序(ASC),降序是Desc
distinct关键字
distinct关键字用于过滤重复的字段信息
举例
select distinct age from person
使用 top n返回指定行数
语法
select top n column1,column2,column3...from table