Do something like this:
WebElement thingie = driver.findElement(By.xpath("//tr[contains(@id,'" + variable + "')]/td[5]"))
if (thingie.findElements(By.tagName("span")).size() != 0) {
thingie.findElement(By.tagName("span")).click();
} else {
thingie.click();
}
Make a starting point WebElement.
Check to see if the <span> exists. If so, click on the span version, otherwise, click the td directly.