I used a column 'Title' in a table 'incident'. This column contains some information .Among this information, three character that indicates the region .these three character are usually found after ('on', ':'). I want to execute a function (mysql) which allows: 1) if the three character taken from the 'Title' column, which are located after 'on', are( kef or bej or jen) so the result will be stored in a column 'test' in the same table. 2) if the first is not achieved then takes the three character which are located after ':' and stored in a column 'test1' in the same table.
there is the code that i used :
delimiter |
CREATE FUNCTION METTER5 (s VARCHAR(2000)) RETURNS VARCHAR(10000)
DETERMINISTIC
BEGIN
DECLARE open INT;
DECLARE close INT;
DECLARE someLimit INT;
DECLARE str VARCHAR(2000);
DECLARE str1 VARCHAR(2000);
DECLARE str2 VARCHAR(2000);
DECLARE str3 VARCHAR(2000);
DECLARE toFind VARCHAR(2000);
DECLARE co VARCHAR(2000);
SET co='';
SET open = 1;
SET close = 1;
SET toFind = s ;
SET someLimit =100;
SET str='';
SET str1='';
SET str2='';
/* SET tofind=concat(tofind,'sur','');*/
SET str =substring(trim(substring_index(s,'sur',-1)),1,3);
SET str1 =substring(trim(substring_index(s,'du',-1)),1,3);
SET str2 =substring(trim(substring_index(s,':',-1)),1,3);
IF (str in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')) =1 THEN set co = str ;
ELSE IF ((str not in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')) and (str1 in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')))=1 THEN set co = str1 ;
ELSE IF ((str1 not in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB'))and (str2 in ('ZAG','TUN','TOZ','TAT','SOS','SIL','SFX','SBO','RNC','BAR','BEJ','BIZ','BSC','GAB','GAF','JEN','KAI','KAS','KEB','KEF','MAH','MED','MON','NAB')))=1 THEN SET co = str2 ;
ELSE set co = '1' ;
END IF;
END IF;
END IF;
return co;
END |
delimiter;
and there is the query that i used :
update incident set test =METTER5 (Title) WHERE Affected_CI like 'other ci' and open_time between '2015-01-01' and '2015-01-30'
but after the running , there is the problem : Unknown column 'description' in 'field list'
thanks.
Related
I want to search in Wp post(title) column and delete entries which contains words longer then 10 characters but i am unable to find a query to do that. can anyone help?
Edit: I made following SP.
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `p`(IN `instring` VARCHAR(255))
begin
declare tempstring varchar(10000);
declare idin int;
declare outstring varchar(100);
declare c1 varchar(100);
declare c2 varchar(100);
declare totallength int DEFAULT 0;
declare checkit int;
declare done int;
DECLARE CUR1 CURSOR for SELECT id,post_title FROM wp_posts;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
drop table if exists occursresults;
create table occursresults (col1 varchar(20), col2 varchar(20),totallength int );
open CUR1;
read_loop: LOOP
FETCH CUR1 INTO idin,tempstring;
if done then leave read_loop; end if;
set checkit = 0;
looper: while tempstring is not null and instr(tempstring,' ') > 0 do
set checkit = checkit + 1;
if checkit > 100 then #In case of infinite loop
leave looper;
end if;
set outstring = substr(tempstring,1,instr(tempstring, ' ') - 1);
set tempstring = ltrim(rtrim(replace(tempstring,concat(outstring,' '),'')));
set c1 = substr(outstring,1,instr(outstring, ' ') - 1);
set c2 = replace(outstring,concat(c1,' '),'');
if Length(c2) > 10 then
delete from wp_posts where id=idin;
end if;
if Length(c2) < 10 then
INSERT INTO occursresults (COL1,COL2,totallength) VALUES (c1,c2,Length(c2));
end if;
end while;
select tempstring;
set outstring = tempstring;
set c1 = substr(outstring,1,instr(outstring, ' ') - 1);
set c2 = replace(outstring,concat(c1,' '),'');
if Length(c2) > 10 then
delete from wp_posts where id=idin;
end if;
if Length(c2) < 10 then
INSERT INTO occursresults (COL1,COL2,totallength) VALUES (c1,c2,Length(c2));
end if;
end loop;
close cur1;
end$$
DELIMITER ;
but when i call it. i get this error.
Error
Static analysis:
1 errors were found during analysis.
Missing expression. (near "ON" at position 25)
SQL query: Edit Edit
SET FOREIGN_KEY_CHECKS = ON;
MySQL said: Documentation
2014 - Commands out of sync; you can't run this command now
You can use a regex to identify the rows to delete:
DELETE FROM post
WHERE title RLIKE '[a-zA-Z]{10}'
This defines a word as a sequence of alphabetic characters. You might want to adapt the regex to add more characters if needed (digits, underscore, dash, ...).
you can use CHAR_LENGTH as a function to get the length.
Select:
SELECT
*
FROM
post
WHERE
CHAR_LENGTH(title) > 10;
Delete query:
DELETE FROM post
WHERE
CHAR_LENGTH(title) > 10;
Note: LENGTH function too works but it will calculate in bytes rather than chars more info on this refer this MySQL - length() vs char_length()
I'm on developing web project and i get some problem with migration from oracle database to mysql database. I want to create function with this code :
DROP FUNCTION IF EXISTS F_MANIFEST_GABUNG_SMR;
DELIMITER //
CREATE FUNCTION F_MANIFEST_GABUNG_SMR (input_val varchar(4000))
RETURNS VARCHAR(4000)
BEGIN
DECLARE return_text VARCHAR(10000) DEFAULT NULL;
DECLARE not_found INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found = 1;
DECLARE x CURSOR FOR SELECT DISTINCT IFNULL(SMR,'-') SMR FROM MANIFEST_EDI_SMR WHERE BL_NBR = input_val; OPEN x;
FETCH x INTO;
WHILE NOT_FOUND=0
DO
SET return_text = concat(ifnull(return_text, '') , ' ' , IFNULL(x.SMR, '')) ;
FETCH INTO;
END WHILE;
CLOSE ;
IF char_length(return_text) > 85 THEN
SET return_text = concat(ifnull(substr(return_text,1,85), '') , ' detail asp BL');
END IF;
RETURN return_text;
END;
//
DELIMITER ;
I am using phpmyadmin to store function with routine. Thanks for your help :)
The error message is self explanatory:you have declare the cursor after handler,need to change the order:
DROP FUNCTION IF EXISTS F_MANIFEST_GABUNG_SMR;
DELIMITER //
CREATE FUNCTION F_MANIFEST_GABUNG_SMR (input_val varchar(4000))
RETURNS VARCHAR(4000)
BEGIN
DECLARE return_text VARCHAR(10000) DEFAULT NULL;
DECLARE not_found INT DEFAULT 0;
-- Declare cursor before handler
DECLARE x CURSOR FOR SELECT DISTINCT IFNULL(SMR,'-') SMR
FROM MANIFEST_EDI_SMR WHERE BL_NBR = input_val; OPEN x;
-- handler need to be after cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET not_found = 1;
FETCH x INTO;
WHILE NOT_FOUND=0
DO
SET return_text = concat(ifnull(return_text, '') , ' ' , IFNULL(x.SMR, '')) ;
FETCH INTO;
END WHILE;
CLOSE ;
IF char_length(return_text) > 85 THEN
SET return_text = concat(ifnull(substr(return_text,1,85), '') , ' detail asp BL');
END IF;
RETURN return_text;
END;
//
DELIMITER ;
More details can be found at:https://dev.mysql.com/doc/refman/8.0/en/cursors.html
I do have a requirement like when two inputs are passed as input to stored proc, inserting into another table need to happen and the number of rows will depend on number of fields passed in input.
I have tried to create a stored proc but its only inserting taking field length as 1
BEGIN
Declare valu varchar(200);
Declare valu2 varchar(200);
Declare fwo varchar(200);
Declare fwo2 varchar(200);
declare len int;
Declare sl int;
Declare valu3 varchar(255);
Declare jval varchar(255);
set #fwo = (select replace(pinput1,',', ''));
set #fwo2 = (select replace(pinput2,',', ''));
-- select #fwo;
set #len = (select length(#fwo));
-- select #fwo,#len;
set #sl = 1;
if #len >0 then
increment: repeat
set #valu = SUBSTRING(#fwo, #sl , 1);
set #valu2 = SUBSTRING(#fwo2, #sl , 1);
set #jval = JSON_OBJECT('id',#valu2,'policy',#valu);
INSERT INTO `Example`(`Column1`,`Column2`) values(#valu2,#jval);
set #sl = #sl+1;
UNTIL #sl > #len END repeat increment ;
END if ;
END$$
DELIMITER ;
When the input are 1,2,3 and a,b,c the insertion is happening correctly, but when we pass 11,12,13 and ab,cd,ef the insertion is happening likethe above condition inputs.The same repetes when the lenght increases more than 1.
Can someone suggestion me to solve this issue
I have a function that is for changing text into proper case.
CREATE FUNCTION `fpropercasetest` (p_Value VARCHAR(8000))
RETURNS VARCHAR(8000)
BEGIN
DECLARE v_i INT; -- counter
DECLARE v_ProperCaseText VARCHAR(5000);
DECLARE v_Word VARCHAR(1000);
DECLARE v_isWhiteSpace TINYINT(1);
DECLARE v_c CHAR(1);
SET v_Word = '';
SET v_i = 1;
SET v_isWhiteSpace = 1;
SET v_ProperCaseText = '';
SET p_Value = LOWER(p_Value);
WHILE (v_i <= LENGTH(p_Value)+1) DO
SET v_c = SUBSTRING(p_Value,v_i,1);
IF v_isWhiteSpace = 1 THEN SET v_c = UPPER(v_c); END IF;
SET v_isWhiteSpace = CASE WHEN (ASCII(v_c) BETWEEN 48 AND 58) THEN 0
WHEN (ASCII(v_c) BETWEEN 64 AND 90) THEN 0
WHEN (ASCII(v_c) BETWEEN 96 AND 123) THEN 0
ELSE 1 END;
IF v_isWhiteSpace = 0 THEN
SET v_Word = CONCAT(v_Word, v_c);
ELSE
SET v_ProperCaseText = CONCAT(v_ProperCaseText, v_Word, v_c);
SET v_Word = '';
END IF;
SET v_i = v_i + 1;
END WHILE;
return v_ProperCaseText;
END;
You can test with the following
SELECT fpropercasetest("this is just some text for you to test with");
When I entered any text with spaces I noticed that it just didn't register (e.g. with the text "this is some text" it would return "ThisIsSomeText" and it should return "This Is Some Text")
I debugged it with Visual Studio and noticed that substring was just ignoring spaces completely, it returns an empty string.
I'm completely stumped by this, any help will be greatly appreciated. Thanks.
Sorry about the delay, I had a few things to take care of before leaving work, here is what I came up with, it does what you want it to do:
FUNCTION `upper_all`(p_Value VARCHAR(8000)) RETURNS varchar(8000) CHARSET latin1
BEGIN
DECLARE pos INT; -- counter
DECLARE result VARCHAR(1000);
SET p_Value = LOWER(p_Value);
SET p_Value = CONCAT(UCASE(LEFT(p_Value, 1)),LCASE(SUBSTRING(p_Value, 2)));
SET pos = LOCATE(' ',p_Value);
SET result = SUBSTR(p_Value,1,LOCATE(' ',p_Value));
SET p_Value = SUBSTR(p_Value FROM pos);
WHILE (pos > 0) DO
/*SET p_Value = CONCAT(p_Value,UCASE(LEFT(p_Value, pos)),LCASE(SUBSTRING(p_Value, 2)));*/
SET pos = LOCATE(' ',p_Value);
IF pos > 0 THEN
SET pos = pos + 1;
SET p_Value = SUBSTR(p_Value FROM pos);
END IF;
SET p_Value = CONCAT(UCASE(LEFT(p_Value, 1)),LCASE(SUBSTRING(p_Value, 2)));
SET result = CONCAT(result,SUBSTR(p_Value,1,LOCATE(' ',p_Value)));
END WHILE;
SET result = CONCAT(result,p_Value);
return result;
END
I didn't have time to comment it out for you, it should self-explanatory. It could use a little cleanup and optimize the code a bit.
create function fn_title_case
(v_input_string varchar(255))
RETURNS varchar(255)
BEGIN
declare i int;
DECLARE punctuation varchar(17);
declare this_character char(1);
declare output_string varchar(255);
declare boolean_value int;
declare input_length int;
set input_length = char_length(v_input_string);
set boolean_value = 0;
set i = 0;
set punctuation = ' ';
set output_string = '';
begin
-- Loop through each character in the input string
while i <= input_length do
-- Set the current substring to position i with length 1
SET this_character = SUBSTRING( v_input_string, i, 1 );
-- If the current character exists in the punctuation string, i.e. if the current character is a space
IF LOCATE( this_character, punctuation ) > 0 THEN
-- Set the current character to null and the boolean to 1
set this_character = '', output_string = concat(output_string, this_character), boolean_value = 1;
elseif boolean_value=1 then
-- Only if the punctuation (a space) was detected in the previous step,
-- Insert a space and capitalize the letter
SET output_string = concat(output_string, ' ', UCASE(this_character)), boolean_value = 0;
else
-- If the space was NOT detected, add the current character in lower case
set output_string = concat(output_string, LCASE(this_character));
end if;
set i = i+1;
end while;
end;
RETURN output_string;
I want to create function in mysql for :
Input: 7589586586 Output: (758) 958-6586
Input: 758ABC6586 Output: (758) 222-6586
Input: 758ABC65 Output: Invalid Formats (like mobile keypad)
The following mysql code gives errors:
DELIMITER $$
CREATE FUNCTION fn_bhagyashreed_phonenumber(input varchar(20))
RETURNS varchar(50)
LANGUAGE SQL
BEGIN
DECLARE compare varchar(30) ;
DECLARE cnt INT;
DECLARE varout varchar(30);
DECLARE val varchar(30);
DECLARE Phoutput varchar(50);
DECLARE var INT;
set var=LENGTH(input);
SET compare ='';
SET cnt =1;
SET varout ='';
SET val = '';
SET Phoutput ='';
if((var<>10)||(input NOT REGEXP '^[[:alnum:]]+$' )) THEN
set Phoutput='Invalid Format';
else if((LENGTH(input))=10) THEN
begin
IF (input REGEXP '^[[:alnum:]]+$' ) THEN
begin
while (cnt<=10) DO
set compare=substring(input,cnt,1);
if compare in('a','b','c','2') THEN
set val=2;
else if compare in('d','e','f','3') THEN
set val=3;
else if compare in('g','h','i','4') THEN
set val=4;
else if compare in('j','k','l','5') THEN
set val=5;
else if compare in('m','n','o','6') THEN
set val=6;
else if compare in('p','q','r','s','7') THEN
set val=7;
else if compare in('t','u','v','8') THEN
set val=8;
else if compare in('w','x','y','z','9') THEN
set val=9;
else if (compare ='1') THEN
set val=1;
else if(compare ='0') THEN
set val=0;
end if;
set varout = CONCAT(varout,val);
set cnt=cnt+1;
end while;
set Phoutput = CONCAT('(',SUBSTR(varout,1,3),')',' ',SUBSTR(varout,4,3),'-',SUBSTR(varout,7,4));
end IF;
end if;
return Phoutput;
end;
$$
DELIMITER ;
The error:
#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 'while; set Phoutput = CONCAT('(',SUBSTR(varout,1,3),')','
',SUBSTR(varout,4,' at line 65
Issues with syntax in your code:
There is no ELSE IF instead there is ELSEIF
You twice opened BEGIN ... END block but never terminated it. In fact you there was no need in using them at all.
A syntactically correct and bit streamlined version of your function might look like this
DELIMITER $$
CREATE FUNCTION fn_bhagyashreed_phonenumber(input VARCHAR(20))
RETURNS VARCHAR(50)
BEGIN
DECLARE compare VARCHAR(30) DEFAULT '';
DECLARE cnt INT DEFAULT 1;
DECLARE varout VARCHAR(30) DEFAULT '';
DECLARE val VARCHAR(30) DEFAULT '';
DECLARE Phoutput VARCHAR(50) DEFAULT '';
DECLARE var INT;
SET var = LENGTH(input);
IF var <> 10 OR input NOT REGEXP '^[[:alnum:]]+$' THEN
SET Phoutput = 'Invalid Format';
ELSE
WHILE cnt <= 10 DO
SET compare = SUBSTRING(input, cnt, 1);
IF compare IN('a','b','c','2') THEN
SET val=2;
ELSEIF compare IN('d','e','f','3') THEN
SET val=3;
ELSEIF compare IN('g','h','i','4') THEN
SET val=4;
ELSEIF compare IN('j','k','l','5') THEN
SET val=5;
ELSEIF compare IN('m','n','o','6') THEN
SET val=6;
ELSEIF compare IN('p','q','r','s','7') THEN
SET val=7;
ELSEIF compare IN('t','u','v','8') THEN
SET val=8;
ELSEIF compare IN('w','x','y','z','9') THEN
SET val=9;
ELSEIF compare = '1' THEN
SET val=1;
ELSEIF compare = '0' THEN
SET val=0;
END IF;
SET varout = CONCAT(varout,val);
SET cnt = cnt + 1;
END WHILE;
SET Phoutput = CONCAT('(',SUBSTR(varout,1,3),')',' ',SUBSTR(varout,4,3),'-',SUBSTR(varout,7,4));
END IF;
RETURN Phoutput;
END$$
DELIMITER ;
Let's try it out:
SELECT fn_bhagyashreed_phonenumber(value) phone
FROM
(
SELECT '7589586586' value UNION ALL
SELECT '758ABC6586' UNION ALL
SELECT '758ABC65'
) q
Output:
| PHONE |
|----------------|
| (758) 958-6586 |
| (758) 222-6586 |
| Invalid Format |
Here is SQLFiddle demo
Cleaned up your code SIGNIFICANTLY:
DELIMITER $$
CREATE FUNCTION fn_phone_number(input VARCHAR(20)) RETURNS VARCHAR(14) LANGUAGE SQL
BEGIN
DECLARE cnt INT;
DECLARE chr CHAR(1);
DECLARE number VARCHAR(10);
SET cnt = 1;
SET number = '';
IF ((LENGTH(input) = 10) && (input REGEXP '^[[:alnum:]]+$')) THEN
WHILE (cnt <= 10) DO
SET chr = SUBSTR(input,cnt,1);
IF chr IN('a','b','c','2') THEN
SET number = CONCAT(number,'2');
ELSEIF chr IN('d','e','f','3') THEN
SET number = CONCAT(number,'3');
ELSEIF chr IN('g','h','i','4') THEN
SET number = CONCAT(number,'4');
ELSEIF chr IN('j','k','l','5') THEN
SET number = CONCAT(number,'5');
ELSEIF chr IN('m','n','o','6') THEN
SET number = CONCAT(number,'6');
ELSEIF chr IN('p','q','r','s','7') THEN
SET number = CONCAT(number,'7');
ELSEIF chr IN('t','u','v','8') THEN
SET number = CONCAT(number,'8');
ELSEIF chr IN('w','x','y','z','9') THEN
SET number = CONCAT(number,'9');
ELSEIF chr IN('0','1') THEN
SET number = CONCAT(number,chr);
END IF;
SET cnt = cnt + 1;
END WHILE;
RETURN CONCAT('(', SUBSTR(number,1,3), ') ', SUBSTR(number,4,3), '-', SUBSTR(number,7,4));
ELSE
RETURN 'Invalid Format';
END IF;
END$$
DELIMITER ;