sql-server-2025

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

🚨 CRITICAL GUIDELINES

🚨 重要指南

Windows File Path Requirements

Windows文件路径要求

MANDATORY: Always Use Backslashes on Windows for File Paths
When using Edit or Write tools on Windows, you MUST use backslashes (
\
) in file paths, NOT forward slashes (
/
).
Examples:
  • ❌ WRONG:
    D:/repos/project/file.tsx
  • ✅ CORRECT:
    D:\repos\project\file.tsx
This applies to:
  • Edit tool file_path parameter
  • Write tool file_path parameter
  • All file operations on Windows systems
强制要求:在Windows系统中始终使用反斜杠表示文件路径
在Windows系统上使用Edit或Write工具时,文件路径必须使用反斜杠(
\
),而不能使用正斜杠(
/
)。
示例:
  • ❌ 错误:
    D:/repos/project/file.tsx
  • ✅ 正确:
    D:\repos\project\file.tsx
此要求适用于:
  • Edit工具的file_path参数
  • Write工具的file_path参数
  • Windows系统上的所有文件操作

Documentation Guidelines

文档编写指南

NEVER create new documentation files unless explicitly requested by the user.
  • Priority: Update existing README.md files rather than creating new documentation
  • Repository cleanliness: Keep repository root clean - only README.md unless user requests otherwise
  • Style: Documentation should be concise, direct, and professional - avoid AI-generated tone
  • User preference: Only create additional .md files when user specifically asks for documentation

除非用户明确要求,否则绝不要创建新的文档文件。
  • 优先级:优先更新现有的README.md文件,而非创建新文档
  • 仓库整洁性:保持仓库根目录整洁——除非用户要求,否则只保留README.md
  • 风格:文档应简洁、直接、专业——避免AI生成的冗余语气
  • 用户偏好:仅当用户明确要求文档时,才创建额外的.md文件

SQL Server 2025 & SqlPackage 170.2.70 Support

SQL Server 2025 & SqlPackage 170.2.70 支持

Overview

概述

SQL Server 2025 is the enterprise AI-ready database with native vector database capabilities, built-in AI model integration, and semantic search from ground to cloud.
SqlPackage 170.2.70 (October 14, 2025) - Latest production release with full SQL Server 2025 support, data virtualization, and parquet file enhancements.
SQL Server 2025是企业级AI就绪数据库,具备原生向量数据库能力、内置AI模型集成,以及从本地到云端的语义搜索功能。
SqlPackage 170.2.70(2025年10月14日)——最新生产版本,全面支持SQL Server 2025,包含数据虚拟化和Parquet文件增强功能。

SqlPackage 170.x Series (2025 Releases)

SqlPackage 170.x系列(2025年版本)

Latest Version: 170.2.70 (October 14, 2025)

最新版本:170.2.70(2025年10月14日)

Three major 2025 releases:
  • 170.2.70 - October 14, 2025 (Current)
  • 170.1.61 - July 30, 2025 (Data virtualization)
  • 170.0.94 - April 15, 2025 (SQL Server 2025 initial support)
2025年三大主要版本:
  • 170.2.70 - 2025年10月14日(当前版本)
  • 170.1.61 - 2025年7月30日(数据虚拟化)
  • 170.0.94 - 2025年4月15日(初始支持SQL Server 2025)

Key 2025 Features

2025年关键功能

Data Virtualization (170.1.61+):
  • Support for Azure SQL Database data virtualization objects
  • Import/export/extract/publish operations for external data sources
  • Parquet file support for Azure SQL Database with Azure Blob Storage
  • Automatic fallback to BCP for CLR types and LOBs > 1MB
New Data Types:
  • VECTOR - Up to 3,996 dimensions with half-precision (2-byte) floating-point
  • JSON - Native JSON data type for Azure SQL Database
New Permissions (170.0+):
  • ALTER ANY INFORMATION PROTECTION
    - SQL Server 2025 & Azure SQL
  • ALTER ANY EXTERNAL MIRROR
    - Azure SQL & SQL database in Fabric
  • CREATE/ALTER ANY EXTERNAL MODEL
    - AI/ML model management
Deployment Options:
  • /p:IgnorePreDeployScript=True/False
    - Skip pre-deployment scripts
  • /p:IgnorePostDeployScript=True/False
    - Skip post-deployment scripts
数据虚拟化(170.1.61及以上版本)
  • 支持Azure SQL Database数据虚拟化对象
  • 外部数据源的导入/导出/提取/发布操作
  • Azure SQL Database与Azure Blob Storage的Parquet文件支持
  • 对于CLR类型和大于1MB的LOB自动回退到BCP
新数据类型
  • VECTOR - 支持最高3996维的半精度(2字节)浮点数
  • JSON - Azure SQL Database的原生JSON数据类型
新权限(170.0及以上版本)
  • ALTER ANY INFORMATION PROTECTION
    - 适用于SQL Server 2025和Azure SQL
  • ALTER ANY EXTERNAL MIRROR
    - 适用于Azure SQL和Fabric中的SQL数据库
  • CREATE/ALTER ANY EXTERNAL MODEL
    - AI/ML模型管理权限
部署选项
  • /p:IgnorePreDeployScript=True/False
    - 跳过预部署脚本
  • /p:IgnorePostDeployScript=True/False
    - 跳过 post-deployment脚本

SqlPackage Commands

SqlPackage命令

bash
undefined
bash
undefined

Publish to SQL Server 2025

发布到SQL Server 2025

sqlpackage /Action:Publish
/SourceFile:Database.dacpac
/TargetServerName:server2025.database.windows.net
/TargetDatabaseName:MyDatabase
/TargetDatabaseEdition:Premium
/p:TargetPlatform=SqlServer2025 # New target platform
sqlpackage /Action:Publish
/SourceFile:Database.dacpac
/TargetServerName:server2025.database.windows.net
/TargetDatabaseName:MyDatabase
/TargetDatabaseEdition:Premium
/p:TargetPlatform=SqlServer2025 # 新增目标平台

Extract from SQL Server 2025

从SQL Server 2025提取

