Reputation: 13
Did quite a bit of searching and found many examples of how to configure a computed column but could find nothing on this.
I have 2 columns - LastName and FirstName. In some instances one or the other of these columns is NULL
.
My computed column syntax is
((CONVERT([varchar](max),[LastName],(0))+', ')+CONVERT([varchar](max),[FirstName],(0))
Which works great if both columns have data.
However, when one or the other is NULL
the computed column is populated with NULL
.
Upvotes: 1
Views: 36
Reputation: 9943
Concatenating strings with null
will result in null
, see the remarks section here for more detail
You should handle the nulls as appropriate
CREATE TABLE People
(
Firstname VARCHAR(50),
Lastname VARCHAR(50) NOT NULL,
Fullname AS CAST(CASE WHEN Firstname IS NOT NULL
THEN Lastname + ', ' + Firstname
ELSE Lastname END AS VARCHAR(105))
)
Arguably though, can it be a full name without both a first and last name, perhaps here null
makes sense
Edit: if either Firstname
or Lastname
can be null then you'd want to do something like this instead
CASE WHEN Firstname IS NULL OR Lastname IS NULL THEN COALESCE(Firstname, Lastname)
ELSE Lastname + ', ' + Firstname END
Upvotes: 1