SQL Server 2008 在 XML 處理上進一步增強:XQuery 建構器支援動態建構 XML、XML DML modify() 新增變數插入語法,大幅提升 XML 資料操作彈性。
可在查詢中直接建構 XML 結構,範例輸出:
<Orders>
<Order>
<Customer>Margaret Smith</Customer>
<ItemCount>1</ItemCount>
</Order>
<Order>
<Customer>Kim Abercrombie</Customer>
<ItemCount>3</ItemCount>
</Order>
</Orders>
限制: 不允許對建構元素直接賦值,需在建構表達式中完成。
modify() 的 insert 運算式現在支援 sql:variable() 函數,可將 XML 變數內容插入現有 XML 結構:
DECLARE @productList XML;
SET @productList = '<Products><Bike>Mountain Bike</Bike><Bike>Road Bike</Bike></Products>';
DECLARE @newBike XML;
SET @newBike = '<Bike>Racing Bike</Bike>';
SET @productList.modify(
'insert sql:variable("@newBike") as last into (/Products)[1]'
);
-- 結果:
-- <Products>
-- <Bike>Mountain Bike</Bike>
-- <Bike>Road Bike</Bike>
-- <Bike>Racing Bike</Bike>
-- </Products>
優勢: 避免字串拼接 XML 片段的語法錯誤與注入風險,型別安全、結構驗證自動生效。
xml 資料型別、大型物件儲存最佳化。這些增強讓關聯式資料與 XML 混合模型在 SQL Server 內原生高效運作,適用於半結構化資料、訊息封包、彈性 Schema 等現代應用場景。