sqlpackage /Action:Extract
/SourceServerName:server2025.database.windows.net
/SourceDatabaseName:MyDatabase
/TargetFile:Database.dacpac
/p:ExtractAllTableData=False
/p:VerifyExtraction=True
sqlpackage /Action:Extract
/SourceServerName:server2025.database.windows.net
/SourceDatabaseName:MyDatabase
/TargetFile:Database.dacpac
/p:ExtractAllTableData=False
/p:VerifyExtraction=True

Export with SQL Server 2025 features

导出包含SQL Server 2025功能的数据

sqlpackage /Action:Export
/SourceServerName:server2025.database.windows.net
/SourceDatabaseName:MyDatabase
/TargetFile:Database.bacpac
undefined
sqlpackage /Action:Export
/SourceServerName:server2025.database.windows.net
/SourceDatabaseName:MyDatabase
/TargetFile:Database.bacpac
undefined

ScriptDom Version 170.0.64

ScriptDom版本170.0.64

New ScriptDom version for SQL Server 2025 syntax parsing:
csharp
// Package: Microsoft.SqlServer.TransactSql.ScriptDom 170.0.64

using Microsoft.SqlServer.TransactSql.ScriptDom;

// Parse SQL Server 2025 syntax
var parser = new TSql170Parser(true);
IList<ParseError> errors;
var fragment = parser.Parse(new StringReader(sql), out errors);

// Supports SQL Server 2025 new T-SQL features
用于SQL Server 2025语法解析的全新ScriptDom版本:
csharp
// 包:Microsoft.SqlServer.TransactSql.ScriptDom 170.0.64

using Microsoft.SqlServer.TransactSql.ScriptDom;

// 解析SQL Server 2025语法
var parser = new TSql170Parser(true);
IList<ParseError> errors;
var fragment = parser.Parse(new StringReader(sql), out errors);

// 支持SQL Server 2025新增的T-SQL功能

Microsoft.Build.Sql 2.0.0 GA (2025)

Microsoft.Build.Sql 2.0.0正式版(2025年)

MAJOR MILESTONE: Microsoft.Build.Sql SDK entered General Availability in 2025!
重要里程碑: Microsoft.Build.Sql SDK在2025年进入正式可用(GA)阶段!

Latest Version: 2.0.0 (Production Ready)

最新版本:2.0.0(生产就绪)

Breaking Change from Preview:
  • SDK is now production-ready and recommended for all new database projects
  • No longer in preview status
  • Full cross-platform support (Windows/Linux/macOS)
  • Requires .NET 8+ (was .NET 6+ in preview)
与预览版的重大变更:
  • SDK现已就绪,推荐用于所有新数据库项目
  • 不再处于预览状态
  • 全面跨平台支持(Windows/Linux/macOS)
  • 需要.NET 8+(预览版为.NET 6+)

SQL Server 2025 Support

SQL Server 2025支持

Current Status: SQL Server 2025 target platform support coming in future Microsoft.Build.Sql release (post-2.0.0).
Workaround for SDK-Style Projects:
xml
<!-- Database.sqlproj (SDK-style with SQL Server 2025 compatibility) -->
<Project Sdk="Microsoft.Build.Sql/2.0.0">
  <PropertyGroup>
    <Name>MyDatabase</Name>
    <!-- Use SQL Server 2022 (160) provider until 2025 provider available -->
    <DSP>Microsoft.Data.Tools.Schema.Sql.Sql160DatabaseSchemaProvider</DSP>
    <TargetFramework>net8.0</TargetFramework>
    <SqlServerVersion>Sql160</SqlServerVersion>

    <!-- SQL Server 2025 features will still work in runtime database -->
    <!-- Only build-time validation uses Sql160 provider -->
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="Tables\" />
    <Folder Include="Views\" />
    <Folder Include="StoredProcedures\" />
  </ItemGroup>
</Project>
当前状态: SQL Server 2025目标平台支持将在Microsoft.Build.Sql的后续版本(2.0.0之后)中推出。
SDK风格项目的临时解决方案:
xml
<!-- Database.sqlproj(兼容SQL Server 2025的SDK风格项目) -->
<Project Sdk="Microsoft.Build.Sql/2.0.0">
  <PropertyGroup>
    <Name>MyDatabase</Name>
    <!-- 在2025版提供程序可用前,使用SQL Server 2022(160)提供程序 -->
    <DSP>Microsoft.Data.Tools.Schema.Sql.Sql160DatabaseSchemaProvider</DSP>
    <TargetFramework>net8.0</TargetFramework>
    <SqlServerVersion>Sql160</SqlServerVersion>

    <!-- SQL Server 2025功能在运行时数据库中仍可正常使用 -->
    <!-- 仅编译时验证使用Sql160提供程序 -->
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="Tables\" />
    <Folder Include="Views\" />
    <Folder Include="StoredProcedures\" />
  </ItemGroup>
</Project>

Visual Studio 2022 Support

Visual Studio 2022支持

Requirement: Visual Studio 2022 version 17.12 or later for SDK-style SQL projects.
Note: Side-by-side installation with original SQL projects (legacy SSDT) is NOT supported.
要求: 用于SDK风格SQL项目的Visual Studio 2022版本17.12或更高。
注意: 不支持与原始SQL项目(传统SSDT)并行安装。

SQL Server 2025 Release Status

SQL Server 2025发布状态

Current Status: SQL Server 2025 (17.x) is in Release Candidate (RC1) stage as of October 2025. Public preview began May 2025.
Predicted GA Date: November 12, 2025 (based on historical release patterns - SQL Server 2019: Nov 4, SQL Server 2022: Nov 16). Expected announcement at Microsoft Ignite conference (November 18-21, 2025).
Not Yet Production: SQL Server 2025 is not yet generally available. All features described are available in RC builds for testing purposes only.
当前状态:截至2025年10月,SQL Server 2025(17.x)处于**候选发布版(RC1)**阶段。公开预览于2025年5月启动。
预计正式发布日期:2025年11月12日(基于历史发布模式——SQL Server 2019:11月4日,SQL Server 2022:11月16日)。预计在Microsoft Ignite大会(2025年11月18-21日)上宣布。
尚未正式发布:SQL Server 2025尚未全面可用。本文描述的所有功能仅在RC版本中提供,仅供测试使用。

SQL Server 2025 New Features

SQL Server 2025新功能

Vector Database for AI

AI向量数据库

