MySQL 5.7 - ASCII Each Character in a String - mysql

I'm looking to do some validation of data replication between some different database systems, with different character sets (potentially) and a third party software that migrates the data. To help test an aspect of this, I'm looking to do something like the following.
ASCII(foo) returns the value for the first character in the string. Is there a way to get the ascii values for all characters in a string in one go, in one select statement? Something like concating the values together, separated by a space. E.g. If the string was hello then the output would be 104 101 108 108 111
Reference:
select ascii('h'); -- 104
select ascii('e'); -- 101
select ascii('l'); -- 108
select ascii('o'); -- 111

Just had the same problem, so here is a procedure that does the work:
DELIMITER $$
CREATE PROCEDURE string_to_ascii(IN inputStr VARCHAR(255))
BEGIN
DECLARE strLen INT DEFAULT 0;
DECLARE idx INT DEFAULT 0;
DECLARE current_char VARCHAR(1);
DECLARE current_char_ascii VARCHAR(10);
DECLARE outputStr TEXT;
IF inputStr IS NULL THEN
SET inputStr = '';
END IF;
SET strLen = CHAR_LENGTH(inputStr);
SET idx = 1;
WHILE idx <= strLen DO
SET current_char = SUBSTR(inputStr, idx, 1);
SET current_char_ascii = ASCII(current_char);
IF idx = 1 THEN
SET outputStr = current_char_ascii;
ELSE
SET outputStr = CONCAT(outputStr, ",", current_char_ascii);
END IF;
SET idx = idx+1;
END WHILE;
SELECT outputStr;
END
$$
DELIMITER ;
Usage:
> CALL string_to_ascii('hello');
+---------------------+
| outputStr |
+---------------------+
| 104,101,108,108,111 |
+---------------------+
If you prefer to use it as a function:
DELIMITER //
CREATE FUNCTION string_to_ascii ( inputStr TEXT )
RETURNS TEXT
DETERMINISTIC
BEGIN
DECLARE strLen INT DEFAULT 0;
DECLARE idx INT DEFAULT 0;
DECLARE current_char VARCHAR(1);
DECLARE current_char_ascii VARCHAR(10);
DECLARE outputStr TEXT;
IF inputStr IS NULL THEN
SET inputStr = '';
END IF;
SET strLen = CHAR_LENGTH(inputStr);
SET idx = 1;
WHILE idx <= strLen DO
SET current_char = SUBSTR(inputStr, idx, 1);
SET current_char_ascii = ASCII(current_char);
IF idx = 1 THEN
SET outputStr = current_char_ascii;
ELSE
SET outputStr = CONCAT(outputStr, ",", current_char_ascii);
END IF;
SET idx = idx+1;
END WHILE;
RETURN outputStr;
END; //
DELIMITER ;
And then the usage will be:
> SELECT string_to_ascii('hello');
+--------------------------+
| string_to_ascii('hello') |
+--------------------------+
| 104,101,108,108,111 |
+--------------------------+

Related

convert TSQL query to MySQL

