如何使用T-SQL和XQuery从XML中进行选择

时间:2015-08-08 14:00:27

标签: sql sql-server xml sql-server-2008

我尝试用sql进行xml解析。

我尝试从Skill标签中进行选择,但只提前一行显示请提前帮助

我的XML格式如下

declare @UserDetails XML
set @UserDetails='
<Registration>
  <objUserBasicData>
    <User_Id>0</User_Id>
    <UserType>0</UserType>
    <UserName>test@test6.com</UserName>
    <Password>user123</Password>
    <LastLoginTime>2015-08-08T18:22:53.9953905+05:30</LastLoginTime>
    <IsActive>true</IsActive>
    <CreatedBy>0</CreatedBy>
    <CreatedOn>2015-08-08T18:22:53.9953905+05:30</CreatedOn>
    <ModifiedBy>0</ModifiedBy>
    <ModifiedOn>2015-08-08T18:22:53.9953905+05:30</ModifiedOn>
  </objUserBasicData>
  <objUserDetails>
    <UserDetails_Id>0</UserDetails_Id>
    <User_Id>0</User_Id>
    <FirstName>test</FirstName>
    <MiddleName />
    <LastName>test</LastName>
    <ContactName />
    <Email>test@test6.com</Email>
    <AlternativeEmail />
    <RegisterDate>2015-08-08T18:22:54.0164133+05:30</RegisterDate>
    <Address1 />
    <Address2 />
    <Country>0</Country>
    <State>0</State>
    <City>1</City>
    <PostCode />
    <HomePhone />
    <Mobile>1231231232</Mobile>
    <Fax />
    <Marketing>false</Marketing>
    <HasCV>false</HasCV>
    <CVName>564195d7-4dfa-42e0-abc1-ef611be588a2.doc</CVName>
    <HasJobsByEmail>false</HasJobsByEmail>
    <Website />
    <CreatedBy>0</CreatedBy>
    <CreatedOn>2015-08-08T18:22:54.0164133+05:30</CreatedOn>
    <ModifiedBy>0</ModifiedBy>
    <ModifiedOn>2015-08-08T18:22:54.0164133+05:30</ModifiedOn>
    <DateOfBirth>2015-08-10T00:00:00</DateOfBirth>
    <CurrentJobTitle>test</CurrentJobTitle>
    <Career_Id>2</Career_Id>
    <PrefferedLocation>1</PrefferedLocation>
    <ExperienceInYears>5</ExperienceInYears>
    <Gender>1</Gender>
  </objUserDetails>
  <Skills>
    <int>2</int>
    <int>1</int>
  </Skills>
</Registration>'

我用查询选择数据是

SELECT
    TEMPTABLE.UserData.value('int[1]','int') AS int
FROM
    @UserDetails.nodes('/Registration/Skills')AS TEMPTABLE(UserData)

结果为

int
-----------
2

缺少1

我用过

    DECLARE @XMLDocPointer INT    
    EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT, @UserDetails    


   SELECT *
   FROM OPENXML(@XMLDocPointer,'/Registration/Skills',3)    
   WITH  ([int] INT)     

   EXEC sp_xml_removedocument @XMLDocPointer  

同样结果是相同的

int
-----------
2

我需要做什么才能得到结果

int
-----------
2
1

1 个答案:

答案 0 :(得分:3)

这是因为你只是通过说int来选择第一个int[1]元素。请尝试这种方式:

SELECT TEMPTABLE.UserData.value('.','int') AS int
FROM
    @UserDetails.nodes('/Registration/Skills/int')AS TEMPTABLE(UserData)

<强> Sqlfiddle Demo

输出

| int |
|-----|
|   2 |
|   1 |