Native Enterprise Vector Store with built-in security, compliance, and DiskANN indexing technology.
Key Capabilities:
  • Up to 3,996 dimensions per vector (half-precision 2-byte floating-point)
  • DiskANN indexing - Disk-based approximate nearest neighbor for efficient large-scale vector search
  • Hybrid AI vector search - Combine vectors with SQL data for semantic + keyword search
  • Built-in security & compliance - Enterprise-grade data protection
Vector Embedding & Text Chunking:
sql
-- Create table with vector column
CREATE TABLE Documents (
    Id INT PRIMARY KEY IDENTITY,
    Title NVARCHAR(200),
    Content NVARCHAR(MAX),
    -- Half-precision vectors support up to 3,996 dimensions
    ContentVector VECTOR(1536)  -- OpenAI ada-002: 1,536 dims
    -- ContentVector VECTOR(3072)  -- OpenAI text-embedding-3-large: 3,072 dims
    -- ContentVector VECTOR(3996)  -- Maximum: 3,996 dims
);

-- Insert vectors (T-SQL built-in embedding generation)
INSERT INTO Documents (Title, Content, ContentVector)
VALUES (
    'AI Documentation',
    'Azure AI services...',
    CAST('[0.1, 0.2, 0.3, ...]' AS VECTOR(1536))
);

-- Semantic similarity search with DiskANN
DECLARE @QueryVector VECTOR(1536) = CAST('[0.15, 0.25, ...]' AS VECTOR(1536));

SELECT TOP 10
    Id,
    Title,
    Content,
    VECTOR_DISTANCE('cosine', ContentVector, @QueryVector) AS Similarity
FROM Documents
ORDER BY Similarity;

-- Create DiskANN vector index for performance
CREATE INDEX IX_Documents_Vector
ON Documents(ContentVector)
USING VECTOR_INDEX
WITH (
    DISTANCE_METRIC = 'cosine',  -- or 'euclidean', 'dot_product'
    VECTOR_SIZE = 1536
);

-- Hybrid search: Combine vector similarity with traditional filtering
SELECT TOP 10
    Id,
    Title,
    VECTOR_DISTANCE('cosine', ContentVector, @QueryVector) AS Similarity
FROM Documents
WHERE Title LIKE '%Azure%'  -- Traditional keyword filter
ORDER BY Similarity;
原生企业级向量存储,具备内置安全、合规性和DiskANN索引技术。
关键能力:
  • 最高3996维向量(半精度2字节浮点数)
  • DiskANN索引 - 基于磁盘的近似最近邻算法,支持高效的大规模向量搜索
  • 混合AI向量搜索 - 将向量与SQL数据结合,实现语义+关键词搜索
  • 内置安全与合规 - 企业级数据保护
向量嵌入与文本分块:
sql
-- 创建包含向量列的表
CREATE TABLE Documents (
    Id INT PRIMARY KEY IDENTITY,
    Title NVARCHAR(200),
    Content NVARCHAR(MAX),
    -- 半精度向量支持最高3996维
    ContentVector VECTOR(1536)  -- OpenAI ada-002:1536维
    -- ContentVector VECTOR(3072)  -- OpenAI text-embedding-3-large:3072维
    -- ContentVector VECTOR(3996)  -- 最大值:3996维
);

-- 插入向量(T-SQL内置嵌入生成)
INSERT INTO Documents (Title, Content, ContentVector)
VALUES (
    'AI文档',
    'Azure AI服务...',
    CAST('[0.1, 0.2, 0.3, ...]' AS VECTOR(1536))
);

-- 使用DiskANN进行语义相似度搜索
DECLARE @QueryVector VECTOR(1536) = CAST('[0.15, 0.25, ...]' AS VECTOR(1536));

SELECT TOP 10
    Id,
    Title,
    Content,
    VECTOR_DISTANCE('cosine', ContentVector, @QueryVector) AS Similarity
FROM Documents
ORDER BY Similarity;

-- 创建DiskANN向量索引以提升性能
CREATE INDEX IX_Documents_Vector
ON Documents(ContentVector)
USING VECTOR_INDEX
WITH (
    DISTANCE_METRIC = 'cosine',  -- 或 'euclidean'、'dot_product'
    VECTOR_SIZE = 1536
);

-- 混合搜索:将向量相似度与传统筛选结合
SELECT TOP 10
    Id,
    Title,
    VECTOR_DISTANCE('cosine', ContentVector, @QueryVector) AS Similarity
FROM Documents
WHERE Title LIKE '%Azure%'  -- 传统关键词筛选
ORDER BY Similarity;

AI Model Integration

AI模型集成

Built into T-SQL - Seamlessly integrate AI services with model definitions directly in the database.
Supported AI Services:
  • Azure AI Foundry
  • Azure OpenAI Service
  • OpenAI
  • Ollama (local/self-hosted models)
  • Custom REST APIs
Developer Frameworks:
  • LangChain integration
  • Semantic Kernel integration
  • Entity Framework Core support
  • GraphQL via Data API Builder (DAB) - Expose SQL Server data through GraphQL endpoints
External Models (ONNX):
sql
-- Create external model from ONNX file
CREATE EXTERNAL MODEL AIModel
FROM 'https://storage.account.blob.core.windows.net/models/model.onnx'
WITH (
    TYPE = 'ONNX',
    INPUT_DATA_FORMAT = 'JSON',
    OUTPUT_DATA_FORMAT = 'JSON'
);

-- Use model for predictions
DECLARE @Input NVARCHAR(MAX) = '{"text": "Hello world"}';
SELECT PREDICT(MODEL = AIModel, DATA = @Input) AS Prediction;

-- Grant model permissions (new SQL Server 2025 permission)
GRANT CREATE ANY EXTERNAL MODEL TO [ModelAdmin];
GRANT ALTER ANY EXTERNAL MODEL TO [ModelAdmin];
GRANT EXECUTE ON EXTERNAL MODEL::AIModel TO [AppUser];
AI Service Integration:
sql
-- Example: Azure OpenAI integration
-- Model definitions built directly into T-SQL
-- Access through REST APIs with built-in authentication
内置到T-SQL中 - 无缝集成AI服务,模型定义直接存储在数据库中。
支持的AI服务:
  • Azure AI Foundry
  • Azure OpenAI Service
  • OpenAI
  • Ollama(本地/自托管模型)
  • 自定义REST API
