design-azure-sql-schema
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDesign a schema Azure SQL Database will not make you rebuild
设计一套不会让 Azure SQL Database 迫使你重建的 Schema
These are the schema decisions Azure SQL Database punishes later, not at .
Normalisation and naming are not here: they are the same everywhere.
CREATE TABLEEverything below holds on Azure SQL Database, where returns
and is .
Open the statements behind each number when
a number below disagrees with your engine, and before changing one.
SERVERPROPERTY('EngineEdition')5EditionSQL Azure| The DDL | succeeds, sometimes with a warning nobody reads |
| The migration | succeeds |
| The failure | arrives on a row, a plan or a failover, weeks later, in production |
A syntax error costs minutes. Each item here costs a table rebuild, a collation rebuild or a
duplicated key.
以下讨论的是 Azure SQL Database 不会在 时报错,却会在日后给你带来代价的 Schema 决策。
规范化和命名不在此讨论范围内,因为它们在任何地方都一样。
CREATE TABLE以下所有内容均适用于 Azure SQL Database,其中 返回 ,
且 为 。
如果下文的某个数值与你的引擎不一致,或者在更改某个设置之前,请打开每个数字背后的依据。
SERVERPROPERTY('EngineEdition')5EditionSQL Azure| DDL | 成功,有时只伴随一条无人会注意的警告 |
| 迁移 | 成功 |
| 故障 | 数周后在生产环境中降临于某一行、某个执行计划或一次故障转移 |
语法错误只需几分钟。这里每一项错误都可能导致重建表、重建排序规则或产生重复键。
1. The index key budget is in bytes, and Unicode spends two per character
1. 索引键预算以字节计算,而 Unicode 每个字符占用两个字节
1700 bytes for a nonclustered index key, 900 for a clustered one, and a composite key spends
the sum. costs bytes, so:
NVARCHAR(n)2n| Position | Widest safe Unicode column | Widest safe UTF-8 column |
|---|---|---|
| Nonclustered index or unique constraint | | |
| Clustered index or clustered primary key | | |
| Anything not in a key | unbounded | unbounded |
NVARCHAR(450)Over-shooting is a warning, message 1945 at severity 10. The index exists, the migration
reports success, short values insert fine:
text
Warning! The maximum key length for a nonclustered index is 1700 bytes.
The index 'ux_acct_email' has maximum length of 2000 bytes.
For some combination of large values, the insert/update operation will fail.The failure waits for the first long row, and this one is an error:
text
Msg 1946, Level 16, State 3
Operation failed. The index entry of length 1800 bytes for the index 'ux_acct_email'
exceeds the maximum length of 1700 bytes for nonclustered indexes.Consequence of being wrong: a write path that has worked for months starts rejecting exactly the
rows that matter, and the fix is an plus an index rebuild on a live table.
ALTER COLUMN- columns do not count against the budget. A covering index can include
INCLUDE.NVARCHAR(MAX) - A foreign key column must match the parent's length and collation exactly, and
Msg 1753, so an oversized parent key propagates to every child.Msg 1757 - ,
NVARCHAR(MAX)andjsoncannot be key columns at all:vector,Msg 1919.Msg 1978
非聚集索引键为 1700 字节,聚集索引键为 900 字节;复合键占用两者之和。 占用 字节,因此:
NVARCHAR(n)2n| 位置 | 最宽的安全 Unicode 列 | 最宽的安全 UTF-8 列 |
|---|---|---|
| 非聚集索引或唯一约束 | | |
| 聚集索引或聚集主键 | | |
| 不包含在键中的列 | 无上限 | 无上限 |
只有 的长度在所有索引位置中都安全,因此 EF Core 会将索引字符串长度收窄到该值。
NVARCHAR(450)超出限制只会产生警告,即严重级别 10 的消息 1945。索引仍然存在,迁移报告成功,较短的值也能正常插入:
text
Warning! The maximum key length for a nonclustered index is 1700 bytes.
The index 'ux_acct_email' has maximum length of 2000 bytes.
For some combination of large values, the insert/update operation will fail.失败会一直等到第一条长记录出现,而下面才是错误:
text
Msg 1946, Level 16, State 3
Operation failed. The index entry of length 1800 bytes for the index 'ux_acct_email'
exceeds the maximum length of 1700 bytes for nonclustered indexes.**选错的后果是:**一条已经运行数月的写入路径会开始拒绝恰恰是那些重要记录的行,而修复方式是在在线表上执行 并重建索引。
ALTER COLUMN- 列不计入预算。因此,覆盖索引可以包含
INCLUDE。NVARCHAR(MAX) - 外键列的长度和排序规则必须与父表键完全一致,否则会报 和
Msg 1753;因此,父键过长会传导到每个子表。Msg 1757 - 、
NVARCHAR(MAX)和json完全不能作为键列:会报vector、Msg 1919。Msg 1978
2. Collation is chosen at CREATE DATABASE, and it decides two things
2. 排序规则在 CREATE DATABASE
时确定,并决定两件事
CREATE DATABASEA new database with no collation stated gets .
SQL_Latin1_General_CP1_CI_ASCIsql
CREATE TABLE dbo.tokens (t NVARCHAR(64) NOT NULL PRIMARY KEY);
INSERT INTO dbo.tokens (t) VALUES (N'aB1x');
INSERT INTO dbo.tokens (t) VALUES (N'Ab1X');
-- Msg 2627, Violation of PRIMARY KEY constraint. The duplicate key value is (Ab1X).Consequence of being wrong: any column holding a case-significant token, API key, slug or short
link code collides at roughly the rate its alphabet implies, as a user-visible insert failure.
The fix is per column:
sql
ALTER TABLE dbo.tokens ALTER COLUMN t NVARCHAR(64) COLLATE Latin1_General_CS_AS NOT NULL;State the collation in , or accept the default deliberately. There is no
server collation to inherit, and afterwards re-collates nothing that
already exists: it succeeds, changes only what is created next, and leaves you joining across a
collation conflict, . The second half of the default's cost is section 3.
CREATE DATABASEALTER DATABASE ... COLLATEMsg 468创建新数据库时如果没有指定排序规则,就会使用 。
SQL_Latin1_General_CP1_CI_ASCIsql
CREATE TABLE dbo.tokens (t NVARCHAR(64) NOT NULL PRIMARY KEY);
INSERT INTO dbo.tokens (t) VALUES (N'aB1x');
INSERT INTO dbo.tokens (t) VALUES (N'Ab1X');
-- Msg 2627, Violation of PRIMARY KEY constraint. The duplicate key value is (Ab1X).**选错的后果是:**任何保存区分大小写的 token、API key、slug 或短链接代码的列,都会大致按其字符集所对应的概率发生碰撞,并以用户可见的插入失败形式暴露出来。
修复方式是按列设置排序规则:
sql
ALTER TABLE dbo.tokens ALTER COLUMN t NVARCHAR(64) COLLATE Latin1_General_CS_AS NOT NULL;在 中明确指定排序规则,或者有意识地接受默认值。 没有可继承的服务器排序规则;事后执行 不会重新设置任何现有对象的排序规则:该语句会成功,只影响之后创建的对象,并使跨排序规则连接出现冲突,即 。默认排序规则的另一半代价见第 3 节。
CREATE DATABASEALTER DATABASE ... COLLATEMsg 4683. The implicit conversion that costs the seek
3. 让索引 Seek 退化的隐式转换
The common drivers bind a string parameter as Unicode by default. Under the default collation,
comparing that parameter to a column converts the column, and a converted column
cannot be sought. With a unique index on :
VARCHARemail| Column | Collation | Parameter | Plan | Logical reads |
|---|---|---|---|---|
| | | Index Scan | the whole index |
| | | Index Seek | a few pages |
| | | Index Seek | a few pages |
| any | | Index Seek | a few pages |
| the default | | Index Seek | a few pages |
text
|--Index Scan(OBJECT:([dbo].[users_v].[ux_v]),
WHERE:(CONVERT_IMPLICIT(nvarchar(320),[dbo].[users_v].[email],0)=[@p]))Row two seeks because a Windows collation lets the optimizer build a range with
. A SQL collation cannot, and the default is a SQL collation.
GetRangeThroughConvertConsequence of being wrong: every lookup on that column reads the whole index instead of a few
pages, forever, with no error and no warning. Two designs avoid it, and one has to be chosen up
front:
- for anything a driver will bind a string to. Correct, and it costs key bytes.
NVARCHAR - A UTF-8 collation on when the data is ASCII-dominant and the key is tight.
VARCHARthen fits a nonclustered key, and the seek survives because UTF-8 collations are Windows collations. The cost is thatVARCHAR(1700)counts bytes.VARCHAR(n)
Do not mix. under the default collation plus an application binding Unicode is row one.
VARCHAR常见驱动程序默认将字符串参数绑定为 Unicode。在默认排序规则下,将该参数与 列比较时,转换发生在列上,而经过转换的列无法执行 Seek。对于 上的唯一索引:
VARCHARemail| 列 | 排序规则 | 参数 | 计划 | 逻辑读取 |
|---|---|---|---|---|
| | | Index Scan | 整个索引 |
| | | Index Seek | 少量页面 |
| | | Index Seek | 少量页面 |
| 任意 | | Index Seek | 少量页面 |
| 默认 | | Index Seek | 少量页面 |
text
|--Index Scan(OBJECT:([dbo].[users_v].[ux_v]),
WHERE:(CONVERT_IMPLICIT(nvarchar(320),[dbo].[users_v].[email],0)=[@p]))第二行之所以能够执行 Seek,是因为 Windows 排序规则允许优化器通过 构建范围。SQL 排序规则不能这样做,而默认排序规则正是 SQL 排序规则。
GetRangeThroughConvert**选错的后果是:**该列上的每次查找都会永久读取整个索引,而不是少量页面,既没有错误,也没有警告。有两种设计可以避免这一问题,必须提前选定其中一种:
- 对于驱动程序会绑定字符串的任何内容,使用 。 这种做法正确,但会增加键字节数。
NVARCHAR - 当数据以 ASCII 为主且键空间较紧时,在 上使用 UTF-8 排序规则。 此时
VARCHAR可以放入非聚集键,而且由于 UTF-8 排序规则属于 Windows 排序规则,Seek 仍可保留。代价是VARCHAR(1700)按字节计数。VARCHAR(n)
不要混用。默认排序规则下的 加上应用程序绑定 Unicode 参数,就是表格中的第一行。
VARCHAR4. Identity gaps are routine here, and the remembered fix does not exist
4. 这里的 IDENTITY 间隙很常见,而记忆中的修复方法并不存在
Across one engine restart, which is what a planned failover looks like from inside:
| Column | Last value before | First value after | Gap |
|---|---|---|---|
| 3 | 1002 | 999 |
| 3 | 10002 | 9999 |
| 2 | 51 | 49 |
| 2 | 3 | none |
| 3 | 4 | none |
Consequence of being wrong: any number a human reads or a regulator counts, an invoice number, a
ticket number, an order reference, develops thousand-wide holes, unrecoverably. Nothing errors.
sql
-- The remembered remedy from a non-PaaS engine. Refused here.
DBCC TRACEON (272, -1); -- container: Msg 40518, DBCC command 'traceon' is not supported
-- Azure SQL Database: Msg 2571, no permission to run DBCC TRACEON
-- The lever that works. It survives a restart and costs a log write per value.
ALTER DATABASE SCOPED CONFIGURATION SET IDENTITY_CACHE = OFF;
-- A human-facing number gets its own sequence, and START WITH is not optional:
-- omitted, the first value is -9223372036854775808.
CREATE SEQUENCE dbo.invoice_no AS BIGINT START WITH 1 INCREMENT BY 1 NO CACHE;A surrogate key may be : gaps in a key nobody reads are free, and the cache is why
inserts are fast. A number a person reads is not a surrogate key.
IDENTITY在一次引擎重启前后——从数据库内部看,计划内故障转移正是这种情况——情况如下:
| 列 | 重启前的最后一个值 | 重启后的第一个值 | 间隙 |
|---|---|---|---|
| 3 | 1002 | 999 |
| 3 | 10002 | 9999 |
| 2 | 51 | 49 |
| 2 | 3 | 无 |
| 3 | 4 | 无 |
**选错的后果是:**任何供人读取或供监管机构统计的数字,例如发票号、工单号或订单参考号,都会产生跨度达上千且无法恢复的空洞。系统不会报任何错误。
sql
-- The remembered remedy from a non-PaaS engine. Refused here.
DBCC TRACEON (272, -1); -- container: Msg 40518, DBCC command 'traceon' is not supported
-- Azure SQL Database: Msg 2571, no permission to run DBCC TRACEON
-- The lever that works. It survives a restart and costs a log write per value.
ALTER DATABASE SCOPED CONFIGURATION SET IDENTITY_CACHE = OFF;
-- A human-facing number gets its own sequence, and START WITH is not optional:
-- omitted, the first value is -9223372036854775808.
CREATE SEQUENCE dbo.invoice_no AS BIGINT START WITH 1 INCREMENT BY 1 NO CACHE;代理键可以使用 :没人会读取的键出现间隙没有代价,而缓存正是插入速度较快的原因。供人读取的数字不应使用代理键。
IDENTITY5. A unique index accepts exactly one NULL
5. 唯一索引恰好接受一个 NULL
This one arrives from PostgreSQL habit, where every NULL is distinct.
sql
CREATE UNIQUE INDEX ux_code ON dbo.accounts (code);
INSERT INTO dbo.accounts (code) VALUES (NULL); -- 1 row
INSERT INTO dbo.accounts (code) VALUES (NULL);
-- Msg 2601, Cannot insert duplicate key row ... The duplicate key value is (<NULL>).
-- Msg 2627 instead, where the constraint is a unique constraint rather than an index.
-- The fix, which accepts many NULL rows:
DROP INDEX ux_code ON dbo.accounts;
CREATE UNIQUE INDEX ux_code ON dbo.accounts (code) WHERE code IS NOT NULL;Consequence of being wrong: an optional unique field, an external account id, a nullable slug,
works for the first row that leaves it empty and rejects the second. A model with two or three
optional unique fields is unusable here and correct on other engines. The session creating a
filtered index, and every session writing to the table, needs , else
. Drivers set it; a command line client may not.
QUOTED_IDENTIFIER ONMsg 1934这个问题源于 PostgreSQL 的使用习惯:在 PostgreSQL 中,每个 NULL 都被视为彼此不同。
sql
CREATE UNIQUE INDEX ux_code ON dbo.accounts (code);
INSERT INTO dbo.accounts (code) VALUES (NULL); -- 1 row
INSERT INTO dbo.accounts (code) VALUES (NULL);
-- Msg 2601, Cannot insert duplicate key row ... The duplicate key value is (<NULL>).
-- Msg 2627 instead, where the constraint is a unique constraint rather than an index.
-- The fix, which accepts many NULL rows:
DROP INDEX ux_code ON dbo.accounts;
CREATE UNIQUE INDEX ux_code ON dbo.accounts (code) WHERE code IS NOT NULL;**选错的后果是:**可选唯一字段、外部账户 ID 或可空 slug 只会接受第一条留空记录,却会拒绝第二条。包含两三个可选唯一字段的模型在这里不可用,而在其他引擎中却能正常工作。创建筛选索引的会话,以及写入该表的每个会话,都需要启用 ,否则会出现 。驱动程序会启用它,但命令行客户端可能不会。
QUOTED_IDENTIFIER ONMsg 19346. Where the json and vector types belong
6. json
与 vector
类型的适用位置
jsonvectorBoth are storage decisions, not key decisions.
| | |
|---|---|---|
| Index key column | no, | no, |
| Primary key | no | no, |
| yes | route to |
Compared with | no, | route to |
| Ceiling | 2 GB | 1998 dimensions at |
A column is not a filter. Promote anything a query filters on every time into a real
column:
jsonsql
ALTER TABLE dbo.doc ADD tenant AS CAST(JSON_VALUE(payload, '$.tenant') AS NVARCHAR(64)) PERSISTED;
CREATE INDEX ix_doc_tenant ON dbo.doc (tenant);A column is a payload beside the key, never part of it. A occupies 6152 of
the 8060 bytes in a row, so keep the table narrow: put the embedding next to an integer key.
vectorvector(1536)两者都是存储决策,而不是键决策。
| | |
|---|---|---|
| 索引键列 | 不支持, | 不支持, |
| 主键 | 不支持 | 不支持, |
| 支持 | 转至 |
使用 | 不支持;与 | 转至 |
| 上限 | 2 GB | |
不能将 列直接用作筛选依据。任何每次查询都会用于筛选的内容,都应提升为真实列:
jsonsql
ALTER TABLE dbo.doc ADD tenant AS CAST(JSON_VALUE(payload, '$.tenant') AS NVARCHAR(64)) PERSISTED;
CREATE INDEX ix_doc_tenant ON dbo.doc (tenant);vectorvector(1536)7. Two boundaries a design cannot cross here
7. 这里的设计无法跨越的两条边界
sql
-- No foreign key reaches another database, even one on the same server.
ALTER TABLE dbo.local_child ADD CONSTRAINT fk_x FOREIGN KEY (parent_id)
REFERENCES otherdb.dbo.some_parent (id);
-- Msg 40515, Reference to database and/or server name in 'otherdb.dbo.some_parent'
-- is not supported in this version of SQL Server.
-- There is one filegroup, so a partition scheme maps everything to it.
SELECT name, type_desc FROM sys.filegroups; -- PRIMARY, and nothing else
CREATE PARTITION SCHEME ps AS PARTITION pf ALL TO ([PRIMARY]);A shared-lookup-database design has no referential integrity here. Partitioning buys
manageability, never storage separation.
sql
-- No foreign key reaches another database, even one on the same server.
ALTER TABLE dbo.local_child ADD CONSTRAINT fk_x FOREIGN KEY (parent_id)
REFERENCES otherdb.dbo.some_parent (id);
-- Msg 40515, Reference to database and/or server name in 'otherdb.dbo.some_parent'
-- is not supported in this version of SQL Server.
-- There is one filegroup, so a partition scheme maps everything to it.
SELECT name, type_desc FROM sys.filegroups; -- PRIMARY, and nothing else
CREATE PARTITION SCHEME ps AS PARTITION pf ALL TO ([PRIMARY]);共享查找数据库的设计在这里无法实现引用完整性。分区带来的是可管理性,而不是存储隔离。
Check it worked
检查是否生效
Run the DDL through with , because message 1945 is severity 10 and alone
does not report severity 10 at all, so a migration that emitted it still exits 0:
sqlcmd-m-1-b-m-1sqlcmdmssql-tools18brew install sqlcmdwinget install sqlcmdMsg-mgrepsys.messagesbash
export SQLCMDPASSWORD='<password>'
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -b -m-1 \
-i schema.sql -o schema.out
grep -nE 'Warning!|^Msg ' schema.outExpect no output from . A line naming a key length is message 1945 and predicts
on a production insert.
grepWarning!Msg 1946Then audit the schema the engine actually has, as :
schema-audit.sqlsql
-- 1. Index keys over budget. Expect zero rows.
SELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name, i.type_desc,
SUM(CASE WHEN c.max_length = -1 THEN 0 ELSE c.max_length END) AS key_bytes,
CASE WHEN i.type = 1 THEN 900 ELSE 1700 END AS budget
FROM sys.indexes AS i
JOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
AND ic.is_included_column = 0
JOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.type IN (1, 2) AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1
GROUP BY i.object_id, i.name, i.type, i.type_desc
HAVING SUM(CASE WHEN c.max_length = -1 THEN 0 ELSE c.max_length END)
> CASE WHEN i.type = 1 THEN 900 ELSE 1700 END;
-- 2. Unique indexes over a nullable column with no filter: one NULL row each. Expect zero.
SELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name, c.name AS column_name
FROM sys.indexes AS i
JOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
AND ic.is_included_column = 0
JOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.is_unique = 1 AND i.has_filter = 0 AND c.is_nullable = 1;
-- 3. VARCHAR or CHAR key columns on a SQL collation: the lost seek. Expect zero rows.
SELECT DISTINCT OBJECT_NAME(c.object_id) AS table_name, c.name AS col, c.collation_name
FROM sys.columns AS c
JOIN sys.index_columns AS ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
AND ic.is_included_column = 0
JOIN sys.types AS t ON t.user_type_id = c.user_type_id
WHERE t.name IN ('varchar', 'char') AND c.collation_name LIKE 'SQL[_]%';
-- 4. Sequences left on the type minimum because START WITH was omitted. Expect zero rows.
SELECT name, CAST(start_value AS BIGINT) AS start_value
FROM sys.sequences WHERE CAST(start_value AS BIGINT) < 0;
-- 5. The two settings the design assumed. Read them, do not assume them.
SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation') AS db_collation,
(SELECT value FROM sys.database_scoped_configurations
WHERE name = 'IDENTITY_CACHE') AS identity_cache;bash
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -W \
-i schema-audit.sql -o schema-audit.outChecks 1 to 4 return no rows in a clean schema. Check 5 is the one you read rather than pass:
of means gaps are off, means an will jump by about a
thousand across the next reconfiguration.
identity_cache01INT IDENTITYLast, confirm the seek survived on one real lookup:
sql
SET STATISTICS IO ON;
DECLARE @p NVARCHAR(320) = N'u9999@example.com';
SELECT id FROM dbo.users WHERE email = @p;
SET STATISTICS IO OFF;Expect single-digit logical reads that do not grow with the table. Reads that grow with the table
are the implicit conversion in section 3, not a cold cache.
通过 的 运行 DDL,因为消息 1945 的严重级别为 10,而单独使用 根本不会报告严重级别 10 的消息,因此即使迁移输出了该消息,仍会以状态码 0 退出:
sqlcmd-m-1-b-m-1sqlcmdmssql-tools18brew install sqlcmdwinget install sqlcmd-mMsggrepsys.messagesbash
export SQLCMDPASSWORD='<password>'
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -b -m-1 \
-i schema.sql -o schema.out
grep -nE 'Warning!|^Msg ' schema.out期望 没有任何输出。指出键长度超限的 行就是消息 1945,它预示着生产环境中的插入操作将出现 。
grepWarning!Msg 1946然后通过 审计引擎实际拥有的 Schema:
schema-audit.sqlsql
-- 1. Index keys over budget. Expect zero rows.
SELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name, i.type_desc,
SUM(CASE WHEN c.max_length = -1 THEN 0 ELSE c.max_length END) AS key_bytes,
CASE WHEN i.type = 1 THEN 900 ELSE 1700 END AS budget
FROM sys.indexes AS i
JOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
AND ic.is_included_column = 0
JOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.type IN (1, 2) AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1
GROUP BY i.object_id, i.name, i.type, i.type_desc
HAVING SUM(CASE WHEN c.max_length = -1 THEN 0 ELSE c.max_length END)
> CASE WHEN i.type = 1 THEN 900 ELSE 1700 END;
-- 2. Unique indexes over a nullable column with no filter: one NULL row each. Expect zero.
SELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name, c.name AS column_name
FROM sys.indexes AS i
JOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
AND ic.is_included_column = 0
JOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.is_unique = 1 AND i.has_filter = 0 AND c.is_nullable = 1;
-- 3. VARCHAR or CHAR key columns on a SQL collation: the lost seek. Expect zero rows.
SELECT DISTINCT OBJECT_NAME(c.object_id) AS table_name, c.name AS col, c.collation_name
FROM sys.columns AS c
JOIN sys.index_columns AS ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
AND ic.is_included_column = 0
JOIN sys.types AS t ON t.user_type_id = c.user_type_id
WHERE t.name IN ('varchar', 'char') AND c.collation_name LIKE 'SQL[_]%';
-- 4. Sequences left on the type minimum because START WITH was omitted. Expect zero rows.
SELECT name, CAST(start_value AS BIGINT) AS start_value
FROM sys.sequences WHERE CAST(start_value AS BIGINT) < 0;
-- 5. The two settings the design assumed. Read them, do not assume them.
SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation') AS db_collation,
(SELECT value FROM sys.database_scoped_configurations
WHERE name = 'IDENTITY_CACHE') AS identity_cache;bash
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -W \
-i schema-audit.sql -o schema-audit.out在干净的 Schema 中,检查 1 至 4 应不返回任何行。检查 5 不是用来判断通过与否,而是需要阅读: 为 表示间隙已关闭;为 表示 会在下一次重新配置时跃升约一千。
identity_cache01INT IDENTITY最后,在一个真实查找上确认 Seek 仍然有效:
sql
SET STATISTICS IO ON;
DECLARE @p NVARCHAR(320) = N'u9999@example.com';
SELECT id FROM dbo.users WHERE email = @p;
SET STATISTICS IO OFF;预期逻辑读取次数为个位数,且不随表的大小增长。读取量随表增长是第 3 节所述的隐式转换导致的,而不是冷缓存造成的。
Do not
不要
- Do not read message 1945 as informational. It is the only notice given, and severity 10 means
neither nor most drivers raise it.
sqlcmd -b - Do not size a key column in characters. The limit is bytes, and Unicode doubles it.
- Do not use under the default collation for anything an application looks up by value.
VARCHAR - Do not add or
LOWER()around a column to fix a collation problem. That costs the index too, and it isUPPER().t-sql-correctness - Do not reach for trace flag 272. It is rejected, with on the container and
Msg 40518(no permission, even asMsg 2571) on Azure SQL Database. The lever isdbo.IDENTITY_CACHE = OFF - Do not put an invoice or ticket number, or anything an auditor reads, on a bare .
IDENTITY - Do not create a without
SEQUENCE.START WITH - Do not give a model two or three optional unique columns and expect PostgreSQL NULL semantics.
- Do not store a value in a document and then filter on it. Promote it.
json - Do not add a clustered index only because you believe this engine demands one. A heap can be created and takes rows.
- 不要把消息 1945 当作纯信息提示。它是唯一的通知,而严重级别 10 意味着 和大多数驱动程序都不会报告该消息。
sqlcmd -b - 不要以字符数确定键列大小。限制以字节为单位,而 Unicode 会将字节数翻倍。
- 不要在默认排序规则下,将 用于任何需要按值查找的内容。
VARCHAR - 不要在列外包裹 或
LOWER()来解决排序规则问题。这同样会使索引无法使用,属于UPPER()的范畴。t-sql-correctness - 不要使用跟踪标志 272。它会被拒绝:容器中会报 ,在 Azure SQL Database 中则会报
Msg 40518,即使以Msg 2571身份运行也没有权限。可用的控制项是dbo。IDENTITY_CACHE = OFF - 不要将发票号、工单号或任何供审计人员读取的数字放在普通的 上。
IDENTITY - 不要创建缺少 的
START WITH。SEQUENCE - 不要设计包含两三个可选唯一列的模型,却期望获得 PostgreSQL 的 NULL 语义。
- 不要把值存储在 文档中后再对其进行筛选。应将其提升为独立列。
json - 不要仅仅因为认为此引擎要求聚集索引就添加聚集索引。堆表也可以创建,并且能够容纳数据行。
References
参考资料
- Open the statements behind each number when you need the statement behind a number above, the two query plans, or the setup to run them.
- Read Maximum capacity specifications before designing a wide composite key.
- Read Collation and Unicode support before choosing a database collation: SQL against Windows collations, and UTF-8.
- Read json data type before putting a document in a column, for the index restrictions and the size limits.
- Read Database scoped configurations
before setting , and T-SQL differences when a statement is refused with 40510, 40515, 40517, 40518 or 2571.
IDENTITY_CACHE - and
ef-core-azure-sql: how each mapper reaches these lengths and the default it lands on. The other mapper skills are listed insqlalchemy-azure-sql.skill.spec.jsonc - for query-level correctness,
t-sql-correctnessfor querying a document column,t-sql-json-and-openjsonfor the vector type and its indexing.vector-search-azure-sql - and
schema-migrations-safelyfor applying a change to a live database, andsql-database-projectsfor creating the database and naming its collation.provision-azure-sql-db
- 当你需要了解上述某个数字背后的依据、两个查询计划或运行它们的设置时,请打开每个数字背后的依据。
- 在设计宽复合键之前,请阅读最大容量规范。
- 在选择数据库排序规则之前,请阅读排序规则和 Unicode 支持:SQL 与 Windows 排序规则,以及 UTF-8。
- 在把文档放入列之前,请阅读 json 数据类型,了解索引限制和大小上限。
- 在设置 之前,请阅读数据库范围配置;当语句因 40510、40515、40517、40518 或 2571 被拒绝时,请阅读 T-SQL 差异。
IDENTITY_CACHE - 和
ef-core-azure-sql:了解每个 mapper 如何达到这些长度限制,以及最终采用的默认值。其他 mapper skill 列于sqlalchemy-azure-sql。skill.spec.jsonc - 用于查询层面的正确性,
t-sql-correctness用于查询文档列,t-sql-json-and-openjson用于 vector 类型及其索引。vector-search-azure-sql - 和
schema-migrations-safely用于把变更应用到在线数据库,sql-database-projects用于创建数据库并指定其排序规则。provision-azure-sql-db