I have a little problem here I can't seem to work out. Small query out putting to XML as the results are insterted into a table on an email, problem is I can't seem to work out how to 'order by' the calculated field... Any ideas greatly recieved. Thanks Dave.
SET @xml = CAST((
SELECT
Emp_Name AS 'td','',
Emp_Job AS 'td','',
CAST(dbo.CalcDistance(G1.Lon, G1.Lat) AS DECIMAL(3,2)) AS 'td','',
Emp_Transport AS 'td',''
FROM Employees
FULL OUTER JOIN Geolocation G1
ON G1.Postcode = REPLACE (Emp_Postcode, RIGHT(Teachers.T_Postcode, 3), '')
WHERE Emp_Status = 'Live'
--ORDER BY Distance
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
Easiest is to repeat the entire expression in the ORDER BY:
SELECT
Emp_Name AS 'td','',
Emp_Job AS 'td','',
CAST(dbo.CalcDistance(G1.Lon, G1.Lat) AS DECIMAL(3,2)) AS 'td','',
Emp_Transport AS 'td',''
FROM Employees
FULL OUTER JOIN Geolocation G1
ON G1.Postcode = REPLACE (Emp_Postcode, RIGHT(Teachers.T_Postcode, 3), '')
WHERE Emp_Status = 'Live'
**ORDER BY CAST(dbo.CalcDistance(G1.Lon, G1.Lat) AS DECIMAL(3,2))**
Cross Apply the calculation, then you can reference it both in the results and the Order By clause:
SELECT
Emp_Name AS 'td','',
Emp_Job AS 'td','',
X.Distance AS 'td','',
Emp_Transport AS 'td',''
FROM Employees
FULL OUTER JOIN Geolocation G1
ON G1.Postcode = REPLACE (Emp_Postcode, RIGHT(Teachers.T_Postcode, 3), '')
CROSS APPLY
(
Select CAST(dbo.CalcDistance(G1.Lon, G1.Lat) AS DECIMAL(3,2)) As Distance
) X
WHERE Emp_Status = 'Live'
ORDER BY X.Distance
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))