Changed SQL function to use a multiple cond statement