Home > Mobile >  adding a column to a sql table from other columns' values
adding a column to a sql table from other columns' values

Time:11-23

I have a sql table like this:

Name  | gender
-----------
John  | Male
Jane  | Female
Alice | Female

I want to add another column to the table that uses the other two columns in its content as follows:

Name  | gender   | Description 
----------------------------
John  | Male     | John is a Male.
Jane  | Female   | Jane is a Female.
Alice | Female   | Alice is a Female.

CodePudding user response:

For MS SQL, you can use the following to generate a computed column. The contents of this column is calculated when it is selected.

ALTER TABLE Foo
ADD Description AS CONCAT(Name, ' is a ', Gender)

If you want the value to be stored on disk (calculated on insert/update), use the following statement

ALTER TABLE Foo
ADD Description AS CONCAT(Name, ' is a ', Gender) PERSISTED

You will generally want to use the first version if the column is selected less often than the other columns are updated. If the data is rarely updated, the second version is generally more appropriate

  •  Tags:  
  • sql
  • Related