0

is it possible to have if statements inside an outer apply? I can't seem to get it work.

this is the existing code that works:

select id
from
residentmemberlease rml
left outer join lease l on rml.leaid = l.leaid
outer apply
(SELECT TOP(1) * FROM dbo.RentalHistory a WITH(NOLOCK) WHERE a.resmID = RML.resmID and rthDisplayBit='1'
ORDER BY ISNULL(a.rthMoveOutDate, a.rthMoveInDate) DESC) AS RH

i want it to look like this depending on the value of the codeleasestatuscode(if its 1 or 2):

select id
from
residentmemberlease rml
left outer join lease l on rml.leaid = l.leaid
outer apply
if(select codeleasestatuscode from lease) = '1'
begin
(SELECT TOP(1) * FROM dbo.RentalHistory a WITH(NOLOCK) WHERE a.resmID = RML.resmID and rthDisplayBit='1'
ORDER BY ISNULL(a.rthMoveOutDate, a.rthMoveInDate) DESC) AS RH
end
if(select codeleasestatuscode from lease) = '2'
begin
(SELECT TOP(1) * FROM dbo.RentalHistory a WITH(NOLOCK) WHERE a.resmID = RML.resmID and rthDisplayBit='0'
ORDER BY ISNULL(a.rthMoveOutDate, a.rthMoveInDate) DESC) AS RH
end
edsamiracle
  • 753
  • 3
  • 12
  • 27

1 Answers1

1
       SELECT id --<<-- best to add aliases to all columns
         FROM residentmemberlease rml
    LEFT JOIN lease l ON rml.leaid = l.leaid
  OUTER APPLY
            (SELECT TOP(1) *
               FROM dbo.RentalHistory a WITH(NOLOCK)
              WHERE a.resmID = RML.resmID
                AND (l.codeleasestatuscode = '1' AND a.rthDisplayBit='1' OR
                     l.codeleasestatuscode = '2' AND a.rthDisplayBit='0')
           ORDER BY ISNULL(a.rthMoveOutDate, a.rthMoveInDate) DESC
            ) AS RH;
RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262