简体   繁体   中英

Computed column not working in SQL Server

I am having a problem with a computed column in a SQL Server 2008 R2 table.

I have the following equation

round((([m1]+[m2]+[m3])/3),0)

in the computed column, and the problem is if you have m1=99 , m2=100 and m3=100 , the result in the computed column should be 100 but what I am getting is 99

Thank you

This is because you get an integer division * , which truncates the result before it gets to ROUND . Evaluate your expression step-by-step to see what's going on:

  • [m1]+[m2]+[m3] is computed, giving you 299
  • The result of [m1]+[m2]+[m3] is integer-divided by 3, giving you 99
  • ROUND(99, 0) gets called, producing 99 .

Here is how you can fix it:

ROUND((cast([m1]+[m2]+[m3] as decimal)/3),0)

Here is a running demo on sqlfiddle, which returns 100.

* I assume that all three of your columns are integer, which would be consistent with the behavior that you observe.

您将不得不将其转换为numeric类型,例如

ROUND((convert(numeric,[m1]+[m2]+[m3])/3),0)

You just need to force SQL Server to use decimal computations instead of assuming all to be INTs. You can do this either by casting (as others have noted) or you can just give it a decimal value for one of the operands. And since you have a hard-coded 3, you can use that one to force to decimal by adding .0 , as in:

round((([m1]+[m2]+[m3])/3.0),0)

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