我之前用过sql server,后来使用频率较少,最近有开始接触了,顺便整理下笔记,为后续准备~
其实与mysql语法几乎一致,然后分页查询与oracle 有点像是利用行号,这里采用docker安装;
下载2017版本
docker pull mcr.microsoft.com/mssql/server:2017-latest
安装命令
docker run -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=sa123456SA' --name sqlserver -p 1433:1433 -v /var/opt/mssql:/var/opt/mssql -d mcr.microsoft.com/mssql/server:2017-latest
密码大于8位且要有大小写字母,否则启动失败
这里密码是: sa123456SA
设置的容器名称为sqlserver 端口号为 1433
挂在数据到 /var/opt/mssql 符号[:] 后面为容器路径
可以通过查看启动日志看到具体的情况docker logs -f sqlserver
主机: ip地址
用户名/密码: sa / sa123456SA
认证是默认的sql server认证
-- 用户表
CREATE TABLE [dbo].[user] (
[id] int NOT NULL,
[name] varchar(255) COLLATE Chinese_PRC_CS_AI_WS NULL,
CONSTRAINT [PK__user__3213E83F4C7BD7DB] PRIMARY KEY CLUSTERED ([id])
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
)
ON [PRIMARY]
GO
ALTER TABLE [dbo].[user] SET (LOCK_ESCALATION = TABLE)
-- 地址表
CREATE TABLE [dbo].[add] (
[id] int NOT NULL,
[add] varchar(255) COLLATE Chinese_PRC_CS_AI_WS NULL,
[user_id] int NULL,
CONSTRAINT [PK__add__3213E83F7989DEE9] PRIMARY KEY CLUSTERED ([id])
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
)
ON [PRIMARY]
GO
ALTER TABLE [dbo].[add] SET (LOCK_ESCALATION = TABLE)
GO
EXEC sp_addextendedproperty
'MS_Description', N'地址',
'SCHEMA', N'dbo',
'TABLE', N'add',
'COLUMN', N'add'
GO
EXEC sp_addextendedproperty
'MS_Description', N'用户id',
'SCHEMA', N'dbo',
'TABLE', N'add',
'COLUMN', N'user_id'
-- 添加数据
INSERT INTO [user] ([id], [name]) VALUES (1, '小明'); GO
INSERT INTO [user] ([id], [name]) VALUES (2, '小红'); GO
INSERT INTO [add] ([id], [add], [user_id]) VALUES (1, '济南', 1); GO
INSERT INTO [add] ([id], [add], [user_id]) VALUES (2, '青岛', 1); GO
SELECT * FROM dbo.[user] WHERE name like '%红%';
select a.*
from dbo.[user] u left JOIN dbo.[add] a on a.user_id = u.id
where u.id = 1
-- 利用行号分页
select * from
(
select ROW_NUMBER() OVER(order by id) as row_number,* from dbo.[user]
)as t
where t.row_number between 2 and 2
-- 利用top分页
-- 第一页
SELECT TOP 1 * FROM dbo.[user]
-- 第二页
SELECT TOP 2 * FROM dbo.[user] WHERE id not in (
SELECT TOP 1 id FROM dbo.[user]
)
-- 利用OFFSET FETCH NEXT
-- 第一页
SELECT id,name,code,price FROM goods ORDER BY id ASC OFFSET 0 ROWS FETCH NEXT 2 ROWS ONLY
-- 第二页
SELECT id,name,code,price FROM goods ORDER BY id ASC OFFSET 2 ROWS FETCH NEXT 4 ROWS ONLY
SELECT @@VERSION AS dbVersion;
mssql 也是遵循sql92标准的,所以语法基本与mysql 等都是一致的,部分函数,关键字用法不一致,还有一些数据类型, 函数等;
示例项目地址 后续完善