Escribe en mayúscula la primera letra. MySQL


¿Alguien sabe el equivalente a este TSQL en lenguaje MySQL?

Estoy tratando de poner en mayúscula la primera letra de cada entrada.

UPDATE tb_Company SET CompanyIndustry = UPPER(LEFT(CompanyIndustry, 1))
+ SUBSTRING(CompanyIndustry, 2, LEN(CompanyIndustry))
Author: Vadim Kotov, 2010-11-24

11 answers

Es casi lo mismo, solo tienes que cambiar para usar la función CONCAT() en lugar del operador+:

UPDATE tb_Company
SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)), 
                             SUBSTRING(CompanyIndustry, 2));

Esto daría vuelta hello a Hello, wOrLd to WOrLd, BLABLA a BLABLA, etc. Si quieres mayúscula la primera letra y minúscula la otra, solo tienes que usar la función LCASE:

UPDATE tb_Company
SET CompanyIndustry = CONCAT(UCASE(LEFT(CompanyIndustry, 1)), 
                             LCASE(SUBSTRING(CompanyIndustry, 2)));

Tenga en cuenta que UPPER y UCASE hacen lo mismo.

 213
Author: Vincent Savard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-24 03:56:55

Vincents excelente respuesta para Mayúsculas Primera Letrafunciona muy bien para la primera letra solo mayúscula de una cadena de columna completa..

PERO, ¿qué pasa si quieres poner en mayúscula la Primera letra de CADA palabra en las cadenas de una columna de tabla?

Por ejemplo: "Abbeville High School"

No había encontrado una respuesta a esto en Stackoverflow. Tuve que improvisar algunas respuestas que encontré en Google para proporcionar una solución sólida al ejemplo anterior. No una función nativa pero una función creada por el usuario que permite MySQL versión 5+.

Si tiene un estado de usuario Super/Admin en MySQL o tiene una instalación local de mysql en su propio equipo, puede crear una FUNCIÓN (como un procedimiento almacenado) que se encuentra en su base de datos y se puede usar en todas las consultas SQL futuras en cualquier parte de la base de datos.

La función que creé me permite usar esta nueva función que llamé "UC_Words" al igual que las funciones nativas incorporadas de MySQL para que pueda actualizar un completa la columna así:

UPDATE Table_name
SET column_name = UC_Words(column_name) 

Para insertar el código de la función, cambié el delimitador estándar de MySQL(;) mientras creaba la función, y luego la restablecí a la normalidad después del script de creación de la función. También personalmente quería que la salida estuviera en el CONJUNTO de caracteres UTF8 también.

Creación de la función =

DELIMITER ||  

CREATE FUNCTION `UC_Words`( str VARCHAR(255) ) RETURNS VARCHAR(255) CHARSET utf8_general_ci  
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 ; 

Esto funciona como un tratamiento que muestra las primeras letras mayúsculas en varias palabras dentro de una cadena.

Asumiendo que su nombre de usuario de inicio de sesión de MySQL tiene privilegios suficientes, si no, y no puede configurar una base de datos temporal en su máquina personal para convertir sus tablas, luego pregunte a su proveedor de alojamiento compartido si configurarán esta función por usted.

 36
Author: Martin Sansone - MiOEE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-21 08:35:44

Puede utilizar una combinación de UCASE(), MID() y CONCAT():

SELECT CONCAT(UCASE(MID(name,1,1)),MID(name,2)) AS name FROM names;
 16
Author: Wouter Dorgelo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-13 05:37:13
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

 7
Author: Root,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-24 22:26:59

Http://forge.mysql.com/tools/tool.php?id=201

Si hay más de 1 palabra en la columna, entonces esto no funcionará como se muestra a continuación. La UDF mencionada anteriormente puede ayudar en tal caso.

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)

O tal vez éste ayude...

Https://github.com/mysqludf/lib_mysqludf_str#str_ucwords

 5
Author: shantanuo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-09 06:22:56

Esto está funcionando bien.

UPDATE state SET name = CONCAT ( UCASE (LEFT (name, 1)), LCASE(SUBSTRING (name, 2)));

 2
Author: Abhinav Sahu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-27 08:15:42
UPDATE tb_Company SET CompanyIndustry = UCASE(LEFT(CompanyIndustry, 1)) + 
SUBSTRING(CompanyIndustry, 2, LEN(CompanyIndustry))
 1
Author: Jasdeep Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-24 03:44:53

CREAR UNA FUNCIÓN:

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)))

UTILICE LA FUNCIÓN

UPDATE tbl_name SET col_name = UC_FIRST(col_name);
 1
Author: Florin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-05 06:24:56

Si alguien intenta poner en mayúscula cada palabra separada por espacio...

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;

Resultado

+--------------+
| name         |
+--------------+
| Abdul Karim  | 
+--------------+
 1
Author: Jahir islam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-16 16:18:17

Esto debería funcionar bien:

UPDATE tb_Company SET CompanyIndustry = 
CONCAT(UPPER(LEFT(CompanyIndustry, 1)), SUBSTRING(CompanyIndustry, 2))
 0
Author: Chris Hutchinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-24 03:48:41
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)));
 0
Author: sandeep kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-28 08:05:16