Saturday, February 25, 2012

Conditional Computed Columns

I have a table with three columns namely "A","B", anc "C".
Column C is a computed column which is derived from Column "B".Something like " IF B < 100 then C=B*0.5 ELSE C=B*0.25"
How do I make it possible in Sql Server?Is there a way of doing this?
Thanks!Use the case when statement. So for your example:

select a,b, case when b < 100 then b*.5 else b*.25 end as c
from ...|||To make ColC a computed column
drop table test
go
create table test
(
colA int,
colB int,
colC as case when ColB < 100 then ColB*0.5 else ColB*0.25 end
)

go
insert test (ColA,ColB) values (100,80)
insert test (ColA,ColB) values (100,100)
go
select *
from test

Output

colA colB colC
---- ---- -----
100 80 40.00
100 100 25.00|||It's working now|||humm.. This really new for me.

Would this create a Trigger??

Originally posted by achorozy
To make ColC a computed column
drop table test
go
create table test
(
colA int,
colB int,
colC as case when ColB < 100 then ColB*0.5 else ColB*0.25 end
)

go
insert test (ColA,ColB) values (100,80)
insert test (ColA,ColB) values (100,100)
go
select *
from test

Output

colA colB colC
---- ---- -----
100 80 40.00
100 100 25.00|||No it doesn't create a trigger, however it does store the computed information in syscomments

No comments:

Post a Comment