Hi @Sudip Bhatt ,
As mentioned in forum link provided by Viorel, SQL is always optimized for set based operations so unless you've really huge table and xml document there's no need to do this in batches. Or it is requested only 10 records at a time.
But in your example, there is no need to use loop since there are only 8 records totally.
CROSS APPLY x.nodes('/Root/Orders[position()>= sql:variable("@START ") and position() <= sql:variable("@Eslam Nader ")]')m(n)
Per my understanding, this part is to get the nodes under /Root/Orders at the specified positions. In your example, the positions are only from 1 to 3.
CROSS APPLY n.nodes('OrderDetails') p(q)
CROSS APPLY is used because there are some sub nodes under /Root/Orders/OrderDetails. We need to apply all of them with related OrderIDs.
Why they use CROSS APPLY ? are they using cross apply for join or for any other purpose ?
when to use cross apply. please guide me a scenario when people should use cross apply?
Please refer below one simple example:
DECLARE @XML XML
SET @XML =
'<Input>
<Courses>
<Course>
<Id>27</Id>
<Students>
<Id>19876</Id>
<Id>19878</Id>
</Students>
</Course>
<Course>
<Id>29</Id>
<Students>
<Id>19879</Id>
</Students>
</Course>
</Courses>
</Input>'
-- Method# 1. Simple approach but bit costly | Query Cost: 60%
select t.c.value('../../Id[1]', 'INT') as CourseId,
t.c.value('.', 'INT') as Students
from @XML.nodes('//Input/Courses/Course/Students/Id') as t(c)
-- Method# 2. By using Cross Apply | Query Cost: 40%
select t.c.value('Id[1]', 'INT') as CourseId,
t1.c1.value('.', 'INT') as Students
from @XML.nodes('//Input/Courses/Course') as t(c)
cross apply t.c.nodes('Students/Id') as t1(c1)
The above 2 approaches shows that the second one with CROSS APPLY is much more performant.
– The traditional approach (#1) traverses the nodes (parent/child) and pulls the desired data.
– But the 2nd one with APPLY clause fetches specific node’s entire row and join it with the SELECTed data.
You could refer more details in below links:
Why is CROSS APPLY needed when using XPath queries?
more examples on querying XML …with CROSS APPLY & XQuery – in SQL Server
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Hot issues October--Users always get connection timeout problem when using multi subnet AG via listener. Especially after failover to another subnet