select only digits, numbers from text - mysql

I have a field text, In it there is information about such
sch hcbhsc hscbshcbc xxxxxxxx sgxfag jdhajdh;
dchbdbc bdcbdh bchdbd xx/xx-xxxx/xx svdhs sbjbsc
bdchbdc jncjdnc jbcjb xx/xx-xxxxx/xx gcvsgc jcbjsb
dchjbd bhjcbdcb bdcbcd xx-xxxx/xx shchscv hscbhsc
dhcbhd jdcbjdb jdcnjdcn xx-xxxxx/xx shcvsch jbscjc
Place x is only a digit, I need to write select and only those numbers are taken

Use SUBSTRING and PATINDEX string functions IN SQL server :
SELECT SUBSTRING(Your_FieldName, PATINDEX('%[0-9]%', Your_FieldName),
LEN(Your_FieldName))
For MYSQL refer below URL :
Query to get only numbers from a string
string

There is no formal PATINDEX() function in MySQL that achieves both the regex pattern lookup with returned character index, define User-Defined function that loops through each character in the length of a string and checks a REGEXP pattern on the character. Once created, use such a function in-line of a query.
DROP FUNCTION IF EXISTS PatIndex;
DELIMITER $$
CREATE FUNCTION PatIndex(pattern VARCHAR(255), tblString VARCHAR(255)) RETURNS INTEGER
DETERMINISTIC
BEGIN
DECLARE i INTEGER;
SET i = 1;
myloop: WHILE (i <= LENGTH(tblString)) DO
IF SUBSTRING(tblString, i, 1) REGEXP pattern THEN
RETURN(i);
LEAVE myloop;
END IF;
SET i = i + 1;
END WHILE;
RETURN(0);
END

Here is a MySQL function (routine) that will do just that. It is an improved version from the solution given here: how-to-get-only-digits-from-string-in-mysql
This improved version can handle much larger numbers. The old solution was limited by the INTEGER value, so if you had phone numbers for example (or string containing many digits), it would fail with out of range for column.
DELIMITER $$
CREATE FUNCTION ExtractNumber (in_string VARCHAR(50))
RETURNS varchar(50)
NO SQL
BEGIN
DECLARE ctrNumber VARCHAR(50);
DECLARE finNumber VARCHAR(50) DEFAULT '';
DECLARE sChar VARCHAR(1);
DECLARE inti VARCHAR(50) DEFAULT 1;
IF LENGTH(in_string) > 0 THEN
WHILE(inti <= LENGTH(in_string)) DO
SET sChar = SUBSTRING(in_string, inti, 1);
SET ctrNumber = FIND_IN_SET(sChar, '0,1,2,3,4,5,6,7,8,9');
IF ctrNumber > 0 THEN
SET finNumber = CONCAT(finNumber, sChar);
END IF;
SET inti = inti + 1;
END WHILE;
RETURN CAST(finNumber AS UNSIGNED);
ELSE
RETURN 0;
END IF;
END$$
DELIMITER ;
Now you can do this:
SELECT ExtractNumber(my_field)
FROM my_table;

Related

REVERSE of a number in mysql

used the following stored procedure to find reverse of a number , but it is showing error:use the right syntax to use near loop.
DELIMITER //
CREATE PROCEDURE ggrepeat1()
begin
declare num1 int;
declare num2 int;
declare rev int default 0;
set #num1:='&num1';
while num1>0
loop
set #num2:=num1 mod 10;
set #rev:=num2+(rev*10);
set #num1:=floor(num1/10);
end loop;
dbms_output.put_line('Reverse number is: '||rev);
end//
DELIMITER ;
As noted in the comments, you can't use oracle syntax in mysql. Regardless, I think you're over-complicating things. A simpler approach would be to cast your number to a string, reverse it using built-in functions and cast it back to a number:
CREATE FUNCTION reverse_int(num INT)
RETURNS INT DETERMINISTIC
RETURN CAST(REVERSE(CAST(num AS CHAT)) AS INT);
The while loop in mysql should be used in this like.
This is the first problem
while n>0 do
content..
end while
The second problem is
dbms_output.put_line('Reverse number is: '||rev);
In mysql you cannot use the above code.
Instead you can use this
Select 'The reverse of number is 'rev;
So your code would be
DELIMITER //
CREATE PROCEDURE ggrepeat1()
begin
declare num1 int;
declare num2 int;
declare rev int default 0;
set #num1:='&num1';
while num1>0 do
set #num2:=num1 mod 10;
set #rev:=num2+(rev*10);
set #num1:=floor(num1/10);
end while;
Select 'Reverse number is: 'rev;
end//
DELIMITER ;

