0% found this document useful (0 votes)
22 views

Universidad Veracruzana: Facultad de Estadística e Informática

This document discusses stored procedures in MySQL. It provides the syntax for creating stored procedures and functions. Some key points covered include: - Stored procedures are created using the CREATE PROCEDURE statement while functions are created with CREATE FUNCTION. - Parameters can be defined as IN, OUT, or INOUT when creating procedures and functions. - Various flow control structures like IF/ELSE blocks can be used within procedures. - Variables can be declared locally within procedures using DECLARE and the SELECT INTO statement can retrieve results into variables.

Uploaded by

Cristyy Garzaa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Universidad Veracruzana: Facultad de Estadística e Informática

This document discusses stored procedures in MySQL. It provides the syntax for creating stored procedures and functions. Some key points covered include: - Stored procedures are created using the CREATE PROCEDURE statement while functions are created with CREATE FUNCTION. - Parameters can be defined as IN, OUT, or INOUT when creating procedures and functions. - Various flow control structures like IF/ELSE blocks can be used within procedures. - Variables can be declared locally within procedures using DECLARE and the SELECT INTO statement can retrieve results into variables.

Uploaded by

Cristyy Garzaa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Universidad Veracruzana

Facultad de Estadstica e
Informtica
Bases de Datos con MySQL

Store procedures

Procedimientos almacenados

MIS. Lizbeth A. Hernndez Gonzlez

CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
CREATE
[DEFINER = { user | CURRENT_USER }]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body

proc_parameter:
[ IN | OUT | INOUT ] param_name type

func_parameter:
param_name type
type:
Any valid MySQL data type

characteristic:
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL
DATA }
| SQL SECURITY { DEFINER | INVOKER }

routine_body:
Valid SQL routine statement

mysql> DELIMITER //
mysql> CREATE PROCEDURE busca_empleado
-> (in idem int)
-> begin
-> select * from empleados where
nopersonal=idem;
-> end
-> //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;
mysql>call busca_empleado(2000);

mysql> create procedure


despliega_empleados () select * from
empleados;

mysql> call despliega_empleados();

select name from mysql.proc


muestra los nombres de todos los procedimientos almacenados
show procedure status where db = database() and type = 'procedure
ms especfico
show procedure status where db = tintoreria;
select * from information_schema.routines where
routine_schema='tintoreria;
select specific_name from `information_schema`.`routines` where
routine_schema=tintoreria
select specific_name from mysql.proc where db = 'tintoreria;

select name from mysql.proc where db = 'tintoreria' and type = function';


select specific_name from mysql.proc where db = 'tintoreria' and type =
'procedure';

select name, type from mysql.proc where db


= database() order by type, name;
select name, type, param_list, returns from
mysql.proc where db = database() order by
type, name;
mysql> SHOW CREATE PROCEDURE
TINTORERIA.BUSCA_EMPLEADO;

ALTER {PROCEDURE | FUNCTION} sp_name


[characteristic ...]
Permite cambiar las caractersticas, para modificar
los parmetros o el cuerpo del procedimiento
utilizar: drop procedure y create procedure.

DROP {PROCEDURE | FUNCTION} [IF EXISTS]

sp_name

Constructores de control de flujo

SELECT col_name[,...] INTO var_name[,...]

table_expr

Esta sintaxis SELECT almacena columnas seleccionadas


directamente en variables. Por lo tanto, slo un registro
puede retornarse.

SELECT id,data INTO x,y FROM test.t1 LIMIT 1;

*En otros SMBDR la sentencia SELECT INTO puede


insertar los datos de la seleccin en una tabla
local o remota.

DECLARE var_name[,...] type [DEFAULT value]


Este comando se usa para declarar variables
locales. Para proporcionar un valor por defecto para
la variable, incluya una clusula DEFAULT. Si la
clusula DEFAULT no est presente, el valor inicial
es NULL.

La visibilidad de una variable local es dentro


del bloque BEGIN ... END en donde est
declarado.

mysql> DELIMITER //
mysql> create procedure cuenta_servicios (OUT param1 INT)
-> begin
-> select count(*) INTO param1 from servicio;
-> end
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;

mysql> call cuenta_servicios(@a);


Query OK, 1 row affected (0.00 sec)
mysql> select @a;
+------+
| @a |
+------+
| 4|
+------+
1 row in set (0.00 sec)

mysql> delimiter //
mysql> create FUNCTION hola (s char(20)) RETURNS char (50)
-> return concat ('Hello, ',s,'!');
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> select hola('mundo cruel');
+---------------------+
| hola('mundo cruel') |
+---------------------+
| Hello, mundo cruel! |
+---------------------+
1 row in set (0.00 sec)

mysql> DELIMITER //
mysql>
mysql> CREATE PROCEDURE numeros_1_hasta_n
(IN n INT)
-> BEGIN
-> DECLARE contador INT DEFAULT 1;
-> WHILE contador<=n DO
-> SELECT contador; //la salida
-> SET contador = contador + 1 ;

-> END WHILE;


-> END//
Query OK, 0 rows affected (0.04 sec)

call numeros_1_hasta_n(4);

+----------+
| contador |
+----------+
|
1|
+----------+
1 row in set (0.00 sec)
+----------+
| contador |
+----------+
|
2|
+----------+
1 row in set (0.00 sec)

+----------+
| contador |
+----------+
|
3|
+----------+
1 row in set (0.00 sec)
+----------+
| contador |
+----------+
|
4|
+----------+
1 row in set (0.01 sec)
Query OK, 0 rows affected (0.01
sec)

mysql> DELIMITER //
mysql> create procedure insertar_puesto(puesto varchar(20), salario
double)
-> comment 'Procedimiento para insertar un puesto'
-> begin
-> IF NOT EXISTS (select p.idpuesto from puestos p where
p.puesto=puesto) THEN
-> INSERT INTO puestos (puesto, salario) VALUES (puesto, salario);
-> ELSE
-> select 'El puesto ya existe en la base de datos';
-> END IF;
-> END
-> //
Query OK, 0 rows affected (0.04 sec)
mysql> DELIMITER ;

> call insertar_puesto('nuevo', 4000);


Query OK, 1 row affected (0.05 sec)

> select * from puestos;


+----------+------------+--------+
| idpuesto | puesto
| salario |
+----------+------------+--------+
|
1 | Gerente | 15000 |
|
2 | Mostrador | 5000 |
|
14 | planchador | 16000 |
|
15 | prueba
| 6000 |
|
16 | nuevo
| 4000 |
+----------+------------+--------+
5 rows in set (0.00 sec)

> call insertar_puesto('nuevo', 6000);


+----------------------------------------+
| El puesto ya existe en la base de datos |
+----------------------------------------+
| El puesto ya existe en la base de datos |
+----------------------------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)

You might also like