开发框架:
  • LangChain集成
  • Semantic Kernel集成
  • Entity Framework Core支持
  • 通过Data API Builder(DAB)实现GraphQL - 通过GraphQL端点暴露SQL Server数据
外部模型(ONNX):
sql
-- 从ONNX文件创建外部模型
CREATE EXTERNAL MODEL AIModel
FROM 'https://storage.account.blob.core.windows.net/models/model.onnx'
WITH (
    TYPE = 'ONNX',
    INPUT_DATA_FORMAT = 'JSON',
    OUTPUT_DATA_FORMAT = 'JSON'
);

-- 使用模型进行预测
DECLARE @Input NVARCHAR(MAX) = '{"text": "Hello world"}';
SELECT PREDICT(MODEL = AIModel, DATA = @Input) AS Prediction;

-- 授予模型权限(SQL Server 2025新增权限)
GRANT CREATE ANY EXTERNAL MODEL TO [ModelAdmin];
GRANT ALTER ANY EXTERNAL MODEL TO [ModelAdmin];
GRANT EXECUTE ON EXTERNAL MODEL::AIModel TO [AppUser];
AI服务集成:
sql
-- 示例:Azure OpenAI集成
-- 模型定义直接内置到T-SQL中
-- 通过内置身份验证的REST API访问

Optimized Locking (Performance Enhancement)

优化锁机制(性能增强)

Key Innovation: Dramatically reduces lock memory consumption and minimizes blocking for concurrent transactions.
Two Primary Components:
  1. Transaction ID (TID) Locking:
    • Each row labeled with last TID (Transaction ID) that modified it
    • Single lock on TID instead of many row locks
    • Locks released as soon as row is updated
    • Only one TID lock held until transaction ends
    • Example: Updating 1,000 rows requires 1,000 X row locks, but each is released immediately, and only one TID lock is held until commit
  2. Lock After Qualification (LAQ):
    • Evaluates query predicates using latest committed version WITHOUT acquiring lock
    • Requires READ COMMITTED SNAPSHOT ISOLATION (RCSI)
    • Predicates checked optimistically on committed data
    • X row lock taken only if predicate satisfied
    • Lock released immediately after row update
Benefits:
  • Reduced lock memory usage
  • Increased concurrency and scale
  • Minimized lock escalation
  • Enhanced application uptime
  • Better performance for high-concurrency workloads
Enabling Optimized Locking:
sql
-- Enable RCSI (required for LAQ)
ALTER DATABASE MyDatabase
SET READ_COMMITTED_SNAPSHOT ON;

-- Optimized locking is automatically enabled at database level
-- No additional configuration needed for SQL Server 2025

-- Verify optimized locking status
SELECT name, is_read_committed_snapshot_on
FROM sys.databases
WHERE name = 'MyDatabase';

-- Monitor optimized locking performance
SELECT *
FROM sys.dm_tran_locks
WHERE request_session_id = @@SPID;
核心创新:大幅减少锁内存消耗,最小化并发事务的阻塞。
两个主要组件
  1. 事务ID(TID)锁
    • 每行标记最后修改它的TID(事务ID)
    • 对TID加单个锁,而非多个行锁
    • 行更新后立即释放锁
    • 事务结束前仅持有一个TID锁
    • 示例:更新1000行需要1000个X行锁,但每个锁会立即释放,事务提交前仅持有一个TID锁
  2. 筛选后加锁(LAQ)
    • 无需加锁,使用最新提交版本评估查询谓词
    • 需要READ COMMITTED SNAPSHOT ISOLATION(RCSI)
    • 乐观检查提交数据的谓词
    • 仅当谓词满足时才获取X行锁
    • 行更新后立即释放锁
优势
  • 减少锁内存使用
  • 提高并发能力和可扩展性
  • 最小化锁升级
  • 提升应用可用性
  • 高并发工作负载下性能更佳
启用优化锁机制
sql
-- 启用RCSI(LAQ必需)
ALTER DATABASE MyDatabase
SET READ_COMMITTED_SNAPSHOT ON;

-- 优化锁机制在数据库级别自动启用
-- SQL Server 2025无需额外配置

-- 验证优化锁机制状态
SELECT name, is_read_committed_snapshot_on
FROM sys.databases
WHERE name = 'MyDatabase';

-- 监控优化锁机制性能
SELECT *
FROM sys.dm_tran_locks
WHERE request_session_id = @@SPID;

Microsoft Fabric Mirroring (Zero-ETL Analytics)

Microsoft Fabric镜像(零ETL分析)

Integration: Near real-time replication of SQL Server databases to Microsoft Fabric OneLake for analytics.
Key Capabilities:
  • Zero-ETL Experience: No complex ETL pipelines required
  • SQL Server 2025-Specific: Uses new change feed technology (vs CDC in SQL Server 2016-2022)
  • Azure Arc Required: SQL Server 2025 requires Azure Arc-enabled server for Fabric communication
  • Real-Time Analytics: Offload analytic workloads to Fabric without impacting production
Supported Scenarios:
  • SQL Server 2025 on-premises (Windows)
  • NOT supported: Azure VM or Linux instances (yet)
How It Works:
sql
-- SQL Server 2025 uses change feed (automatic)
-- Azure Arc agent handles replication to Fabric OneLake

-- Traditional SQL Server 2016-2022 approach (CDC):
-- EXEC sys.sp_cdc_enable_db;
-- EXEC sys.sp_cdc_enable_table ...

-- SQL Server 2025: Change feed is built-in, no CDC setup needed
Benefits:
  • Free Fabric compute for replication
  • Free OneLake storage (based on capacity size)
  • Near real-time data availability
  • BI and analytics without production load
  • Integration with Power BI, Synapse, Azure ML
Configuration:
  1. Enable Azure Arc on SQL Server 2025 instance
  2. Configure Fabric workspace and OneLake
  3. Enable mirroring in Fabric portal
  4. Select database and tables to mirror
  5. Data automatically replicated with change feed
Monitoring:
sql
-- Monitor replication lag
SELECT
    database_name,
    table_name,
    last_sync_time,
    rows_replicated,
    replication_lag_seconds
