Question : order by in union works in sql 2005 but not in sql 2000

I have a function that works fine in SQL 2005 but not in SQL 2000.

(Select Top 1 case isdate(refdate)
--when 1 then convert(char(10), convert(datetime, refdate,112), 101)
--Else '01/01/1899'
--End   refDate from  
--(SELECT     TOP 1 declinedDate refDate
--FROM          dbo.order_ AS o2  with (nolock)
--WHERE     o2.enterprise_id = '00001' and o2.practice_id = '0001' and  o2.person_id = p.person_id  
--AND (actCode IN ('90718')) AND  
--(declinedDate IS NOT NULL) AND (isdate(declinedDate) = 1) and (declinedDate BETWEEN Convert(char(8), DateAdd(yy,-10, @e),112) AND @e)  
--ORDER BY declinedDate DESC
--union
--SELECT     TOP 1 cancelledDate refDate
--FROM          dbo.order_ AS o2  with (nolock)
--WHERE   o2.enterprise_id = '00001' and o2.practice_id = '0001' and  o2.person_id = p.person_id  
--AND (actCode IN ('90718')) AND  
--(cancelledDate IS NOT NULL) AND (isdate(cancelledDate) = 1) and (cancelledDate BETWEEN Convert(char(8), DateAdd(yy,-10, @e),112) AND @e)  
--ORDER BY cancelledDate DESC
--) TdPast10yearsRefuse
--order by refDate desc )AS TdPast10yearsRefusedDate,  

Answer : order by in union works in sql 2005 but not in sql 2000

OK, I have looked again and I think I understand what the problem is. You refer to p.personID in the subqueries, but they can't resolve "p" because of the extra level of nesting.

I have tried rewriting the UNION query as I believe you were doing more than necessary within the subquery. The problem was being caused by the ORDER BYs in the subquery, but these were unnecessary as you were ordering the dates in the outer query anyway, when you select the TOP 1 value.

So please try the following:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
(
Select Top 1 case isdate(refdate)
when 1 then convert(char(10), convert(datetime, refdate,112), 101)
Else '01/01/1899'
End   refDate from  
(

SELECT     declinedDate refDate
FROM          dbo.order_ AS o2  with (nolock)
WHERE     o2.enterprise_id = '00001' and o2.practice_id = '0001' and  o2.person_id = p.person_id  
AND (actCode IN ('90718')) AND  
(declinedDate IS NOT NULL) AND (isdate(declinedDate) = 1) and (declinedDate BETWEEN Convert(char(8), DateAdd(yy,-10, @e),112) AND @e)  

union

SELECT     cancelledDate refDate
FROM          dbo.order_ AS o2  with (nolock)
WHERE   o2.enterprise_id = '00001' and o2.practice_id = '0001' and  o2.person_id = p.person_id  
AND (actCode IN ('90718')) AND  
(cancelledDate IS NOT NULL) AND (isdate(cancelledDate) = 1) and (cancelledDate BETWEEN Convert(char(8), DateAdd(yy,-10, @e),112) AND @e)  

) TdPast10yearsRefuse

order by refDate desc 
)
AS TdPast10yearsRefusedDate,
Random Solutions  
 
programming4us programming4us