SQL Server XML查询无法返回预期结果

时间:2018-10-14 04:47:30

标签: sql-server xml

如您所见,我的表中有这个xml数据:

<ArrayOfFlowDetailParameters xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FlowDetailParameters>
    <DepartmentId>23</DepartmentId>
    <UserId xsi:nil="true" />
    <Username />
    <FullName />
    <ConfirmDateTime xsi:nil="true" />
    <Comment />
    <Status>Pending</Status>
    <AttachmentId />
  </FlowDetailParameters>
  <FlowDetailParameters>
    <DepartmentId>22</DepartmentId>
    <UserId xsi:nil="true" />
    <Username />
    <FullName />
    <ConfirmDateTime xsi:nil="true" />
    <Comment />
    <Status>Pending</Status>
    <AttachmentId />
  </FlowDetailParameters>
  <FlowDetailParameters>
    <DepartmentId>7</DepartmentId>
    <UserId xsi:nil="true" />
    <Username />
    <FullName />
    <ConfirmDateTime xsi:nil="true" />
    <Comment />
    <Status>Pending</Status>
    <AttachmentId />
  </FlowDetailParameters>
  <FlowDetailParameters>
    <DepartmentId>18</DepartmentId>
    <UserId xsi:nil="true" />
    <Username />
    <FullName />
    <ConfirmDateTime xsi:nil="true" />
    <Comment />
    <Status>Pending</Status>
    <AttachmentId />
  </FlowDetailParameters>
</ArrayOfFlowDetailParameters>

当我想用departmentid查找value=22时,我的查询返回0个结果,但是当我搜索value = 23时,它返回1个结果,我认为是因为[1]。

 declare @departmentId nvarchar(max)
 set @departmentId=22
 select  Requests.*   from Requests
 where    
 and (FlowDetailParameter.value('(/ArrayOfFlowDetailParameters/FlowDetailParameters/DepartmentId/text())[1]','bigint') = @departmentId  )

1 个答案:

答案 0 :(得分:2)

听起来好像您正在尝试查询请求列表,其中FlowDetailParameter列的XML包含一个DepartmentId与您的@departmentId变量匹配的记录,对吗?

查询中的[1]指定仅检查每行的FlowDetailParameter XML中首次出现的DepartmentId。除非XML中的 first DepartmentId与您的参数匹配,否则您将不会获得匹配。

相反,您可以使用以下查询使用nodes()方法查找所有FlowDetailParameter与@departmentid变量匹配的请求。

SELECT r.*
FROM @Requests r
WHERE EXISTS (SELECT *
        FROM r.FlowDetailParameter.nodes('/ArrayOfFlowDetailParameters/FlowDetailParameters/DepartmentId') as Parms(DepartmentId)
        WHERE DepartmentId.value('.', 'bigint') = @departmentid)