FROM sys.dm_fabric_replication_status;
集成:SQL Server数据库近实时复制到Microsoft Fabric OneLake用于分析。
关键能力
  • 零ETL体验:无需复杂的ETL管道
  • SQL Server 2025专属:使用新的变更源技术(对比SQL Server 2016-2022的CDC)
  • 需要Azure Arc:SQL Server 2025需要启用Azure Arc的服务器与Fabric通信
  • 实时分析:将分析工作负载卸载到Fabric,不影响生产环境
支持的场景
  • 本地SQL Server 2025(Windows)
  • 暂不支持:Azure VM或Linux实例
工作原理
sql
-- SQL Server 2025使用内置的变更源
-- Azure Arc代理处理到Fabric OneLake的复制

-- 传统SQL Server 2016-2022方式(CDC):
-- EXEC sys.sp_cdc_enable_db;
-- EXEC sys.sp_cdc_enable_table ...

-- SQL Server 2025:变更源内置,无需配置CDC
优势
  • 复制使用免费的Fabric计算资源
  • 免费的OneLake存储(基于容量大小)
  • 近实时数据可用性
  • 不影响生产环境的BI和分析
  • 与Power BI、Synapse、Azure ML集成
配置步骤
  1. 在SQL Server 2025实例上启用Azure Arc
  2. 配置Fabric工作区和OneLake
  3. 在Fabric门户中启用镜像
  4. 选择要镜像的数据库和表
  5. 数据通过变更源自动复制
监控
sql
-- 监控复制延迟
SELECT
    database_name,
    table_name,
    last_sync_time,
    rows_replicated,
    replication_lag_seconds
FROM sys.dm_fabric_replication_status;

Native JSON Support Enhancements

原生JSON支持增强

New JSON Data Type: Native JSON data type for Azure SQL Database (coming to SQL Server 2025).
sql
-- New JSON data type
CREATE TABLE Products (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100),
    Metadata JSON  -- Native JSON type
);

-- JSON functions enhanced
INSERT INTO Products (Id, Name, Metadata)
VALUES (1, 'Laptop', JSON('{"brand": "Dell", "ram": 16, "ssd": 512}'));

-- Query JSON with improved performance
SELECT
    Id,
    Name,
    JSON_VALUE(Metadata, '$.brand') AS Brand,
    JSON_VALUE(Metadata, '$.ram') AS RAM
FROM Products;
新JSON数据类型:Azure SQL Database的原生JSON数据类型(即将引入SQL Server 2025)。
sql
-- 新JSON数据类型
CREATE TABLE Products (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100),
    Metadata JSON  -- 原生JSON类型
);

-- JSON函数增强
INSERT INTO Products (Id, Name, Metadata)
VALUES (1, '笔记本电脑', JSON('{"brand": "Dell", "ram": 16, "ssd": 512}'));

-- 以更高性能查询JSON
SELECT
    Id,
    Name,
    JSON_VALUE(Metadata, '$.brand') AS 品牌,
    JSON_VALUE(Metadata, '$.ram') AS 内存
FROM Products;

Regular Expression (RegEx) Support

正则表达式(RegEx)支持

T-SQL RegEx Functions: Validate, search, and manipulate strings with regular expressions.
sql
-- RegEx matching
SELECT REGEXP_LIKE('test@example.com', '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$') AS IsValidEmail;

-- RegEx replace
SELECT REGEXP_REPLACE('Phone: 555-1234', '\d+', 'XXX') AS MaskedPhone;

-- RegEx extract
SELECT REGEXP_SUBSTR('Order #12345', '\d+') AS OrderNumber;
T-SQL RegEx函数:使用正则表达式验证、搜索和操作字符串。
sql
-- RegEx匹配
SELECT REGEXP_LIKE('test@example.com', '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$') AS IsValidEmail;

-- RegEx替换
SELECT REGEXP_REPLACE('Phone: 555-1234', '\d+', 'XXX') AS MaskedPhone;

-- RegEx提取
SELECT REGEXP_SUBSTR('Order #12345', '\d+') AS OrderNumber;

REST API Integration

REST API集成

Built-in REST Capabilities: Call external REST APIs directly from T-SQL.
sql
-- Call REST API from T-SQL
DECLARE @Response NVARCHAR(MAX);

EXEC sp_invoke_external_rest_endpoint
    @url = 'https://api.example.com/data',
    @method = 'GET',
    @headers = '{"Authorization": "Bearer token123"}',
    @response = @Response OUTPUT;

SELECT @Response AS APIResponse;

-- Enrich database data with external APIs
UPDATE Customers
SET EnrichedData = (
    SELECT JSON_VALUE(response, '$.data')
    FROM OPENROWSET(REST, 'https://api.example.com/customer/' + CustomerId)
)
WHERE CustomerId = 12345;
内置REST功能:直接从T-SQL调用外部REST API。
sql
-- 从T-SQL调用REST API
DECLARE @Response NVARCHAR(MAX);

EXEC sp_invoke_external_rest_endpoint
    @url = 'https://api.example.com/data',
    @method = 'GET',
    @headers = '{"Authorization": "Bearer token123"}',
    @response = @Response OUTPUT;

SELECT @Response AS APIResponse;

-- 使用外部API丰富数据库数据
UPDATE Customers
SET EnrichedData = (
    SELECT JSON_VALUE(response, '$.data')
    FROM OPENROWSET(REST, 'https://api.example.com/customer/' + CustomerId)
)
WHERE CustomerId = 12345;

Optional Parameter Plan Optimization (OPPO)

可选参数计划优化(OPPO)

Performance Enhancement: SQL Server 2025 introduces OPPO to enable optimal execution plan selection based on customer-provided runtime parameter values.
Key Benefits:
  • Solves parameter sniffing issues
  • Optimizes plans for specific runtime parameters
  • Improves query performance with parameter-sensitive workloads
  • Reduces need for query hints or plan guides
Enabling OPPO:
sql
-- Enable at database level
ALTER DATABASE MyDatabase
SET PARAMETER_SENSITIVE_PLAN_OPTIMIZATION = ON;

-- Check status
SELECT name, is_parameter_sensitive_plan_optimization_on
FROM sys.databases
WHERE name = 'MyDatabase';

