Função extenso() no MySQL

Forum sobre SQL.

Moderador: Moderadores

Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

Estou querendo criar uma função de extenso no MySQL, mas sem idéia.
Alguém pode me dar uma luz como se criam funções/variáveis/etc.?

Pode ser uma função de somar A + B pra começar, criando a variável C pra retorno.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

Já tentei algumas mas não deu.
Por exemplo, assim:

Código: Selecionar todos

delimiter //
CREATE FUNCTION ze_extenso( nValor DECIMAL )
BEGIN
DECLARE ctxt VARCHAR;
ctxt = CONCAT( nvalor,'');
End
//
Já tentei com IN, OUT, DECLARE, RETURNS, etc., conforme exemplos que encontrei.
Dá erro na criação.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
Itamar M. Lins Jr.
Administrador
Administrador
Mensagens: 7928
Registrado em: 30 Mai 2007 11:31
Localização: Ilheus Bahia
Curtiu: 1 vez

Função extenso() no MySQL

Mensagem por Itamar M. Lins Jr. »

Olá!
https://eduardolegatti.blogspot.com/200 ... lo-de.html

https://www.forumrm.com.br/topic/476-va ... resolvido/
Esse segundo tem que se escrever para baixar.

Saudações,
Itamar M. Lins Jr.
Saudações,
Itamar M. Lins Jr.
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

Começou a dar sinal de vida.

https://mariadb.com/kb/pt-br/create-function/

Código: Selecionar todos

CREATE function ze_extenso ( nValue decimal(10,2) )
RETURNS VARCHAR(500)  DETERMINISTIC 
RETURN CONCAT( 'Hello ', nValue, ' !' );
extenso.png
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

Encontrei uma diferença interessante:

Código: Selecionar todos

RETURN CONCAT_WS( ' ', 'Hello', nValue, '!' )
extenso2.png
No CONCAT() vém inteiro, no CONCAT_WS() vém decimal.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

Na hora que vai declarar variável, não vai

Código: Selecionar todos

cTxt VARCHAR(500);

set cTxt := CONCAT_WS( ' ', 'Hello', nValue, cTxt, '!' );

RETURN cTxt
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

uma coisa simples assim não vai

Código: Selecionar todos

DROP FUNCTION if exists ze_extenso;
SET delimiter $$
create function ze_extenso( nValue DECIMAL(15,2) )
RETURNS VARCHAR(500)  DETERMINISTIC 
BEGIN
DECLARE ctxt VARCHAR(500);
SET ctxt = CONCAT( 'Hello ', nValue, cTxt, ' !' );
RETURN cTxt
end$$			
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

ufa, finalmente.

Código: Selecionar todos

DROP FUNCTION if exists ze_extenso;
delimiter $$
create function ze_extenso( nValue DECIMAL(15,2) )
RETURNS VARCHAR(500)  DETERMINISTIC 
BEGIN
DECLARE ctxt VARCHAR(500);
SET ctxt = CONCAT( 'Hello ', nValue, ' !' );
RETURN cTxt;
END
$$			
delimiter ;
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

A propósito....
DETERMINISTIC....
Sei lá pra que serve, pode ser assim ou NOT.
Nesse manual não diz, apenas mostra que pode usar DETERMINISTIC ou NOT DETERMINISTIC.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

Bom, a parte principal tá pronta.
Falta só o extenso, que vou tentar converter a minha do Harbour.

Código: Selecionar todos

DROP FUNCTION if exists ze_extenso;
delimiter $$
create function ze_extenso( nValor DECIMAL(15,2) )
RETURNS VARCHAR(500)  DETERMINISTIC 
BEGIN
DECLARE cTxt VARCHAR(500);
SET cTxt := '';
if nvalor != 0 then
   SET cTxt := CONCAT( ' ', 'extenso', LPAD( Ceil(nValor * 100 ), 15, '0' ), '!' );
