Share via


정렬 포함 XQuery

적용 대상:SQL Server

관계형 데이터베이스에는 시퀀스 개념이 없습니다. 예를 들어 "데이터베이스에서 첫 번째 고객 가져오기"와 같은 요청을 수행할 수 없습니다. 그러나 XML 문서를 쿼리하고 첫 번째 <Customer> 요소를 검색할 수 있습니다. 그런 다음 항상 동일한 고객을 검색합니다.

이 항목에서는 문서에 노드가 표시되는 순서에 따라 쿼리를 보여 줍니다.

A. 제품의 두 번째 작업 센터 위치에서 제조 단계 검색

특정 제품 모델의 경우 다음 쿼리는 제조 프로세스의 작업 센터 위치 시퀀스에서 두 번째 작업 센터 위치에서 제조 단계를 검색합니다.

SELECT Instructions.query('  
     declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";  
    <ManuStep ProdModelID = "{sql:column("Production.ProductModel.ProductModelID")}"  
                ProductModelName = "{ sql:column("Production.ProductModel.Name") }" >  
     <Location>  
       { (//AWMI:root/AWMI:Location)[2]/@* }  
       <Steps>  
         { for $s in (//AWMI:root/AWMI:Location)[2]//AWMI:step  
           return  
              <Step>  
               { string($s) }  
              </Step>  
         }  
        </Steps>  
      </Location>  
     </ManuStep>  
') as Result  
FROM Production.ProductModel  
WHERE ProductModelID=7  

이전 쿼리의 다음 사항에 유의하세요.

  • 중괄호의 식은 평가 결과로 바뀝니다. 자세한 내용은 XML 생성(XQuery)을 참조하세요.

  • @* 는 두 번째 작업 센터 위치의 모든 특성을 검색합니다.

  • FLWOR 반복(FOR ... RETURN)은 두 번째 작업 센터 위치의 모든 <step> 자식 요소를 검색합니다.

  • sql:column() 함수(XQuery)에는 생성되는 XML의 관계형 값이 포함됩니다.

결과는 다음과 같습니다.

<ManuStep ProdModelID="7" ProductModelName="HL Touring Frame">  
  <Location LocationID="20" SetupHours="0.15"   
              MachineHours="2"  LaborHours="1.75" LotSize="1">  
  <Steps>  
   <Step>Assemble all frame components following blueprint 1299.</Step>  
     ...  
  </Steps>  
 </Location>  
</ManuStep>    

이전 쿼리에서는 단지 텍스트 노드만 검색합니다. 전체 <step> 요소를 대신 반환하려면 쿼리에서 string() 함수를 제거합니다.

B. 제품 제조의 두 번째 작업 센터 위치에서 사용되는 모든 재료 및 도구 찾기

특정 제품 모델의 경우 다음 쿼리는 제조 프로세스의 작업 센터 위치 시퀀스에서 두 번째 작업 센터 위치에서 사용되는 도구와 자료를 검색합니다.

SELECT Instructions.query('  
    declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";  
   <Location>  
      { (//AWMI:root/AWMI:Location)[1]/@* }  
       <Tools>  
         { for $s in (//AWMI:root/AWMI:Location)[1]//AWMI:step//AWMI:tool  
           return  
              <Tool>  
                { string($s) }  
              </Tool>  
          }  
        </Tools>  
        <Materials>  
            { for $s in (//AWMI:root/AWMI:Location)[1]//AWMI:step//AWMI:material  
              return  
                 <Material>  
                    { string($s) }  
                 </Material>  
             }  
         </Materials>  
  </Location>  
') as Result  
FROM Production.ProductModel  
where ProductModelID=7  

이전 쿼리의 다음 사항에 유의하세요.

  • 쿼리는 Location> 요소를 생성<하고 데이터베이스에서 해당 특성 값을 검색합니다.

  • 여기에서는 두 개의 FLWOR (for...return) 반복문이 사용되며, 이 중 하나는 도구를 검색하고 다른 하나는 사용된 자재를 검색합니다.

결과는 다음과 같습니다.

<Location LocationID="10" SetupHours=".5"   
          MachineHours="3" LaborHours="2.5" LotSize="100">  
  <Tools>  
    <Tool>T-85A framing tool</Tool>  
    <Tool>Trim Jig TJ-26</Tool>  
    <Tool>router with a carbide tip 15</Tool>  
    <Tool>Forming Tool FT-15</Tool>  
  </Tools>  
  <Materials>  
    <Material>aluminum sheet MS-2341</Material>  
  </Materials>  
</Location>  

C. 제품 카탈로그에서 처음 두 제품 기능 설명 검색

특정 제품 모델의 경우 쿼리는 제품 모델 카탈로그의 요소에서 <Features> 처음 두 가지 기능 설명을 검색합니다.

SELECT CatalogDescription.query('  
     declare namespace p1="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription";  
     <ProductModel ProductModelID= "{ data( (/p1:ProductDescription/@ProductModelID)[1] ) }"  
                   ProductModelName = "{ data( (/p1:ProductDescription/@ProductModelName)[1] ) }" >  
       {  
         for $F in /p1:ProductDescription/p1:Features  
         return   
           $F/*[position() <= 2]   
       }  
     </ProductModel>  
      ') as x  
FROM Production.ProductModel  
where ProductModelID=19  

이전 쿼리의 다음 사항에 유의하세요.

쿼리 본문은 ProductModelID 및 ProductModelName 특성이 있는 요소를 포함하는 <ProductModel> XML을 생성합니다.

  • 쿼리는 FOR ...를 사용합니다. 제품 모델 기능 설명을 검색하는 RETURN 루프입니다. position() 함수는 처음 두 기능을 검색하는 데 사용됩니다.

결과는 다음과 같습니다.

<ProductModel ProductModelID="19" ProductModelName="Mountain 100">  
 <p1:Warranty   
  xmlns:p1="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain">  
  <p1:WarrantyPeriod>3 year</p1:WarrantyPeriod>  
  <p1:Description>parts and labor</p1:Description>  
 </p1:Warranty>  
 <p2:Maintenance   
  xmlns:p2="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelWarrAndMain">  
  <p2:NoOfYears>10</p2:NoOfYears>  
  <p2:Description>maintenance contact available through your dealer   
            or any AdventureWorks retail store.  
  </p2:Description>  
 </p2:Maintenance>  
</ProductModel>   

D. 제품 제조 프로세스의 첫 번째 작업 센터 위치에서 사용되는 처음 두 도구를 찾습니다.

제품 모델의 경우 이 쿼리는 제조 프로세스의 작업 센터 위치 시퀀스에서 첫 번째 작업 센터 위치에서 사용되는 처음 두 도구를 반환합니다. 쿼리는 Production.ProductModel 테이블의 지침 열에 저장된 제조 지침에 대해 지정됩니다.

SELECT Instructions.query('  
     declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";  
   for $Inst in (//AWMI:root/AWMI:Location)[1]  
   return   
     <Location>  
       { $Inst/@* }  
       <Tools>  
         { for $s in ($Inst//AWMI:step//AWMI:tool)[position() <= 2]  
           return  
             <Tool>  
               { string($s) }  
             </Tool>  
         }  
       </Tools>  
     </Location>  
') as Result  
FROM Production.ProductModel  
where ProductModelID=7  

결과는 다음과 같습니다.

<Location LocationID="10" SetupHours=".5"   
            MachineHours="3" LaborHours="2.5" LotSize="100">  
  <Tools>  
    <Tool>T-85A framing tool</Tool>  
    <Tool>Trim Jig TJ-26</Tool>  
  </Tools>  
</Location>   

E. 특정 제품 제조의 첫 번째 작업 센터 위치에서 마지막 두 제조 단계를 찾습니다.

쿼리는 마지막() 함수를 사용하여 마지막 두 제조 단계를 검색합니다.

SELECT Instructions.query('   
declare namespace AWMI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions";  
  <LastTwoManuSteps>  
   <Last-1Step>   
     { (/AWMI:root/AWMI:Location)[1]/AWMI:step[(last()-1)]/text() }  
   </Last-1Step>  
   <LastStep>   
     { (/AWMI:root/AWMI:Location)[1]/AWMI:step[last()]/text() }  
   </LastStep>  
  </LastTwoManuSteps>') as Result  
FROM Production.ProductModel  
where ProductModelID=7  

결과는 다음과 같습니다.

<LastTwoManuSteps>  
   <Last-1Step>When finished, inspect the forms for defects per   
               Inspection Specification .</Last-1Step>  
   <LastStep>Remove the frames from the tool and place them in the   
             Completed or Rejected bin as appropriate.</LastStep>  
</LastTwoManuSteps>  

참고 항목

XML 데이터(SQL Server)
XQuery 언어 참조(SQL Server)
XML 생성(XQuery)