SQL

MS SQL Server学习笔记

2019-04-26  本文已影响0人  jacob_

1 引言

2 数据库的创建

2.1 利用ssms(SQL Server Managerment Studio)创建

ssms是一个图形界面,在对象资源管理器中数据库栏右键新建数据库即可。一般接收默认值创建。

2.2 利用Transact-SQL脚本进行创建

点击新建查询输入下列代码

Create Database taskDb
On Primary(
name = 'taskdb',
filename = 'G:\testdb\testdb.mdf',
size = 10MB,
maxsize = 100MB,
filegrowth = 5MB
)
Log On(
name = 'testdb_log',
filename = 'G:\testdb\testdb.ldf',
size = 10MB,
maxsize = 100MB,
filegrowth = 5MB
)

3 数据库的修改

exec sp_helpdb taskDb;
数据库查看
alter database taskDb
modify name = taskDb01;
alter database taskDb01
modify file(
name = taskDb,
size = 20MB,
maxsize = 50MB,
filegrowth = 10MB
);

这里要注意,taskDb01是指数据库名称,而taskDb是数据库文件名称,不要搞错。

drop database taskDb01

4 数据类型

4.1 数字类型

4.2 时间类型

4.3 字符串类型

5 表的创建

过程:创建表,设置主键
同样可以使用GUI操作创建于SQL脚本创建。

create table product(
productId int primary key not null,
productName varchar (25) not null,
price money null
)

6表的修改与删除

alter table 表名
alter column 字段名 Int not null
alter table 表名
add constraint 主键名 primary key(字段名)
exec sp_rename '表名.字段名',
'更改后的字段名','COLUMN'
alter table 表名
add 字段名 字段类型 default null

7 表的主键与外键

//对从表table1添加外键uid(列),FK_product 为外键名称,主表是product,对应主表的主键是productId。
alter table table1
add constraint FK_product foreign key(uid)
references product(productId)

8 新增表记录

insert into 表格1(列1,列2)
select 列1,列2
from 表格2;
insert into 表格 (列1,列2)
values ('data','time')

9 查询表记录

查前多少行数据。

select Top 行数 列名
from 表名
select * from role
where name like '%管理员'

需要注意的是,'%'的作用是匹配,这样利用'%管理员'可以查找到商品管理员、超级管理员、系统管理员等。

select * from role
where uid between 0 and 5

查询uid在0-5之间的数据,不一定要int类型,char也可以,例如'2019-04-29'and'2019-05-01'.例如下面这个

select * from role
where time between '2019-04-01' and getdata();
select * from role
where uid not between 0 and 5

查询uid不在0-5之间的数据

select * from user1
where userid in (1,3)

查询在集合(1,3)的数据

select * from user1
where userid  not in (1,3)

查询不在集合(1,3)的数据

select * from user1
where username in (select username from user2)

查询username出现在user2表的数据

select a.userid from user1 as a
where exists (select * from userinfo as b where (a.userid = b.uid) and b.uid = 1)

这句话的意思是①把user1取别名a②条件限制语句,选择满足a.userid = b.uid并且b.uid=1的字段③需要注意的是:exists返回的是一个Bool值(其检查子查询是否至少会返回一行数据),若返回true则选择这行数据。

select * from user1
order by userid,name desc

其意义在于,先按userid升序排序,若有userid相同的,再按照name降序排序。

10 关联查询

select * from table1
inner join table2
on table1.字段号 = table2.字段号
select * from table1
left join table2
on table1.字段号 = table2.字段号
select * from table1
right join table2
on table1.字段号 = table2.字段号

例子如下

class表
student表
关联查询
select * from student
inner join class
on student.ClassNo = class.ClassNo
关联查询结果
select * from student
left join class
on student.ClassNo = class.ClassNo
左关联查询结果

11 聚合函数(AVG/SUM)

select avg(字段名)
from 表名
select sum(字段名)
from 表名

例如:

select sum(score) as sum_score from students
结果

12 聚合函数(MIN/MAX)

select min/max(字段名)
from 表名

13 LEN()函数

select *,len(grade) as len_grade from class

结果如下:


len函数
select *,datalength(grade) as len_grade from class

一个字符两个字节:


datalength()

14 随机数的产生

15 getdate()与getutcdate()

16 CONVERT函数

select convert(varchar(10),getdate(),110)

17 DATEDIFF与DATEADD函数

17.1DATEDIFF

17.2DATEADD

select datediff(day,'2019-04-01','2019-05-01')
select datediff(month,'2019-04-01','2019-05-01')
select datediff(minute,'2019-04-01','2019-05-01')
select datediff(second,'2019-04-01','2019-05-01')
select dateadd(day,30,'2019-04-01')
select dateadd(month,5,'2019-04-01')
代码对应结果
主要注意的是,小日期在前,大日期在后
select dateadd(day,5,'2019-05-01')
select convert(varchar(10),dateadd(day,5,'2019-05-01'),120)
结果对比

18 DATEPART函数

select month(getdate())
select DATEPART(month,getdate())
select datename(month,getdate())

19 CHARINDEX函数

select charindex('cc','aabbccdd')
select charindex('cc','aabbccdd',6)
select patindex('cc','aabbccdd')
select patindex('%cc%','aabbccdd')
--以a开头--
select patindex('aa%','aabbccdd')
--以d结尾
select patindex('%dd','aabbccdd')
select *,charindex('年',Grade) as index_grade from te.dbo.class
where id = 1
结果

20 Stuff函数

select stuff('aabbccdd',5,2,'')
select stuff('aabbccdd',5,2,'eegg')
select *,stuff(grade,2,1,'nian') from te.dbo.class 
where id = 3

21 SUBSTRING函数

select substring('abcdefg',3,5)
select *,substring(grade,2,2) as substring_grade from te.dbo.class
where id = 3

22 LEFT()/RIGHT()

select *,left(grade,2) from te.dbo.class
where id = 3

23 LTRIM()/RTRIM()

24 UPPER()/LOWER()

25 REPLACE()

26 REPLICATE()

27 SPACE()

27 REVERSE()

27 CAST()

select 'abc' + cast(1 as varchar(5))

28 CASE()

--简单CASE函数
select *,case Sex 
when '男' then 'man'
else 'woman'
end from te.dbo.student
--搜索CASE函数
select *,case 
when studentno>1506 then 'no1'
when studentno>1505 and studentno<1507 then 'no2'
else 'no3' end
from te.dbo.student

29 Duplicate Emails

Write a SQL query to find all duplicate emails in a table named Person.

+----+---------+
| Id | Email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+
For example, your query should return the following for the above table:

+---------+
| Email   |
+---------+
| a@b.com |
+---------+
select Email
from Person
group by Email
having count(*) > 1

29 Employees Earning More Than Their Managers

The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.

+----+-------+--------+-----------+
| Id | Name  | Salary | ManagerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | NULL      |
| 4  | Max   | 90000  | NULL      |
+----+-------+--------+-----------+
Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.

+----------+
| Employee |
+----------+
| Joe      |
+----------+
select a.name as Employee
from employee as a,employee as b
where a.managerid = b.id
and a.salary > b.salary
上一篇下一篇

猜你喜欢

热点阅读