end if;
RETURN cTxt;
END
$$			
delimiter ;
Na consulta, ela está assim:

Código: Selecionar todos

CREATE DEFINER=`jpatecnologia`@`%` FUNCTION `ze_extenso`(
	`nValue` DECIMAL(15,2)
)
RETURNS varchar(500) CHARSET latin1
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
RETURN CONCAT_WS( ' ', 'Hello', nValue, '!' )
extenso.png
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

dezenove.png
Uia, de 1 a 19 tá pronto.
O difícil foi aquele começo mesmo.

Código: Selecionar todos

DROP FUNCTION if exists ze_extensoUnidade;
delimiter $$
create function ze_extensoUnidade( nValor INT )
RETURNS VARCHAR(500)  DETERMINISTIC 
BEGIN
DECLARE cTxt VARCHAR(500);
SET cTxt := (
case
when nvalor = 1 then 'HUM'
when nvalor = 2 then 'dois'
when nvalor = 3 then 'tres'
when nvalor = 4 then 'quatro'
when nvalor = 5 then 'cinco'
when nvalor = 6 then 'seis'
when nvalor = 7 then 'sete'
when nvalor = 8 then 'oito'
when nvalor = 9 then 'nove'
when nvalor = 10 then 'dez'
when nvalor = 11 then 'onze'
when nvalor = 12 then 'doze'
when nvalor = 13 then 'treze'
when nvalor = 14 then 'quatorze'
when nvalor = 15 then 'quinze'
when nvalor = 16 then 'dezesseis'
when nvalor = 17 then 'dezessete'
when nvalor = 18 then 'dezoito'
when nvalor = 19 then 'dezenove'
ELSE ''
END );
RETURN cTxt;
END
$$			
delimiter ;
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

extenso2.png

Código: Selecionar todos

DROP FUNCTION if exists ze_extensoDezena;
delimiter $$
create function ze_extensodezena( nValor INT )
RETURNS VARCHAR(500)  DETERMINISTIC 
BEGIN
DECLARE cTxt VARCHAR(500);
DECLARE ndezena INT;
DECLARE nunidade INT;
SET ctxt = '';
if nvalor > 0 then 
   if nvalor < 20 then
      set cTxt = ze_ExtensoUnidade( nValor );
   else
      SET ndezena = floor( nvalor / 10 );
      SET nunidade = nvalor - ( ndezena * 10 );
	   set cTxt = (
		case 
		when ndezena = 2 then 'VINTE'
		when ndezena = 3 then 'TRINTA'
		when ndezena = 4 then 'QUARENTA'   
		when ndezena = 5 then 'CINQUENTA'
		when ndezena = 6 then 'SESSENTA'
		when ndezena = 7 then 'SETENTA'
		when ndezena = 8 then 'OITENTA'
		when ndezena = 9 then 'NOVENTA'
		ELSE '' 
		END );
	   if nunidade != 0 then
		   set cTxt = CONCAT( ctxt, ' E ', ze_extensounidade( nUnidade ) );
   	END if ;
	END if;
END if	;
RETURN cTxt;
END
$$			
delimiter ;
Eu gostei de como ficou minha função de extenso no Harbour.
Só ver como tá interessante converter pra MySQL.

Agora dezenas resolvido.
Próximo passo: CENTENAS
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

CENTENA.png
Uia....
Agora tá pronto extenso pra qualquer grupo de centena.
A de centena apaguei o comando, tive que pegar a salva.

Código: Selecionar todos

CREATE DEFINER=`jpatecnologia`@`%` FUNCTION `ze_extensocentena`(
	`nValor` INT
)
RETURNS varchar(500) CHARSET latin1
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE cTxt VARCHAR(500);
DECLARE ncentena INT;
DECLARE ndezena INT;
SET ctxt = '';
if nvalor > 0 then 
   if nvalor = 100 then
      set cTxt = 'CEM';
   else
      SET ncentena = floor( nvalor / 100 );
      SET ndezena = nvalor - ( ncentena * 100 );
	   set cTxt = (
	   case 
	   when ncentena = 1 then 'CENTO'
	   when nCENTENA = 2 then 'DUZENTOS'
	   when nCENTENA = 3 then 'TREZENTOS'
	   when nCENTENA = 4 then 'QUATROCENTOS'   
	   when nCENTENA = 5 then 'QUINHENTOS'
	   when nCENTENA = 6 then 'SEISSENTOS'
	   when nCENTENA = 7 then 'SETECENTOS'
	   when nCENTENA = 8 then 'OITOCENTOS'
	   when nCENTENA = 9 then 'NOVECENTOS'
		ELSE '' 
		END );
	   if nDEZENA != 0 then
		   set cTxt = CONCAT( ctxt, IF( NCENTENA = 0, '', ' e ' ), ze_extensoDEZENA( nDEZENA ) );
   	END if ;
	END if;
END if	;
RETURN cTxt;
END
Aliás, também apaguei a de dezena, a sorte é que salvei aqui no fórum e peguei de volta.
Agora só falta as unidades monetárias, e juntar os blocos.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

visaogeral.png
Pra quem não entendeu ainda.
Estou criando a função DENTRO DO BANCO DE DADOS.

Vantagem?
Se está no banco de dados, QUALQUER LINGUAGEM DE PROGRAMAÇÃO vai poder usar.

Entenderam?

Aquilo de converter pra outra linguagem de programação.....
É converter pra SQL e tem tudo pronto pra qualquer coisa.

Mas o melhor: pode procurar coisa pronta na internet de qualquer linguagem de programação que use SQL.

Lógico, convém lembrar: existem algumas diferenças entre os SQL de SQL Server, MySQL, Firebird, etc.

E como viram aqui, eu apanhei um pouco pra criar a primeira função.
Agora tá começando a dar certo.

Lembrando também: são comandos SQL, que também poderiam ser usados nos SELECTs, pra buscar informações.
Aqui usando pra criar função, que vai ficar disponível para o aplicativo.

Como eu disse tempos atrás, é começar a usar, e vamos descobrindo as possibilidades aos poucos.
Acho que Isso ainda faz parte do básico, de tanta coisa que tem pra aprender.
Podemos viver sem isso, não é obrigado a aprender, mas.... com isso as possibilidades aumentam cada vez mais.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar do usuário
JoséQuintas
Administrador
Administrador
Mensagens: 20267
Registrado em: 26 Fev 2007 11:59
Localização: São Paulo-SP

Função extenso() no MySQL

Mensagem por JoséQuintas »

Aproveitando também....

Trocar DBF pra MySQL/SQL não se trata apenas de como salvar as informações, ou de não ter índice corrompido.
É um "mundo novo", repleto de possibilidades.

No aplicativo, no caso de ADO, vai ser algo como

Código: Selecionar todos

rs := conexao:Execute(  "SELECT ze_Extenso( " + Str( Valor ) + " ) AS EXTENSO"  )
? rs:Fields( "EXTENSO" ):Value
rs:Close()
O servidor vai dar o extenso pronto para o terminal.

E com essas coisinhas.... desenvolver pra web depois pode ser fácil, porque fica tudo no SQL.

Então, ao invés de quebrar a cabeça agora com o que vai usar no futuro, é só começar a usar SQL, e vai deixando tudo preparado.
Vai aprendendo, vai testando, e vai evoluindo o conhecimento.

Sem pressa...
Isso de função, de vez em quando eu tentava alguma coisa....
Ainda não sei direito o que vou fazer, mas primeiro precisava funcionar, o que agora funcionou.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg mt, fivewin 25.04, multithread, dbfcdx, MySQL, ADOClass, PDFClass, SefazClass, (hwgui mt), (hmg3), (hmg extended), (oohg), PNotepad, ASP, stored procedure, stored function, Linux (Flagship/harbour 3.2)
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Responder