How would I strip spaces from a string from an added column in a database by using a function in MySQL?
Something like this format.
CREATE FUNCTION clean_string (str VARCHAR (50))
RETURNS VARCHAR(50) DETERMINISTIC
BEGIN
SQL statements/queries
END
I'm very new with this stuff, so any help would be greatly appreciated.
There is no need to write your own function, use mysql's own replace() function to remove spaces by substituting them with an empty string:
replace(field_name, ' ','')
No need to write your own, you can simply use REPLACE:
mysql> SELECT REPLACE('foo bar qux', ' ', '');
+---------------------------------+
| REPLACE('foo bar qux', ' ', '') |
+---------------------------------+
| foobarqux |
+---------------------------------+
So you can use:
UPDATE `table` SET `column` = REPLACE(`column`, ' ', '');
to remove all spaces from the specified column of specified table.
Or you can define a function:
CREATE FUNCTION clean_string (str VARCHAR (50))
RETURNS VARCHAR(50) DETERMINISTIC
RETURN REPLACE(str, ' ', '');
and then you an update with:
UPDATE `table` SET `column` = clean_string(`column`);
But since here you only substitute one function call for another there is not much added value here.
Related
I'm looking for a single query that's purely MySQL. The goal of this query is to utilize things such as SUBSTRING_INDEX, CONCAT, or whatever it needs to, in order to find a value in a string.
Let's say that the string looks something like this:
{"name":34,"otherName":55,"moreNames":12,"target":26,"hello":56,"hi":26,"asd":552,"p":3722,"bestName":11,"cc":6,"dd":10,}
My goal is to get the value of target, in this case, 26. However, "target":26 might not always be in that location in the string. Neither would any of the other properties. On top of that, the value might not always be 26. I need some way to check what number comes after "target": but before the , after "target":. Is there any way of doing this?
This one ?
create table sandbox (id integer, jsoncolumn varchar(255));
insert into sandbox values (1,'{"name":34,"otherName":55,"moreNames":12,"target":26,"hello":56,"hi":26,"asd":552,"p":3722,"bestName":11,"cc":6,"dd":10}');
mysql root#localhost:sandbox> SELECT jsoncolumn->'$.target' from sandbox;
+--------------------------+
| jsoncolumn->'$.target' |
|--------------------------|
| 26 |
+--------------------------+
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html
Please try this function to get value from JSON string in MYSQL
DROP FUNCTION IF EXISTS CAP_FIRST_CHAR;
DELIMITER $$
CREATE FUNCTION getValueFromJsonSring(jsonStr VARCHAR(250), getKey VARCHAR(250))
RETURNS VARCHAR(250) deterministic
BEGIN
DECLARE output VARCHAR(250); -- Holds the final value.
DECLARE data VARCHAR(250); -- Holds the exctracted value from JSON
SET getKey=CONCAT('"',getKey,'"');
SET data= TRIM(LEADING ':' FROM
substring_index(
substring_index(
substring_index(
substring_index(
SUBSTRING(jsonStr, 2, LENGTH(jsonStr)-2)
, getKey , '2'),
getKey,
-1
)
, ',', '1'),
',',
-1
)
);
SET output =SUBSTRING(data, 2, LENGTH(data)-2);
RETURN output;
END;
$$
DELIMITER ;
SELECT getValueFromJsonSring('{"amount":"400.34","departmentId":"7","date":"2017-06-02","PONumber":"0000064873","vendor":"44"}',"departmentId");
I am trying to remove apostrophes, below is the whole procedure.
BEGIN
SET _myparam = replace(_myparam, "'", '');
UPDATE `Table` SET NAME=_myparam WHERE UID=_someotherparam;
END
I also tried:
SET _myparam = replace(_myparam, '\'', '');
SET _myparam = replace(_myparam, '''', '');
SET _myparam = replace(_myparam, CHAR(39), '');
SET _myparam = replace(_myparam, '%\'%', '');
This seems to work with any other character but not the apostrophe. Nothing here seems to remove the apostrophe character. Any help would be appreciated.
I Googled everything I could think of, and have been pulling out hair for hours. Thanks!
I just tested this standard select out and it works. have you just tried
'\'' ?
ie, this works in standard select:
SELECT REPLACE("hi th'ere", '\'', '');
this does not:
SELECT REPLACE("hi th'ere",'%\'%', '');
of course this also works:
SELECT REPLACE("hi th'ere","'", '');
Edit: Here is the solution as MySQL Stored Procedure.
DELIMITER //
CREATE PROCEDURE TestStoredProc(IN _myvariable VARCHAR(25))
BEGIN
SET _myvariable = REPLACE(_myvariable, '\'', '');
SELECT _myvariable;
END //
DELIMITER ;
and
CALL TestStoredProc("hi th'ere");
You can also use two single-quotes which means one literal single-quote in standard SQL.
REPLACE("I wan't to be alone", '''', '')
FYI, in standard SQL, double-quotes are for delimiting identifiers like table names and column names. Single quotes are for delimiting strings and dates. It's a non-standard MySQLism to treat double-quotes as the same as single-quotes. But I use it in the example above, so I don't have to escape the apostrophe.
I also tested:
USE test;
DROP TABLE IF EXISTS `Table`;
CREATE TABLE `Table` (
UID INT PRIMARY KEY,
NAME TEXT
);
INSERT INTO `Table` VALUES (1, 'foo');
DROP PROCEDURE IF EXISTS q;
DELIMITER !!
CREATE PROCEDURE q(_myparam TEXT, _someotherparam INT)
BEGIN
SET _myparam = REPLACE(_myparam, '''', '');
UPDATE `Table` SET NAME=_myparam WHERE UID=_someotherparam;
END!!
DELIMITER ;
CALL q("I wan't to be alone", 1);
SELECT * FROM `Table`;
+-----+--------------------+
| UID | NAME |
+-----+--------------------+
| 1 | I want to be alone |
+-----+--------------------+
It seems to work just fine. I also tested using VARCHAR(20) for _myparam and that works too.
I am trying to create a stored that will accept two values, a column name and a value. It will then check if there is a record that exists for the passed in column name with the passed in value. I've tried the following
CREATE PROCEDURE p_HasActiveReference
#pi_colName varchar(100)
,#pi_colValue varchar(100)
AS
BEGIN
SET NOCOUNT ON
declare #sql varchar(1000)
set #sql = 'IF EXISTS(SELECT TOP 1 p.PaymentId
FROM Payments p
WHERE ' + #pi_colName + ' = ' + #pi_colValue + 'AND Active = 1)
SELECT ''True'' AS RETVAL
ELSE
SELECT ''False'' AS RETVAL'
exec(#sql)
END
However, I always get this error
Conversion failed when converting the varchar value 'InternalOr' to data type int.
When I call the procedure with the following
p_HasActiveReference 'InternalOrgCode', '10110'
The internalOrgCode column is of value varchar(10)
I am not a SQL expert, so I am not even sure if what I need to achieve is even possible using that technique!
Thanks!
At least one issue: you should be surrounding your string value with single quotes, and to escape those inside a string you need to double them up:
WHERE ' + #pi_colName + ' = ''' + #pi_colValue + ''' AND ...
You also may want to declare your #sql variable as something bigger than 100 characters! Looks like your string is getting truncated.
If the possible values for #pi_colName are finite, the data type is always string, and the columns are collation compatible, you could do something like this and avoid dynamic SQL:
SELECT ...
WHERE CASE #pi_colName
WHEN 'col1' THEN col1
WHEN 'col2' THEN col2
END = #pi_ColValue;
i have a table with address as column.
values for address is "#12-3/98 avenue street", which has numbers, special characters and alphabets.
i want to write my sql query usng regex to remove special characters from the address value
ex: "12398avenuestreet" will be the value i want after removing the special characters
thank you.
maybe this function help you
CREATE FUNCTION strip_non_alpha(
_dirty_string varchar(40)
)
RETURNS varchar(40)
BEGIN
DECLARE _length int;
DECLARE _position int;
DECLARE _current_char varchar(1);
DECLARE _clean_string varchar(40);
SET _clean_string = '';
SET _length = LENGTH(_dirty_string);
SET _position = 1;
WHILE _position <= _length DO
SET _current_char = SUBSTRING(_dirty_string, _position, 1);
IF _current_char REGEXP '[A-Za-z0-9]' THEN
SET _clean_string = CONCAT(_clean_string, _current_char);
END IF;
SET _position = _position + 1;
END WHILE;
RETURN CONCAT('', _clean_string);
END;
so you need to call this like
update mytable set address = strip_non_alpha(address);
You don't need RegExp for simple character replacement.
MySQL string functions
Unfortunately, MySQL regular expressions are "match only", you cannot do a replace in your query. This leaves you with only something like this (witch is very-very stupid):
SELECT REPLACE(REPLACE(address, '?', ''), '#', '') -- and many many other nested replaces
FROM table
Or put this logic inside your application (the best option here).
MySQL regular expressions is only for pattern matching and not replacing, so your best bet is to create a function or a repetative use of Replace().
As far as I know, it is not possible to replace via MySQL regex, since these functions are only used for matching.
Alternatively, you can use MySQL Replace for this:
SELECT REPLACE(REPLACE(REPLACE(REPLACE(address, '#', ''), '-', ''), '/', ''), ' ', '') FROM table;
Which will remove #, -, / and spaces and result in the string you want.
You may use this MySQL UDF. And then simply,
update my_table set my_column = PREG_REPLACE('/[^A-Za-z0-9]/' , '' , my_column);
I find that find_in_set only search by a single string :-
find_in_set('a', 'a,b,c,d')
In the above example, 'a' is the only string used for search.
Is there any way to use find_in_set kind of functionality and search by multiple strings, like :-
find_in_set('a,b,c', 'a,b,c,d')
In the above example, I want to search by three strings 'a,b,c'.
One way I see is using OR
find_in_set('a', 'a,b,c,d') OR find_in_set('b', 'a,b,c,d') OR find_in_set('b', 'a,b,c,d')
Is there any other way than this?
there is no native function to do it, but you can achieve your aim using following trick
WHERE CONCAT(",", `setcolumn`, ",") REGEXP ",(val1|val2|val3),"
The MySQL function find_in_set() can search only for one string in a set of strings.
The first argument is a string, so there is no way to make it parse your comma separated string into strings (you can't use commas in SET elements at all!). The second argument is a SET, which in turn is represented by a comma separated string hence your wish to find_in_set('a,b,c', 'a,b,c,d') which works fine, but it surely can't find a string 'a,b,c' in any SET by definition - it contains commas.
You can also use this custom function
CREATE FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');
DELIMITER $$
CREATE FUNCTION `FIND_SET_EQUALS`(`s1` VARCHAR(200), `s2` VARCHAR(200))
RETURNS TINYINT(1)
LANGUAGE SQL
BEGIN
DECLARE a INT Default 0 ;
DECLARE isEquals TINYINT(1) Default 0 ;
DECLARE str VARCHAR(255);
IF s1 IS NOT NULL AND s2 IS NOT NULL THEN
simple_loop: LOOP
SET a=a+1;
SET str= SPLIT_STR(s2,",",a);
IF str='' THEN
LEAVE simple_loop;
END IF;
#Do check is in set
IF FIND_IN_SET(str, s1)=0 THEN
SET isEquals=0;
LEAVE simple_loop;
END IF;
SET isEquals=1;
END LOOP simple_loop;
END IF;
RETURN isEquals;
END;
$$
DELIMITER ;
SELECT FIND_SET_EQUALS('a,c,b', 'a,b,c')- 1
SELECT FIND_SET_EQUALS('a,c', 'a,b,c')- 0
SELECT FIND_SET_EQUALS(null, 'a,b,c')- 0
Wow, I'm surprised no one ever mentioned this here.In a nutshell, If you know the order of your members, then just query in a single bitwise operation.
SELECT * FROM example_table WHERE (example_set & mbits) = mbits;
Explanation:
If we had a set that has members in this order: "HTML", "CSS", "PHP", "JS"... etc.
That's how they're interpreted in MySQL:
"HTML" = 0001 = 1
"CSS" = 0010 = 2
"PHP" = 0100 = 4
"JS" = 1000 = 16
So for example, if you want to query all rows that have "HTML" and "CSS" in their sets, then you'll write
SELECT * FROM example_table WHERE (example_set & 3) = 3;
Because 0011 is 3 which is both 0001 "HTML" and 0010 "CSS".
Your sets can still be queried using the other methods like REGEXP , LIKE, FIND_IN_SET(), and so on. Use whatever you need.
Amazing answer by #Pavel Perminov! - And also nice comment by #doru for dynamically check..
From there what I have made for PHP code CONCAT(',','" . $country_lang_id . "', ',') REGEXP CONCAT(',(', REPLACE(YourColumnName, ',', '|'), '),') this below query may be useful for someone who is looking for ready code for PHP.
$country_lang_id = "1,2";
$sql = "select a.* from tablename a where CONCAT(',','" . $country_lang_id . "', ',') REGEXP CONCAT(',(', REPLACE(a.country_lang_id, ',', '|'), '),') ";
You can also use the like command for instance:
where setcolumn like '%a,b%'
or
where 'a,b,c,d' like '%b,c%'
which might work in some situations.
you can use in to find match values from two values
SELECT * FROM table WHERE myvals in (a,b,c,d)