2

我在编写查询时遇到问题,以便可以查询 Elmah_Error 表中 AllXml 列的内容。

如何列出所有项目节点作为查询的输出。我如何编写查询以仅列出某些项目节点?

我想获得以下结果集:

项目价值

===== =====

ALL_HTTP HTTP_CONNECTION:xxxx

ALL_RAW 连接:xxxxx

我还希望能够通过 ErrorID 过滤查询

AllXml 列的内容可能如下所示。

<error
  application="/"
  message="hello world"
  source="TestWebElmah"
  detail="xxxxx">
  <serverVariables>
    <item
      name="ALL_HTTP">
      <value
        string="HTTP_CONNECTION:xxxx" />
    </item>
    <item
      name="ALL_RAW">
      <value
        string="Connection: xxxxx" />
    </item>

  </serverVariables>
</error>
4

2 回答 2

7

远程地址节点

select T.N.value('(value/@string)[1]', 'varchar(30)') as REMOTE_ADDR
from 
(select cast(AllXml as xml) as AllXml from ELMAH_Error) e
   cross apply AllXml.nodes('//item[@name="REMOTE_ADDR"]') as T(N)

包含mozilla的 HTTP 用户代理

select T.N.value('(value/@string)[1]', 'varchar(30)') as HTTP_USER_AGENT
from 
(select cast(AllXml as xml) as AllXml from ELMAH_Error) e
   cross apply AllXml.nodes('//item[@name="HTTP_USER_AGENT"]') as T(N)
where T.N.value('(value/@string)[1]', 'varchar(30)') like '%mozilla%'

Elmah table stores the AllXml column as nvarchar so it needs to be casted to xml

all tags + values, by error id

select T.N.value('@name', 'varchar(30)') as Name,
       T.N.value('(value/@string)[1]', 'varchar(30)') as Value
from 
(select cast(AllXml as xml) as AllXml from ELMAH_Error where ErrorId = 'DC82172B-F2C0-48CE-8621-A60B702ECF93') e
cross apply AllXml.nodes('/error/serverVariables/item') as T(N)



Before voting down this answer, because uses most of the part of Mikael Eriksson's answer, I let you know I'll happily accept the downvotes only for this reason, since is mainly true

于 2012-04-04T22:45:29.883 回答
2

此查询将为您提供所有item节点

select T.N.value('@name', 'varchar(30)') as Name,
       T.N.value('(value/@string)[1]', 'varchar(30)') as Value
from Elmah_Error
  cross apply AllXml.nodes('/error/serverVariables/item') as T(N)

如果要过滤任何值,可以将其放在子查询中,应用常规 where 子句。

select Name, 
       Value
from
  (
    select T.N.value('@name', 'varchar(30)') as Name,
           T.N.value('(value/@string)[1]', 'varchar(30)') as Value
    from Elmah_Error
      cross apply AllXml.nodes('/error/serverVariables/item') as T(N)
  ) T
where Name = 'ALL_HTTP'
于 2012-04-04T22:18:32.403 回答