mysql - 存储过程将 int 转换为十进制

标签 mysql stored-procedures return-value

我正在编写一个存储过程来返回一些统计信息。我有两个不同的表,一个包含系统投入使用后收集的统计数据,另一个包含自使用以来的统计数据

我的程序如下:

CREATE PROCEDURE getStats(IN uID INT, IN since_date DateTime)
BEGIN
  DECLARE rowcount int;
  select klubid from core_medlemmer where id = uID into @klubid;
  select create_date from core_klub where id = @klubid into @create_date;

  if since_date < @create_date then
    -- select from historic and current
    select sum(attendance) from core_historic_modestatistik where medlemsid = uID into @historic_total;
    SELECT @historic_total + count(*) as total_attendance from core_fremmode where medlemsid= uID and dato >= since_date;
  else 
    -- select only current
    SELECT count(*) as total_attendance from core_fremmode where medlemsid= uID and dato >= since_date;
  end if;
END //
DELIMITER ;

使用 select sum(attendance) from core_historic_modestatistik where medlemsid = uID 执行此存储过程看起来正确:

+-----------------+
| sum(attendance) |
+-----------------+
|             655 | 
+-----------------+

但加法似乎将其转换为实数:

+------------------------------------+
| total_attendance                   |
+------------------------------------+
| 656.000000000000000000000000000000 |
+------------------------------------+

我要求和的列是一个 int,并且 count() 函数应该只能返回 INT,因此有关为什么会发生这种情况的任何提示,以及如何最好地解决这个问题将不胜感激。

最佳答案

我发现在存储过程中强制选择类型的最佳方法是 INSERT...SELECT 到临时表(在过程中使用所需类型创建),然后从中进行选择。您可以尝试CAST(x AS SIGNED),但是您无法控制BIGINT、INT等..

编辑:CAST 在存储过程/查询中通常很好;但是,当您需要更多定义的类型来与 API 调用交互时,例如 GetInt32(fieldnum),临时表方法会非常有用。

关于mysql - 存储过程将 int 转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48914748/

相关文章:

php - 允许的内存大小为 134217728 字节耗尽(尝试分配 42 字节)

php - PDO 新手,努力将结果的 id 放入变量中

php - 自动在数据库表中创建条目(php/mysql)

SQL Server IF NOT EXISTS 用法?

mysql - 没有函数和过程可以做到这一点吗?

c++ - 'List::operator=': 必须返回一个值

go - 在 Golang 中正常函数返回 'ok' 之类的映射

php - 将列表值作为变量发布

oracle - 使用 pl/sql 过程记录错误并处理异常

swift - 返回从 HTTP 请求中检索到的值的方法