I need to convert this tSQL query into MySQL query version 5.7.14
I tried declare parameter with the following syntax
declare #commissionType INT;
but I reached a dead end and need help to convert this query
CREATE PROCEDURE MyProc
#chainId int
as
BEGIN
declare #commissionMethod int
declare #commissionType int
declare #value decimal(18,2)
set #commissionMethod = 1
set #value = 200000
set #commissionType = (select CommissionType from CommissionRules
where ChainId = #chainId )
IF(#commissionMethod = 1)
BEGIN
print('alert')
select (Fixed * #value) / 100 from CommissionRules where ChainId = #chainId
END
END
This is pretty much a literal conversion. But check your logic. It doesn't make any sense. v_commissionMethod is always 1 and v_commissionType is not even being used after selecting a value.
DELIMITER //
CREATE PROCEDURE MyProc (
p_chainId int)
BEGIN
declare v_commissionMethod int;
declare v_commissionType int;
declare v_value decimal(18,2);
set v_commissionMethod = 1;
set v_value = 200000;
select CommissionType into v_commissionType from CommissionRules
where ChainId = p_chainId ;
IF(v_commissionMethod = 1)
THEN
/* print('alert') */
select (Fixed * v_value) / 100 from CommissionRules where ChainId = p_chainId;
END IF;
END;
//
DELIMITER ;
Something like this:
DELIMITER $$
CREATE PROCEDURE MyProc (
in_chainId unsigned
) as
BEGIN
select v_CommissionType := CommissionType,
v_commissionMethod = 1,
v_value = 200000
from CommissionRules
where ChainId = in_chainId;
if v_commissionMethod = 1 then
select 'alert';
select (Fixed * v_value) / 100
from CommissionRules
where ChainId = in_chainId
end if;
END;$$
DELIMITER ;

count total even and odd number between 20-50 with mysqll procedure

i'm having hard time with my homework , because im beginner using mysql procedure.
to search total numbers odd and even between 20-50 with looping.
i want to make output like this using mysql procedure to call:
total_odd_numbers :15
total_even_numbers:16
i tried for sum up for even numbers like this :
`DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `genap`()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
declare total int;
SET x = 20;
SET str = '';
set total = 0;
loop_label: LOOP
IF x = 50 THEN
LEAVE loop_label;
END IF;
SET x =x+1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str,x,',');
SET total= total+x;
END IF;
END LOOP;
SELECT sum(total);
END`
Try this procedure:
DROP PROCEDURE IF EXISTS ShowOddEvesBetween;
DELIMITER ;;
CREATE PROCEDURE ShowOddEvesBetween(IN fromNum INT, IN toNum INT)
BEGIN
DECLARE odds INT DEFAULT 0;
DECLARE evens INT DEFAULT 0;
DECLARE x INT;
SET x = fromNum;
WHILE x <= toNum DO
IF x % 2 THEN
SET odds = odds + 1;
ELSE
SET evens = evens + 1;
END IF;
SET x = x + 1;
END WHILE;
SELECT CONCAT("total_odd_numbers: ", odds, ", total_even_numbers: ", evens) AS "Odds & Evens";
END;
;;
Then call it
CALL ShowOddEvesBetween(20, 50);
Will output what you want
MariaDB [test]> CALL ShowOddEvesBetween(20, 50);
+-----------------------------------------------+
| Odds & Evens |
+-----------------------------------------------+
| total_odd_numbers: 15, total_even_numbers: 16 |
+-----------------------------------------------+
1 row in set (0.00 sec)

mysql selection first letter of each word in a cell

I would like to return the first letter of each word in a MySQL column called 'initials'.
For example, my table may look like this:
| project_unit | initials |
+---------------------------------------+----------+
| Mbita Clinic Rehabilitation | MCR |
| Management Strategy for Thrips Cowpea | MSTC |
Any suggestions?
You can use below mentioned function to achieve your requirement.
DELIMITER $$
CREATE FUNCTION split_string(split_string varchar(255),my_delimiter varchar(1)) RETURNS varchar(10)
BEGIN
DECLARE temp_string varchar(255);
DECLARE occurance INT;
DECLARE i INT;
DECLARE temp_result varchar(10);
DECLARE final_result varchar(10);
SET temp_result = '';
SET occurance=length(split_string)-length(replace(split_string,' ',''))+1;
IF occurance > 0 then
set i=1;
while i <= occurance do
set temp_string = (select SUBSTRING_INDEX(SUBSTRING_INDEX(split_string, my_delimiter, i),my_delimiter ,-1));
set temp_result = CONCAT(temp_result, SUBSTRING(temp_string,1,1));
set i=i+1;
end while;
ELSE
set temp_result = SUBSTRING(split_string,1,1);
END IF;
set occurance=0;
SET final_result = temp_result;
RETURN (final_result);
END $$
DELIMITER ;
You can use it like this :
SELECT Projcect_unit, split_string(Projcect_unit,' ') as initials FROM main_table;
Since MySQL does not support Regex replacement, you will need to first include UDF (User Defined Function) which you can get from this link.
Once you have the regexp_replace function, you can simply use
select regexp_replace('Mbita Clinic Rehabilitation', '[a-z ]', '')
which would return MRC.
Note that the current regex will remove lowercase letter and spaces, but if your field can contains number or any other character you will have to modify the regex.
Hope this helped.
MySql does not provide such try string operation function so you need create function and call function with query
DELIMITER $$
CREATE FUNCTION `GetUpperCase`(InputString VARCHAR(1024)) RETURNS varchar(1024) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE return_string,inputDATA VARCHAR(1024);
DECLARE schar VARCHAR(1);
DECLARE string_length, char_code INT;
SET string_length = LENGTH(InputString);
SET inputDATA = InputString ;
SET return_string = '';
WHILE string_length > 0 DO
SET schar = SUBSTRING(inputDATA FROM (-1 * string_length) FOR 1);
SET char_code = ORD(schar);
IF char_code >= 65 AND char_code <= 90 THEN
SET return_string = CONCAT(return_string, schar);
END IF;
SET string_length = string_length - 1;
END WHILE;
RETURN return_string;
END $$
DELIMITER ;
and call function with SQL select query
mysql> SELECT GetUpperCase("Mbita Clinic Rehabilitation Management Strategy for Thrips Cowpea") AS `initials`;
+----------+
| initials |
+----------+
| MCRMSTC |
+----------+

For loop example in MySQL

In MySQL, I have this stored procedure with a LOOP:
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
DECLARE a INT Default 0 ;
simple_loop: LOOP
SET a=a+1;
select a;
IF a=5 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
It always prints 1. What is the correct syntax for a MySQL Loop?
drop table if exists foo;
create table foo
(
id int unsigned not null auto_increment primary key,
val smallint unsigned not null default 0
)
engine=innodb;
drop procedure if exists load_foo_test_data;
delimiter #
create procedure load_foo_test_data()
begin
declare v_max int unsigned default 1000;
declare v_counter int unsigned default 0;
truncate table foo;
start transaction;
while v_counter < v_max do
insert into foo (val) values ( floor(0 + (rand() * 65535)) );
set v_counter=v_counter+1;
end while;
commit;
end #
delimiter ;
call load_foo_test_data();
select * from foo order by id;
While loop syntax example in MySQL:
delimiter //
CREATE procedure yourdatabase.while_example()
wholeblock:BEGIN
declare str VARCHAR(255) default '';
declare x INT default 0;
SET x = 1;
WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;
select str;
END//
Which prints:
mysql> call while_example();
+------------+
| str |
+------------+
| 1,2,3,4,5, |
+------------+
REPEAT loop syntax example in MySQL:
delimiter //
CREATE procedure yourdb.repeat_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 5;
SET str = '';
REPEAT
SET str = CONCAT(str,x,',');
SET x = x - 1;
UNTIL x <= 0
END REPEAT;
SELECT str;
END//
Which prints:
mysql> call repeat_loop_example();
+------------+
| str |
+------------+
| 5,4,3,2,1, |
+------------+
FOR loop syntax example in MySQL:
delimiter //
CREATE procedure yourdatabase.for_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = -5;
SET str = '';
loop_label: LOOP
IF x > 0 THEN
LEAVE loop_label;
END IF;
SET str = CONCAT(str,x,',');
SET x = x + 1;
ITERATE loop_label;
END LOOP;
SELECT str;
END//
Which prints:
mysql> call for_loop_example();
+-------------------+
| str |
+-------------------+
| -5,-4,-3,-2,-1,0, |
+-------------------+
1 row in set (0.00 sec)
Do the tutorial: http://www.mysqltutorial.org/stored-procedures-loop.aspx
If I catch you pushing this kind of MySQL for-loop constructs into production, I'm going to shoot you with the foam missile launcher. You can use a pipe wrench to bang in a nail, but doing so makes you look silly.
Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below
CREATE TABLE `table1` (
`col1` VARCHAR(50) NULL DEFAULT NULL
)
Now if you want to insert number from 1 to 50 in that table then use following stored procedure
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
DECLARE a INT Default 1 ;
simple_loop: LOOP
insert into table1 values(a);
SET a=a+1;
IF a=51 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
To call that stored procedure use
CALL `ABC`()
You can exchange this local variable for a global, it would be easier.
DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
SET #a = 0;
simple_loop: LOOP
SET #a=#a+1;
select #a;
IF #a=5 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$

mysql question - way to update case for field?

I have some entries in a field that look like this: NEvada city or nevada City... Is there a way to update the database so that entries have initial caps: Nevada City?
You can use:
UPDATE `table` SET
`field` = CONCAT(UPPER(LEFT(`field`, 1)), LOWER(SUBSTRING(`field`, 2)))
But still you will need to modify it to allow a capital Letter for the next word like City...
Source here
UPDATE:
Found this example at MySQL's forum, it is exactly what you need:
DROP FUNCTION IF EXISTS proper;
SET GLOBAL log_bin_trust_function_creators=TRUE;
DELIMITER |
CREATE FUNCTION proper( str VARCHAR(128) )
RETURNS VARCHAR(128)
BEGIN
DECLARE c CHAR(1);
DECLARE s VARCHAR(128);
DECLARE i INT DEFAULT 1;
DECLARE bool INT DEFAULT 1;
DECLARE punct CHAR(17) DEFAULT ' ()[]{},.-_!#;:?/';
SET s = LCASE( str );
WHILE i < LENGTH( str ) DO
BEGIN
SET c = SUBSTRING( s, i, 1 );
IF LOCATE( c, punct ) > 0 THEN
SET bool = 1;
ELSEIF bool=1 THEN
BEGIN
IF c >= 'a' AND c <= 'z' THEN
BEGIN
SET s = CONCAT(LEFT(s,i-1),UCASE(c),SUBSTRING(s,i+1));
SET bool = 0;
END;
ELSEIF c >= '0' AND c <= '9' THEN
SET bool = 0;
END IF;
END;
END IF;
SET i = i+1;
END;
END WHILE;
RETURN s;
END;
|
DELIMITER ;