Scenario:
You are working as SQL Server Developer for one of the Law Firm. You have created a dbo.Customer table by using below definitionCREATE TABLE Customer ( CustomerId INT Identity(1, 1) ,FirstName VARCHAR(50) ,LastName VARCHAR(50) ,Age SMALLINT ,PhoneNumber CHAR(9) ,DOB DATE ,Gender CHAR(1) )
You need to have Full Name that should consist of First Name and Last Name. You don't want to save the duplicate data into table by adding new column for Full Name. What are your options?
Also depending upon Age, We would like to Add New Column call IsSenior and mark it 1 if above 65 else 0.
Solution:
SQL Server provide us Computed Column, that is virtual column and it does not store data unless it is marked as Persisted. That means that we can create computed column (Full name) that will use First Name and Last Name data. By creating Computed Column we don't have to save duplicate data for full Name column.Let's go ahead and create Computed Columns Full Name and IsSenior depending upon our criteria.
CREATE TABLE Customer ( CustomerId INT Identity(1, 1) ,FirstName VARCHAR(50) ,LastName VARCHAR(50) ,Age SMALLINT ,PhoneNumber CHAR(9) ,DOB DATE ,Gender CHAR(1) ,FullName AS FirstName + ' ' + LastName ,IsSenior AS CASE WHEN Age > 65 THEN 1 ELSE 0 END )We concatenated First Name and Last Name for Full Name and wrote the Case Statement for IsSenior Computer Column. Let's go ahead and insert couple of records.
insert into dbo.Customer(FirstName,LastName,Age) Values('Aamir','Shahzad',66), ('Raza','M',44)
Noticed I have not inserted anything for FullName and IsSenior Columns. The values for these columns will be calculated when we will select the data.
How to add Computed Columns in SQL Server Table - T-SQL Tutorial
If you need to add Computed Column to exiting Table, you can use below syntax
Alter Table SchemaName.TableName
Add ColumnName AS Logic( such as FistName +''+LastName)
Let's say if we want to add FullName Computer Column to Customer table, we can use below script.
Alter table dbo.Customer Add FullName AS FirstName+' '+LastName
Drop Computed Column from SQL Server Table:
The syntax for dropping Computed or normal column is same.
Alter Table SchemaName.TableName
drop Column ColumnName
Let's say if we want to drop FullName computed column from dbo.Customer Table. We can use below script.
Alter table dbo.Customer drop column FullName
No comments:
Post a Comment