May 27, 2024
SQLYoga: Adding Computed Columns in SQL Server
A scenario that required me to add one calculated column came up today. When a column is computed, it can be used in queries just like any other column and allows us to change one or more columns from the same table.
Create One Table: tblTestComputed CREATE TABLE tblTestComputed( FirstName VARCHAR(50), LastName VARCHAR(50) )
INSERT INTO tblTestComputed(FirstName, LastName) SELECT 'Tejas', 'Shah' UNION SELECT 'Hiral', 'Shah'
SELECT * FROM tblTestComputed
Output
- I now require the display name to be something like “Shah Tejas” or “Shah Hiral”. I therefore created a new column and named it:
ALTER TABLE tblTestComputed ADD FullName AS (ISNULL(LastName,'') + ' ' + ISNULL(FirstName,''))
SELECT * FROM tblTestComputed
Output
- Add a computed column called FullName to your table to combine first and last names, updating automatically.
- However, it’s essential to note that computed columns cannot be updated directly since they are derived from other columns.
- For a deeper dive into computed columns and their applications, click here to learn more. Join SQLYoga to boost your SQL and database skills with tutorials, articles, and expert tips. Be part of a growing community of learners.