Sql server 如何在SQLServer中拆分和查询节点动态的xml列
我们有一个xml列,其中节点名称随站点的不同而变化(基本上,除了我们提供的标准字段外,我们还允许用户创建自定义字段,这些字段保存在我提到的xml列中Sql server 如何在SQLServer中拆分和查询节点动态的xml列,sql-server,tsql,sqlxml,Sql Server,Tsql,Sqlxml,我们有一个xml列,其中节点名称随站点的不同而变化(基本上,除了我们提供的标准字段外,我们还允许用户创建自定义字段,这些字段保存在我提到的xml列中 <Dictionary><UnitNumber>56</UnitNumber><AptNo>12</AptNo></Dictionary> 因此,这个表是客户作为where子句传入的(应该转换为从t中选择*,其中UnitNumber=56,AptNo=12) 然后我们从结果将
<Dictionary><UnitNumber>56</UnitNumber><AptNo>12</AptNo></Dictionary>
因此,这个表是客户作为where子句传入的(应该转换为从t中选择*,其中UnitNumber=56,AptNo=12)
然后我们从结果将来自的表中拆分xml列。由于我们使用nodes()函数和OUTER APPLY,最终的CTE有一些重复的标识,因为它们有多个节点
我们进行xml分解的sql语句如下
SELECT T.C.value('local-name(.)', 'nvarchar(100)') as CustomFieldName,
T.C.value('.', 'nvarchar(100)') as CustomFieldValue,
#tempTable.*
FROM #tempTable
OUTER APPLY #tempTable.CustomFields.nodes('/Dictionary/child::*') as T(C)
这返回类似于
CustomFieldName CustomFieldValue EntityId
--------------- ---------------- ----------
UnitNumber 56 1
AptNo 12 1
UnitNumber 56 2
因此,当我们将CTE与temp表连接时,我们将继续连接
CustomFieldName = field and CustomFieldValue = value
查询同时返回entityId 1和entityId 2,但我希望它只返回entityId 1,因为这是唯一满足这两个条件的实体
(UnitNumber = 56 AND AptNo = 12)
我还没有找到一种方法来实现这一点。当然,如果我们存储CustomFields的方式是结构化的,这将非常有用,但这是一个已建立的系统,目前无法更改
非常感谢您给我的任何建议。谢谢!像这样的建议可以让您更亲近。在我的脑海中:
Select top 1 EntityId from #cte
left join #tempTable
on CustomFieldName = field
and CustomFieldValue = value
group by EntityId
order by count(entityid) desc
它确实让我接近了。下面是我最后做的
SELECT ROW_NUMBER() OVER(PARTITION BY EntityId ORDER BY EntityId DESC) As EntityCount, EntityId
from CTE JOIN #tempTable ON
CustomFieldName = field and CustomFieldValue = value
Where EntityCount = (select count(*) from #temptable)
谢谢您的帮助。问题很好。谢谢您的发帖,我期待着阅读答案。我仍在尝试如何使用stackoverflow的约定,但想感谢您的回答。这非常有帮助。
SELECT ROW_NUMBER() OVER(PARTITION BY EntityId ORDER BY EntityId DESC) As EntityCount, EntityId
from CTE JOIN #tempTable ON
CustomFieldName = field and CustomFieldValue = value
Where EntityCount = (select count(*) from #temptable)