-- Monitor OPPO usage
SELECT
    query_plan_hash,
    parameter_values,
    execution_count,
    avg_duration_ms
FROM sys.dm_exec_query_stats
WHERE is_parameter_sensitive = 1;
性能增强:SQL Server 2025引入OPPO,可根据客户提供的运行时参数值选择最优执行计划。
关键优势:
  • 解决参数嗅探问题
  • 针对特定运行时参数优化计划
  • 提升参数敏感型工作负载的查询性能
  • 减少对查询提示或计划指南的需求
启用OPPO:
sql
-- 在数据库级别启用
ALTER DATABASE MyDatabase
SET PARAMETER_SENSITIVE_PLAN_OPTIMIZATION = ON;

-- 检查状态
SELECT name, is_parameter_sensitive_plan_optimization_on
FROM sys.databases
WHERE name = 'MyDatabase';

-- 监控OPPO使用情况
SELECT
    query_plan_hash,
    parameter_values,
    execution_count,
    avg_duration_ms
FROM sys.dm_exec_query_stats
WHERE is_parameter_sensitive = 1;

Microsoft Entra Managed Identities

Microsoft Entra托管标识

Security Enhancement: SQL Server 2025 adds support for Microsoft Entra managed identities for improved credential management.
Key Benefits:
  • Eliminates hardcoded credentials
  • Reduces security vulnerabilities
  • Provides compliance and auditing capabilities
  • Simplifies credential rotation
Configuration:
sql
-- Create login with managed identity
CREATE LOGIN [managed-identity-name] FROM EXTERNAL PROVIDER;

-- Grant permissions
CREATE USER [managed-identity-name] FOR LOGIN [managed-identity-name];
GRANT CONTROL ON DATABASE::MyDatabase TO [managed-identity-name];

-- Use in connection strings
-- Connection string: Server=myserver;Database=mydb;Authentication=Active Directory Managed Identity;
安全增强:SQL Server 2025新增对Microsoft Entra托管标识的支持,改进凭据管理。
关键优势:
  • 消除硬编码凭据
  • 减少安全漏洞
  • 提供合规性和审计能力
  • 简化凭据轮换
配置:
sql
-- 使用托管标识创建登录名
CREATE LOGIN [managed-identity-name] FROM EXTERNAL PROVIDER;

-- 授予权限
CREATE USER [managed-identity-name] FOR LOGIN [managed-identity-name];
GRANT CONTROL ON DATABASE::MyDatabase TO [managed-identity-name];

-- 在连接字符串中使用
-- 连接字符串:Server=myserver;Database=mydb;Authentication=Active Directory Managed Identity;

Enhanced Information Protection

增强的信息保护

Sensitivity classification and encryption:
sql
-- Classify sensitive columns
ADD SENSITIVITY CLASSIFICATION TO
    Customers.Email,
    Customers.CreditCard
WITH (
    LABEL = 'Confidential',
    INFORMATION_TYPE = 'Financial'
);

-- Query classification
SELECT
    schema_name(o.schema_id) AS SchemaName,
    o.name AS TableName,
    c.name AS ColumnName,
    s.label AS SensitivityLabel,
    s.information_type AS InformationType
FROM sys.sensitivity_classifications s
INNER JOIN sys.objects o ON s.major_id = o.object_id
INNER JOIN sys.columns c ON s.major_id = c.object_id AND s.minor_id = c.column_id;
敏感度分类和加密:
sql
-- 对敏感列进行分类
ADD SENSITIVITY CLASSIFICATION TO
    Customers.Email,
    Customers.CreditCard
WITH (
    LABEL = 'Confidential',
    INFORMATION_TYPE = 'Financial'
);

-- 查询分类信息
SELECT
    schema_name(o.schema_id) AS SchemaName,
    o.name AS TableName,
    c.name AS ColumnName,
    s.label AS SensitivityLabel,
    s.information_type AS InformationType
FROM sys.sensitivity_classifications s
INNER JOIN sys.objects o ON s.major_id = o.object_id
INNER JOIN sys.columns c ON s.major_id = c.object_id AND s.minor_id = c.column_id;

Deployment to SQL Server 2025

部署到SQL Server 2025

Using SqlPackage

使用SqlPackage

bash
undefined
bash
undefined

Publish with 2025 features

发布包含2025年功能的数据库

sqlpackage /Action:Publish
/SourceFile:Database.dacpac
/TargetConnectionString:"Server=tcp:server2025.database.windows.net;Database=MyDb;Authentication=ActiveDirectoryManagedIdentity;"
/p:BlockOnPossibleDataLoss=True
/p:IncludeCompositeObjects=True
/p:DropObjectsNotInSource=False
/p:DoNotDropObjectTypes=Users;RoleMembership
/p:GenerateSmartDefaults=True
/DiagnosticsFile:deploy.log
undefined
sqlpackage /Action:Publish
/SourceFile:Database.dacpac
/TargetConnectionString:"Server=tcp:server2025.database.windows.net;Database=MyDb;Authentication=ActiveDirectoryManagedIdentity;"
/p:BlockOnPossibleDataLoss=True
/p:IncludeCompositeObjects=True
/p:DropObjectsNotInSource=False
/p:DoNotDropObjectTypes=Users;RoleMembership
/p:GenerateSmartDefaults=True
/DiagnosticsFile:deploy.log
undefined

Using MSBuild

使用MSBuild

xml
<!-- Database.publish.xml -->
<Project>
  <PropertyGroup>
    <TargetConnectionString>Server=tcp:server2025.database.windows.net;Database=MyDb;Authentication=ActiveDirectoryManagedIdentity;</TargetConnectionString>
    <BlockOnPossibleDataLoss>True</BlockOnPossibleDataLoss>
    <TargetDatabaseName>MyDatabase</TargetDatabaseName>
    <ProfileVersionNumber>1</ProfileVersionNumber>
  </PropertyGroup>

  <ItemGroup>
    <SqlCmdVariable Include="Environment">
      <Value>Production</Value>
    </SqlCmdVariable>
  </ItemGroup>
