简体   繁体   English

如何在创建表的约束或列级别内使用选择

[英]How to use select within constraint or column level in create table

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 我想输入id并分享剩余的列,应自动计算其中value为shares*30 ,百分比为value除以total(值/总计),total为所有列值的总和

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: 您可以将某些列声明为“计算列”,但是“ Total列有所不同,我们需要创建一些触发器来更新该列:

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)

Demo . 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM