首页 \ 问答 \ 如何从SQL Server中的表查询Xml值和属性?(How to query for Xml values and attributes from table in SQL Server?)

如何从SQL Server中的表查询Xml值和属性?(How to query for Xml values and attributes from table in SQL Server?)

我有一个包含Xml列的表:

SELECT * 
FROM Sqm

在此输入图像描述

一行xml数据的示例将是:

<Sqm version="1.2">
  <Metrics>
    <Metric id="TransactionCleanupThread.RecordUsedTransactionShift" type="timer" unit="µs" count="1" sum="21490"   average="21490"   minValue="73701"    maxValue="73701"                               >73701</Metric>
    <Metric id="TransactionCleanupThread.RefundOldTrans"             type="timer" unit="µs" count="1" sum="184487"  average="184487"  minValue="632704"   maxValue="632704"                              >632704</Metric>
    <Metric id="Database.CreateConnection_SaveContextUserGUID"       type="timer" unit="µs" count="2" sum="7562"    average="3781"    minValue="12928"    maxValue="13006"    standardDeviation="16"     >12967</Metric>
    <Metric id="Global.CurrentUser"                                  type="timer" unit="µs" count="6" sum="4022464" average="670411"  minValue="15"       maxValue="13794345" standardDeviation="1642047">2299194</Metric>
    <Metric id="Global.CurrentUser_FetchIdentityFromDatabase"        type="timer" unit="µs" count="1" sum="4010057" average="4010057" minValue="13752614" maxValue="13752614"                            >13752614</Metric>
  </Metrics>
</Sqm>

在这个数据的情况下,我想要:

SqmId  id                                                   type   unit  count  sum      minValue  maxValue  standardDeviation  Value
=====  ===================================================  =====  ====  =====  ======   ========  ========  =================  ======
1      TransactionCleanupThread.RecordUsedTransactionShift  timer  µs    1      21490    73701     73701     NULL               73701
1      TransactionCleanupThread.RefundOldTrans              timer  µs    1      184487   632704    632704    NULL               632704
1      Database.CreateConnection_SaveContextUserGUID        timer  µs    2      7562     12928     13006     16                 12967
1      Global.CurrentUser                                   timer  µs    6      4022464  15        13794345  1642047            2299194
1      Global.CurrentUser_FetchIdentityFromDatabase         timer  µs    1      4010057  13752614  13752614  NULL               13752614
2      ...

最后我会实际执行SUM()MIN()MAX()聚合。 但是现在我只是想查询 xml列。

在伪代码中,我会尝试像:

SELECT
    SqmId,
    Data.query('/Sqm/Metrics/Metric/@id') AS id,
    Data.query('/Sqm/Metrics/Metric/@type') AS type,
    Data.query('/Sqm/Metrics/Metric/@unit') AS unit,
    Data.query('/Sqm/Metrics/Metric/@sum') AS sum,
    Data.query('/Sqm/Metrics/Metric/@count') AS count,
    Data.query('/Sqm/Metrics/Metric/@minValue') AS minValue,
    Data.query('/Sqm/Metrics/Metric/@maxValue') AS maxValue,
    Data.query('/Sqm/Metrics/Metric/@standardDeviation') AS standardDeviation,
    Data.query('/Sqm/Metrics/Metric') AS value
FROM Sqm

但是SQL查询不起作用:

消息2396,第16级,状态1,行2
XQuery [Sqm.data.query()]:属性可能不会出现在元素之外

我已经搜索过,令人惊奇的是,Xml查询是如何记录不好或者是示例的。 大多数资源而不是查询 ,查询变量 ; 我没有做 大多数资源只使用xml查询进行过滤和选择,而不是读取值。 大多数资源读取硬编码的子节点(按索引),而不是实际值。

我看过的相关资源

  • https://stackoverflow.com/questions/966441/xml-query-in-sql-server-2008
  • SQL Server查询元素值的xml属性值
  • SQL查询XML属性
  • SQL Server 2005 XQuery和XML-DML - 第1部分
  • BOL:Microsoft SQL Server 2005中的XML支持
  • 在SQL Server中查询XML
  • 基本SQL Server XML查询
  • BOL:query()方法(xml数据类型)
  • XML Workshop V - 从XML列中读取值
  • SQL SERVER - 发现XML数据类型方法 - 入门简介

更新:.value而不是.query

我尝试随机使用.value ,代替.query

SELECT
    Sqm.SqmId,
    Data.value('/Sqm/Metrics/Metric/@id', 'varchar(max)') AS id,
    Data.value('/Sqm/Metrics/Metric/@type', 'varchar(max)') AS type,
    Data.value('/Sqm/Metrics/Metric/@unit', 'varchar(max)') AS unit,
    Data.value('/Sqm/Metrics/Metric/@sum', 'varchar(max)') AS sum,
    Data.value('/Sqm/Metrics/Metric/@count', 'varchar(max)') AS count,
    Data.value('/Sqm/Metrics/Metric/@minValue', 'varchar(max)') AS minValue,
    Data.value('/Sqm/Metrics/Metric/@maxValue', 'varchar(max)') AS maxValue,
    Data.value('/Sqm/Metrics/Metric/@standardDeviation', 'varchar(max)') AS standardDeviation,
    Data.value('/Sqm/Metrics/Metric', 'varchar(max)') AS value
