azure-sql-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAzure SQL Database Best Practices
Azure SQL Database 最佳实践
Comprehensive best practices guide for Azure SQL Database development and optimization. This skill helps AI agents analyze and improve T-SQL scripts, application database code, indexing strategies, security configurations, and connection patterns.
Based on:
针对Azure SQL Database开发与优化的全面最佳实践指南。本指南可帮助AI Agent分析并改进T-SQL脚本、应用数据库代码、索引策略、安全配置及连接模式。
基于:
When to Apply
适用场景
Reference these guidelines when:
- Writing new T-SQL queries, stored procedures, or scripts
- Reviewing database code for performance issues
- Configuring Azure SQL Database settings
- Implementing data access patterns in applications
- Optimizing indexing strategies
- Auditing security configurations
- Refactoring existing database code
- Migrating from SQL Server to Azure SQL Database
在以下场景中可参考本指南:
- 编写新的T-SQL查询、存储过程或脚本
- 评审数据库代码以排查性能问题
- 配置Azure SQL Database设置
- 在应用中实现数据访问模式
- 优化索引策略
- 审计安全配置
- 重构现有数据库代码
- 从SQL Server迁移至Azure SQL Database
Rule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Query Performance | CRITICAL | |
| 2 | Indexing Strategy | CRITICAL | |
| 3 | Security & Compliance | HIGH | |
| 4 | Connection Management | HIGH | |
| 5 | T-SQL Patterns | MEDIUM-HIGH | |
| 6 | SSDT Code Analysis | MEDIUM-HIGH | |
| 7 | Database Configuration | MEDIUM | |
| 8 | Data Modeling | MEDIUM | |
| 9 | Monitoring & Diagnostics | LOW-MEDIUM | |
| 优先级 | 类别 | 影响级别 | 前缀 |
|---|---|---|---|
| 1 | 查询性能 | 关键 | |
| 2 | 索引策略 | 关键 | |
| 3 | 安全与合规 | 高 | |
| 4 | 连接管理 | 高 | |
| 5 | T-SQL模式 | 中高 | |
| 6 | SSDT代码分析 | 中高 | |
| 7 | 数据库配置 | 中 | |
| 8 | 数据建模 | 中 | |
| 9 | 监控与诊断 | 中低 | |
SSDT Code Analysis Rules (Microsoft Static Analysis)
SSDT代码分析规则(微软静态分析)
These rules are from Microsoft's SQL Server Data Tools (SSDT) static code analysis. They are enforced in Visual Studio Database Projects.
这些规则来自微软SQL Server数据工具(SSDT)的静态代码分析,在Visual Studio数据库项目中强制执行。
Design Issues (SR0001, SR0008-SR0014)
设计问题(SR0001, SR0008-SR0014)
| Rule ID | Description | Severity |
|---|---|---|
| SR0001 | Avoid SELECT * in queries | HIGH |
| SR0008 | Use SCOPE_IDENTITY() instead of @@IDENTITY | MEDIUM |
| SR0009 | Avoid VARCHAR/NVARCHAR with size 1 or 2 | LOW |
| SR0010 | Avoid deprecated = and = join syntax | MEDIUM |
| SR0013 | Output parameter not populated in all code paths | MEDIUM |
| SR0014 | Potential data loss from implicit type casting | HIGH |
| 规则ID | 描述 | 严重级别 |
|---|---|---|
| SR0001 | 避免在查询中使用SELECT * | 高 |
| SR0008 | 使用SCOPE_IDENTITY()替代@@IDENTITY | 中 |
| SR0009 | 避免使用长度为1或2的VARCHAR/NVARCHAR | 低 |
| SR0010 | 避免使用已弃用的*=和=*连接语法 | 中 |
| SR0013 | 输出参数未在所有代码路径中赋值 | 中 |
| SR0014 | 隐式类型转换可能导致数据丢失 | 高 |
Performance Issues (SR0004-SR0007, SR0015)
性能问题(SR0004-SR0007, SR0015)
| Rule ID | Description | Severity |
|---|---|---|
| SR0004 | Avoid non-indexed columns in IN predicates | HIGH |
| SR0005 | Avoid LIKE patterns starting with '%' | HIGH |
| SR0006 | Move column reference to one side of comparison | MEDIUM |
| SR0007 | Use ISNULL(column, default) on nullable columns | MEDIUM |
| SR0015 | Extract deterministic function calls from WHERE | MEDIUM |
| 规则ID | 描述 | 严重级别 |
|---|---|---|
| SR0004 | 避免在IN谓词中使用未索引的列 | 高 |
| SR0005 | 避免使用以'%'开头的LIKE模式 | 高 |
| SR0006 | 将列引用移至比较运算符的一侧 | 中 |
| SR0007 | 对可为空的列使用ISNULL(column, default) | 中 |
| SR0015 | 从WHERE子句中提取确定性函数调用 | 中 |
Naming Issues (SR0011, SR0012, SR0016)
命名问题(SR0011, SR0012, SR0016)
| Rule ID | Description | Severity |
|---|---|---|
| SR0011 | Avoid special characters in object names | LOW |
| SR0012 | Avoid reserved words for type names | MEDIUM |
| SR0016 | Avoid sp_ prefix for stored procedures | MEDIUM |
| 规则ID | 描述 | 严重级别 |
|---|---|---|
| SR0011 | 避免在对象名称中使用特殊字符 | 低 |
| SR0012 | 避免使用保留字作为类型名称 | 中 |
| SR0016 | 避免为存储过程使用sp_前缀 | 中 |
Quick Reference
快速参考
1. Query Performance (CRITICAL)
1. 查询性能(关键)
- (SR0001) - Never use SELECT * in production code
query-avoid-select-star - - Always use parameterized queries to prevent SQL injection and enable plan caching
query-parameterize - - Don't apply functions to columns in WHERE clauses
query-avoid-functions-on-columns - - Write SARGable (Search ARGument ABLE) predicates for index usage
query-sargable - - Batch INSERT/UPDATE/DELETE operations to reduce round trips
query-batch-operations - - Replace cursors with set-based operations
query-avoid-cursors - - Use TOP or OFFSET-FETCH for pagination
query-limit-results - (SR0014) - Match data types to prevent implicit conversions
query-avoid-implicit-conversion - - Order joins for optimal execution plans
query-join-optimization - - Use EXISTS instead of COUNT(*) > 0
query-exists-vs-count - (SR0005) - Avoid LIKE '%value' patterns
query-avoid-leading-wildcard
- (SR0001) - 生产环境代码中严禁使用SELECT *
query-avoid-select-star - - 始终使用参数化查询以防止SQL注入并启用执行计划缓存
query-parameterize - - 不要在WHERE子句中对列应用函数
query-avoid-functions-on-columns - - 编写支持索引使用的SARGable(可搜索参数)谓词
query-sargable - - 批量处理INSERT/UPDATE/DELETE操作以减少往返次数
query-batch-operations - - 使用基于集合的操作替代游标
query-avoid-cursors - - 使用TOP或OFFSET-FETCH实现分页
query-limit-results - (SR0014) - 匹配数据类型以避免隐式转换
query-avoid-implicit-conversion - - 合理排序连接顺序以生成最优执行计划
query-join-optimization - - 使用EXISTS替代COUNT(*) > 0
query-exists-vs-count - (SR0005) - 避免使用LIKE '%value'模式
query-avoid-leading-wildcard
2. Indexing Strategy (CRITICAL)
2. 索引策略(关键)
- - Create covering indexes for frequent queries
index-cover-queries - - Balance read vs write performance
index-avoid-over-indexing - - Use DMVs to identify missing indexes
index-missing-index-dmv - - Remove unused indexes consuming resources
index-unused-indexes - - Monitor and address index fragmentation
index-fragmentation - - Use columnstore indexes for analytics workloads
index-columnstore - - Use filtered indexes for subset queries
index-filtered - - Use INCLUDE for non-key columns
index-include-columns - - Order index keys by selectivity
index-key-order - - Keep index keys narrow
index-avoid-wide-keys - (SR0004) - Ensure columns in IN predicates are indexed
index-in-predicate
- - 为频繁执行的查询创建覆盖索引
index-cover-queries - - 平衡读取与写入性能
index-avoid-over-indexing - - 使用DMV识别缺失的索引
index-missing-index-dmv - - 删除占用资源的未使用索引
index-unused-indexes - - 监控并解决索引碎片问题
index-fragmentation - - 为分析型工作负载使用列存储索引
index-columnstore - - 为子集查询使用筛选索引
index-filtered - - 为非键列使用INCLUDE子句
index-include-columns - - 按选择性排序索引键
index-key-order - - 保持索引键简洁
index-avoid-wide-keys - (SR0004) - 确保IN谓词中的列已建立索引
index-in-predicate
3. Security & Compliance (HIGH)
3. 安全与合规(高)
- - Prevent SQL injection with parameters
security-parameterize-queries - - Grant minimum required permissions
security-least-privilege - - Never use sa or dbo for application access
security-avoid-sa - - Always use encrypted connections
security-encrypt-connections - - Implement RLS for multi-tenant apps
security-row-level-security - - Mask sensitive data
security-dynamic-data-masking - - Use Always Encrypted for sensitive columns
security-always-encrypted - - Enable Transparent Data Encryption
security-tde - - Enable SQL Audit for compliance
security-audit-logging - - Regular vulnerability scans
security-vulnerability-assessment
- - 使用参数化查询防止SQL注入
security-parameterize-queries - - 授予最小必要权限
security-least-privilege - - 切勿使用sa或dbo账户进行应用访问
security-avoid-sa - - 始终使用加密连接
security-encrypt-connections - - 为多租户应用实现行级安全性(RLS)
security-row-level-security - - 对敏感数据进行掩码处理
security-dynamic-data-masking - - 对敏感列使用Always Encrypted
security-always-encrypted - - 启用透明数据加密(TDE)
security-tde - - 启用SQL审计以满足合规要求
security-audit-logging - - 定期进行漏洞扫描
security-vulnerability-assessment
4. Connection Management (HIGH)
4. 连接管理(高)
- - Always use connection pooling
connection-pooling - - Implement retry logic for transient failures
connection-retry-logic - - Set appropriate connection timeouts
connection-timeout - - Always close/dispose connections
connection-close-dispose - - Use async/await for database calls
connection-async - - Use read replicas for read workloads
connection-read-replicas - - Set ApplicationIntent for read replicas
connection-application-intent - - Enable for geo-replicated databases
connection-multisubnetfailover
- - 始终使用连接池
connection-pooling - - 为瞬态故障实现重试逻辑
connection-retry-logic - - 设置合适的连接超时时间
connection-timeout - - 始终关闭/释放连接
connection-close-dispose - - 对数据库调用使用async/await
connection-async - - 为读取工作负载使用只读副本
connection-read-replicas - - 为只读副本设置ApplicationIntent
connection-application-intent - - 为异地复制数据库启用该选项
connection-multisubnetfailover
5. T-SQL Patterns (MEDIUM-HIGH)
5. T-SQL模式(中高)
- - Use SET NOCOUNT ON in stored procedures
tsql-set-nocount - - Always schema-qualify object names
tsql-schema-qualify - - Avoid query hints unless necessary
tsql-avoid-hints - - Choose appropriately between temp tables and table variables
tsql-temp-tables-vs-variables - - Keep transactions short
tsql-transaction-scope - - Use TRY-CATCH with proper error handling
tsql-error-handling - - Minimize trigger usage
tsql-avoid-triggers - - Use CTEs for readability and recursion
tsql-cte-vs-subquery - - Use MERGE with caution
tsql-merge-carefully - - Minimize dynamic SQL, parameterize when used
tsql-avoid-dynamic-sql - (SR0008) - Use SCOPE_IDENTITY() instead of @@IDENTITY
tsql-scope-identity - (SR0010) - Use ANSI JOIN syntax, not = or =
tsql-avoid-deprecated-joins - (SR0013) - Populate output parameters in all code paths
tsql-output-params - (SR0016) - Don't prefix stored procedures with sp_
tsql-avoid-sp-prefix
- - 在存储过程中使用SET NOCOUNT ON
tsql-set-nocount - - 始终使用架构限定对象名称
tsql-schema-qualify - - 除非必要,否则避免使用查询提示
tsql-avoid-hints - - 合理选择临时表与表变量
tsql-temp-tables-vs-variables - - 保持事务简短
tsql-transaction-scope - - 使用TRY-CATCH实现适当的错误处理
tsql-error-handling - - 尽量减少触发器的使用
tsql-avoid-triggers - - 使用CTE提高可读性并支持递归
tsql-cte-vs-subquery - - 谨慎使用MERGE语句
tsql-merge-carefully - - 尽量减少动态SQL的使用,必要时使用参数化
tsql-avoid-dynamic-sql - (SR0008) - 使用SCOPE_IDENTITY()替代@@IDENTITY
tsql-scope-identity - (SR0010) - 使用ANSI JOIN语法,而非*=或=*
tsql-avoid-deprecated-joins - (SR0013) - 在所有代码路径中为输出参数赋值
tsql-output-params - (SR0016) - 不要为存储过程添加sp_前缀
tsql-avoid-sp-prefix
6. Data Type Best Practices (MEDIUM)
6. 数据类型最佳实践(中)
- (SR0009) - Avoid VARCHAR(1) or VARCHAR(2), use CHAR instead
type-appropriate-size - - Don't use TEXT, NTEXT, IMAGE types
type-avoid-deprecated - - Match parameter types to column types
type-match-column-types - - Use specific sizes instead of MAX when possible
type-avoid-max-unnecessarily - (SR0007) - Use ISNULL on nullable columns in expressions
type-nullable-handling - (SR0012) - Don't use reserved words for type names
type-reserved-words
- (SR0009) - 避免使用VARCHAR(1)或VARCHAR(2),改用CHAR
type-appropriate-size - - 不要使用TEXT、NTEXT、IMAGE类型
type-avoid-deprecated - - 匹配参数类型与列类型
type-match-column-types - - 尽可能使用特定长度而非MAX
type-avoid-max-unnecessarily - (SR0007) - 在表达式中对可为空的列使用ISNULL
type-nullable-handling - (SR0012) - 不要使用保留字作为类型名称
type-reserved-words
7. Naming Conventions (MEDIUM)
7. 命名规范(中)
- (SR0011) - Avoid special characters in object names
naming-avoid-special-chars - (SR0012) - Don't use reserved words as identifiers
naming-avoid-reserved-words - - Use consistent casing (PascalCase or snake_case)
naming-consistent-case - - Use descriptive, meaningful names
naming-descriptive - - Avoid Hungarian notation prefixes
naming-avoid-prefixes
- (SR0011) - 避免在对象名称中使用特殊字符
naming-avoid-special-chars - (SR0012) - 不要使用保留字作为标识符
naming-avoid-reserved-words - - 使用一致的大小写(PascalCase或snake_case)
naming-consistent-case - - 使用具有描述性的有意义名称
naming-descriptive - - 避免使用匈牙利命名法前缀
naming-avoid-prefixes
8. Database Configuration (MEDIUM)
8. 数据库配置(中)
- - Enable Query Store for performance insights
config-query-store - - Enable automatic tuning
config-auto-tuning - - Configure appropriate MAXDOP
config-max-dop - - Monitor memory grants
config-memory-grant - - Use appropriate compatibility level
config-compatibility-level - - Enable auto create/update statistics
config-auto-stats - - Use CHECKSUM for page verification
config-page-verify - - Choose appropriate recovery model
config-recovery-model - - Optimize tempdb configuration
config-tempdb - - Enable Accelerated Database Recovery
config-accelerated-recovery
- - 启用查询存储以获取性能洞察
config-query-store - - 启用自动调优
config-auto-tuning - - 配置合适的MAXDOP
config-max-dop - - 监控内存授予
config-memory-grant - - 使用合适的兼容级别
config-compatibility-level - - 启用自动创建/更新统计信息
config-auto-stats - - 使用CHECKSUM进行页验证
config-page-verify - - 选择合适的恢复模式
config-recovery-model - - 优化tempdb配置
config-tempdb - - 启用加速数据库恢复
config-accelerated-recovery
9. Data Modeling (MEDIUM)
9. 数据建模(中)
- - Normalize appropriately (3NF minimum)
model-normalization - - Use appropriate data types
model-appropriate-types - - Minimize NULL columns where possible
model-avoid-nullable - - Implement partitioning for large tables
model-partition-strategy - - Use computed columns for derived values
model-computed-columns - - Use constraints for data integrity
model-constraint-enforcement - - Use hierarchical partition keys for scale
model-hierarchical-pk - - Use temporal tables for audit trails
model-temporal-tables - - Use JSON columns judiciously
model-json-columns
- - 合理规范化(至少3NF)
model-normalization - - 使用合适的数据类型
model-appropriate-types - - 尽可能减少可为空的列
model-avoid-nullable - - 为大型表实现分区策略
model-partition-strategy - - 使用计算列存储派生值
model-computed-columns - - 使用约束保证数据完整性
model-constraint-enforcement - - 使用分层分区键实现扩展
model-hierarchical-pk - - 使用时态表实现审计追踪
model-temporal-tables - - 谨慎使用JSON列
model-json-columns
10. Monitoring & Diagnostics (LOW-MEDIUM)
10. 监控与诊断(中低)
- - Use Query Performance Insight
monitor-query-performance-insight - - Leverage DMVs for diagnostics
monitor-dmvs - - Use Extended Events for tracing
monitor-extended-events - - Enable Intelligent Insights
monitor-intelligent-insights - - Track DTU/vCore usage
monitor-resource-utilization - - Analyze and prevent deadlocks
monitor-deadlock-analysis - - Monitor wait statistics
monitor-wait-statistics - - Monitor transaction log I/O
monitor-log-io
- - 使用查询性能洞察
monitor-query-performance-insight - - 利用DMV进行诊断
monitor-dmvs - - 使用扩展事件进行跟踪
monitor-extended-events - - 启用智能洞察
monitor-intelligent-insights - - 跟踪DTU/vCore使用情况
monitor-resource-utilization - - 分析并预防死锁
monitor-deadlock-analysis - - 监控等待统计信息
monitor-wait-statistics - - 监控事务日志I/O
monitor-log-io
How to Use
使用方法
Read individual rule files for detailed explanations and code examples:
rules/query-avoid-select-star.md
rules/index-cover-queries.md
rules/security-parameterize-queries.md
rules/tsql-code-analysis.mdEach rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- How to detect violations
- References and additional context
阅读单个规则文件获取详细说明及代码示例:
rules/query-avoid-select-star.md
rules/index-cover-queries.md
rules/security-parameterize-queries.md
rules/tsql-code-analysis.md每个规则文件包含:
- 规则重要性的简要说明
- 错误代码示例及解释
- 正确代码示例及解释
- 如何检测违规
- 参考资料及额外上下文
Full Compiled Document
完整编译文档
For the complete guide with all rules expanded:
AGENTS.md如需包含所有规则扩展说明的完整指南,请查看:
AGENTS.mdScripts
脚本
Helper scripts for automated analysis:
- - Analyze T-SQL files for violations (includes SSDT rules)
scripts/analyze-tsql.py - - Check for missing/unused indexes
scripts/check-indexes.sql - - Security configuration audit
scripts/security-audit.sql - - Run SQL Assessment API checks
scripts/run-assessment.ps1
用于自动化分析的辅助脚本:
- - 分析T-SQL文件以检测违规(包含SSDT规则)
scripts/analyze-tsql.py - - 检查缺失/未使用的索引
scripts/check-indexes.sql - - 安全配置审计
scripts/security-audit.sql - - 运行SQL Assessment API检查
scripts/run-assessment.ps1
References
参考资料
- - SQL Assessment API overview
references/sql-assessment-api.md - - Useful DMV queries for diagnostics
references/dmv-queries.md - - Connection string best practices
references/connection-strings.md - - SSDT Code Analysis rules reference
references/ssdt-code-analysis.md
- - SQL Assessment API概述
references/sql-assessment-api.md - - 用于诊断的实用DMV查询
references/dmv-queries.md - - 连接字符串最佳实践
references/connection-strings.md - - SSDT代码分析规则参考
references/ssdt-code-analysis.md