Let’s look at how to create these columns.
CREATE TABLE [dbo].[Billing](
[BillID] [int] NOT NULL,
[CustomerName] [varchar](50) NOT NULL,
[City] [varchar](50) NULL,
[BillAmount] [float] NULL,
[Tax] AS (([BillAmount]*(10))/(100)),
[TotalAmount] AS ([BillAmount]+([BillAmount]*(10))/(100)))
If you look at above table, the columns Tax and TotalAmount do not have any datatype assosiated but it depends on BillAmount field.
You can also create this by using SQL table editor as shown below
insert into Billing values (1,'ABC','Blr',100)
insert into Billing values (2,'XYZ','NY',200)
The data is inserted and now lets look at our table to see how is our computed columns.
Here we go
What happens if you try to insert data tp computed columns? Let’s try that
insert into Billing (BillID,CustomerName,City,BillAmount,Tax,TotalAmount) values (3,'XYZ','NY',200,10,110)
Msg 271, Level 16, State 1, Line 1
The column "Tax" cannot be modified because it is either a computed column or is the result of a UNION operator.
Msg 271, Level 16, State 1, Line 1
The column "TotalAmount" cannot be modified because it is either a computed column or is the result of a UNION operator.
Error!!!! Yes you need to remember that you cannot insert or update computed column data.
We can also create index on these columns. To create index on these column, you need to specify the column as PERSISTED. For more details on this http://msdn.microsoft.com/en-us/library/ms191250.aspx
We can also add the case statements on the computed columns. Let’s try that
CREATE TABLE MyTable (
number1 INT,
number2 INT,
operatoration CHAR,
total AS CASE operatoration
WHEN '+' THEN number1+number2
WHEN '-' THEN number1-number2
ELSE number1*number2
END
) ;
I am going to insert few records to the table
insert into MyTable values(10,10,'+')
insert into MyTable values(20,10,'-')
insert into MyTable values(20,10,'')
Look at the result now
I found one more interesting article on computed columns. http://www.mssqltips.com/tip.asp?tip=1682 Take a look at it.
Super!!!
ReplyDelete