所以要构建这个问题Selecting from XML field where XML field = X,并使用相同的SQL小提琴,http://sqlfiddle.com/#!3/7c0a0/5。
我似乎无法弄清楚如何获取包含具有值为“付款方式”的FIELD的项目并且具有NEWVALUE为25的项目的记录。
我尝试了以下内容并没有返回任何结果。我假设因为它正在寻找其中一个不存在的节点中的where子句中的所有内容。
SELECT
ID
FROM
T1
CROSS APPLY
XmlField.nodes('/ITEMS/ITEM') as XTbl(XItem)
WHERE
XItem.exist('FIELD[.="Payment method"]') = 1
and XItem.exist('NEWVALUE[.="25"]') = 1
我错过了什么?
答案 0 :(得分:1)
;with cte as
(
SELECT
ID, t1.XMLFIELD, row_number() over (partition by ID order by ID) rn
FROM
t1
CROSS APPLY
XmlField.nodes('/ITEMS/ITEM') as XTbl(XItem)
)
select XMLFIELD from cte
where ID IN (
select ID from cte
where XMLFIELD.exist('/ITEMS/ITEM/FIELD[.="Payment method"]') = 1
and XMLFIELD.exist('/ITEMS/ITEM/NEWVALUE[.="25"]') = 1)
and rn=1
或更简单......
select
*
from
t1
where
XMLFIELD.value('count(/ITEMS/ITEM/FIELD[.="Payment method"])','int') > 0
and
XMLFIELD.value('count(/ITEMS/ITEM/NEWVALUE[.="25"])','int') > 0
答案 1 :(得分:1)
如果您只想要符合条件的单个项目,那么您可以这样做:
select
T1.ID, T.C.query('.')
from T1
cross apply XMLFIELD.nodes('/ITEMS/ITEM[FIELD[.="Payment method"] and NEWVALUE[.="Debit"]]') as T(C)
或
select
T1.ID, T.C.query('.')
from T1
cross apply XMLFIELD.nodes('/ITEMS/ITEM') as T(C)
where
T.C.value('FIELD[1]', 'nvarchar(max)') = 'Payment method' and
T.C.value('NEWVALUE[1]', 'nvarchar(max)') = 'Debit'
在你评论之后,我想,你可能需要这样的东西:
select
T1.*
from T1
where
XMLFIELD.exist
('/ITEMS[
ITEM[FIELD[.="Payment method"] and NEWVALUE[.="Debit"]] and
ITEM[DATATYPE[.="4"] and NEWVALUE[.="25"]]
]'
) = 1