I have this table
ID | shares | value | percentage | total|
---------------------
1 2 60 0.222 270
2 4 120 0.444 270
3 3 90 0.333 270
I want to enter id and shares the remain column should be calculated automaticly where value is shares*30
and percentage is value divide total (value/total) and total is sum of all column value
I try computed columns but it does not work in total column
How can I do that?
You can declare some columns as Computed columns however the Total
column is different, we need to create some Trigger to update that column:
create table mytable(
ID int primary key,
Shares int,
Value as Shares * 30,
Percentage as cast(cast(Shares * 30 as decimal)*100/Total as decimal(4,2)),
Total int)
go
--create the trigger to update the Total column when any change is made on Shares
create trigger mytrigger on mytable
for update, insert
as
if update(Shares)
update mytable
set Total = (select sum(Value) from mytable)
Insert some data to test:
insert into mytable(ID,Shares) values(1,2)
insert into mytable(ID,Shares) values(2,4)
insert into mytable(ID,Shares) values(3,3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.