(EXT) http://tec.5lulu.com/detail/104krn1e6p2w78d77.html
An existing string, such as Apple,banana,orange,pears,grape, to be separated by commas (,):
Apple
Banana
Orange
Pears
Grape
Then use the Where in () method to query.
1, the specific function:
- # function: Func_split_totallength
- DELIMITER $$
- DROP function IF EXISTS ' func_split_totallength ' $$
- CREATE definer=' root '@'% ' FUNCTION ' func_split_totallength '
- (f_string varchar (+),f_delimiter varchar(5)) RETURNS int( One )
- BEGIN
- # Calculates the total length of the incoming string
- return 1+ (length(f_string) - length(replace(f_ String,f_delimiter," ));
- END$$
- DELIMITER;
- # function: Func_split
- DELIMITER $$
- DROP function IF EXISTS ' func_split ' $$
- CREATE definer=' root '@'% ' FUNCTION ' func_split '
- (f_string varchar (+),f_delimiter varchar(5),f_order int ) RETURNS varchar(255) CHARSET UTF8
- BEGIN
- # Splits the passed-in string, returning the new string after splitting
- DECLARE result varchar(255) default ';
- set Result = reverse(substring_index (reverse (substring_index (f) _string,f_delimiter,f_order)),f_delimiter,1);
- return result;
- END$$
- DELIMITER;
- # Stored Procedure : splitstring
- DELIMITER $$
- DROP PROCEDURE IF EXISTS ' splitstring ' $$
- CREATE PROCEDURE ' splitstring '
- (in f_string varchar (+), inf_delimiter varchar(5))
- BEGIN
- # Split Results
- DECLARE CNT int default 0;
- DECLARE i int default 0;
- Set cnt = func_split_totallength(f_string,f_delimiter);
- DROP TABLE IF EXISTS ' tmp_split ';
- Create temporary table ' Tmp_split ' (' status ' varchar(+) not null ) DEFAULT CHARSET=UTF8;
- While I < cnt
- Do
- set i = i + 1;
- Insert into tmp_split(' status ') values (func_split(f_string ,f_delimiter,i));
- End while;
- END$$
- DELIMITER;
2. Whether the test can be successfully segmented
- Call splitstring("Apple,banana,orange,pears,grape",",");
- Select * from tmp_split;
The results of the operation are as follows, stating that the segmentation succeeded:
Mysql> call Splitstring ("Apple,banana,orange,pears,grape", ",");
SELECT * from Tmp_split;
Query OK, 1 row affected
+--------+
| Status |
+--------+
| Apple |
| Banana |
| Orange |
| Pears |
| Grape |
+--------+
5 rows in Set
Mysql>
3. Apply where in () query
- # first pass in string, save in temp table tmp_split
- call Splitstring ( "Apple,banana,orange,pears,grape" ,
- # use the results of the query as conditions for other queries using
- select * fruit where in ( Span class= "KWD" >select * from Tmp_split
Splitting strings with MySQL stored procedures