How to sperated character from Mysql?

I use the example below :
select '10+20+30'
and generate value :
'++'
In other words, strip any digit and leave only signs.
Function:
DROP FUNCTION IF EXISTS getMOps;
DELIMITER $$
CREATE FUNCTION getMOps
( s varchar(100)
)
RETURNS VARCHAR(100) DETERMINISTIC
BEGIN
DECLARE sOut VARCHAR(100);
DECLARE theLen,iLooper INT;
SET iLooper=1;
SET theLen=LENGTH(s);
SET sOut='';
WHILE iLooper<theLen DO
IF SUBSTR(s,iLooper,1) IN ('+','-','*','/','^') THEN
SET sOut=CONCAT(sOut,SUBSTR(s,iLooper,1));
END IF;
SET iLooper=iLooper+1;
END WHILE;
return (sOut);
END$$
DELIMITER ;
Test:
select getMOps('fish'); -- blank string
select getMOps('1+2+7-1'); -- '++-'
Modify the IN clause to suit your tastes. I am sure there are better ways.

MySQL syntax (function) is error

CREATE FUNCTION FC_IDKRITERIA()
RETURNS CHAR(3)
AS
BEGIN
DECLARE #MAX INT , #KODEBARU CHAR(3)
SELECT #MAX = MAX (RIGHT(IDKRITERIA,2)) FROM KRITERIA
IF #MAX IS NULL
SET #MAX = 0
SET #KODEBARU = 'K' + RIGHT('0'+CONVERT(VARCHAR(3),#MAX+ 1 ) ,2)
RETURN #KODEBARU
END
Every statement in a procedure must end with ;. To keep this from ending the function definition, use the DELIMITER command to change the command delimiter to something else.
And when doing a variable assignment in a SELECT clause, you have to use :=.
There's no AS at the beginning of a function definition.
You don't declare variables that begin with #.
You need THEN and END IF in an IF statement.
To concatenate strings, use CONCAT(), not +.
You have the arguments to CONVERT() in the wrong order, and VARCHAR(3) is not a valid type argument, it should be CHAR(3).
In a function, you can't use a SELECT statement at the top-level, because that means to return the result set, and functions can only return single values. So you have to assign #MAX from a (SELECT ...) expression.
DELIMITER $$
CREATE FUNCTION FC_IDKRITERIA() RETURNS CHAR(3)
BEGIN
SET #MAX = (SELECT MAX (RIGHT(IDKRITERIA,2)) FROM KRITERIA);
IF #MAX IS NULL
THEN SET #MAX = 0;
END IF;
SET #KODEBARU = CONCAT('K', RIGHT('0'+CONVERT(#MAX+ 1, CHAR(3)) ,2));
RETURN #KODEBARU;
END;
$$
DELIMITER ;

Relace multiple Substrings in MySQL result