</Project>
bash
undefined
xml
<!-- Database.publish.xml -->
<Project>
  <PropertyGroup>
    <TargetConnectionString>Server=tcp:server2025.database.windows.net;Database=MyDb;Authentication=ActiveDirectoryManagedIdentity;</TargetConnectionString>
    <BlockOnPossibleDataLoss>True</BlockOnPossibleDataLoss>
    <TargetDatabaseName>MyDatabase</TargetDatabaseName>
    <ProfileVersionNumber>1</ProfileVersionNumber>
  </PropertyGroup>

  <ItemGroup>
    <SqlCmdVariable Include="Environment">
      <Value>Production</Value>
    </SqlCmdVariable>
  </ItemGroup>
</Project>
bash
undefined

Deploy using MSBuild

使用MSBuild部署

msbuild Database.sqlproj
/t:Publish
/p:PublishProfile=Database.publish.xml
/p:TargetPlatform=SqlServer2025
undefined
msbuild Database.sqlproj
/t:Publish
/p:PublishProfile=Database.publish.xml
/p:TargetPlatform=SqlServer2025
undefined

CI/CD Best Practices 2025

CI/CD最佳实践(2025年)

Key Principles

核心原则

State-Based Deployment (Recommended):
  • Source code represents current database state
  • All objects (procedures, tables, triggers, views) in separate .sql files
  • SqlPackage generates incremental scripts automatically
  • Preferred over migration-based approaches
Testing & Quality:
  • tSQLt - Unit testing for SQL Server stored procedures and functions
  • Tests produce machine-readable results
  • Abort pipeline on test failure with immediate notifications
  • Never continue deployment if tests fail
Security:
  • Windows Authentication preferred for CI/CD (avoid plain text passwords)
  • Never commit credentials to source control
  • Use Azure Key Vault or GitHub Secrets for connection strings
Version Control:
  • All database objects in source control
  • Test scripts versioned and executed in Build step
  • Require comments on check-ins
  • Configure custom check-in policies
基于状态的部署(推荐):
  • 源代码代表当前数据库状态
  • 所有对象(存储过程、表、触发器、视图)存放在单独的.sql文件中
  • SqlPackage自动生成增量脚本
  • 优于基于迁移的方法
测试与质量:
  • tSQLt - 用于SQL Server存储过程和函数的单元测试
  • 测试生成机器可读结果
  • 测试失败时立即终止管道并发送通知
  • 测试失败绝不能继续部署
安全:
  • 优先使用Windows身份验证进行CI/CD(避免明文密码)
  • 绝不要将凭据提交到源代码控制
  • 使用Azure Key Vault或GitHub Secrets存储连接字符串
版本控制:
  • 所有数据库对象都在源代码控制中
  • 测试脚本版本化并在构建步骤中执行
  • 签入需要添加注释
  • 配置自定义签入策略

GitHub Actions (2025 Pattern)

GitHub Actions(2025年模式)

yaml
name: Deploy to SQL Server 2025

on:
  push:
    branches: [main]

jobs:
  build-and-test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4

    - name: Setup .NET 8
      uses: actions/setup-dotnet@v4
      with:
        dotnet-version: '8.0.x'

    - name: Install SqlPackage 170.2.70
      run: dotnet tool install -g Microsoft.SqlPackage --version 170.2.70

    - name: Build DACPAC
      run: dotnet build Database.sqlproj -c Release

    - name: Run tSQLt Unit Tests
      run: |
        # Run unit tests and capture results
        # Abort if tests fail
        echo "Running tSQLt unit tests..."
        # Add your tSQLt test execution here

    - name: Generate Deployment Report
      run: |
        sqlpackage /Action:DeployReport \
          /SourceFile:bin/Release/Database.dacpac \
          /TargetConnectionString:"${{ secrets.SQL_CONNECTION_STRING }}" \
          /OutputPath:deploy-report.xml \
          /p:BlockOnPossibleDataLoss=True

    - name: Publish to SQL Server 2025
      run: |
        sqlpackage /Action:Publish \
          /SourceFile:bin/Release/Database.dacpac \
          /TargetConnectionString:"${{ secrets.SQL_CONNECTION_STRING }}" \
          /p:TargetPlatform=SqlServer2025 \
          /p:BlockOnPossibleDataLoss=True \
          /DiagnosticsFile:publish.log \
          /DiagnosticsLevel:Verbose

    - name: Upload Artifacts
      if: always()
      uses: actions/upload-artifact@v4
      with:
        name: deployment-logs
        path: |
          publish.log
          deploy-report.xml
yaml
name: Deploy to SQL Server 2025

on:
  push:
    branches: [main]

jobs:
  build-and-test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4

    - name: Setup .NET 8
      uses: actions/setup-dotnet@v4
      with:
        dotnet-version: '8.0.x'

    - name: Install SqlPackage 170.2.70
      run: dotnet tool install -g Microsoft.SqlPackage --version 170.2.70

    - name: Build DACPAC
      run: dotnet build Database.sqlproj -c Release

    - name: Run tSQLt Unit Tests
      run: |
        # 运行单元测试并捕获结果
        # 测试失败则终止
        echo "Running tSQLt unit tests..."
        # 在此添加你的tSQLt测试执行代码

    - name: Generate Deployment Report
      run: |
        sqlpackage /Action:DeployReport \
          /SourceFile:bin/Release/Database.dacpac \
          /TargetConnectionString:"${{ secrets.SQL_CONNECTION_STRING }}" \
          /OutputPath:deploy-report.xml \
          /p:BlockOnPossibleDataLoss=True

    - name: Publish to SQL Server 2025
      run: |
        sqlpackage /Action:Publish \
          /SourceFile:bin/Release/Database.dacpac \
          /TargetConnectionString:"${{ secrets.SQL_CONNECTION_STRING }}" \
          /p:TargetPlatform=SqlServer2025 \
          /p:BlockOnPossibleDataLoss=True \
          /DiagnosticsFile:publish.log \
          /DiagnosticsLevel:Verbose

    - name: Upload Artifacts
      if: always()
      uses: actions/upload-artifact@v4
      with:
        name: deployment-logs
        path: |
          publish.log
          deploy-report.xml

Azure DevOps

Azure DevOps

yaml
trigger:
- main

pool:
  vmImage: 'windows-2022'

steps:
- task: MSBuild@1
  displayName: 'Build Database Project'
  inputs:
    solution: 'Database.sqlproj'
    configuration: 'Release'

