简体   繁体   中英

SQL Server 2008 - A Calculated Column

I have two tables:

1) Streams

2) Comments

Inside Streams I want to create a Comments columns. I would like to have the Comments column in the Streams table calculated depending on how many Comments there are with the matching StreamId.

Is there an easy way to alter the current Streams table? Thank you.

If you want a "real" column value, look at using a trigger. Another option, though, might be a view that calculates this field -- it should be a really fast calculation if you're counting comments based on a primary key value.

You can use

-- be careful, I do asume lot of field names
create view withCount as
select s.*, c.cant 
from Streams s
left join 
   (select Streams_ID, count(*) as cant from Comments group by Streams_ID) as c
   on s.id = c.Streams_ID

And then

select * from withCount where ... order by ...  // or whatever you want

Do not use triggers to this task, they are more dificult to maintain and to understud

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.

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