2

我有两个表 tblUser 和 tblUserPermissions,我需要 tblUser 中每个用户的下面 xml 列 (XmlData) 中的所有权限元素。每个 XmlData 中只有一个 userid 元素。

<User xmlns="">
  <userid>user1</userid>
  <permissions>
    <permission>per1</permission>
    <permission>per2</permission>
    <permission>per3</permission>
  </permissions>
  //Other elements here
</User>

我正在尝试这个查询。

SELECT u.UserID, UserPermissions.perm.value('permission', 'varchar(50)')
FROM tblUserPermissions up WITH (NOLOCK)
INNER JOIN tblUser u ON u.UserID = up.XmlData.value('(/User/userid)[1]', 'int')
cross apply up.XmlData.nodes('/User/permissions') AS UserPermissions (perm)

我怎样才能得到如下所示的结果?

UserID | Permission

user1 | per1
user1 | per2
user1 | per3
user2 | per1
user2 | per2
user3 | per1
user3 | per2
user3 | per3

我收到如下错误。知道在我的查询中需要更改什么吗?感谢您的任何建议!

XQuery [tblVORRequest.RequestXml.value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'
4

1 回答 1

1

Copied from this link

XQuery [value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'

Although there is only one ProductID attribute in the XML instance, the static typing rules require you to explicitly specify that the path expression returns a singleton. Therefore, the additional [1] is specified at the end of the path expression. For more information about static typing, see XQuery and Static Typing.

So to start you off, all you need to do is something like this.

DROP TABLE IF EXISTS #temp
CREATE TABLE #temp (test XML)

INSERT INTO #temp
(
    test
)
VALUES
('<User xmlns="">
  <userid>user1</userid>
  <permissions>
    <permission>per1</permission>
    <permission>per2</permission>
    <permission>per3</permission>
  </permissions>
  //Other elements here
</User>'
    )

SELECT UserPermissions.perm.value('permission[1]', 'varchar(50)')
FROM #temp up
cross apply up.test.nodes('/User/permissions') AS UserPermissions (perm)
于 2020-03-06T23:29:41.207 回答