This is my table: enter image description here in my table i should use
SELECT
Title+' '+FirstName+' '+MiddleName+' '+LastName as FullName
from employees
Where BusinessEntityID IN (1,2,4)
But as a result i get only the middle row because that is the only one that does not contain NULL value. The concat()
works fine but i was wondering if there is a solution also with coalesce
function for this problem.
Can you please help?
2条答案
按热度按时间fcy6dtqo1#
On SQL Server 2017 or later, the
CONCAT_WS
function provides a nice way of doing this:CONCAT_WS()
will ignore null parameters.4ioopgfo2#
So the problem you have is (naive) concatenation of nulls makes the whole string null. The question of whether to just use
concat
/concat_ws
orcoalesce
/isnull
comes down to whether or not you want null values to be interpreted as an empty string, or if you want to substitute a different value in there.If all you want is an empty string, a variant of
concat
is the simplest way to go. You would typically want/need to reach forcoalesce/isnull
if you wanted to replace the value with something other than an empty string (I've given a few examples like if for some reason you want to give everyone a default middle name ofx
. Ridiculous, I know.). That's not to say you cant do it that way, it's just easier withconcat
.Here are a couple different ways you could look at your problem. Please not however, that if your middle name is null, the fact that you're doing
' ' + isnull(Middle, '') + ' '
or you're usingconcat
rather thanconcat_ws
, that means that if your middle name is null, you're going to have two spaces in your string, not one. You'll need to take that into consideration when you handle your nulls.