- task: SqlAzureDacpacDeployment@1
  displayName: 'Deploy to SQL Server 2025'
  inputs:
    azureSubscription: 'Azure Subscription'
    authenticationType: 'servicePrincipal'
    serverName: 'server2025.database.windows.net'
    databaseName: 'MyDatabase'
    deployType: 'DacpacTask'
    deploymentAction: 'Publish'
    dacpacFile: '$(Build.SourcesDirectory)/bin/Release/Database.dacpac'
    additionalArguments: '/p:TargetPlatform=SqlServer2025'
yaml
trigger:
- main

pool:
  vmImage: 'windows-2022'

steps:
- task: MSBuild@1
  displayName: 'Build Database Project'
  inputs:
    solution: 'Database.sqlproj'
    configuration: 'Release'

- task: SqlAzureDacpacDeployment@1
  displayName: 'Deploy to SQL Server 2025'
  inputs:
    azureSubscription: 'Azure Subscription'
    authenticationType: 'servicePrincipal'
    serverName: 'server2025.database.windows.net'
    databaseName: 'MyDatabase'
    deployType: 'DacpacTask'
    deploymentAction: 'Publish'
    dacpacFile: '$(Build.SourcesDirectory)/bin/Release/Database.dacpac'
    additionalArguments: '/p:TargetPlatform=SqlServer2025'

New SqlPackage Diagnostic Features

新SqlPackage诊断功能

bash
undefined
bash
undefined

Enable detailed diagnostics

启用详细诊断

sqlpackage /Action:Publish
/SourceFile:Database.dacpac
/TargetServerName:server2025.database.windows.net
/TargetDatabaseName:MyDatabase
/DiagnosticsLevel:Verbose
/DiagnosticPackageFile:diagnostics.zip
sqlpackage /Action:Publish
/SourceFile:Database.dacpac
/TargetServerName:server2025.database.windows.net
/TargetDatabaseName:MyDatabase
/DiagnosticsLevel:Verbose
/DiagnosticPackageFile:diagnostics.zip

Creates diagnostics.zip containing:

生成的diagnostics.zip包含:

- Deployment logs

- 部署日志

- Performance metrics

- 性能指标

- Error details

- 错误详情

- Schema comparison results

- 架构对比结果

undefined
undefined

Microsoft Fabric Data Warehouse Support

Microsoft Fabric数据仓库支持

New in SqlPackage 162.5+: Full support for SQL database in Microsoft Fabric.
Fabric Deployment:
bash
undefined
SqlPackage 162.5及以上版本新增: 全面支持Microsoft Fabric中的SQL数据库。
Fabric部署:
bash
undefined

Deploy to Fabric Warehouse

部署到Fabric数据仓库

sqlpackage /Action:Publish
/SourceFile:Warehouse.dacpac
/TargetConnectionString:"Server=tcp:myworkspace.datawarehouse.fabric.microsoft.com;Database=mywarehouse;Authentication=ActiveDirectoryInteractive;"
/p:DatabaseEdition=Fabric
/p:DatabaseServiceObjective=SqlDbFabricDatabaseSchemaProvider
sqlpackage /Action:Publish
/SourceFile:Warehouse.dacpac
/TargetConnectionString:"Server=tcp:myworkspace.datawarehouse.fabric.microsoft.com;Database=mywarehouse;Authentication=ActiveDirectoryInteractive;"
/p:DatabaseEdition=Fabric
/p:DatabaseServiceObjective=SqlDbFabricDatabaseSchemaProvider

Extract from Fabric

从Fabric提取

sqlpackage /Action:Extract
/SourceConnectionString:"Server=tcp:myworkspace.datawarehouse.fabric.microsoft.com;Database=mywarehouse;Authentication=ActiveDirectoryInteractive;"
/TargetFile:Fabric.dacpac
sqlpackage /Action:Extract
/SourceConnectionString:"Server=tcp:myworkspace.datawarehouse.fabric.microsoft.com;Database=mywarehouse;Authentication=ActiveDirectoryInteractive;"
/TargetFile:Fabric.dacpac

New permission: ALTER ANY EXTERNAL MIRROR (Fabric-specific)

新权限:ALTER ANY EXTERNAL MIRROR(Fabric专属)

GRANT ALTER ANY EXTERNAL MIRROR TO [FabricAdmin];
undefined
GRANT ALTER ANY EXTERNAL MIRROR TO [FabricAdmin];
undefined

Best Practices for SQL Server 2025

SQL Server 2025最佳实践

  1. Use Target Platform Specification:
xml
<PropertyGroup>
  <TargetPlatform>SqlServer2025</TargetPlatform>
</PropertyGroup>
  1. Test Vector Operations:
sql
-- Verify vector support
SELECT SERVERPROPERTY('IsVectorSupported') AS VectorSupport;
  1. Monitor AI Model Performance:
sql
-- Track model execution
SELECT
    model_name,
    AVG(execution_time_ms) AS AvgExecutionTime,
    COUNT(*) AS ExecutionCount
FROM sys.dm_exec_external_model_stats
GROUP BY model_name;
  1. Implement Sensitivity Classification:
sql
-- Classify all PII columns
ADD SENSITIVITY CLASSIFICATION TO dbo.Customers.Email
WITH (LABEL = 'Confidential - GDPR', INFORMATION_TYPE = 'Email');
  1. 指定目标平台:
xml
<PropertyGroup>
  <TargetPlatform>SqlServer2025</TargetPlatform>
</PropertyGroup>
  1. 测试向量操作:
sql
-- 验证向量支持
SELECT SERVERPROPERTY('IsVectorSupported') AS VectorSupport;
  1. 监控AI模型性能:
sql
-- 跟踪模型执行情况
SELECT
    model_name,
    AVG(execution_time_ms) AS AvgExecutionTime,
    COUNT(*) AS ExecutionCount
FROM sys.dm_exec_external_model_stats
GROUP BY model_name;
  1. 实施敏感度分类:
sql
-- 对所有PII列进行分类
ADD SENSITIVITY CLASSIFICATION TO dbo.Customers.Email
WITH (LABEL = 'Confidential - GDPR', INFORMATION_TYPE = 'Email');

Resources

资源