[英]Get values from XML field with SQL Server
我想使用 T-SQL 從 xml 列中獲取值。
我的名為XML
xml 列包含:
<SIMBATCHJOB ONFAIL="2" ID="4" ONPASS="0"/>
如何獲取第二個參數? 例如這里的ID。
我嘗試過這樣的請求:
DECLARE @xml XML
SELECT @xml = N'<SIMBATCHJOB ONFAIL="2" ID="4" ONPASS="0"/>'
SELECT
T.C.value('(SIMBATCHJOB)[1]', 'int') as test1
FROM
@xml.nodes('SIMBATCHJOB') T(C)
我的表結構如下:
ID | XML
如果我嘗試這個查詢:
Select ID
,Value = cast([xml] as xml).value('SIMBATCHJOB[1]/@ID','int')
From SIM_JOBS
where id = 179
此查詢返回 ID,值為空
你明白嗎 ?
提前致謝
Jeroen 是 100% 正確的,但一種選擇是使用 CROSS APPLY 並規范化您的屬性。
序列將適用於實際 XML 中的序列。 我懷疑您可以根據需要進行過濾。
例子
Declare @XML xml = '<SIMBATCHJOB ONFAIL="2" ID="4" ONPASS="0"/>'
Select Seq = row_number() over (Order By (Select NULL))
,Attribute = a.value('local-name(.)','varchar(100)')
,Value = a.value('.','varchar(max)')
From @XML.nodes('/SIMBATCHJOB ') as C1(n)
Cross Apply C1.n.nodes('./@*') as C2(a)
退貨
Seq Attribute Value
1 ONFAIL 2
2 ID 4
3 ONPASS 0
編輯 - 更新評論---
這將返回第二個屬性/值,無論是什么
Declare @YourTable table (ID int,[xml] xml)
Insert Into @YourTable values
(1,'<SIMBATCHJOB ONFAIL="2" ID="4" ONPASS="0"/>'),
(2,'<SIMBATCHJOB ONFAIL="2" ID="99" ONPASS="1"/>')
Select A.ID
,B.*
From @YourTable A
Cross Apply (
Select *
From (
Select Seq = row_number() over (Order By (Select NULL))
,Attribute = a.value('local-name(.)','varchar(100)')
,Value = a.value('.','varchar(max)')
From A.xml.nodes('/SIMBATCHJOB ') as C1(n)
Cross Apply C1.n.nodes('./@*') as C2(a)
) B1
Where B1.Seq=2
) B
退貨
ID Seq Attribute Value
1 2 ID 4
2 2 ID 99
編輯 2: - 無論序列如何,只獲取 ID
Declare @YourTable table (ID int,[xml] xml)
Insert Into @YourTable values
(1,'<SIMBATCHJOB ONFAIL="2" ID="4" ONPASS="0"/>'),
(2,'<SIMBATCHJOB ONFAIL="2" ID="99" ONPASS="1"/>')
Select A.ID
,Value = [xml].value('SIMBATCHJOB[1]/@ID','int')
From @YourTable A
退貨
ID Value
1 4
2 99
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.