首页 > 解决方案 > 将商或更长的表达式分配给局部(实)变量 T SQL

问题描述

很高兴知道这一点,我肯定是在犯错误......

如果我DECLARE是一个实数(或十进制)局部变量,我不能分配(SET)表达式的值?我必须先设置一个值,然后逐步执行表达式。如果我尝试一次“做数学”,我会得到0.

所以,这行得通..

DECLARE @HitRate real
SET @HitRate = 805499
SET @HitRate = (@HitRate / 847125) * 100
--SET @HitRate = (805499 / 847125) * 100  --But this does not work?
SELECT @HitRate

标签: sqlsql-servertsql

解决方案


演示您需要将 805499 设置为 805499.00,这意味着 int 浮动

DECLARE @HitRate real
SET @HitRate = 805499
SET @HitRate = (@HitRate / 847125) * 100
SET @HitRate = (805499.00 / 847125) * 100.00  --this will  work now
SELECT @HitRate

你得到 0 是因为 805499/847125 = 0.95 但 db engine 返回 0 因为它需要一个整数值,这就是为什么当你将 100 乘以 0 时它也会输出 0

或者你可以明确地cast喜欢下面

SET @HitRate = (cast( 805499 as float) / 847125) * 100 

它也会回来 95.0862


推荐阅读