DECLARE @first varchar(10) = 'First' DECLARE @middle varchar(10) = '' DECLARE @last varchar(10) = 'Last' LTRIM(RTRIM( @first + ISNULL(NULLIF(' '+LTRIM(RTRIM(@middle)),' '),'') + ISNULL(NULLIF(' '+LTRIM(RTRIM(@last)),' '),'') ))
WHY IT WORKS
Fields are reduced to an empty string if NULL or spaces using the LTRIM, RTRIM, and ISNULL functions.
LTRIM(RTRIM(ISNULL(@middle,''))) -- Result is a trimmed non-null string value.
This value is prefixed with a single space, and then compared to a single space using the NULLIF function. If it is equal, the result is NULL. If not equal, then the value is used.
NULLIF(' '+'',' ') -- this would return NULL NULLIF(' '+'Smith',' ') -- this would return ' Smith'
Finally, ISNULL () is used to convert the NULL passed to NULLIF to an empty string.
ISNULL(NULL,'') -- this would return '' ISNULL(' Smith','') -- this would return ' Smith'
source share