Wednesday, 15 June 2016

SQL : CASE IN COMPUTED COLUMNS

This time i come up with very basic but important concept of Computed columns in SQL.
Let's start with new fresh example that will expedite your understanding.
Step 1 : Create new Customer Table
CREATE TABLE CUSTOMER(Customer_Id INT, Customer_Name Varchar(100))
Step 2: Insert few records
INSERT INTO CUSTOMER VALUES(1,'A'),VALUES(2,'B'),VALUES(3,'C')
Step 3 : Execute below query, you will get all the records
SELECT * FROM CUSTOMER
Step 4 : Now, add new computed column with case statement in definition as below
ALTER TABLE CUSTOMER
ADD ADDRESS AS CAST (CAST WHEN Customer_ID=1 THEN 2 ELSE 3 END AS VARCHAR(100))
Step 5 : Execute step 3 query again, you will get new column named Address with values as per condition.

Author : Feel free to ask if have any query


1 comment:

SQLGeek said...

Awesome :)