I have this piece of code written by someone that helped me and it took me a while to figure out the code being new to SQL/TSQL, but I don't understand how to interpret the logic of the CROSS APPLY calling the other one in the example below .
I know that a CROSS APPLY is a process to be applied to each row from the left table but I don't see how this CROSS APPLY calls another one and applies this calculation to each row.. ?
I would like to understand how to interpret the logic of this double CROSS APPLY statement, as in understanding how it behaves against the table that will be returned by this SELECT statement, as well as how come a CROSS APPLY can call another one and how to understand what it does.
SELECT
P.Name,
CAST(DT.LocalTime AS CHAR(5)) AS LocalTime,
DT.LocalWeekdayName,
CASE WHEN O.IsOpen = 1 THEN 'Open' ELSE 'Closed' END AS OpenOrClosed
FROM Place AS P
JOIN Timezone TZ ON TZ.TimezoneId = P.TimezoneId
CROSS APPLY (
SELECT
@UtcNow AT TIME ZONE 'UTC' AT TIME ZONE TZ.Name AS LocalDateTime
) AS LT
-- THAT MEANS APPLY THE LOCAL WEEKDAY AND LOCAL TIME TO EACH ROW OF THE PLACE TABLE ?
CROSS APPLY (
SELECT
-- It's using LT's CROSS APPLY, can a CROSS APPLY mention another CROSS APPLY ?
DATENAME(weekday, LT.LocalDateTime) AS LocalWeekdayName,
CAST(LT.LocalDateTime AS TIME) AS LocalTime
) AS DT
JOIN DayOfTheWeek DOW ON DOW.DayName = DT.LocalWeekdayName
I have tried to look up for an answer online because I haven't seen anything like this in my TSQL book but I couldn't find anything.