RSS

SQL : CASE IN COMPUTED COLUMNS

29 Apr

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

 

 

 

Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: