Skip to content

Instantly share code, notes, and snippets.

@JRGGRoberto
Last active August 29, 2015 14:05
Show Gist options
  • Save JRGGRoberto/221fe71a58b801f4d0b7 to your computer and use it in GitHub Desktop.
Save JRGGRoberto/221fe71a58b801f4d0b7 to your computer and use it in GitHub Desktop.
--criação do database
CREATE DATABASE Teste DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
USE Teste;
--criação de uma tabela de teste
CREATE TABLE `nomes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nome` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
--Alguns insert
insert into nomes(nome) value ('Roberto');
insert into nomes(nome) value ('Joelma');
--Criação de um Procedimento para inserir um nome
DROP PROCEDURE IF EXISTS insere_nome;
CREATE PROCEDURE insere_nome(IN v_nome varchar(25), OUT chave int)
BEGIN
insert into nomes(nome) value (v_nome);
select id into chave from nomes where nome = v_nome;
END;
--Como chama-lo
call insere_nome('Góes',@saida);
select @saida
-- 3
--Resultado
select * from nomes;
------------------
-- id | nome |
-- 1 | Roberto |
-- 2 | Joelma |
-- 3 | Góes |
DROP FUNCTION IF EXISTS teste.insert_nome;
CREATE FUNCTION teste.insert_nome(v_nome varchar(25))
RETURNS INT
DETERMINISTIC
BEGIN
declare chave int;
insert into nomes(nome) value (v_nome);
select id into chave from nomes where nome = v_nome;
return chave;
END;
-- Chamar procedimento:
select insert_nome('João Paulo');
--Resultado
--select insert_nome('João Paulo')
-- 4
--Resultado
select * from nomes;
---------------------
-- id | nome |
-- 1 | Roberto |
-- 2 | Joelma |
-- 3 | Góes |
-- 4 | João Paulo |
@JRGGRoberto
Copy link
Author

Exemplo de procedure em MySQL com parametros de entrada e saida.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment