SQL Server 2017:过滤XML列中SourceAccount与DestinationAccount值相等的记录
解决方案
假设你使用的是SQL Server,以下是实现需求的查询语句:
SELECT ID, noteID, columnXML FROM TempTable WHERE -- 获取DestinationAccount对应的Value值 columnXML.value('(ArrayOfNoteParameterDC/NoteParameterDC[ParameterEnum/text()="DestinationAccount"]/Value/text())[1]', 'nvarchar(max)') = -- 获取SourceAccount对应的Value值 columnXML.value('(ArrayOfNoteParameterDC/NoteParameterDC[ParameterEnum/text()="SourceAccount"]/Value/text())[1]', 'nvarchar(max)') -- 可选:过滤掉缺少目标节点的记录,避免NULL比较导致的无结果 AND columnXML.exist('ArrayOfNoteParameterDC/NoteParameterDC[ParameterEnum/text()="DestinationAccount"]') = 1 AND columnXML.exist('ArrayOfNoteParameterDC/NoteParameterDC[ParameterEnum/text()="SourceAccount"]') = 1
关键逻辑说明
columnXML.value(...):通过XPath定位到指定ParameterEnum值的NoteParameterDC节点,提取对应的Value文本内容。[1]确保只取第一个匹配的节点值(若存在多个同名节点)。columnXML.exist(...):用来排除缺少DestinationAccount或SourceAccount节点的记录,避免因NULL值比较(SQL中NULL=NULL返回未知,不会命中结果)导致的漏判或错误。
如果你的XML是通过ParameterName标识账户类型(比如ParameterName的值为"DestinationAccount"),只需将XPath中的ParameterEnum替换为ParameterName即可:
SELECT ID, noteID, columnXML FROM TempTable WHERE columnXML.value('(ArrayOfNoteParameterDC/NoteParameterDC[ParameterName/text()="DestinationAccount"]/Value/text())[1]', 'nvarchar(max)') = columnXML.value('(ArrayOfNoteParameterDC/NoteParameterDC[ParameterName/text()="SourceAccount"]/Value/text())[1]', 'nvarchar(max)') AND columnXML.exist('ArrayOfNoteParameterDC/NoteParameterDC[ParameterName/text()="DestinationAccount"]') = 1 AND columnXML.exist('ArrayOfNoteParameterDC/NoteParameterDC[ParameterName/text()="SourceAccount"]') = 1
内容的提问来源于stack exchange,提问作者bruno valverde
相关产品推荐
相关产品推荐

