As I have mentioned in my question title below Mysql function returns null always :
CREATE DEFINER=`root`@`localhost` FUNCTION `nextCode`(tbl_name VARCHAR(30), prv_code VARCHAR(30)) RETURNS varchar(30) CHARSET utf8
READS SQL DATA
BEGIN
DECLARE nxtCode VARCHAR(30);
SELECT ds.prefix, ds.suffix, ds.is_used, ds.next_number, CHAR_LENGTH(ds.pattern)
INTO @prefix, @suffix, @isUsed, @nxtNum, @pLength
FROM ths_inventory.doc_sequnce ds WHERE ds.`table_name` = tbl_name;
SET nxtCode = CONCAT(@prefix, LPAD((CASE WHEN @isUsed
THEN
(ExtractNumber(prv_code) + 1)
ELSE
(@nxtNum)
END
), @pLength,'0'), @suffix);
RETURN nxtCode;
END
But once I change the below line :
CONCAT(@prefix, LPAD((CASE WHEN @isUsed
THEN
(ExtractNumber(prv_code) + 1)
ELSE
(@nxtNum)
END
), @pLength,'0'), @suffix)
To some static values like below :
CONCAT('PR', LPAD((CASE WHEN true
THEN
(ExtractNumber(prv_code) + 1)
ELSE
(5)
END
), 6,'0'), '')
function start returning values accordingly.
Here is how I call my function :
nextCode('item','PR000002');
UPDATE:
I defined this function to get the next possible code for Item table :
According to my requirement the next possible code should be PR000000005
.
But instead of getting it, I always get empty result .
SELECT nextCode('item',(SELECT `code` FROM item ORDER BY id DESC LIMIT 1)) AS next_code;
Any help would be appreciable.
Run a query that uses the function, and then...
SELECT @prefix, @suffix, @isUsed, @nxtNum, @pLength;
...to inspect the values. The @
prefix means these are user-defined variables, so they have session scope, not program scope, and will still hold their values after the funcfion executes.
This should help pinpoint your problem.
But, you have two other problems you will need to solve after that.
SELECT ... INTO
does not set the target variables when no row matches the query, so once you fix your issue, you will get very wrong results if you pass in arguments that don't match anything.
To resolve this, the function needs to set all these variables to null before the SELECT ... INTO
query.
SET @prefix = NULL, @suffix = NULL, @isUsed = NULL, @nxtNum = NULL, @pLength = NULL;
See https://dba.stackexchange.com/a/35207/11651.
Also, your function does not handle concurrency, so two threads trying to find the "next" value for the same table, concurrently, will produce the same answer, so you will need to insure that your code handles this correctly with unique constraints and transactions or other appropriate locks.