sql - 将商或更长的表达式分配给局部(实)变量 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
- 如果我注释掉前 2 个
SET
语句并只使用我得到的第三个语句0
- 如果我使用 all
3
,我会得到0
- 如果
CAST(@HitRate As DECIMAL(9,2))
我得到0
解决方案
演示您需要将 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
推荐阅读
- javascript - 使用 Jasmine 测试遗留的全局脚本文件
- python - 当我在单独的类上运行 Tensorflow 模型时,它以元组的形式出现
- c# - 请求异常过多是否影响其他用户
- pandas - 将日期格式从“20200613”更改为“2020-06-13”
- mysql - 如何仅保留数据字段的最高值行并删除其他行
- typescript - Angular9中代码的执行顺序应该是什么?
- dll - 在 Windows 10 上运行简单的汇编程序时出现问题
- pandas - 将多列分解成行,维护单个列表元素顺序熊猫
- javascript - lerna 独立版本控制 + Github Actions 的问题
- excel - Excel:带有通配符的 SUMPRODUCT 与确切的单元格内容不匹配