Any code with that many open and close brackets is going to be a nightmare to untangle!
First thing you need to do is simplify your conditions ...
For example
if @OType != 'LTD' or 'PLC'
could be better expressed as
if @OType NOT IN ('LTD','PLC')
Next
@CDate
can
only be
BETWEEN T2.DateAdded AND T2.DateRemoved
or
not - there are no other options. So you can simplify
If @LNumber = T2.Number
if @OType !=
if T2.CTPS = 1
if @CDate BETWEEN T2.DateAdded AND T2.DateRemoved
return "Yes"
if @LNumber = T2.Number
if @OType NOT IN (
if T2.CTPS = 1
if @CDate NOT BETWEEN T2.DateAdded AND T2.DateRemoved
return "No"
To become
If @LNumber = T2.Number
if @OType !=
if T2.CTPS = 1
if @CDate BETWEEN T2.DateAdded AND T2.DateRemoved
return "Yes" else return "No"
Finally, consider building a "Truth Table" (google it if you're not sure) to look at all of your conditions - sometimes you will spot patterns that make the whole thing simpler and easier to read. You may also spot the conditions you haven't catered for ... such as what to do if
@CDate == T1.Date
and the fact you have a
return
which returns nothing at all.
Give that a go and hopefully you'll be able to solve the problem yourself