mysql存储函数if,MySQL存储函数的正确if子句语法是什么?

I am brand new to MySQL, so I apologize if some of this is relatively elementary.

I'm trying to write a stored function to round a digit to a certain number of significant figures. I have a function which, in theory, should work - I consulted another helpful StackOverflow to nail down the logic (Round to n Significant Figures in SQL). However, numbers between 1 and -1 (excluding 0, because I threw in the edge case catch) fail to round appropriately; for instance, a call of sfround(.00123456789, 5), which should yield 0.0012345, instead yields 0.0012345999712124467.

In an attempt to fix this, I was hoping to truncate digits between 1 and -1 (excluding 0) to the number of trivial zeros PLUS the number of necessary sig figs. In the code below, the IF clause is intended to carry out this truncation. However, I find that whenever I include this IF clause, it results in an error:

'Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE numDigits INT;

SET numDigits = FLOOR(LOG10(ABS(number))); #total d' at line 5).

Even when I experimented with a very simple IF statement, such as

IF (5 = 5) THEN DECLARE dummyvar INT; END IF;

I still got the same error at this line, which leads me to think that I am missing something simple in my MySQL syntax for an IF clause.

DELIMITER $$

USE `vg_summary1`$$

DROP FUNCTION IF EXISTS `sfround`$$

CREATE FUNCTION 'sfround`(number FLOAT, sf INT) RETURNS FLOAT

DETERMINISTIC

BEGIN

IF ((ABS(number) < 1) AND (ABS(number) > 0)) THEN

DECLARE numDigits INT;

SET numDigits = FLOOR(LOG10(ABS(number)));

DECLARE trivialDigits INT;

SET trivialDigits = 0;

DECLARE placeholder FLOAT;

SET placeholder = ABS(number);

WHILE placeholder < 1

BEGIN

placeholder = placeholder * 10;

IF (placeholder < 1) THEN trivialDigits = trivialDigits + 1;

END IF;

END;

DECLARE keptDigits = trivialDigits + sf;

DECLARE special_answer FLOAT;

SET special_answer = ROUND(number, keptDigits-1-FLOOR(LOG10(ABS(number))));

RETURN special_answer;

END IF;

DECLARE r FLOAT;

SET r = CASE WHEN number = 0 THEN 0 ELSE ROUND(number, sf-1-FLOOR(LOG10(ABS(number)))) END;

RETURN r;

END$$

DELIMITER ;

If anyone has any suggestions in terms of syntax errors or more logical ways to fix the original error, I would be very grateful to hear them! Thank you so much!

解决方案DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值