Is there a way to replace multiple substrings in a single mysql column field?
In my result, there are fields like:
'&DY, &Q3'
In this case, DY and Q3 are match codes which I have to replace with a defined Word.
I tried to work with this regex_replace function
CREATE FUNCTION `regex_replace`(pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000)) RETURNS varchar(1000)
DETERMINISTIC
BEGIN
DECLARE temp VARCHAR(1000);
DECLARE ch VARCHAR(1);
DECLARE i INT;
SET i = 1;
SET temp = '';
IF original REGEXP pattern THEN
loop_label: LOOP
IF i>CHAR_LENGTH(original) THEN
LEAVE loop_label;
END IF;
SET ch = SUBSTRING(original,i,1);
IF NOT ch REGEXP pattern THEN
SET temp = CONCAT(temp,ch);
ELSE
SET temp = CONCAT(temp,replacement);
END IF;
SET i=i+1;
END LOOP;
ELSE
SET temp = original;
END IF;
RETURN temp;
END
My SQL Query:
SELECT REGEX_REPLACE(fm.column,'(\&[\w]{2})*','My Word') FROM `table` fm WHERE id = '123'
didn't work. Maybe one problem is, that my substrings begin with "&" which is an operator in regex!?
try this, but i have use MariaDB they have REGEX_REPLACE internal
https://mariadb.com/kb/en/mariadb/regexp_replace/
SELECT REGEXP_REPLACE('&DY, &Q3','\(\&[A-Z0-9]+\),*','My Word');
Result:
My Word My Word

Create a function with optional arguments in MySQL

I want to create a function with optional arguments in MySQL. For instance, I want to create function that calculates the average of its arguments. I create a function of five arguments, but when user passes just two arguments to the function then it should still run and return the average of the two arguments.
You cannot set optional parameters in MySQL stored procedures.
You can however set optional parameters in a MySQL UDF.
You do know that MySQL has an AVG aggregate function?
Workaround
If you can face the ugliness of this workaround here's samplecode that uses a comma separated string with values as input and returns the average.
DELIMITER $$
CREATE FUNCTION MyAvg(valuestr varchar) RETURNS float
BEGIN
DECLARE output float;
DECLARE arg_count integer;
DECLARE str_length integer;
DECLARE arg float;
DECLARE i integer;
SET output = NULL;
SET i = LENGTH(valuestr);
IF i > 0 THEN BEGIN
SET arg_count = 1;
WHILE i > 0 DO BEGIN
IF MID(valuestr, i, 1)
SET i = i - 1;
END; END WHILE;
/* calculate average */
SET output = 0;
SET i = arg_count;
WHILE i > 0 DO BEGIN
SET arg = SUBSTRING_INDEX(
SUBSTRING_INDEX(valuestr, ',' , i)
, ',', -1 );
SET output = output + arg;
SET i = i - 1;
END; END WHILE;
SET output = output / arg_count;
END; END IF;
RETURN output;
END $$
DELIMITER ;
Use concat_ws to feed the function.
SELECT MyAvg(CONCAT_WS(',',100,200,300,500)) AS test;
You can also write an UDF in C(++) or Delphi/Lazarus
While far from an ideal solution, here's how I solved optional parameters for a concat function I needed:
delimiter ||
create function safeConcat2(arg1 longtext, arg2 varchar(1023))
returns longtext
return safeConcat3(arg1, arg2, '');
||
create function safeConcat3(arg1 longtext, arg2 varchar(1023), arg3 varchar(1023))
returns longtext
return safeConcat4(arg1, arg2, arg3, '');
||
create function safeConcat4(arg1 longtext, arg2 varchar(1023), arg3 varchar(1023), arg4 varchar(1023))
returns longtext
begin
declare result longText;
set result = concat(arg1, arg2, arg3, arg4);
if( result is null) then
set result=arg1;
end if;
return result;
end
||
Note: This means you have to call the method that corresponds to the number of args.
Another approach is to pass only one 'super' parameter which is string with commas in it separating the real parameters. The mysql procedure can then parse the 'super' parameter into the separate real parameters.
Example:
create procedure procWithOneSuperParam(param1 varchar(500))
declare param2 varchar(100);
begin
if LOCATE(',',param1) > 0 then
.. param2=<extract the string after the ',' from param1> ..