SQL Database for Modern Developers
好书分享,面向开发者的Azure SQL Database最佳实践,也适用SQL Server 2016以上的版本。应对不同场景使用的数据库功能,包括内存表,列存储表,非聚集列存储索引,JSON等等。
下载地址:
https://all-ebook.info/9978-practical-azure-sql-database-for-modern-developers.html
基础SQL
Subqueries
Common Table Expressions
Union
Merge
MERGE INTO
[Warehouse].[Colors] AS [target]
USING
(VALUES
(50, 'Deep Sea Blue'),
(51, 'Deep Sea Light Blue'),
(52, 'Deep Sea Dark Blue')
) [source](Id, [Name])
ON
[target].[ColorID] = [source].[Id]
WHEN MATCHED THEN
UPDATE SET [target].[ColorName] = [source].[Name]
WHEN NOT MATCHED THEN
INSERT ([ColorID], [ColorName], [LastEditedBy]) VALUES ([source].Id,
[source].[Name], 1)
WHEN NOT MATCHED BY SOURCE AND [target].[ColorID] BETWEEN 50 AND 100 THEN
DELETE
Windowing Functions
SELECT
[OrderID],
[OrderLineID],
[Description],
[Quantity],
SUM(Quantity) OVER ( PARTITION BY [OrderID] ORDER BY [OrderLineID] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal
FROM
[Sales].[OrderLines]
WHERE
[OrderID] in (37, 39)
进阶SQL
Variables
T-SQL doesn't support arrays, lists, or dictionaries, you can use a Table Variable
DECLARE @t AS TABLE (
[Id] INT NOT NULL,
[Name] NVARCHAR(50) NOT NULL
);
INSERT INTO @t VALUES (42, N'John');
SELECT * FROM @t;
Temporary Tables
Views
Functions
Stored Procedures
使用json传递多值参数
CREATE OR ALTER PROCEDURE dbo.GetOrderForCustomer
@CustomerInfo NVARCHAR(MAX)
AS
IF (ISJSON(@CustomerInfo) != 1) BEGIN
THROW 50000, '@CustomerInfo is not a valid JSON document', 16
END
SELECT [Value] INTO #T FROM OPENJSON(@CustomerInfo, '$.CustomerId') AS ci;
SELECT
[CustomerID],
COUNT(*) AS OrderCount,
MIN([OrderDate]) AS FirstOrder,
MAX([OrderDate]) AS LastOrder
FROM
Sales.[Orders]
WHERE
[CustomerID] IN (SELECT [Value] FROM #T)
GROUP BY
[CustomerID];
EXEC dbo.GetOrderForCustomer N'{"CustomerId": [106, 193, 832]}';
unless you have some specific use case that is perfectly suited for a Function, the recommendation is to use Stored Procedures
永远不要用触发器了
JSON
动态参数,拓展属性列,弹性域
CSV
STRING_SPLIT
CREATE PROCEDURE dbo.AddTagsToPost
@PostId INT,
@Tags NVARCHAR(MAX)
AS
INSERT INTO dbo.PostTags
SELECT @PostId, T.[value] FROM STRING_SPLIT(@Tags, '|') AS T
EXEC dbo.AddTagsToPost 1, 'azure-sql|string_split|csv'
Change Tracking
CDC
替代方案Debezium+ Kafka
Row-Level Security
CREATE FUNCTION rls.LoginSecurityPolicy(@PersonID AS INT)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
SELECT
1 As [Authorized]
FROM
[Application].[People]
WHERE
LoginName = SESSION_CONTEXT(N'Login')
AND
PersonID = @PersonId;
system function SESSION_CONTEXT to retrieve the value of the Logon key
Dynamic Data Masking
Always Encrypted
多模
JSON
SELECT
severity,
ip = JSON_VALUE(log, '$.ip'),
duration = AVG(CAST(JSON_VALUE(log,'$.duration') as int))
FROM
WebSite.Logs
WHERE
CAST(JSON_VALUE(log,'$.date') as datetime) > @datetime
GROUP BY
severity, JSON_VALUE(log, '$.ip')
HAVING
AVG(CAST(JSON_VALUE(log,'$.duration') as int) ) > 100
ORDER BY
AVG(CAST(JSON_VALUE(log,'$.duration') as int) );
ALTER TABLE Webite.Logs
ADD CONSTRAINT [Data should be formatted as JSON]
CHECK (ISJSON(log) = 1);
CREATE CLUSTERED COLUMNSTORE INDEX cci ON WebSite.Logs;
alter table WebSite.Logs
add [$severity] AS JSON_VALUE(log, '$.severity');
go
create index ix_severity on WebSite.Logs ([$severity]);
Graph
Spatial data
XML data
Key-value
Azure SQL doesn't have a specialized structure that holds key-value pairs.
With memory-optimized tables, you can index the key column using B-tree or Hash indexes-使用内存表代替
CREATE TABLE [Cache] (
[key] BIGINT IDENTITY,
value NVARCHAR(MAX),
INDEX IX_Hash_Key HASH ([key]) WITH (BUCKET_COUNT = 100000)
) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_ONLY);
More Than Tables
列存储表
聚集列存储表
非聚集列存储索引
内存表
using classic rowstore tables with NCCI indexes for HTAP scenarios is the general approach,
Memory-Optimized Clustered Columnstore Indexes are used only on very performance-intensive workloads.
--Columnstore memory-optimized tables
CREATE TABLE Accounts (
AccountKey int NOT NULL PRIMARY KEY NONCLUSTERED,
Description nvarchar (50),
Type nvarchar(50),
UnitSold int,
INDEX cci CLUSTERED COLUMNSTORE
) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA)
--memory-optimized tables and the NONCLUSTERED HASH index
CREATE TABLE [dbo].[Employees](
[EmpID] [int] NOT NULL
CONSTRAINT PK_Employees_EmpID PRIMARY KEY
NONCLUSTERED HASH (EmpID) WITH (BUCKET_COUNT = 100000),
[EmpName] [varchar](50) NOT NULL,
[EmpAddress] [varchar](50) NOT NULL,
[EmpDEPID] [int] NOT NULL,
[EmpBirthDay] [datetime] NULL
) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA)
Natively compiled code
CREATE FUNCTION PeopleData(@json nvarchar(max))
RETURNS TABLE
WITH NATIVE_COMPILATION, SCHEMABINDING
AS RETURN (
SELECT Title, HireDate, PrimarySalesTerritory,
CommissionRate, OtherLanguages
FROM OPENJSON(@json)
WITH(Title nvarchar(50),
HireDate datetime2,
PrimarySalesTerritory nvarchar(50),
CommissionRate float,
OtherLanguages nvarchar(max) AS JSON)
)
--调用函数
select p.FullName, p.EmailAddress, j.Title, j.CommissionRate
from Application.People p
cross apply PeopleData(p.CustomFields) j
Temporal tables
--当前表使用内存表
--历史表使用列存储表+非聚集行索引
CREATE CLUSTERED COLUMNSTORE INDEX cci_DepartmentHistory
ON DepartmentHistory;
CREATE NONCLUSTERED INDEX IX_DepartmentHistory_ID_PERIOD_COLUMNS
ON DepartmentHistory (SysEndTime, SysStartTime, DeptID);
HTAP
列存储索引+内存表做实时混合负载,HTAP场景
本书作者的博客
insert if not exists
insert into [dbo].[tags] ([post_id], [tag])
select * from (
values (10, 'tag123') -- sample value
) as s([post_id], [tag])
where not exists (
select * from [dbo].[tags] t with (updlock)
where s.[post_id] = t.[post_id] and s.[tag] = t.[tag]
)
https://devblogs.microsoft.com/azure-sql/the-insert-if-not-exists-challenge-a-solution/
多行插入使用JSON, Table Valued Parameters,与MERGE的比较
key-value store性能测试
https://devblogs.microsoft.com/azure-sql/azure-sql-database-as-a-key-value-store/
IoT场景性能测试
JSON性能测试
开源web sql编辑器SQLPad
https://devblogs.microsoft.com/azure-sql/querying-and-visualizing-data-using-sqlpad/
DevOps for Azure SQL
https://devblogs.microsoft.com/azure-sql/devops-for-azure-sql/
SQL Database for Modern Developers的更多相关文章
- HTML5教程之html 5 本地数据库(Web Sql Database)
HTML5的Web SQL Databases(html5 本地数据库)的确很诱惑人,当你发现可以用与mysql查询一样的查询语句来操作本地数据库时,你会发现这东西挺有趣的.今天,我们一起来了解HTM ...
- Azure SQL Database (19) Stretch Database 概览
<Windows Azure Platform 系列文章目录> Azure SQL Database (19) Stretch Database 概览 Azure SQL Da ...
- Azure SQL Database (20) 使用SQL Server 2016 Upgrade Advisor
<Windows Azure Platform 系列文章目录> Azure SQL Database (19) Stretch Database 概览 Azure SQL Da ...
- Azure SQL Database (21) 将整张表都迁移到Azure Stretch Database里
<Windows Azure Platform 系列文章目录> Azure SQL Database (19) Stretch Database 概览 Azure SQL Da ...
- Azure SQL Database (22) 迁移部分数据到Azure Stretch Database
<Windows Azure Platform 系列文章目录> Azure SQL Database (19) Stretch Database 概览 Azure SQL Da ...
- Azure SQL Database Active Geo-Replication简介
笔者在<迁移SQL Server 数据库到 Azure SQL 实战>一文中,介绍了如何把一个本地版的 SQL Server 数据库迁移到 Azure SQL Database.迁移虽然顺 ...
- HTML5本地存储——Web SQL Database
在HTML5 WebStorage介绍了html5本地存储的Local Storage和Session Storage,这两个是以键值对存储的解决方案,存储少量数据结构很有用,但是对于大量结构化数据就 ...
- HTML5 学习笔记(三)——本地存储(LocalStorage、SessionStorage、Web SQL Database)
一.HTML4客户端存储 B/S架构的应用大量的信息存储在服务器端,客户端通过请求响应的方式从服务器获得数据,这样集中存储也会给服务器带来相应的压力,有些数据可以直接存储在客户端,传统的Web技术中会 ...
- web sql database数据存储位置
Q1: 数据存储在哪儿? Web Storage / Web SQL Database / Indexed Database 的数据都存储在浏览器对应的用户配置文件目录(user profile di ...
随机推荐
- R - 0 or 1(最短路)
Given a n*n matrix C ij (1<=i,j<=n),We want to find a n*n matrix X ij (1<=i,j<=n),which ...
- hdu 4315 Climbing the Hill && poj 1704 Georgia and Bob阶梯博弈--尼姆博弈
参考博客 先讲一下Georgia and Bob: 题意: 给你一排球的位置(全部在x轴上操作),你要把他们都移动到0位置,每次至少走一步且不能超过他前面(下标小)的那个球,谁不能操作谁就输了 题解: ...
- hdu3516 Tree Construction
Problem Description Consider a two-dimensional space with a set of points (xi, yi) that satisfy xi & ...
- Codeforces Round #644 (Div. 3) D. Buying Shovels (数学)
题意:商店里有\(k\)个包裹,第\(i\)个包裹中含有\(i\)个物品,现在想要买\(n\)物品,你可以选择某一个包裹购买任意次,使得物品数刚好等于\(n\),求最少的购买次数. 题解:首先,假如\ ...
- c语言中qsort函数的使用、编程中的一些错误
qsort()函数: 功能:相当于c++sort,具有快排的功能,复杂度的话nlog(n)注:C中的qsort()采用的是快排算法,C++的sort()则是改进的快排算法.两者的时间复杂度都是nlog ...
- AtCoder Beginner Contest 177 D - Friends (并查集)
题意:有\(n\)个人,给你\(m\)对朋友关系,朋友的朋友也是朋友,现在你想要将他们拆散放到不同的集合中,且每个集合中的人没有任何一对朋友关系,问最少需要多少集合. 题解:首先用并查集将朋友关系维护 ...
- LINUX - 通信
为什么三次握手: 让服务端和客户端都知道,自己的收信能力和发信能力没有问题: 第一次:客户端发给服务端--服务端知道了,自己的收信能力和客户端的发信能力没有问题: 第二次:服务端回复客户端--客户端知 ...
- VS中使用TreeView的Checked属性问题
VS中使用TreeView,当需要用到Checked属性,并需要同步子节点和父节点的Checked属性时,若使用AfterCheck事件会导致死循环,这里我使用的是NodeMouseClick事件.代 ...
- STM32 单片机的USART的奇偶校验 误区(坑)
当STM32的串口配置成带有奇偶校验位的情况下,需要软件校验是否发生奇偶校验错误,硬件只是置起奇偶校验错误标志位,并将错误的数据放到DR寄存器中,同时置起RXEN标志位,如果使能中断还是会正常进入中断 ...
- HaiYaaaa & 嗨呀
HaiYaaaa & 嗨呀 海呀... 嗨呀... refs Uncle Roger https://www.youtube.com/results?search_query=uncle+Ro ...