Reputation: 137
I am new to SQL, which is perhaps why I have not been able to locate a solution to the following problem.
I have this database table where all columns are of type VARCHAR(50)
:
And I want to update the values in FullName
so that they are a combination of FirstName
and LastName
, separated by a space.
This is what I would like to end up with:
I do not want to update each row manually.
Upvotes: 0
Views: 5819
Reputation: 84735
I do not want to update each row manually.
I will show you two solutions:
UPDATE
the column with a single statement. It's not really such a hassle:
UPDATE Names
SET FullName = FirstName + ' ' + LastName;
-- or: … = CONCAT(FirstName, ' ', LastName);
You said that all your columns are defined as VARCHAR(50)
, so take note that FirstName + ' ' + LastName
could reach a maximum length of 50 + 1 + 50 = 101 characters. Therefore there is the possibility that FullName
gets truncated: That column will only store the first 50 characters (or less); if there are more, they get thrown away. So you might want to re-define FullName
as VARCHAR(101)
.
Alternatively, turn FullName
into a computed column:
ALTER TABLE Names
DROP COLUMN FullName;
ALTER TABLE Names
ADD FullName AS (FirstName + ' ' + LastName);
This solution has three distinct advantages:
FullName
can never contradict FirstName
and LastName
, because it is automatically derived (at the time of querying it) from them via the specified expression.FullName
; SQL Server figures it out automatically, based on the expression.FullName
will not take up any storage space (unless perhaps when it is included in an index).Upvotes: 1