Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split strings using mysql

Tags:

I want to create a stored procedure which will do matching of two tables. My requirement is to match two tables based on the columns user passes as an input.

Syntax:

CREATE PROCEDURE reconcile.matchTables(   IN TAB1 VARCHAR(25),    IN TAB1 VARCHAR(25),    IN COLS1 VARCHAR(250) ,    IN COLS2 VARCHAR(250)) 

EX:

matchTables('table1', 'table2', 'col1#col2#col3#col4' , 'col2#col13#col1#col8') 

Now the stored procedure should form the where clause like the following

table1.col1 = table2.col2    and table1.col2 = table2.col13    and table1.col3 = table2.col1    and table1.col4 = table2.col8 
like image 384
Anil Kumar.C Avatar asked Oct 12 '10 11:10

Anil Kumar.C


People also ask

How do I split a string in MySQL?

In MySQL, we use SUBSTRING_INDEX() to split the string. It usually consists of three arguments i.e., string, delimiter, and position. The string value will be split based on the position.

Can you split a string in SQL?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument.

What is SUBSTRING_INDEX in MySQL?

SUBSTRING_INDEX() function in MySQL is used to return a substring from a string before a specified number of occurrences of the delimiter.


1 Answers

MySQL does not include a function to split a delimited string. However, it’s very easy to create your own function.

User define function:

CREATE [AGGREGATE] FUNCTION function_name RETURNS {STRING|INTEGER|REAL|DECIMAL} 

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, ''); 

Usage:

SELECT SPLIT_STR(string, delimiter, position) 
like image 195
Nilesh Patel Avatar answered Sep 21 '22 15:09

Nilesh Patel