FROM Sqm

但这也不行:

Msg 2389,Level 16,State 1,Line 3 XQuery [Sqm.data.value()]:
'value()'需要一个单例(或空序列),找到的操作数类型为'xdt:untypedAtomic *'


I have a table that contains a Xml column:

SELECT * 
FROM Sqm

enter image description here

A sample of the xml data of a row would be:

<Sqm version="1.2">
  <Metrics>
    <Metric id="TransactionCleanupThread.RecordUsedTransactionShift" type="timer" unit="µs" count="1" sum="21490"   average="21490"   minValue="73701"    maxValue="73701"                               >73701</Metric>
    <Metric id="TransactionCleanupThread.RefundOldTrans"             type="timer" unit="µs" count="1" sum="184487"  average="184487"  minValue="632704"   maxValue="632704"                              >632704</Metric>
    <Metric id="Database.CreateConnection_SaveContextUserGUID"       type="timer" unit="µs" count="2" sum="7562"    average="3781"    minValue="12928"    maxValue="13006"    standardDeviation="16"     >12967</Metric>
    <Metric id="Global.CurrentUser"                                  type="timer" unit="µs" count="6" sum="4022464" average="670411"  minValue="15"       maxValue="13794345" standardDeviation="1642047">2299194</Metric>
    <Metric id="Global.CurrentUser_FetchIdentityFromDatabase"        type="timer" unit="µs" count="1" sum="4010057" average="4010057" minValue="13752614" maxValue="13752614"                            >13752614</Metric>
  </Metrics>
</Sqm>

In the case of this data, I would want:

SqmId  id                                                   type   unit  count  sum      minValue  maxValue  standardDeviation  Value
=====  ===================================================  =====  ====  =====  ======   ========  ========  =================  ======
1      TransactionCleanupThread.RecordUsedTransactionShift  timer  µs    1      21490    73701     73701     NULL               73701
1      TransactionCleanupThread.RefundOldTrans              timer  µs    1      184487   632704    632704    NULL               632704
1      Database.CreateConnection_SaveContextUserGUID        timer  µs    2      7562     12928     13006     16                 12967
1      Global.CurrentUser                                   timer  µs    6      4022464  15        13794345  1642047            2299194
1      Global.CurrentUser_FetchIdentityFromDatabase         timer  µs    1      4010057  13752614  13752614  NULL               13752614
2      ...

In the end I'll actually be performing SUM(), MIN(), MAX() aggregation. But for now I'm just trying to query an xml column.

In pseudo-code, I would try something like:

SELECT
    SqmId,
    Data.query('/Sqm/Metrics/Metric/@id') AS id,
    Data.query('/Sqm/Metrics/Metric/@type') AS type,
    Data.query('/Sqm/Metrics/Metric/@unit') AS unit,
    Data.query('/Sqm/Metrics/Metric/@sum') AS sum,
    Data.query('/Sqm/Metrics/Metric/@count') AS count,
    Data.query('/Sqm/Metrics/Metric/@minValue') AS minValue,
    Data.query('/Sqm/Metrics/Metric/@maxValue') AS maxValue,
    Data.query('/Sqm/Metrics/Metric/@standardDeviation') AS standardDeviation,
    Data.query('/Sqm/Metrics/Metric') AS value
FROM Sqm

But that SQL query doesn't work:

Msg 2396, Level 16, State 1, Line 2
XQuery [Sqm.data.query()]: Attribute may not appear outside of an element

I've hunted, and it's amazing how poorly documented, or exampled, Xml querying is. Most resources rather than querying a table, query a variable; which I'm not doing. Most resources only use xml querying for filtering and selection, rather than reading values. Most resources read hard-coded child nodes (by index), rather than actual values.

Related resources that I read

Update: .value rather than .query

I tried randomly using .value, in place of .query:

SELECT
    Sqm.SqmId,
    Data.value('/Sqm/Metrics/Metric/@id', 'varchar(max)') AS id,
    Data.value('/Sqm/Metrics/Metric/@type', 'varchar(max)') AS type,
    Data.value('/Sqm/Metrics/Metric/@unit', 'varchar(max)') AS unit,
    Data.value('/Sqm/Metrics/Metric/@sum', 'varchar(max)') AS sum,
    Data.value('/Sqm/Metrics/Metric/@count', 'varchar(max)') AS count,
    Data.value('/Sqm/Metrics/Metric/@minValue', 'varchar(max)') AS minValue,
    Data.value('/Sqm/Metrics/Metric/@maxValue', 'varchar(max)') AS maxValue,
    Data.value('/Sqm/Metrics/Metric/@standardDeviation', 'varchar(max)') AS standardDeviation,
    Data.value('/Sqm/Metrics/Metric', 'varchar(max)') AS value
FROM Sqm

But that also doesn't work:

Msg 2389, Level 16, State 1, Line 3 XQuery [Sqm.data.value()]:
'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'


