表的创建及增删改查
新建表
create table student(
ID int primary key not null, --是否设置为主键,是否为空
name varchar(10) not null,
age int null
);
修改删除表结构
alter table student
alter column name varchar(20); --等于重新定义列,如果不加not null默认允许为null
alter table student
alter column age float;
alter table student
alter column name varchar(20) not null;
alter table student
add grade varchar(6) not null; --增加列
EXEC sp_rename '旧表名', '新表名' --修改表名
EXEC sp_rename '表名.[旧列名]','新列名','COLUMN' --修改列名
定义表主键、外键
新增表记录
--增加单行
insert into student(ID,name,age)
values('1','张三','10')
--增加多行
insert into student(ID,name,age)
values('1','张三','10'),('1','张三','10') --之间用“,”隔开
--通过其他表增加记录
insert into student(ID,name,age)
values select ID,name,age from students
查询表记录
select * from student
select top 10 * from student --查询前10行数据
select distinct 字段名 from student --查询不重复的数据
修改表记录
update student
set name='张三' --如果不加限制条件where,将把name列全部修改为“张三”
删除表记录
delete from student --from可以省略
条件查询
where用法
select * from student
where name like '%三%'
select getdate() --查询当前SQL服务器时间
between and用法
in用法
子查询(in和exists)、主查询
记录排序
order by 字段名 asc|desc 升序或降序
关联查询
交叉关联
select * from 表1
inner join 表2
on 表1.字段号=表2.字段号
左关联
select * from 表1
left join 表2
on 表1.字段号=表2.字段号
右关联