我正努力使用sql select语句从xml字段中提取一个值。
xml字段是info,表是results。
<Screens>
<Results>
<Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse=""
DataAction="" DataValue="2" DataScore="0" />
</Results>
</Screens>
我需要拉属性
DataValue
。为了上面的记录,我要找2个。任何帮助都将不胜感激。
最佳答案
对于SQL Server,它是这样的:
DECLARE @xml XML=
'<Screens>
<Results>
<Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse=""
DataAction="" DataValue="2" DataScore="0" />
</Results>
</Screens>';
SELECT @xml.value('(/Screens/Results/Result/@DataValue)[1]','int') AS DataValue
编辑:数据来自表
把我的
@tbl
换成你真正的桌子--test scenario with two data rows, one has DataValue=2 the other =99
DECLARE @tbl TABLE(ID INT IDENTITY,info XML);
INSERT INTO @tbl(info) VALUES
(
'<Screens>
<Results>
<Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse=""
DataAction="" DataValue="2" DataScore="0" />
</Results>
</Screens>'
)
,(
'<Screens>
<Results>
<Result ID="54722094-8b36-4a01-b089-3ecabebbf962" DataResponse=""
DataAction="" DataValue="99" DataScore="0" />
</Results>
</Screens>'
);
--this is the query
SELECT info.value('(/Screens/Results/Result/@DataValue)[1]','int') AS DataValue
FROM @tbl
结果是2和99