原文:https://stackoverflow.com/questions/19165213
更新时间:2022-05-23 13:05

最满意答案

您的查询返回它应该返回的结果(无结果),因为您加入了caballos.Cod字段,并且您将不同数量的Cod字段过滤为2.由于Cod字段是用于caballos表的唯一标识符, caballos它被使用在连接条件下,每个组的值不能超过1个。

您可以在过滤条件中使用Disciplina字段,因为它只是Disciplina字段,可能在结果集中的两个单独记录中具有不同的值:

HAVING COUNT(DISTINCT d.Disciplina)=2

Your query returns what it should (no result) because you join on the caballos.Cod field, and you filter on the distinct number of Cod fields being 2. Since the Cod field sems to be a unique identifier for caballos table and it is used in the join condition, it cannot have more than 1 distinct value per group.

You could use the Disciplina field in the filter criteria instead because it is only the Disciplina field that could have different values in 2 separate records in the resultset:

HAVING COUNT(DISTINCT d.Disciplina)=2

相关问答

更多
  • 复合查询不支持括号,但子查询可以: SELECT a, b FROM table1 INTERSECT SELECT * FROM (SELECT a, b FROM table2 EXCEPT SELECT a, b FROM table3) 请注意, INTERSECT没有比EXCEPT更高的优先级, 实际规则是: 当三个或更多简单的SELECT连接到复合SELECT时,它们从左到右分组。 由于INTERSECT是可交换的,你可以简单地写下这 ...
  • 首先尝试这样,检查你是否拥有所有演员。 如果你有同名演员,我必须添加codactor。 SELECT a.codactor, a.nombre -- add ', *' to see all columns and test query is ok. FROM actores a JOIN participacion p ON a.codactor = p.actor JOIN peliculas m ON p.titulo = m.titulo AND p.ano = m.ano JOIN ...
  • INTERSECT在更新方面没有任何意义。 您的SELECT查询实际上是同时运行的五个独立查询,以便返回五个独立结果集的交集。 由于UPDATE不生成结果集,因此尝试将其非结果与SELECT查询的结果相交是一个错误。 使用复杂的WHERE子句的单个SELECT查询似乎更好地服务于您的原始目的,因为五个查询中的每一个都针对检查不同条件的同一个表运行。 INTERSECT doesn't have any meaning in terms of updates. Your SELECT query is act ...
  • 您的查询返回它应该返回的结果(无结果),因为您加入了caballos.Cod字段,并且您将不同数量的Cod字段过滤为2.由于Cod字段是用于caballos表的唯一标识符, caballos它被使用在连接条件下,每个组的值不能超过1个。 您可以在过滤条件中使用Disciplina字段,因为它只是Disciplina字段,可能在结果集中的两个单独记录中具有不同的值: HAVING COUNT(DISTINCT d.Disciplina)=2 Your query returns what it should ...
  • 是。 正如其他人已经回答的那样,你可以使用Where ,但是对于大套装来说,效率将是非常低的。 如果性能受到关注,可以调用Join : var results = original.Join(idsToFind, o => o.Id, id => id, (o, id) => o); 如果idsToFind可以包含重复项,则需要在ID或结果上调用Distinct() ,或者使用idsToFind替换Join ( GroupJoin的参数将相同)。 Yes. As other people have ans ...
  • 如上所述,如果你想得到4的结果,你可以这样做: var nonintersect = array2.Except(array1); 如果你想要真正的非交叉(也是1和4),那么这应该是诀窍: var nonintersect = array1.Except(array2).Union( array2.Except(array1)); 这不是最有效的解决方案,但对于小列表,它应该可以正常工作。 As stated, if you want to get 4 as the result, you can do ...
  • SELECT subjectid FROM exam_subjects WHERE examid IN (SELECT examid FROM exams) GROUP BY subjectid HAVING COUNT(*) = (SELECT COUNT(examid) FROM exams); 我在堆栈溢出的类似问题的帮助下得到了这个如何在组合表上进行交集 SELECT subjectid FROM exam_subjects WHERE examid IN (SELECT examid ...
  • 你想要做的是计算你的结果。 SELECT CASE WHEN COUNT(*) = 0 THEN 'Yes' ELSE 'No' END FROM ( SELECT CITY FROM DNAME WHERE DNAME='RESEARCH' INTERSECT SELECT CITY FROM DNAME WHERE DNAME='SCIENCE' ); 当然还有其他方法可以达到相同的效果。 这个演示了如何使用INTERSECT查询来完成它。 What you want to do is ...
  • 相交的日期: SELECT E.name, O.start_date, O.end_date FROM dbo.Names E INNER JOIN dbo.Dates O ON O.name = E.name AND O.start_date < @end_date AND O.end_date > @start_date WHERE E.name LIKE 'A' 不相交的日期与日期相反: SELECT E.name, O ...
  • 这绝对是可能的。 看这个例子: http://msdn.microsoft.com/en-us/library/bb399392.aspx It is definitely possible. See this example: http://msdn.microsoft.com/en-us/library/bb399392.aspx

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)