在 AI 驅動的時代,資料庫不僅僅是儲存與查詢的工具,還是智能運算的核心。過去想要在資料庫實作語義搜尋(Semantic Search)或 RAG(Retrieval-Augmented Generation)時,往往必須額外串接多個外部服務與資料庫:
現在,SQL Server 2025 直接把這些現代 AI 能力內建進來!
你可以用 SQL 原生支援外部 AI 模型呼叫、向量資料型別、語義相似度查詢與嵌入生成,所有流程都在資料庫內部安全地完成,無須維護多套系統。
接下來先分別介紹這些功能,最後再整個整合起來。
SQL Server 2025 新增的 sp_invoke_external_rest_endpoint
,可在 T-SQL 直接呼叫外部 REST API,像打 OpenAI API 這樣:
使用之前,請先確定有啟用external rest endpoint enabled
設定,如下:
EXECUTE sp_configure 'external rest endpoint enabled', 1;
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure 'external rest endpoint enabled'; -- config_value 要為 1
然後就可以透過 sp_invoke_external_rest_endpoint
呼叫 OpenAI Chat API 了 :
declare @url nvarchar(4000) = N'https://api.openai.com/v1/chat/completions';
declare @headers nvarchar(4000) = N'{"Authorization":"Bearer [你的 apikey]"}'
DECLARE @payload NVARCHAR(MAX) = N'{"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": "You are an AI assistant that helps people find information."},
{"role": "user", "content": "你說一個笑話"}
]
}';
DECLARE @ret INT, @response NVARCHAR(MAX);
EXEC @ret = sp_invoke_external_rest_endpoint@url = @url,
@method = 'POST',
@headers = @headers,
@payload = @payload,
@timeout = 230,
@response = @response OUTPUT;
SELECT @ret AS ReturnCode, @response AS Response , JSON_VALUE(choices.value, '$.message.content') AS ai_reply
FROM OPENJSON(@response, '$.result.choices') AS choices
結果是一個 JSON 字串,可透過 JSON_VALUE
取得 AI 回覆內容,如下圖:
當然,也可以呼叫地端的 REST API,只要把 URL 改成你自己的 API 即可。 如下,
SQL Server 2025 新增的 VECTOR_DISTANCE
函數,可以計算兩個向量間的相似度。用法如下:
DECLARE@car vector(2) = '[1,0]'
,@bus vector(2) = '[0.8,0]'
,@queen vector(2) = '[0,1]'
SELECT [Car vs Bus] = VECTOR_DISTANCE('cosine',@car,@bus)
,[Car Vs Queen] = VECTOR_DISTANCE('cosine',@car,@queen)
,[Bus Vs Queen] = VECTOR_DISTANCE('cosine',@bus,@queen)
從結果可以發現,car 與 bus 語義是相近的,car 與 queen 語義是相對遠的。
所以當資料中有 Car ,而使用 bus 去搜尋時,如果信心度設為 80%,會找出 Car 而不會找出 Queen。
進行向量搜尋時,通常會把長篇文章分段,然後對每一段進行向量生成,再進行搜尋。SQL Server 2025 新增的 AI_GENERATE_CHUNKS
函數,可以將一段文字分段,用法如下:
DECLARE @payload NVARCHAR(MAX) = N'叡揚資訊股份有限公司與臺北市立復興高級中學於近日正式簽署產學合作備忘錄 雙方將在資訊安全教育、人才培育及實習計劃等方面展開全面合作。此舉不僅能為學生提供多元化的學習體驗,更能有效提升學生未來升學及就業所需的專業技能。';
SELECT *
FROM (SELECT @payload as PAYLOAD) P
CROSS APPLY AI_GENERATE_CHUNKS(source = @payload,
chunk_type = N'FIXED',
chunk_size = 50,
overlap = 10) C
可以發現,第二段開始,會後前一段的 overlap 部分內容,如下圖:
你可以把 OpenAI、Ollama 等 embedding API 註冊成 SQL Server 外部模型,後續直接呼叫。
開始前 Database 需要有 MASTER KEY,如果沒有請先建立一個,如下:
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'YourStrong@Passw0rd';
GO
如果 embedding model 需要驗證的話,還需要再建立 DATABASE SCOPED CREDENTIAL,然後指定給 EXTERNAL MODEL,如下:
CREATE DATABASE SCOPED CREDENTIAL [https://api.openai.com]
WITH IDENTITY = 'HTTPEndpointHeaders', secret = '{"Authorization":"Bearer openai-apikey"}';
GO
CREATE EXTERNAL MODEL openai
WITH (LOCATION = 'https://api.openai.com/v1/embeddings',
API_FORMAT = 'OpenAI',
MODEL_TYPE = EMBEDDINGS,
MODEL = 'text-embedding-ada-002',
CREDENTIAL = [https://api.openai.com]
);
-- openai 相容的地端 embedding api
CREATE DATABASE SCOPED CREDENTIAL [https://rm.gss.com.tw]
WITH IDENTITY = 'HTTPEndpointHeaders', secret = '{"Authorization":"Bearer apikey"}';
GO
CREATE EXTERNAL MODEL gss_model
WITH (LOCATION = 'https://rm.gss.com.tw/v1/embeddings',
API_FORMAT = 'OpenAI',
MODEL_TYPE = EMBEDDINGS,
MODEL = 'e5-large',
CREDENTIAL = [https://rm.gss.com.tw]
);
CREATE DATABASE SCOPED CREDENTIAL [https://my-azure-openai-endpoint.openai.azure.com]WITH IDENTITY = 'HTTPEndpointHeaders', secret = '{"api-key":"aoai-apikey"}';
GO
CREATE EXTERNAL MODEL aoai
WITH (LOCATION = 'https://my-azure-openai-endpoint.openai.azure.com/openai/deployments/text-embedding-ada-002/embeddings?api-version=2023-05-15',
API_FORMAT = 'Azure OpenAI',
MODEL_TYPE = EMBEDDINGS,
MODEL = 'text-embedding-ada-002',
CREDENTIAL = [https://my-azure-openai-endpoint.openai.azure.com]
);
select * from sys.database_scoped_credentials;
--查看 external model
SELECT * FROM sys.external_models;
The database scoped credential 'your credential name' cannot be used to invoke an external rest endpoint. 的錯誤
。有了外部模型,就可以呼叫外部模型,產生向量了,用法如下:
SELECT AI_GENERATE_EMBEDDINGS('hello world' USE MODEL openai) AS [Embedding];
SELECT AI_GENERATE_EMBEDDINGS('hello world' USE MODEL gss_model) AS [Embedding];
SELECT AI_GENERATE_EMBEDDINGS('hello world' USE MODEL aoai) AS [Embedding];
最後,我們來實作一個完整的語義搜尋範例,使用 AdventureWorks2022 資料庫,如下:
-- 加入要放 Chunk & 向量的欄位
ALTER TABLE [Production].[Product]ADD embeddings VECTOR (1536),
chunk NVARCHAR (2000);
-- 取出要建立向量資料的字串
SELECT p.Name + ' ' + ISNULL(p.Color, 'No Color') + ' '
+ ISNULL(c.Name, 'No Category') + ' '
+ ISNULL(m.Name, 'No Model') + ' ' + ISNULL(d.Description, '')
FROM Production.Product p
LEFT JOIN Production.ProductSubCategory sc
ON p.ProductSubcategoryID = sc.ProductSubcategoryID
LEFT JOIN Production.ProductCategory c
ON sc.ProductCategoryID = c.ProductCategoryID
LEFT JOIN Production.ProductModel m
ON p.ProductModelID = m.ProductModelID
LEFT JOIN Production.vProductAndDescription d
ON p.ProductID = d.ProductID
AND d.CultureID = 'en'
WHERE p.embeddings IS NULL;
-- 先更新 chunk
UPDATE p
SET chunk = p.Name + ' ' + ISNULL(p.Color, 'No Color') + ' '
+ ISNULL(c.Name, 'No Category') + ' '
+ ISNULL(m.Name, 'No Model') + ' ' + ISNULL(d.Description, '')
FROM Production.Product p
LEFT JOIN Production.ProductSubCategory sc
ON p.ProductSubcategoryID = sc.ProductSubcategoryID
LEFT JOIN Production.ProductCategory c
ON sc.ProductCategoryID = c.ProductCategoryID
LEFT JOIN Production.ProductModel m
ON p.ProductModelID = m.ProductModelID
LEFT JOIN Production.vProductAndDescription d
ON p.ProductID = d.ProductID
AND d.CultureID = 'en';
-- 設定 向量資料, 使用 aoai external model
UPDATE p
SET embeddings = AI_GENERATE_EMBEDDINGS(chunk USE MODEL aoai)
FROM Production.Product p;
SELECT chunk, embeddingsFROM Production.Product;
完成 embedding 欄位建立與資料更新後,接下來就能直接用自然語言查詢產品資料。例如,查詢「紅色腳踏車」相關產品:
DECLARE @search_text NVARCHAR(MAX) = N'紅色腳踏車';
DECLARE @search_vector VECTOR(1536) = AI_GENERATE_EMBEDDINGS(@search_text USE MODEL aoai);
SELECT TOP(5) p.ProductID, p.Name, p.chunk,VECTOR_DISTANCE('cosine', @search_vector, p.embeddings) AS distance
FROM Production.Product p
ORDER BY distance;
取最小distance的前 5 筆資料。
以往要做語義搜尋、RAG,常要額外建向量資料庫、自己串 embedding API 並搞資料同步,還要處理資料權限控管。
SQL Server 2025 直接將 AI 語義搜尋變成 SQL 查詢本身的能力(Vector Store, Model Management, Embeddings built-in, Simple semantic serrching, Framework integration(LangChain, Semantic Kernel, EF Core …) ),不僅開發更快、維運更安全,資料不離開資料庫,讓 AI 搜尋的所有需求都能一站搞定! 或許以後的功能除了提供一般的欄位 Where 查詢外,還需要再提供自然語言的查詢方式。
SQL Server 2025 Vector Search 過程如下圖(from SQL Server 2025: The Database Developer Reimagined):
CREATE EXTERNAL MODEL
sp_invoke_external_rest_endpoint
AI_GENERATE_CHUNKS
AI_GENERATE_EMBEDDINGS
Getting started with AI in SQL Server 2025 on Windows
SQL Server 2025: The Database Developer Reimagined