How to split the name string in mysql? - mysql
How to split the name string in mysql ?
E.g.:
name
-----
Sachin ramesh tendulkar
Rahul dravid
Split the name like firstname,middlename,lastname:
firstname middlename lastname
--------- ------------ ------------
sachin ramesh tendulkar
rahul dravid
I've separated this answer into two(2) methods. The first method will separate your fullname field into first, middle, and last names. The middle name will show as NULL if there is no middle name.
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
If( length(fullname) - length(replace(fullname, ' ', ''))>1,
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 2), ' ', -1) ,NULL)
as middle_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 3), ' ', -1) AS last_name
FROM registeredusers
This second method considers the middle name as part of the lastname. We will only select a firstname and lastname column from your fullname field.
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
TRIM( SUBSTR(fullname, LOCATE(' ', fullname)) ) AS last_name
FROM registeredusers
There's a bunch of cool things you can do with substr, locate, substring_index, etc. Check the manual for some real confusion. http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
There is no string split function in MySQL. so you have to create your own function. This will help you. More details at this link.
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)
Example:
SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;
+-------+
| third |
+-------+
| ccc |
+-------+
Well, nothing I used worked, so I decided creating a real simple split function, hope it helps:
DECLARE inipos INTEGER;
DECLARE endpos INTEGER;
DECLARE maxlen INTEGER;
DECLARE item VARCHAR(100);
DECLARE delim VARCHAR(1);
SET delim = '|';
SET inipos = 1;
SET fullstr = CONCAT(fullstr, delim);
SET maxlen = LENGTH(fullstr);
REPEAT
SET endpos = LOCATE(delim, fullstr, inipos);
SET item = SUBSTR(fullstr, inipos, endpos - inipos);
IF item <> '' AND item IS NOT NULL THEN
USE_THE_ITEM_STRING;
END IF;
SET inipos = endpos + 1;
UNTIL inipos >= maxlen END REPEAT;
You can use bewlo one also:
SELECT SUBSTRING_INDEX(Name, ' ', 1) AS fname,
SUBSTRING_INDEX(SUBSTRING_INDEX(Name,' ', 2), ' ',-1) AS mname,
SUBSTRING_INDEX(Name, ' ', -1) as lname FROM mytable;
Here is the split function I use:
--
-- split function
-- s : string to split
-- del : delimiter
-- i : index requested
--
DROP FUNCTION IF EXISTS SPLIT_STRING;
DELIMITER $
CREATE FUNCTION
SPLIT_STRING ( s VARCHAR(1024) , del CHAR(1) , i INT)
RETURNS VARCHAR(1024)
DETERMINISTIC -- always returns same results for same input parameters
BEGIN
DECLARE n INT ;
-- get max number of items
SET n = LENGTH(s) - LENGTH(REPLACE(s, del, '')) + 1;
IF i > n THEN
RETURN NULL ;
ELSE
RETURN SUBSTRING_INDEX(SUBSTRING_INDEX(s, del, i) , del , -1 ) ;
END IF;
END
$
DELIMITER ;
SET #agg = "G1;G2;G3;G4;" ;
SELECT SPLIT_STRING(#agg,';',1) ;
SELECT SPLIT_STRING(#agg,';',2) ;
SELECT SPLIT_STRING(#agg,';',3) ;
SELECT SPLIT_STRING(#agg,';',4) ;
SELECT SPLIT_STRING(#agg,';',5) ;
SELECT SPLIT_STRING(#agg,';',6) ;
select (case when locate('(', LocationName) = 0
then
horse_name
else
left(LocationName, locate('(', LocationName) - 1)
end) as Country
from tblcountry;
concat(upper(substring(substring_index(NAME, ' ', 1) FROM 1 FOR 1)), lower(substring(substring_index(NAME, ' ', 1) FROM 2 FOR length(substring_index(NAME, ' ', 1))))) AS fname,
CASE
WHEN length(substring_index(substring_index(NAME, ' ', 2), ' ', -1)) > 2 THEN
concat(upper(substring(substring_index(substring_index(NAME, ' ', 2), ' ', -1) FROM 1 FOR 1)), lower(substring(substring_index(substring_index(f.nome, ' ', 2), ' ', -1) FROM 2 FOR length(substring_index(substring_index(f.nome, ' ', 2), ' ', -1)))))
ELSE
CASE
WHEN length(substring_index(substring_index(f.nome, ' ', 3), ' ', -1)) > 2 THEN
concat(upper(substring(substring_index(substring_index(f.nome, ' ', 3), ' ', -1) FROM 1 FOR 1)), lower(substring(substring_index(substring_index(f.nome, ' ', 3), ' ', -1) FROM 2 FOR length(substring_index(substring_index(f.nome, ' ', 3), ' ', -1)))))
END
END
AS mname
To get the rest of the string after the second instance of the space delimiter
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 1), ' ', -1) AS first_name,
SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2), ' ', -1)
AS middle_name,
SUBSTRING('Sachin ramesh tendulkar',LENGTH(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2))+1) AS last_name
SELECT
p.fullname AS 'Fullname',
SUBSTRING_INDEX(p.fullname, ' ', 1) AS 'Firstname',
SUBSTRING(p.fullname, LOCATE(' ',p.fullname),
(LENGTH(p.fullname) - (LENGTH(SUBSTRING_INDEX(p.fullname, ' ', 1)) + LENGTH(SUBSTRING_INDEX(p.fullname, ' ', -1))))
) AS 'Middlename',
SUBSTRING_INDEX(p.fullname, ' ', -1) AS 'Lastname',
(LENGTH(p.fullname) - LENGTH(REPLACE(p.fullname, ' ', '')) + 1) AS 'Name Qt'
FROM people AS p
LIMIT 100;
Explaining:
Find firstname and lastname are easy, you have just to use SUBSTR_INDEX function
Magic happens in middlename, where was used SUBSTR with Locate to find the first space position and LENGTH of fullname - (LENGTH firstname + LENGTH lastname) to get all the middlename.
Note that LENGTH of firstname and lastname were calculated using SUBSTR_INDEX
You could use the common_schema and use the tokenize function. For more information about this, follow the links. Your code the would end up like:
call tokenize(name, ' ');
However, be aware that a space is not a reliable separator for first and last name. E.g. In Spain it is common to have two last names.
CREATE DEFINER=`root`#`localhost` FUNCTION `getNameInitials`(`fullname` VARCHAR(500), `separator` VARCHAR(1)) RETURNS varchar(70) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE `result` VARCHAR(500) DEFAULT '';
DECLARE `position` TINYINT;
SET `fullname` = TRIM(`fullname`);
SET `position` = LOCATE(`separator`, `fullname`);
IF NOT `position`
THEN RETURN LEFT(`fullname`,1);
END IF;
SET `fullname` = CONCAT(`fullname`,`separator`);
SET `result` = LEFT(`fullname`, 1);
cycle: LOOP
SET `fullname` = SUBSTR(`fullname`, `position` + 1);
SET `position` = LOCATE(`separator`, `fullname`);
IF NOT `position` OR NOT LENGTH(`fullname`)
THEN LEAVE cycle;
END IF;
SET `result` = CONCAT(`result`,LEFT(`fullname`, 1));
-- SET `result` = CONCAT_WS(`separator`, `result`, `buffer`);
END LOOP cycle;
RETURN upper(`result`);
END
1.Execute this function in mysql.
2.this will create a function. Now you can use this function anywhere you want.
SELECT `getNameInitials`('Kaleem Ul Hassan', ' ') AS `NameInitials`;
3. The above getNameInitails first parameter is string you want to filter and second is the spectator character on which you want to separate you string.
4. In above example 'Kaleem Ul Hassan' is name and i want to get initials and my separator is space ' '.
We have stored the value of course Name and chapter name in single column ChapterName.
Value stored like : " JAVA : Polymorphism "
you need to retrieve CourseName : JAVA and ChapterName : Polymorphism
Below is the SQL select query to retrieve .
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(ChapterName, ' ', 1), ' ', -1) AS
CourseName,
REPLACE(TRIM(SUBSTR(ChapterName, LOCATE(':', ChapterName)) ),':','') AS
ChapterName
FROM Courses where `id`=1;
Please let me know if any question on this.
Combined a few answers here to create a SP that returns the parts of the string.
drop procedure if exists SplitStr;
DELIMITER ;;
CREATE PROCEDURE `SplitStr`(IN Str VARCHAR(2000), IN Delim VARCHAR(1))
BEGIN
DECLARE inipos INT;
DECLARE endpos INT;
DECLARE maxlen INT;
DECLARE fullstr VARCHAR(2000);
DECLARE item VARCHAR(2000);
create temporary table if not exists tb_split
(
item varchar(2000)
);
SET inipos = 1;
SET fullstr = CONCAT(Str, delim);
SET maxlen = LENGTH(fullstr);
REPEAT
SET endpos = LOCATE(delim, fullstr, inipos);
SET item = SUBSTR(fullstr, inipos, endpos - inipos);
IF item <> '' AND item IS NOT NULL THEN
insert into tb_split values(item);
END IF;
SET inipos = endpos + 1;
UNTIL inipos >= maxlen END REPEAT;
SELECT * from tb_split;
drop table tb_split;
END;;
DELIMITER ;
To get the rest of the string after the second instance of the space delimiter:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(MsgRest, ' ', 1), ' ', -1) AS EMailID
, SUBSTRING_INDEX(SUBSTRING_INDEX(MsgRest, ' ', 2), ' ', -1) AS DOB
, IF(
LOCATE(' ', `MsgRest`) > 0,
TRIM(SUBSTRING(SUBSTRING(`MsgRest`, LOCATE(' ', `MsgRest`) +1),
LOCATE(' ', SUBSTRING(`MsgRest`, LOCATE(' ', `MsgRest`) +1)) +1)),
NULL
) AS Person
FROM inbox
DELIMITER $$
DROP FUNCTION IF EXISTS `split_name`$$
CREATE FUNCTION split_name (p_fullname TEXT, p_part INTEGER)
RETURNS TEXT
READS SQL DATA
BEGIN
DECLARE v_words INT UNSIGNED;
DECLARE v_name TEXT;
SET p_fullname=RTRIM(LTRIM(p_fullname));
SET v_words=(SELECT SUM(LENGTH(p_fullname) - LENGTH(REPLACE(p_fullname, ' ', ''))+1));
IF v_words=1 THEN
IF p_part=1 THEN
SET v_name=p_fullname;
ELSEIF p_part=2 THEN
SET v_name=NULL;
ELSEIF p_part=3 THEN
SET v_name=NULL;
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words=2 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET v_name=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
ELSEIF p_part=3 THEN
SET v_name=NULL;
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words=3 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=3 THEN
SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
SET v_name=REVERSE(p_fullname);
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words>3 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET p_fullname=REVERSE(SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname,SUBSTRING_INDEX(p_fullname,' ',1)+1) + 1);
SET v_name=REVERSE(p_fullname);
ELSEIF p_part=3 THEN
SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
SET v_name=REVERSE(p_fullname);
ELSE
SET v_name=NULL;
END IF;
ELSE
SET v_name=NULL;
END IF;
RETURN v_name;
END;
SELECT split_name('Md. Obaidul Haque Sarker',1) AS first_name,
split_name('Md. Obaidul Haque Sarker',2) AS middle_name,
split_name('Md. Obaidul Haque Sarker',3) AS last_name
First Create Procedure as Below:
CREATE DEFINER=`root`#`%` PROCEDURE `sp_split`(str nvarchar(6500), dilimiter varchar(15), tmp_name varchar(50))
BEGIN
declare end_index int;
declare part nvarchar(6500);
declare remain_len int;
set end_index = INSTR(str, dilimiter);
while(end_index != 0) do
/* Split a part */
set part = SUBSTRING(str, 1, end_index - 1);
/* insert record to temp table */
call `sp_split_insert`(tmp_name, part);
set remain_len = length(str) - end_index;
set str = substring(str, end_index + 1, remain_len);
set end_index = INSTR(str, dilimiter);
end while;
if(length(str) > 0) then
/* insert record to temp table */
call `sp_split_insert`(tmp_name, str);
end if;
END
After that create procedure as below:
CREATE DEFINER=`root`#`%` PROCEDURE `sp_split_insert`(tb_name varchar(255), tb_value nvarchar(6500))
BEGIN
SET #sql = CONCAT('Insert Into ', tb_name,'(item) Values(?)');
PREPARE s1 from #sql;
SET #paramA = tb_value;
EXECUTE s1 USING #paramA;
END
How call test
CREATE DEFINER=`root`#`%` PROCEDURE `test_split`(test_text nvarchar(255))
BEGIN
create temporary table if not exists tb_search
(
item nvarchar(6500)
);
call sp_split(test_split, ',', 'tb_search');
select * from tb_search where length(trim(item)) > 0;
drop table tb_search;
END
call `test_split`('Apple,Banana,Mengo');
Based on previous answers and do some modifications...
note:
p_delimiter has to be VARCHAR(1) couse CHAR(1) if is ' ' (space) gives '' (removes space and returns empty string)
Instead use of LENGTH I prefer CHAR_LENGTH which is safe for multibyte characters like UTF
DROP FUNCTION IF EXISTS FN_SPLIT_STR;
DELIMITER ;;
CREATE FUNCTION FN_SPLIT_STR(
p_input VARCHAR(2000), p_delimiter VARCHAR(1), p_position INT
)
RETURNS VARCHAR(2000)
DETERMINISTIC
BEGIN
DECLARE chunks INT;
SET chunks := CHAR_LENGTH(p_input) - CHAR_LENGTH(REPLACE(p_input, p_delimiter, '')) + 1;
IF p_position > chunks THEN
RETURN NULL;
END IF;
RETURN SUBSTRING_INDEX(SUBSTRING_INDEX(p_input, p_delimiter, p_position), p_delimiter, -1);
END;;
DELIMITER ;
SELECT "SUBSTRING_INDEX(name, ' ', 1) as first_name", "TRIM(REPLACE(name, SUBSTRING_INDEX(name, ' ', 1), '')) as last_name" FROM tbl;
Related
Mysql search & replace with random characters
I have in text some URLS src="https://example.com/public/images/someimage.jpg?itok=WDGFySy" I need remove in every url this garbage token ?itok=WDGFySy, all tokens obviously are random :). I try do it directly in database like this: UPDATE wp_posts SET post_content = REPLACE(post_content, 'itok=[[:xdigit:]]{8}', '') WHERE post_content LIKE 'itok=[[:xdigit:]]{8} '; But i cant find any of this tokens like this. LIKE this [a-fA-F0-9]{8} also wont help. Any advice? Thank you for any suggestions.
You can only use regex if you have MySQL 8.0. However, if your links are in separate fields, it is possible to create and use SP to clean them up: DELIMITER $$ CREATE FUNCTION CLEANUP( aString VARCHAR(255) , aName VARCHAR(15) ) RETURNS VARCHAR(255) BEGIN SET #u = SUBSTRING_INDEX(aString, '?', 1); SET #q = SUBSTRING_INDEX(aString, '?', -1); IF #q = aString THEN RETURN aString; -- no '?' char found ELSE SET #f = LOCATE(CONCAT(aName, '='), #q); SET #query = IF(#f > 1, SUBSTR(#q, 1, #f - 1), ''); IF #f > 0 THEN SET #t = LOCATE('&', #q, #f + LENGTH(aName) + 1); IF #t > 0 THEN SET #query = CONCAT(#query, SUBSTR(#q, #t + 1)); END IF; END IF; IF #query = '' THEN RETURN #u; ELSE RETURN CONCAT(#u, '?', TRIM('&' FROM #query)); END IF; END IF; END $$ DELIMITER ; Then: SELECT CLEANUP('https://example.com/public/images/someimage.jpg?itok=WDGFySy&b=2', 'itok') , CLEANUP('https://example.com/public/images/someimage.jpg?itok=WDGFySy', 'itok') , CLEANUP('https://example.com/public/images/someimage.jpg?a=1&itok=WDGFySy', 'itok') , CLEANUP('https://example.com/public/images/someimage.jpg?a=1&itok=WDGFySy&b=2', 'itok') ;
Update col1 for capitalising the first letter of each word in a string in col1 with SQL Server
After searching a code for capitalise the first letter of each word in a string in SQL Server I found this : CREATE FUNCTION [dbo].[InitCap] (#InputString varchar(4000) ) RETURNS VARCHAR(4000) AS BEGIN DECLARE #Index INT DECLARE #Char CHAR(1) DECLARE #PrevChar CHAR(1) DECLARE #OutputString VARCHAR(255) SET #OutputString = LOWER(#InputString) SET #Index = 1 WHILE #Index <= LEN(#InputString) BEGIN SET #Char = SUBSTRING(#InputString, #Index, 1) SET #PrevChar = CASE WHEN #Index = 1 THEN ' ' ELSE SUBSTRING(#InputString, #Index - 1, 1) END IF #PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(') BEGIN IF #PrevChar != '''' OR UPPER(#Char) != 'S' SET #OutputString = STUFF(#OutputString, #Index, 1, UPPER(#Char)) END SET #Index = #Index + 1 END RETURN #OutputString END GO but I don't now how to associate with updating code in SSMS ... something like this update tabel1 set #InputString = #OutputString
You Cross apply Cross Apply executes for Each row of outer query,so Assuming tableyouwanttoupdate has the string you want to capitalize ,you can pass it function and use that in your update Update t1 set t1.string=b.string from tableyouwanttoupdate t1 cross apply [dbo].[InitCap] (t1.string) b(string)
What about this: DECLARE #tbl TABLE (ID INT IDENTITY,s NVARCHAR(100)); INSERT INTO #tbl(s) VALUES ('this is all lower case!') ,('Here we have a sentence. And another one!') ,('This IS mIxEd!!! CoMMpletelY MixeD!'); WITH Splitted AS ( SELECT ID ,s ,CAST(N'<x>' + REPLACE((SELECT s AS [*] FOR XML PATH('')),N' ',N'</x><x>') + N'</x>' AS XML) AS InParts FROM #tbl ) SELECT ID ,s ,( STUFF( ( SELECT ' ' + UPPER(LEFT(x.value('.','nvarchar(max)'),1)) + LOWER(SUBSTRING(x.value('.','nvarchar(max)'),2,1000)) FROM Splitted.InParts.nodes('/x') AS A(x) FOR XML PATH('') ),1,1,'') ) AS NewString FROM Splitted The result ID s NewString 1 this is all lower case! This Is All Lower Case! 2 Here we have a sentence. And another one! Here We Have A Sentence. And Another One! 3 This IS mIxEd!!! CoMMpletelY MixeD! This Is Mixed!!! Commpletely Mixed! UPDATE If you want to update your column this is very easy too: DECLARE #tbl TABLE (ID INT IDENTITY,s NVARCHAR(100)); INSERT INTO #tbl(s) VALUES ('this is all lower case!') ,('Here we have a sentence. And another one!') ,('This IS mIxEd!!! CoMMpletelY MixeD!'); WITH Splitted AS ( SELECT ID ,s ,CAST(N'<x>' + REPLACE((SELECT s AS [*] FOR XML PATH('')),N' ',N'</x><x>') + N'</x>' AS XML) AS InParts FROM #tbl ) UPDATE Splitted SET s= ( STUFF( ( SELECT ' ' + UPPER(LEFT(x.value('.','nvarchar(max)'),1)) + LOWER(SUBSTRING(x.value('.','nvarchar(max)'),2,1000)) FROM Splitted.InParts.nodes('/x') AS A(x) FOR XML PATH('') ),1,1,'') ) FROM Splitted; SELECT * FROM #tbl;
MySQL function if elseif 1064
I'm trying to use MySQL but since 2 days I'm stuck on it. I've got an 1064 error which mean syntax error. I tried a lot of things but none worked. DELIMITER $$ CREATE FUNCTION set_libelle(civilite VARCHAR(4), prenom VARCHAR(30), nom VARCHAR(30)) RETURNS VARCHAR(20) BEGIN IF (LEN(civilite)+LEN(prenom)+LEN(nom)<19) THEN RETURN civilite + ' ' + prenom + ' ' + nom; ELSEIF (LEN(civilite)+LEN(nom)<17) THEN RETURN civilite + ' ' + LEFT(prenom,1) + '. ' + nom; ELSE RETURN civilite + ' ' + LEFT(prenom,1) + '. ' + LEFT(nom, (17-(LEN(civilite))); END IF; END$$ DELIMITER ; Have you got an idea why this doesn't work ? Thank you
You are using + for string concatenation rather than concat(). The proper syntax is: DELIMITER // CREATE FUNCTION set_libelle(civilite VARCHAR(4), prenom VARCHAR(30), nom VARCHAR(30)) RETURNS VARCHAR(20) BEGIN IF (LEN(civilite) + LEN(prenom) + LEN(nom) < 19) THEN RETURN CONCAT_WS(' ', civilite, prenom, ',', nom); ELSEIF (LEN(civilite) + LEN(nom) < 17) THEN RETURN CONCAT_WS(' ', civilite, LEFT(prenom, 1), '.', nom); ELSE RETURN CONCAT_WS(' ', civilite, LEFT(prenom, 1), '.', LEFT(nom, 17 - LEN(civilite)) ); END IF; END; // DELIMITER ; Here is a SQL Fiddle.
how to convert MSSQL Stored Procedure to Mysql SP using 'With' Keyword in mysql?
this is my Stored Procedure of MSSQL and I want to be convert this SP to MySQL,but i cant understand what to used instead of 'with' keyword in MySql so any one help me ??? Thanx in Advance!!!!! ALTER PROCEDURE [dbo].[TPortRateOnKm_SP_List] #qtype varchar(MAX) = NULL, #query varchar(MAX)= NULL, #Sortname varchar(MAX) =NULL, #sortorder varchar(MAX) =NULL , #PageNo int, #RecordsPerPage int, #likesearch int AS BEGIN DECLARE #temp INT; DECLARE #qry varchar(MAX) = ''; DECLARE #qry1 varchar(MAX) = ''; set #temp = (#PageNo - 1) * #RecordsPerPage If #query is not null and #query <> '' Begin Set #qry1= ' Where '+ #query End Else Begin Set #qry1= '' End If #query is not null and #query <> '' Begin Set #query= ' Where ('+ #query + ') and (RowNo > ' + cast(((#PageNo-1) *#RecordsPerPage) as varchar) + ' AND RowNo <= ' + cast(#PageNo * #RecordsPerPage as varchar)+ ') ' End Else Begin Set #query= ' Where (RowNo > ' + cast(((#PageNo-1) *#RecordsPerPage) as varchar) + ' AND RowNo <= ' + cast(#PageNo * #RecordsPerPage as varchar)+ ') ' End If #sortorder is not null and #sortorder <> '' Begin Set #sortorder= ' Order By '+ #sortorder End Else Begin Set #sortorder= ' ORDER BY VehicleId' End here is 'With' Keyword set #qry = 'Set dateformat dmy ;WITH CustomTable as (Select ROW_NUMBER() OVER ( '+ #sortorder+') as RowNo,A.* From (select Convert(varchar,T.WefDate,103) As WefDate,T.VehicleId as VehicleId,V.VehicleNo as VehicleNo,T.StartKm,T.EndKm,T.Rate from TrnRateOnKmRange T left outer join MasterVehicle V on V.VehicleId=T.VehicleId) A ' Set #qry= #qry + #qry1 Set #qry= #qry + ' ) SELECT CAST(RowNo AS INT) as RowNo,WefDate,VehicleId,VehicleNo,StartKm,EndKm,Rate FROM CustomTable' Set #qry=#qry + #query + #sortorder EXECUTE (#qry) END can any one do this ??
Capitalize first letter. MySQL
Does any one know the equivalent to this TSQL in MySQL parlance? I am trying to capitalize the first letter of each entry. UPDATE tb_Company SET CompanyIndustry = UPPER(LEFT(CompanyIndustry, 1)) + SUBSTRING(CompanyIndustry, 2, LEN(CompanyIndustry))
It's almost the same, you just have to change to use the CONCAT() function instead of the + operator : UPDATE tb_Company SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)), SUBSTRING(CompanyIndustry, 2)); This would turn hello to Hello, wOrLd to WOrLd, BLABLA to BLABLA, etc. If you want to upper-case the first letter and lower-case the other, you just have to use LCASE function : UPDATE tb_Company SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)), LCASE(SUBSTRING(CompanyIndustry, 2))); Note that UPPER and UCASE do the same thing.
Vincents excellent answer for Uppercase First Letter works great for the first letter only capitalization of an entire column string.. BUT what if you want to Uppercase the First Letter of EVERY word in the strings of a table column? eg: "Abbeville High School" I hadn't found an answer to this in Stackoverflow. I had to cobble together a few answers I found in Google to provide a solid solution to the above example. Its not a native function but a user created function which MySQL version 5+ allows. If you have Super/Admin user status on MySQL or have a local mysql installation on your own computer you can create a FUNCTION (like a stored procedure) which sits in your database and can be used in all future SQL query on any part of the db. The function I created allows me to use this new function I called "UC_Words" just like the built in native functions of MySQL so that I can update a complete column like this: UPDATE Table_name SET column_name = UC_Words(column_name) To insert the function code, I changed the MySQL standard delimiter(;) whilst creating the function, and then reset it back to normal after the function creation script. I also personally wanted the output to be in UTF8 CHARSET too. Function creation = DELIMITER || CREATE FUNCTION `UC_Words`( str VARCHAR(255) ) RETURNS VARCHAR(255) CHARSET utf8 DETERMINISTIC BEGIN DECLARE c CHAR(1); DECLARE s VARCHAR(255); DECLARE i INT DEFAULT 1; DECLARE bool INT DEFAULT 1; DECLARE punct CHAR(17) DEFAULT ' ()[]{},.-_!#;:?/'; SET s = LCASE( str ); WHILE i < LENGTH( str ) DO BEGIN SET c = SUBSTRING( s, i, 1 ); IF LOCATE( c, punct ) > 0 THEN SET bool = 1; ELSEIF bool=1 THEN BEGIN IF c >= 'a' AND c <= 'z' THEN BEGIN SET s = CONCAT(LEFT(s,i-1),UCASE(c),SUBSTRING(s,i+1)); SET bool = 0; END; ELSEIF c >= '0' AND c <= '9' THEN SET bool = 0; END IF; END; END IF; SET i = i+1; END; END WHILE; RETURN s; END || DELIMITER ; This works a treat outputting Uppercase first letters on multiple words within a string. Assuming your MySQL login username has sufficient privileges - if not, and you cant set up a temporary DB on your personal machine to convert your tables, then ask your shared hosting provider if they will set this function for you.
You can use a combination of UCASE(), MID() and CONCAT(): SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names;
mysql> SELECT schedule_type AS Schedule FROM ad_campaign limit 1; +----------+ | Schedule | +----------+ | ENDDATE | +----------+ 1 row in set (0.00 sec) mysql> SELECT CONCAT(UCASE(MID(schedule_type,1,1)),LCASE(MID(schedule_type,2))) AS Schedule FROM ad_campaign limit 1; +----------+ | Schedule | +----------+ | Enddate | +----------+ 1 row in set (0.00 sec) http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_mid
This is working nicely. UPDATE state SET name = CONCAT(UCASE(LEFT(name, 1)), LCASE(SUBSTRING(name, 2)));
http://forge.mysql.com/tools/tool.php?id=201 If there are more than 1 word in the column, then this will not work as shown below. The UDF mentioned above may help in such case. mysql> select * from names; +--------------+ | name | +--------------+ | john abraham | +--------------+ 1 row in set (0.00 sec) mysql> SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names; +--------------+ | name | +--------------+ | John abraham | +--------------+ 1 row in set (0.00 sec) Or maybe this one will help... https://github.com/mysqludf/lib_mysqludf_str#str_ucwords
UPDATE tb_Company SET CompanyIndustry = UCASE(LEFT(CompanyIndustry, 1)) + SUBSTRING(CompanyIndustry, 2, LEN(CompanyIndustry))
CREATE A FUNCTION: CREATE DEFINER=`root`#`localhost` FUNCTION `UC_FIRST`(`oldWord` VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 RETURN CONCAT( UCASE( LEFT(oldWord, 1)), LCASE(SUBSTRING(oldWord, 2))) USE THE FUNCTION UPDATE tbl_name SET col_name = UC_FIRST(col_name);
If anyone try to capitalize the every word separate by space... CREATE FUNCTION response(name VARCHAR(40)) RETURNS VARCHAR(200) DETERMINISTIC BEGIN set #m=''; set #c=0; set #l=1; while #c <= char_length(name)-char_length(replace(name,' ','')) do set #c = #c+1; set #p = SUBSTRING_INDEX(name,' ',#c); set #k = substring(name,#l,char_length(#p)-#l+1); set #l = char_length(#k)+2; set #m = concat(#m,ucase(left(#k,1)),lcase(substring(#k,2)),' '); end while; return trim(#m); END; CREATE PROCEDURE updateNames() BEGIN SELECT response(name) AS name FROM names; END; Result +--------------+ | name | +--------------+ | Abdul Karim | +--------------+
This should work nicely: UPDATE tb_Company SET CompanyIndustry = CONCAT(UPPER(LEFT(CompanyIndustry, 1)), SUBSTRING(CompanyIndustry, 2))
UPDATE users SET first_name = CONCAT(UCASE(LEFT(first_name, 1)), LCASE(SUBSTRING(first_name, 2))) ,last_name = CONCAT(UCASE(LEFT(last_name, 1)), LCASE(SUBSTRING(last_name, 2)));
select CONCAT(UCASE(LEFT('CHRIS', 1)),SUBSTRING(lower('CHRIS'),2)); Above statement can be used for first letter CAPS and rest as lower case.
The solution in PostgreSQL (as far as googling may lead to this page) INITCAP(firstname || ' ' || lastname) AS fullname
Uso algo simples assim ;) DELIMITER $$ DROP FUNCTION IF EXISTS `uc_frist` $$ CREATE FUNCTION `uc_frist` (str VARCHAR(200)) RETURNS varchar(200) BEGIN set str:= lcase(str); set str:= CONCAT(UCASE(LEFT(str, 1)),SUBSTRING(str, 2)); set str:= REPLACE(str, ' a', ' A'); set str:= REPLACE(str, ' b', ' B'); set str:= REPLACE(str, ' c', ' C'); set str:= REPLACE(str, ' d', ' D'); set str:= REPLACE(str, ' e', ' E'); set str:= REPLACE(str, ' f', ' F'); set str:= REPLACE(str, ' g', ' G'); set str:= REPLACE(str, ' h', ' H'); set str:= REPLACE(str, ' i', ' I'); set str:= REPLACE(str, ' j', ' J'); set str:= REPLACE(str, ' k', ' K'); set str:= REPLACE(str, ' l', ' L'); set str:= REPLACE(str, ' m', ' M'); set str:= REPLACE(str, ' n', ' N'); set str:= REPLACE(str, ' o', ' O'); set str:= REPLACE(str, ' p', ' P'); set str:= REPLACE(str, ' q', ' Q'); set str:= REPLACE(str, ' r', ' R'); set str:= REPLACE(str, ' s', ' S'); set str:= REPLACE(str, ' t', ' T'); set str:= REPLACE(str, ' u', ' U'); set str:= REPLACE(str, ' v', ' V'); set str:= REPLACE(str, ' w', ' W'); set str:= REPLACE(str, ' x', ' X'); set str:= REPLACE(str, ' y', ' Y'); set str:= REPLACE(str, ' z', ' Z'); return str; END $$ DELIMITER ;