Skip to content

Commit

Permalink
Added function lastIndexOf
Browse files Browse the repository at this point in the history
  • Loading branch information
bstjean committed Jan 27, 2020
1 parent c8bd9ec commit 82563b4
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
63 changes: 63 additions & 0 deletions Functions_and_procedures/lastindexof.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='STRICT_TRANS_TABLES';

DROP FUNCTION IF EXISTS lastIndexOf;

DELIMITER //

CREATE FUNCTION lastIndexOf ( stringparam VARBINARY(255), targetstr VARBINARY(255))
RETURNS TINYINT UNSIGNED
DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
COMMENT 'Returns the position of the last occurrence of substring targetstr in string stringparam (v1.00)'

/*****************************************************************************
*
* DESCRIPTION: Returns the position of the last occurrence of substring targetstr in string stringparam (or 0 if not found or stringparam is null)
*
* AUTHOR: Benoît St-Jean <bstjean@yahoo.com>
* URL: http://www.endormitoire.wordpress.com
* VERSION: 1.00
*
* USAGE: SELECT lastIndexOf('ab00ab00ab00', 'ab');
* RESULT: 9
*
* PARAMETERS: stringparam string to be searched
* targetstr string we are trying to locate in stringparam
*
* RETURN: TINYINT UNSIGNED
*
* NOTES: This function is CASE SENSITIVE !!!
*
******************************************************************************/

BEGIN
DECLARE foundAnother TINYINT UNSIGNED;
DECLARE oldIndex TINYINT UNSIGNED;
DECLARE newIndex TINYINT UNSIGNED;

SET foundAnother = 1;
SELECT LOCATE(targetstr, stringparam) INTO oldIndex;

IF (oldIndex IS NULL) THEN
RETURN 0;
ELSEIF (oldIndex = 0) THEN
RETURN 0;
END IF;


WHILE foundAnother DO
SET newIndex = LOCATE(targetstr, stringparam, oldIndex+1);
IF newIndex > oldIndex THEN
SET oldIndex = newIndex;
ELSE
SET foundAnother = 0;
END IF;
END WHILE;

RETURN oldIndex;
END //

DELIMITER ;

SET SQL_MODE=@OLD_SQL_MODE;
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ A collection of useful (I hope!) functions, stored procedures and SQL scripts to
**initcap** : Returns a character string with the first letter of each word converted to uppercase. This function EXACTLY mimics INITCAP of Oracle.
**isProvince** : Returns 1 if argument is a Canadian 2-letter province code, 0 otherwise.
**isState** : Returns 1 if argument is an American 2-letter state code, 0 otherwise.
**lastindexof** : Returns the position of the last occurrence of a substring in a source string.
**occurrences** : Returns the number of occurrences of a search string inside a source string.
**rot5** : Encodes/decodes a string with the ROT5 substitution cipher.
**rot13** : Encodes/decodes a string with the ROT13 substitution cipher.
Expand Down

0 comments on commit 82563b4

Please sign in to comment.