2

这是我目前使用的查询:

DECLARE @Index AS INT
SET @Index = 1
SELECT
  auditId,
  parameters.value('(params/param[position()=sql:variable("@Index")]/node())[1]', 'nvarchar(256)') AS value,
  parameters.value('(params/param[position()=sql:variable("@Index")]/@entityId)[1]', 'nvarchar(256)') AS entityId,
  parameters.value('(params/param[position()=sql:variable("@Index")]/@entityType)[1]', 'bigint') AS entityType,
  parameters.value('(params/param[position()=sql:variable("@Index")]/@localizable)[1]', 'bit') AS localizable
FROM
  audit

我的审计表包含一个看起来像这样的参数 XML 节点:用户名计算机名

我想知道是否有办法摆脱多余的parameters.value('(params/param[position()=sql:variable("@Index")]部分,也许可以作为一个连接来做?

4

1 回答 1

3

您可以使用cross apply.

SELECT
  auditId,
  T.N.value('.', 'nvarchar(256)') AS value,
  T.N.value('@entityId', 'nvarchar(256)') AS entityId,
  T.N.value('@entityType', 'bigint') AS entityType,
  T.N.value('@localizable', 'bit') AS localizable
FROM audit
  CROSS APPLY parameters.nodes('/params/param[sql:variable("@Index")]') AS T(N)
于 2012-08-07T13:38:27.347 回答