Está en la página 1de 38

Procedimientos Almacenados

Def.Son procesos que realizan una tarea específica con una o más tablas
de datos.USP (User Stored Procedure)

Ejemplos:
-- 1. Crear USP que muestre los productos almacenados u ordenados por
nombre.

Create procedure usp_Listar_Productos


As
select IdProducto,NombreProducto,PrecioUnidad,UnidadesEnExistencia from
Productos
order by NombreProducto
return-- ó Go
--Prueba
execute usp_Listar_Productos

-- 2. Crear USP con transferencia de parámetros.


Liste los productos según su categoría.
Create procedure usp_Listar_ProductosxCate
@xCate int
As
select IdProducto,NombreProducto,IdCategoría from Productos
where IdCategoría = @xCate
order by NombreProducto
return
---Prueba
execute usp_Listar_ProductosxCate1

Laboratorios SQL
1
--3.Crear USP que liste los productos según su nombre.

createprocedure usp_Listar_Productos_Nombre
@xN asVarchar(40)
As
select NombreProducto From Productos
where NombreProducto Like @xN +'%'
OrderBy NombreProducto
return
exec usp_Listar_Productos_Nombre'Ca'---''

--4.Crear un USP que permita listar los pedidos entre dos fechas enviadas
como parámetros.
createprocedure usp_Pedidos_Fechas
@f1 SmallDateTime,
@f2 SmallDateTime
As
select IdPedido,IdCliente,IdEmpleado ,FechaPedido,Cargo from Pedidos
where FechaPedido between @f1 and @f2
return
---Prueba
execute usp_Pedidos_Fechas'01/01/1995','31/03/1995'

Laboratorios SQL
2
-- 5. Crear un USP que muestra los pedidos de un país enviados en un año
específico.
createprocedure usp_Pedidos_Enviados
@PE varchar(15),
@Año int
As
Select IdPedido,IdCliente, IdEmpleado,PaísDestinatario,FechaEnvío from
Pedidos
whereYEAR(FechaEnvío)= @Año and PaísDestinatario =@PE
orderby IdPedido desc
return
---Prueba
execute usp_Pedidos_Enviados'Alemania',1996

-- 6. Pedidos por Cliente.


createProc usp_Pedidos_Clientes
@IdCli varchar(5)
As
select P.IdPedido, P.FechaPedido,P.IdCliente,NombreCompañía,E.Nombre+' '+
E.Apellidos as Empleado, P.PaísDestinatario
from Pedidos P Join Clientes C on P.IdCliente=C.IdCliente
Join Empleados E on P.IdEmpleado=E.IdEmpleado
where P.IdCliente = @IdCli
order by P.FechaPedido Desc
return
---Prueba
execute usp_Pedidos_Clientes'BERGS'

Laboratorios SQL
3
--7. Listar Pedidos por el IdEmpleado.
CreateProc usp_Pedidos_Empleado
@IdEmple int
As
select P.IdPedido, P.FechaPedido,P.IdCliente,NombreCompañía,
E.Nombre +' '+ E.Apellidos as Empleado, P.PaísDestinatario
from Pedidos P Join Clientes C on P.IdCliente=C.IdCliente
Join Empleados E on P.IdEmpleado=E.IdEmpleado
where P.IdEmpleado = @IdEmple
return
---Prueba
Execute usp_Pedidos_Empleado5

--8. Listar pedidos por País.


Create procedure usp_Pedidos_País
@País nvarchar(15)
As
Select P.IdPedido,P.FechaPedido,P.PaísDestinatario,
E.Nombre+' '+E.Apellidos as Empleado,P.IdCliente,C.NombreCompañía
From Pedidos P Join Clientes C on P.IdCliente = C.IdCliente
Join Empleados E on P.IdEmpleado = E.IdEmpleado
Where P.PaísDestinatario=@País
return

---Prueba
Execute usp_Pedidos_País 'Alemania'

Laboratorios SQL
4
--9.Listar Pedidos_ListarTodos.
Create proc usp_Pedidos_ListarTodos
As
Select P.IdPedido, P.FechaPedido, P.PaísDestinatario, P.IdCliente,
NombreCompañía,E.Nombre +' '+ E.Apellidos as Empleado, P.PaísDestinatario
From Pedidos P Join Clientes C on P.IdCliente=C.IdCliente
Join Empleados E on P.IdEmpleado=E.IdEmpleado
Return

---Prueba
execute usp_Pedidos_ListarTodos

Laboratorios SQL
5
-------------------------------------------------------------------------
Consulta de datos agrupados
Devuelve un conjunto de filas correspondiente a grupos de datos en común
en la tabla.

Clase GROUP BY.


Sirve para calcular datos estadísticos con los datos numéricos de una columna de la tabla.

1.select Idpedido ,IdCliente,PaísDestinatario From Pedidos


Group by PaísDestinatario,Idpedido,IdCliente

2.select PaísDestinatario,COUNT(*)As npedidos From Pedidos


Group by PaísDestinatario ---filtrados de una columna.

Modificador Distinct.No se repitan los datos iguales

Select Distinct PaísDestinatario From Pedidos


Select Distinct CargoContacto From Clientes

Select Distinct Nombre ,Cargo ,Ciudad From Empleados

-------------------------------------------------------------------------

Laboratorios SQL
6
Funciones Estadísticas
AVG Promedio / Sum Suma / Max  Mínimo
select PaísDestinatario,
COUNT(*)As NPedidos,
AVG(Cargo)As PromedioCargo ,
MAX(Cargo)As MayorCargo,
MIN(Cargo)As MenorCargo ,
SUM(Cargo)As Totalcargo From Pedidos
Groupby PaísDestinatario
Having PaísDestinatario<>'Brail'or PaísDestinatario <>'Argentina'

Having
Es una claúsula que permite establecer una condición de datos agrupados

1.select PaísDestinatario,
COUNT(*)As NPedidos,
AVG(Cargo)As PromedioCargo ,
MAX(Cargo)As MayorCargo,
MIN(Cargo)As MenorCargo ,
SUM(Cargo)As Totalcargo From Pedidos
Group by PaísDestinatario
Having COUNT(*)>=50 and AVG(Cargo)>=60

2.select PaísDestinatario,
COUNT(*)As NPedidos,
AVG(Cargo)As PromedioCargo ,
MAX(Cargo)As MayorCargo,
MIN(Cargo)As MenorCargo ,
SUM(Cargo)As Totalcargo From Pedidos
Groupby PaísDestinatario
Having PaísDestinatario In('Brasil','Argentina')
---- Having not PaísDestinatario In ('Brasil','Argentina')

Laboratorios SQL
7
3.Hacer una estadística de los productos agrupados por sus categorías de
solo los productos que no esten suspendidos ,el resultado debe mostrar el
nombre de la categoría.
select C.NombreCategoría,
COUNT(*)As nProductos ,
SUM(P.UnidadesEnExistencia)As TotalStock,
AVG(P.PrecioUnidad)AS PromedoPrecio,
MAX(P.PrecioUnidad)As MayorPrecio,
MIN(P.PrecioUnidad)As MínimoPrecio
From Productos P Inner Join Categorías C -- unir(INNER JOIN) dos tablas
On P.IdCategoría = C.IdCategoría --con el campos en común
Where P.Suspendido=0 -- el valor suspendido es dato tipo bye
Group by C.NombreCategoría

Laboratorios SQL
8
-------------------------------------------------------------------------
Procedimientos Almacenados_Mantenimiento-Empleados
---1.Listar empleados
Create procedure usp_Listar_Empleados
As
select
IdEmpleado,Nombre,Apellidos,Cargo,Tratamiento,Dirección,Ciudad,País
from Empleados
order by IdEmpleado
return

---2.Ubicar un empleado
Create procedure usp_Empleado_Buscar
@IdEmpl int
As
select
IdEmpleado,Nombre,Apellidos,Cargo,Tratamiento,Dirección,Ciudad,País,TelDo
micilio
from Empleados
where IdEmpleado=@IdEmpl
return
--Prueba
execute usp_Empleado_Buscar6---no olvidarse enviar el parámetro

--- 3.Adicionar Empleado


Create procedure usp_Empleado_Adicionar
--parámetro de Salida--
@Id int output,
--parámetros de entrada--
@Nombre varchar(10),
@Apellidos varchar(20),
@Cargo varchar(30),
@Trata varchar(25),
@Tel varchar(60),
@Dir varchar(15),
@Ciudad varchar (20),
@País varchar (15)
As
---se escribe en el orden en el que se escribieron los parámetros
Insert into Empleados
(Nombre ,Apellidos ,Cargo ,Tratamiento ,TelDomicilio ,Dirección ,Ciudad ,País )
Values (@Nombre,@Apellidos,@Cargo,@Trata,@Tel,@Dir,@Ciudad,@País)
--el @Id no se coloca porque es automático
set @Id=@@IDENTITY
-------------------------------------------------------------------------
Nota:@@IDENTITY es una variable del sistema o también Return '@@Identity'
-------------------------------------------------------------------------------------------
--Prueba
Declare @x int-- declaro la variable que se asociara con @Id
Execute usp_Empleado_Adicionar@x
output,'Juber','Ortega','Gerente','Sr.','455825','Av.Trebol 7895 Los
Olivos','Chanchamayo','Perú'
Print @x

Laboratorios SQL
9
---4.Actualizar datos del Empleado
Create procedure usp_Empleado_Actualizar
@Id int,
@Nombre varchar(10),
@Apellidos varchar(20),
@Cargo varchar(30),
@Trata varchar(25),
@Tel varchar(60),
@Dir varchar(15),
@Ciudad varchar (20),
@País varchar (15)
As
Update Empleados set
Nombre=@Nombre,Apellidos=@Apellidos,Cargo=@Cargo,Tratamiento=@Trata,
TelDomicilio=@Tel,Dirección=@Dir,Ciudad=@Ciudad,País=@País
where IdEmpleado=@Id
return
---Prueba
Execute USP_Empleado_Actualizar 34,
'Antony','Florencio','Recepcionisto','Ms.', '987654321',
'Av. Marco Polo 789 los jardines','Lima','Perú'
Select * From Empleados

---5.Eliminar Empleado
Create procedure usp_Empleado_Eliminar
@Id int
As
Delete from Empleados
where IdEmpleado = @Id
return
---Prueba
execute usp_Empleado_Eliminar 34

-------------------------------------------------------------------------

Laboratorios SQL
10
Procedimientos Almacenados_Mantenimiento - Productos
--- 1.Adicionar Producto
Create procedure usp_Producto_Adicionar
@IdProducto int output,--parametro de salida
@NombreProductoVarchar(40),
@IdProveeint,
@IdCateint,
@Precio money,
@stock smallint
as
insert intoProductos
(NombreProducto,IdProveedor,IdCategoría,PrecioUnidad,UnidadesEnExistencia)
values(@NombreProducto,@IdProvee,@IdCate,@Precio,@stock)
set @IdProducto =@@IDENTITY

--- 2.Actualizar Producto


Create procedure usp_Producto_Actualizar
@IdProducto int,
@Nombre Varchar(40),
@IdProvee int,
@IdCate int,
@Precio money,
@stock smallint
As
Update Productos set NombreProducto=@Nombre ,IdProveedor =@IdProvee
,IdCategoría =@IdCate ,PrecioUnidad=@Precio,UnidadesEnExistencia =@stock
where IdProducto = @IdProducto
return

--- 3.Eliminar Producto


Createprocedure usp_Producto_Eliminar
@IdProducto int
as
Delete from Productos where IdProducto=@IdProducto

--- 4.Producto Mostrar


Create procedure usp_Producto_Mostrar
@IdProducto int
as
select
IdProducto,NombreProducto,IdProveedor,IdCategoría,PrecioUnidad,UnidadesEn
Existencia from Productos
Where IdProducto=@IdProducto
go

--- 5.Productos Listar


Createprocedure usp_Producto_Listar
as
selectIdProducto,NombreProducto,IdProveedor,IdCategoría,PrecioUnidad,Unid
adesEnExistenciafromProductos
orderby 2
go

Laboratorios SQL
11
-------------------------------------------------------------------------
Procedimientos Almacenados_Mantenimiento - Pedidos
--- 1.Adicionar Pedidos
Create procedure usp_Pedidos_Adicionar
@IdPed int output,’variable que devuleva el código del pedido
@IdCliente int,
@IdEmpleado int,
@Fecha_Pedido datetime,
@Cargo money,
@Destinatario varchar (40),
@Dirección varchar (60),
@País varchar (10)
as
insert into
Pedidos(IdCliente,IdEmpleado,FechaPedido,Cargo,Destinatario,DirecciónDest
inatario,PaísDestinatario)
values(@IdCliente,@IdEmpleado ,@Fecha_Pedido ,@Cargo,@Destinatario
,@Dirección,@País)
set @IdPed=@@IDENTITY

--- 2.Actualizar Pedidos


createprocedureusp_Pedidos_Actualizar
@IdPed int,
@IdCliente int,
@IdEmpleado int,
@Fecha_Pedido datetime,
@Cargo money,
@Destinatario varchar (40),
@Dirección varchar (60),
@País varchar (10)
as
Update Pedidos set IdPedido=@IdPed,IdCliente=@IdCliente
,IdEmpleado=@IdEmpleado,FechaPedido=@Fecha_Pedido,Cargo=@Cargo
,Destinatario =@Destinatario,
DirecciónDestinatario=@Dirección,PaísDestinatario=@País
Where IdPedido = @IdPed
Return

--- 3.Eliminar Pedidos


Create procedure usp_Pedidos_Eliminar
@IdPed int
as
Delete from Pedidos where IdPedido=@IdPed

--- 4.Pedidos Mostrar


Create Proc Usp_Pedidos_Mostrar
@IdPed int
as
Select
IdPedido,IdCliente,IdEmpleado,FechaEntrega,FechaEnvío,FormaEnvío,Cargo,De
stinatario,DirecciónDestinatario,CiudadDestinatario,RegiónDestinatario,Có
dPostalDestinatario,PaísDestinatario From Pedidos
Where IdPedido=@IdPed

Laboratorios SQL
12
-------------------------------------------------------------------------
Subconsultas
Def.Una subconsulta es una consulta dentro de otra que puede ser incorporada en
una clausula where ó en una lista de campos ,las subconsultas son aplicadas a
instrucciones select,update,insert into.

Ejercicios
--- 1.Mostrar los clientes que le vendieron durante el año 1996.
Select IdCliente,NombreCompañía,NombreContacto,País from Clientes
Where IdCliente in
(select distinct IdCliente from Pedidos where YEAR(FechaPedido)=1996)

--Otra forma
Select distinct C.IdCliente,C.NombreCompañía,C.NombreContacto,C.País
From Clientes C INNERJOIN Pedidos P
on C.IdCliente =P.IdCliente
where YEAR(P.FechaPedido)=1996
*No se puede relacionar pedidos con producto porque la relación es muchos
a muchos,se necesita una tabla intermedia.

--- 2.Mostrar los clientes que se le enviaron el producto té tharansala


en el año 1996.
Select distinct IdCliente,NombreCompañía,NombreContacto,País
from Clientes
where IdCliente in(select IdCliente from Pedidos
where IdPedido in(select IdPedido from[Detalles de pedidos]
where IdProducto in(select IdProducto from Productos
where NombreProducto='Té Dharamsala')) and YEAR(FechaEnvío)=1996)

--- 3.Mostrar los productos que tienen un precio mayor a dos veces el
promedio de precio de todos los productos.
Select IdProducto,NombreProducto,CantidadPorUnidad from Productos
Where PrecioUnidad >=(select AVG(PrecioUnidad)from Productos)

Laboratorios SQL
13
EJERCICIOS
--- 1.Mostrar los Productos con un campo calculado que muestre el total
de ventas de cada producto que haya tenido descuento.
-------------------------------------------------------------------------
Nota:Se elige un producto luego se utiliza la tabla detalles_Pedidos
-------------------------------------------------------------------------
Select IdProducto as Código,NombreProducto as Producto,
(selectSUM(PrecioUnidad*Cantidad*(1-Descuento))
From[Detalles de pedidos]
whereIdProducto=Productos.IdProducto and Descuento>0)as Total
From[Productos]

---2.Mostrar los Productos de la categoría lácteos que tengan un precio


por debajo de los precios de esa categoría.
select [NombreProducto] as Producto,C.NombreCategoría as categoría,
P.PrecioUnidad as precio from
Productos P inner join Categorías C
on P.IdCategoría = C.IdCategoría
where C.NombreCategoría = 'Lácteos' and P.PrecioUnidad < (select
AVG(PrecioUnidad)from Productos)

Laboratorios SQL
14
---3.Mostrar los países donde se enviaron el producto "pez espada"
durante los meses de Enero a Marzo del año 1995.
-------------------------------------------------------------------------
Nota:EXISTSes una función SQL que devuelve verdadero cuando una
subconsulta retorna al menos una fila.
-------------------------------------------------------------------------
selectdistinctPaísDestinatariofromdbo.Pedidos
whereEXISTS(Select*from[Detalles de pedidos]
whereIdProducto in
(SelectIdProductoFROMProductos whereNombreProducto='Pez
espada'))andFechaEnvíoin('01/01/1995','31/03/1995')

--- 4.Mostar los Productos que tengan igual precio que "Te Dharamsa".

---5.Mostar los clientes de Alemania, y la cantidad de Pedidos realizados


por esos clientes durante el año 1996.
selectC.NombreCompañía asClientes,COUNT(D.IdPedido)asCantidad,C.País
FromPedidosPinnerjoinClientesC
onP.IdCliente=C.IdCliente
innerjoin[Detalles de pedidos]D
onP.IdPedido=D.IdPedido
WhereC.País='Alemania'andYEAR(P.FechaPedido)=1996
GroupByC.NombreCompañía,C.País
Go

--- 6.Crear usp que muestre la cantidad de pedido que ha sido vendido un
Producto(X) por un Vendedor(Y).
createprocedureusp_CantidadPedidosVendidos
@NomProdvarchar(40),
@NomVend varchar(20)
as
selectEmpleados.Apellidos,
Productos.NombreProducto,COUNT([Detalles de pedidos].IdPedido)asCantidad
fromPedidosINNER JOINEmpleados
onPedidos.IdEmpleado=Empleados.IdEmpleado
INNERJOIN[Detalles de pedidos]
onPedidos.IdPedido=[Detalles de pedidos].IdPedido

Laboratorios SQL
15
INNERJOINProductos
on[Detalles de pedidos].IdProducto=Productos.IdProducto
GroupbyEmpleados.Apellidos,Productos.NombreProducto
HavingProductos.NombreProducto=@NomProdandEmpleados.Apellidos=@NomVendGO
-------------------------------------------------------------------------
Nota:Paraaplicar la condición en los grupos utilizoHAVING no uso WHERE.
-------------------------------------------------------------------------
Execute usp_CantidadPedidosVendidos'Pez espada ','Davolio'

PRÁCTICA 06/08/11
--- 1.Crear el Proc q muestre los paises en donde se han enviado un
determinado producto,el Proc recibirá como parametro el ID del Producto.
CreateProcUsp_Listar_Producto_xPais
@IdProInt
As
SelectDistinctPaísDestinatario
FromPedidos
WhereEXISTS(Select*From[Detalles de pedidos]
WhereIdProducto in(SelectIdProductoFromProductos
whereIdProducto=@IdPro))
--Prueba
executeUsp_Listar_Producto_xPais'1'

--- 2.Crear el Proc almacenado que actualize el stock de los Productos


según la cantidad y el Id del Producto que se envia al procedimiento
almacenado.
CreateProcedureUsp_Actualizar_Stock
@IdProint,
@Cantint
As
SelectIdProducto,NombreProducto,PrecioUnidad,UnidadesEnExistenciafromProd
uctos
updateProductosSETUnidadesEnExistencia=UnidadesEnExistencia +@Cant

Laboratorios SQL
16
WHEREIdProducto=@IdPro
go
--Prueba
execUsp_Actualizar_Stock1,60

--- 3.Crear el Proc almcenado que elimine los pedidos entre 2 Fechas de
un País determinado.
CreateProcedure Usp_Eliminar_Entre_Fechas
@PaisChar(15),
@Fech1SmallDateTime,
@Fech2SmallDateTime
As
DeleteFromPedidos
WherePaísDestinatario=@PaisandFechaPedidoin(@Fech1,@Fech2)
go
--Prueba
executeUsp_Eliminar_Entre_Fechas'Brasil','1995-08-01','1994-08-12'

--- 4.Crear el Proc almacenado que permita adicionar un nuevo empleado a


la tabla empleados, considerando que elcampo IDempleado es Identidad y
que deverá mostrar el nuevo Id generado por la operación.
CreateProcedureUsp_Adicionar_Empleado
@IdEmpleintoutput,
@ApellidosChar(30),
@Nombchar(15),
@CargoChar(15),
@Ciudadchar(15)
As

Laboratorios SQL
17
InsertIntoEmpleados (Apellidos,Nombre,Cargo,Ciudad)
values(@Apellidos,@Nomb,@Cargo,@Ciudad)
set@IdEmple=@@IDENTITY
Go
--Prueba
Declare@Idint
execUsp_Adicionar_Empleado @Idoutput,'Juber','Conter','Jefe','Cuzco'
go

EJERCICIOS 07/08/11
---1.Crear el usp que liste los productos que comiencen con un texto
enviado como parámetro.

Ifexists(selectnamefromsysobjects--La tabla sysobjects se guardan todos los objetos


que se generan en una base de datos como: tablas,vistas,usp,funciones,triggers,etc.
wherename='usp_Listar_Productos_texto'andtype='P')
dropprocedureusp_Listar_Productos_texto-- drop,elimina el usp
go
createprocedureusp_Listar_Productos_texto
@xDatovarchar(40)=''
as
selectNombreProductofromProductos
whereNombreProductoLike@xDato+'%'
return
----
executeusp_Listar_Productos_texto'e'--si no le envio nada en paréntesis.

-- EXISTS .- es una función SQL que devuelve verdadero cuando una subconsulta retorna al
menos una fila y devuelve falso cuando no retorna ninguna fila.
--SELECT CO_CLIENTE,NOMBRE FROM CLIENTES
WHERE EXISTS(SELECT * FROM MOROSOS WHERE CO_CLIENTE = CLIENTES.CO_CLIENTE AND PAGADO = 'N')

---2.Crear un usp que actualice el stock de los productos según un


porcentaje enviado como parámetro

IfOBJECT_ID('usp_Productos_Actualizar','P')IsNOTNULL-- verifica si el
procedimiento devuelve un valor
DropProcedureusp_Productos_Actualizar
go
createprocedureusp_Productos_Actualizar
@porcentajereal=0,--si no lo envio el porcentaje lo pone cero,valor por defecto.

Laboratorios SQL
18
@cateint=0 --no se asigna un texto a un número
as
updateProductos
setUnidadesEnExistencia=convert(int,
UnidadesEnExistencia+UnidadesEnExistencia*@porcentaje/100 )
whereIdCategoría=@cate
return
----
executeusp_Productos_Actualizar10,1

---3.Se desea incrementar los precios de los productos según las


categorías(1,2,3,...,8),enviando como parámetros los porcentajes que se
deben incrementar en el orden de los códigos de las categorías

createprocedureusp_Precios_Actualizar
@porcentajereal=0,--si no lo envio el porcentaje lo pone cero,valor por defecto.
@cateint=0 --no se asigna un texto a un número
as
updateProductos
setPrecioUnidad=PrecioUnidad+PrecioUnidad*@porcentaje/100
whereIdCategoría=@cate
return
----
executeusp_Precios_Actualizar10,1
Creación de una Base de Datos
--Archivos: Archivo de datos primario(extensión.mdf), Archivo de datos
secundario(extensión.ndf)Transacciones(extensión.ldf)
--Tienen nombres : Físicos
Lógicosnombre(administracion de la base datos)

USEMASTER
GO
Create DATABASE MASTER_EMPRESA--Nombre lógico
on
PRIMARY--Se crea con valores por defecto

--CREANDO ARCHIVO PRIMARIO DE DATOS


(NAME=SYSDATOS1,
FILENAME='E:\SYSDATOS1.mdf',--ARCHIVO FISICO
SIZE=200MB,--Defines tamaño de BD en megabytes
MAXSIZE=400MB,
FILEGROWTH=20),--Tamaño del incremento-FILEGROWTH(10% del original) del
grupo de archivos.

--CREANDO ARCHIVO SECUNDARIO DE DATOS(se guardan la data pura)


(NAME=SYSDATOS2,
FILENAME='E:\SYSDATOS2.ndf',
SIZE=200MB,
MAXSIZE=400MB,
FILEGROWTH=20)

--CREANDO ARCHIVO DE TRANSACCIONES (se registra procedimientos


almacenados,vistas,funciones,etc).
LOGON
(NAME=SYSLOG1,

Laboratorios SQL
19
FILENAME='E:\SYSLOG1.ldf',
SIZE=200MB,
MAXSIZE=400MB,
FILEGROWTH=20),
(NAME=SYSLOG2,
FILENAME='E:\SYSLOG2.ldf',
SIZE=200MB,
MAXSIZE=400MB,
FILEGROWTH=20)
Go

--CREAR TABLA EN EL GRUPO DE VENTAS


CREATETABLECHEQUES
(
IdDOCSmallint,
Ndocvarchar(30),
IdClientevarchar(10),
FechaSmalldatetime,
Verificadobit,
Empleadosmallint
)
onGrupo_Ventas--tabla se crea dentro de este grupo de archivos de la BD.
go

--Nota:Si no se define un tamaño para el Archivo primario entonces se


fija un tamaño inicial de 3 mb y no se fijará un tamaño máximo y el
FILEGROUP será un 10% del tamaño inicial del archivo primario.

--Consulta de devuelve el nombre del grupo


selectFILEGROUP_NAME(1)
selectFILEGROUP_NAME(2)

Unión de tablas
CreateDatabaseBDMASTER
UseBDMASTER
--CREAR TABLAS --
CreateTableTabla01
(IdPedidointPrimaryKey,
IdClientechar (5)notnull,
MontoSmallmoneynotnull,
FechaSmallDateTime
)
go
CreateTableTabla02
(IdPedidointPrimaryKey,
IdClientechar (5)notnull,
MontoSmallmoneynotnull,
FechaSmallDateTime
)
go
CreateTableTabla03
(IdPedidointPrimaryKey,
IdClientechar (5)notnull,
MontoSmallmoneynotnull,
FechaSmallDateTime

Laboratorios SQL
20
)
go

Adicionar data a las tablas


--Tabla 01--
INSERTINTOTabla01values(1,'aaaaa',250,'01/10/2011')
INSERTINTOTabla01values(2,'bbbbb',450,'02/10/2011')
INSERTINTOTabla01values(3,'ccccc',550,'03/10/2011')
go
--Tabla 02--
INSERTINTOTabla02values(4,'ddddd',350,'04/10/2011')
INSERTINTOTabla02values(5,'eeeee',150,'05/10/2011')
INSERTINTOTabla02values(6,'fffff',650,'06/10/2011')
go
--Tabla 03--
INSERTINTOTabla03values(4,'ddddd',1050,'10/10/2011')
INSERTINTOTabla03values(7,'eeeee',1503,'11/10/2011')
INSERTINTOTabla03values(8,'fffff',6050,'12/10/2011')
go

Combinar tablas mediante el operador UNION


--Caso1.- Usando el operador UNION sin quitar las filas duplicadas del
conjunto de resultados.
select*fromTabla01
UNION
(Select*fromTabla02
UNION
select*fromTabla03)
go
---Agregar un registro de la tabla03 a la tabla02
INSERTINTOTabla02values(8,'fffff',6050,'12/10/2011')
--Caso2.- Cuando los datos son iguales el operador UNION quita las filas
duplicadas.
select*fromTabla01
UNION
(Select*fromTabla02
UNION
select*fromTabla03)
go
--Caso3.- Cuando el oprerador incluye todas las filas duplicadas.
select*fromTabla01
UNIONALL-- une todos
(Select*fromTabla02
UNIONALL
select*fromTabla03)
go
select*intoTablaFinalfromTabla01
UNIONALL
(Select*fromTabla02
UNIONALL
select*fromTabla03)

Laboratorios SQL
21
Modificar la estructura de una tabla
--Adicionar una columna
Alter Table TablaFinal
Add Estado bit null
go
exec sp_help TablaFinal

--Modificar una columna--


Alter Table TablaFinal
AlterColumnEstadointnull
go
execsp_helpTablaFinal

--Eliminar una columna--


AlterTableTablaFinal
dropcolumnEstado
go
execsp_helpTablaFinal

Revisión de restricciones con columnas Primary Key y Foreing Key


--Establece que los datos que existe en una columna también debe existir
en la otra tabla.

--Creamos la tabla principal con clave primaria


createtableClientes
(IdClienteintPrimaryKey)
go

--Creamos la tabla secundaria con clave foránea


--Establecer una retriccion de Integridad Referencial
createtablepedidos
(
IdPedido int IDENTITY PrimaryKey,
IdCliente int notnull REFERENCES Clientes(IdCliente)
)
go

---Prueba--
InsertIntoPedidos(IdCliente)values(5)
--error porque no existe el cliente(5)

--Si adicionamos el cliente(5)


InsertIntoClientesvalues(5)
InsertIntoClientesvalues(6)
InsertIntoClientesvalues(7)
InsertIntopedidos(IdCliente)values(5)
InsertIntopedidos(IdCliente)values(6)
InsertIntopedidos(IdCliente)values(7)

Laboratorios SQL
22
--otra forma
CreateTableComprobantes
(
IdDocumento int Identity PrimaryKey,
IdPedi int
foreignkey(IdPedi) References Pedidos(IdPedido)
)
Go

--Prueba--
InsertIntoComprobantes(IdPedi)values(2)
InsertIntoComprobantes(IdPedi)values(4)
InsertIntoComprobantes(IdPedi)values(5)

select*frompedidos
select*fromComprobantes
select*fromClientes

PRÁCTICA 02/11/11

--- 1.Crear el procedimiento almacenado que muestre los pedidos que


pertenecen aun mes y un año , mostrando el nombre del cliente, el
contacto y el nombre del vendedor.

Createprocusp_pedidos_mostrar
@mesint,
@anoint
As
SELECTP.IdPedido,P.FechaPedido,C.NombreCompañíaasCliente,C.NombreContactoasContac
to,E.Apellidos+' '+E.NombreAsVendedor
FROMPedidosPInnerJoinClientesC
OnP.Idcliente=C.IdCliente
InnerJoinEmpleadosE
OnP.IdEmpleado=E.IdEmpleado
WHEREMONTH(FechaPedido)=@mesANDYEAR(FechaPedido)=@ano

OrderByC.NombreCompañía
Go
--- Prueba ---
execusp_pedidos_mostrar5,1996

Laboratorios SQL
23
---2.Crear el procedimiento almacenado que muestre la cantidad de pedidos
de un vendedor en donde haya enviado un determinado producto.

CreateprocPedidos_Vendedor
@provarchar(20),
@venvarchar(30)
as
selectcount([Detalles de pedidos].IdPedido)ascantidad
FROMPedidosINNERJOINEmpleados
ONPedidos.IdEmpleado=Empleados.IdEmpleado
innerjoin[Detalles de pedidos]
onPedidos.IdPedido=[Detalles de pedidos].IdPedido
innerjoinProductos
on[Detalles de pedidos].IdProducto=Productos.IdProducto
groupbyEmpleados.Apellidos,Productos.NombreProducto

HAVINGProductos.NombreProducto=@proandEmpleados.Apellidos=@ven
Go
--Prueba--
execPedidos_Vendedor'Pez espada','King'

Laboratorios SQL
24
---3.Crear el procedimiento almacenado que devuelva el total de
descuentos de los pedidos realizados entre dos fechas.

CREATEPROCEDUREusp_Estadistica3
@Rrealoutput,
@f1smalldatetime,
@f2smalldatetime
AS
Select@R=SUM(D.Cantidad*D.PrecioUnidad*(1-D.Descuento))---A que precio fue vendido
From PedidosPinnerjoin[Detalles de pedidos]D
onP.IdPedido=D.IdPedido
whereFechaPedidobetween@f1and@f2
Return@R
--Prueba--
Declare@Resulreal
Executeusp_Estadistica3@Resuloutput,'01/01/1995','31/01/1995'
print@Resul

EXÁMEN PARCIAL 09/11/11

---1.Crear una base de datos mediante un script T-SQL, con las siguientes
características:
Nombre : SysExamen
Archivo de Datos : SysExa_Dat
Tamaño : 500MB
Archivo de transacciones: SysExa_Log

CreateDataBaseSysExamen
on
primary
(NAME=SysExa_Dat,
Filename='E:\SysExa_Dat.mdf',
size=500MB,
filegrowth=20)
logon
(NAME=SysExa_log,
Filename='E:\SysExa_log.ldf',
size=50MB,--- El tamanó es un 10% del tamaño del archivo de datos.

Laboratorios SQL
25
filegrowth=20)
go

---2.Crear una tabla con la instrucción select into , de los 10 productos


más carosllamada Productos _Caros copiando: el IdProducto,
NombreProducto,PrecioUnidad y NombreCategoría.

selecttop 10
P.IdProductoasCódigo,P.NombreProductoasProducto,P.PrecioUnidadasPrecio,P.
SuspendidoasSituación,C.NombreCategoríaasCategoríaintoProductosCaros
fromProductosPinnerjoinCategoríasC
onP.IdCategoría=C.IdCategoría
orderbyP.PrecioUnidaddesc
select*fromProductosCaros

---3.Crear en la base de datos SysMaster,escribir los scripts T-SQL, que


permitas crear las siguientes tablas:
clientes -->datos principales del cliente
cuenta_ahorros -->datos de la cuenta de la cuenta de ahorra del cliente
operaciones -->operaciones que realiza el cliente con una de ahorros en
una fecha determinada.

CreateDataBaseSysMaster
useSysMaster

--tabla clientes
createtableClientes
(IdClienteintprimaryKey,
NombreClientechar(40)notnull,
Direcciónchar (50)notnull,
telchar (10)notnull,
)
go

--tabla Cuenta de Ahorros

Laboratorios SQL
26
createtableCuenta_Ahorros
(NroCuentaintprimarykey,
tipoCuentachar (20)notnull,
cargosmallmoneynotnull,
IdClienteint
foreignkey (IdCliente)ReferencesClientes(IdCliente)
)
go

--tabla Operaciones
createtableOperaciones
(CodOpechar(5)primaryKeynotnull,
nomOpevarchar(20)notnull,
Fecha_opesmalldatetimenotnull,
nroCuentaint
foreignkey(NroCuenta)ReferencesCuenta_Ahorros(NroCuenta)
)
go

Funciones definidas por el usuario


---Es una porción encapsulada de código que puede ser reutilizada por
diferentes programas.

--Ventaja.permite obtener tiempos de ejecución mucho más rápidos

---1.FUNCIÓN CON VALOR DE TABLA DE VARIAS INSTRUCCIONES

--Creamos la función ListadoPais,luego el parámetro de entrada(@pais)con


su tipo de dato

CreatefunctionListadoPais(@paisvarchar(100))

--Con la clásula returns defino el nombre de variable local para la tabla


returns@clientestable-- tipo de dato "table"

--Formato de la tabla
(IdClientevarchar(5),NombreCompañíavarchar(50),NombreContacto
varchar(100),Paísvarchar(15))

Laboratorios SQL
27
As

--Cuerpo de la instruccion "begin..end"


begin
--Inserto filas en la variable(tabla que sera retornada)
Insert@clientes
selectIdCliente,NombreCompañía,NombreContacto,País fromClientes
wherePaís=@pais
Return-- Return indica que las filas insertadas en la variable son retornadas
end

---Prueba---
--Este tipo de función puede ser referenciada en el "from" de una consulta.

Select*fromdbo.ListadoPais('Argentina')

---2.FUNCIÓN CON VALOR DE TABLA EN LÍNEA

--Def.Una función con valores de tabla en línea retorna una


tabla(DataTable) que es el resultado de una única instrucción "select".

--Creamos la funcion ListadoPais2 luego declaramos el parámetro @pais con


su tipo de dato
CreatefunctionListadoPais2(@paisvarchar(15))
returnstable--- Con return especifico "table" con el tipo de dato a retornar
as
return--- La clásula return contiene una sola instruccion "select" entre paréntesis
(
selectIdCliente,NombreCompañía,NombreContacto,País fromclientes
wherePaís=@pais
)
---Prueba---
Select*fromdbo.ListadoPais2('Argentina')

Laboratorios SQL
28
--- 3.FUNCIÓN CON VALOR DE TABLAEN LÍNEA
IFOBJECT_ID(N'fn_VentasHistoricas',N'IF')ISNOTNULL
DROPFUNCTIONfn_VentasHistoricas;
GO
CREATEFUNCTIONfn_VentasHistoricas(@idchar(5))
RETURNSTABLE
AS
RETURN
(SELECTP.IdProducto,P.NombreProducto,SUM(D.Cantidad*D.PrecioUnidad)AS'Tot
al'
FROMPedidosINNERJOINClientes
onPedidos.IdCliente=Clientes.IdCliente
INNERJOIN[Detalles de pedidos]D
onPedidos.IdPedido=D.IdPedido
INNERJOINProductosP
onD.IdProducto=P.IdProducto
WHEREClientes.IdCliente=@id
GROUPBYP.IdProducto,P.NombreProducto);
GO
---Prueba—
SELECT*FROMfn_VentasHistoricas('Bergs')

--- 4. FUNCIÓN CON VALOR ESCALAR


--- Retorna un resultado con un valor escalar(un dato lógico,un texto,dato de
tipo boolean).

IFOBJECT_ID(N'dbo.GetWeekDay',N'FN')ISNOTNULL
DROPFUNCTIONdbo.GetWeekDay;

--- La función evalúa una fecha proporcionada y devuelve un valor


que designa la posición de esa fecha en una semana.

CREATEFUNCTIONdbo.GetWeekDay(@Datedatetime)
RETURNSint
AS
BEGIN
RETURNDATEPART(weekday,@Date)
END
GO

Laboratorios SQL
29
---Prueba—
SELECTdbo.GetWeekDay(CONVERT(DATETIME,'20020201',101))ASDayOfWeek;
GO

--- 5. FUNCIÓN CON VALOR ESCALAR

CREATEFUNCTION[dbo].[CalcularSemanas](@DATEdatetime)
RETURNSint
AS
BEGIN
DECLARE@nSemanasint
SET@nSemanas=DATEPART(wk,@DATE)+1
-DATEPART(wk,CAST(DATEPART(yy,@DATE)
ASCHAR(4))+'0104')
IF (@nSemanas= 0)
SET@nSemanas=dbo.CalcularSemanas(CAST(DATEPART(yy,@DATE)-1
ASCHAR(4))+'12'+CAST(24 +DATEPART(DAY,@DATE)
ASCHAR(2)))+ 1
IF ((DATEPART(mm,@DATE)=12)AND
((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28))
SET@nsemanas= 1
RETURN(@nSemanas)
END

TRIGGERS
--Un trigger (o disparador), es un procedimiento que se ejecuta cuando se cumple
una condición establecidaal realizar una operación de inserción
(INSERT),actualización (UPDATE) o borrado (DELETE).

--Tipos:
 Data Manipulation Languaje (DML): se ejecutan con las intrucciones INSERT,
UPDATE or DELETE.
 Data Definition Languaje (DFL): se ejecutan cuando se crean, alteran o
borran objetos de la base de datos.

--Efectos y Características:
 No aceptan parámetros o argumentos (pero podrían almacenar los datos
afectados en tablas temporales)
 No pueden ejecutar las operaciones COMMIT o ROLLBACK por que estas son
parte de la sentencia SQL del disparador (únicamente a través de
transacciones autónomas)

Laboratorios SQL
30
Pueden causar errores de mutaciones en las tablas, si se han escrito de manera
deficiente.

--Por ejemplo, puede crearse un trigger de inserción en la tabla "ventas" que


compruebe el campo "stock" de un artículo en la tabla "articulos"; el disparador
controlaría que, cuando el valor de "stock" sea menor a la cantidad que se
intenta vender, la inserción del nuevo registro en "ventas" no se realice.
--Los triggers se crean con la instrucción “createtrigger”.Esta instrucción
especifica la tabla en la que se define el disparador,los eventos para los que se
ejecuta y la instrucciones que contiene.

Mantenimiento de la Tabla Productos

--- 1.Adicionar Producto---

CreateTriggerT_Prod_Adicionar---Nombre del disparador


ONProductos--nombre de la tabla para la cual se establece el trigger
FORINSERT-- se define el evento que activará el trigger
AS-- se especifican las condiciones y acciones del disparador
BEGIN
SELECTNombreProducto,IdProveedor,IdCategoría,PrecioUnidad,UnidadesEnExi
stenciaFROMINSERTED
END
---Prueba---
InsertintoProductos(NombreProducto,IdProveedor,IdCategoría,PrecioUnidad,U
nidadesEnExistencia)
values('Mostaza',20,3,19,16)

---2.Actualizar Producto---

a.CreateTriggerT_Prod_Actualizar
OnProductos
FORUPDATE
AS
IFUPDATE(NombreProducto)
BEGIN
SELECTNombreProductoFROMINSERTED
END
---Prueba---
UpDateProductos
SetNombreProducto='Chokolate Choko'
WhereIdProducto=85

Laboratorios SQL
31
b.CreateTRIGGERControlActualizarProducto
OnProductos
FORUPDATE
AS
IFUPDATE(PrecioUnidad)
BEGIN
SELECT'EL PRECIO DEBE SER MAYOR 0.00'asMensaje
SELECTPrecioUnidadasNuevoPrecioFROMINSERTED
END
---Prueba---
UpdateProductos
setPrecioUnidad=4.5
whereIdProducto=74

--- 3. Eliminar Producto---

CREATETRIGGERControlEliminarProducto
OnProductos
FORDELETE
AS
BEGIN
INSERTINTOEmpleados(Apellidos,Nombre,Notas)
values('Choque','Alexander','Elimino un Producto')
END
---Prueba---
deletefromProductos
whereIdProducto=80

Laboratorios SQL
32
--- 4. El siguiente trigger DML imprime un mensaje en el cliente cuando
alguien intenta agregar o cambiar datos en la tabla Clientes.

CREATETRIGGERtr_Alerta
ONClientes
AFTERINSERT,UPDATE
AS
RAISERROR ('Notificando Atención al Cliente', 16, 10)
GO
---Prueba---
InsertintoClientes(IdCliente,NombreCompañía,NombreContacto)
Values('ISTBP','Instituto El Buen Cordero','Jaime Saucedo')

--- 5. En el ejemplo siguiente se utiliza un trigger DDL para imprimir un


mensaje si se produce un evento CREATE DATABASE en la instancia actual
del servidor y se utiliza la función EVENTDATA para recuperar el texto de
la instrucción Transact-SQL correspondiente.

IFEXISTS(SELECT*FROMsys.server_triggers
WHEREname='ControlBD')
DROPTRIGGERControlBD
ONALLSERVER
GO
----
CREATETRIGGERControlBD
ONALLSERVER
FORCREATE_DATABASE

Laboratorios SQL
33
AS
PRINT'Base deDatos ha sido Creada.'
SELECTEVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]'
,'nvarchar(max)')asBaseDatos
GO
---Prueba---
CreateDatabaseEclipse

Triggers DML

CREATEDATABASECONSORCIO
/*CREANDO TABLA en db_trigger*/

CREATETABLERegistro_Operacion )
(
Tipo_tCHAR(1)NOTNULL, CREATETABLETransaccion_Clientes
FechaDATETIMENOTNULL, (
EstacionVARCHAR(30)NOTNULL, IdCHAR(1)NOTNULL,
NumclieINTNOTNULL, FechaDATETIMENOTNULL,
NombreVARCHAR(30)NULL, EstacionVARCHAR(30)NOTNULL,
RepclieINTNULL, NumclieINTNOTNULL,
LimitecreditoMONEYNULL, NombreVARCHAR(30)NULL,

Laboratorios SQL
34
RepclieINTNULL, )
LimitecreditoMONEYNULL,
/*CREANDO UN TRIGGER PARA REGISTRAR UNA INSERCCION*/
--- 1.CreateTRIGGERtr_InsertCliente
ONTransaccion_Clientes
FORINSERT
AS
Begin
INSERTINTORegistro_Operacion(Tipo_t,Fecha,Estacion,Numclie,Nombre,Repclie,
Limitecredito)
SELECT'I',getdate(),host_name(),
Numclie,Nombre,Repclie,LimitecreditoFROMINSERTED
End
go
/*INSERTANDO DATOS EN LA TABLA c_cliente*/
INSERTINTOTransaccion_ClientesVALUES('M','14/05/1989','INVIERNO',2100,'JU
AN',129,9999.99)
INSERTINTOTransaccion_ClientesVALUES('J','08/10/1988','OTOÑO',3588,'JOSE'
,105,99999.99)

SELECT*FROMTransaccion_Clientes

SELECT*FROMRegistro_Operacion

/*CREANDO UN TRIGGER PARA ACTUALIZAR UN REGISTRO DE CLIENTE*/


--- 2.createTRIGGERtr_Updatecliente
ONTransaccion_Clientes
FORUPDATE
AS
BEGIN
INSERTINTORegistro_Operacion(Tipo_t,Fecha,Estacion,Numclie,
Nombre,Repclie,Limitecredito)SELECT'A',getdate(),host_name(),
Numclie,Nombre,Repclie,LimitecreditoFROMINSERTED
End
Go
/*ACTUALIZANDO DATOS EN LA TABLA Transaccion_Clientes*/
UPDATETransaccion_ClientesSETLimitecredito=0 WHEREId='J'

Laboratorios SQL
35
SELECT*FROMTransaccion_Clientes

SELECT*FROMRegistro_Operacion

/*Triggers DDL*/
CREATETRIGGERSEGURIDAD
ONDATABASE
FORCREATE_TABLE,DROP_TABLE,ALTER_TABLE
AS
BEGIN
RAISERROR ('Imposible crear, borrar ni modificar tablas,Faltan
permisos…', 16, 1)
ROLLBACKTRANSACTION
END
---Prueba----
DROPTABLEPRODUCTOS

TRANSACCIONES.Tecnica de recuperación de datos


createdatabasePRUEBA
usePRUEBA
CreatetableUSUARIOS( )
CODIGOnchar(5)notnull, CreatetableNIVEL
LOGInchar (30)null, (
PASSnchar (30)null, IdUsuariointIDENTITY(1,1)notnull,
EMAILnchar (30)null, IdNivelbigint,
FECHAsmalldatetimenull, constraintPK_IdUsuarioPRIMARYKEY
CONSTRAINTPK_CODIGOPRIMARYKEY(COD (IdUsuario)
IGO) )
--Crear usp utlizando una transacciones

Laboratorios SQL
36
createproceduresp_AdicionarUsuario
@CODIGOnchar(5),
@LOGInchar (30),
@PASSnchar (30),
@EMAILnchar (30),
@IdNivelbigin’t,
@MSGvarchar(100)output
AS
BEGIN--- Se utiliza cuando se realiza varias intrucciones
SETNOCOUNTon;
BEGINTRANtr_Adicionar
BeginTry
InsertIntoUSUARIOS(CODIGO,LOGI,PASS,EMAIL,FECHA)
Values(@CODIGO,@LOGI,@PASS,@EMAIL,GETDATE())
InsertIntoNIVEL(IdNivel)VALUES (@IdNivel)
Set@MSG='El usuario registro datos correctamente..'
CommitTrantr_Adicionar---confirmar la transaccion
EndTry
BeginCatch
set@MSG='Ocurrio un error:'+ERROR_MESSAGE()+'en la
línea:'+CONVERT(varchar(255),ERROR_LINE())+'.'
--ROLLBACK.cancela los cambios propuestos en una transacción de base de datos en espera
ROLLBACKTRANtr_Adicionar
EndCatch
End
--Prueba--
DECLARE@mesgvarchar(100)
EXECsp_AdicionarUsuario'US002','HULK','114','hulk@hotmail.com',10,@mesgou
tput
print@mesg

DECLARE@mesgvarchar(100)
EXECsp_AdicionarUsuario'US0020000','IROMAN','115','IROMAN@hotmail.com',9,
@mesgoutput
print@mesg

---1.Crear el procedimiento almacenado que permita modificar el precio


unitario de los productos que hayan tenido descuento, de los pedidos
enviados en un determinado año. El nuevo precio sera : el precio actual
menos el porcentaje de descuento, que se encuentra en la tabla detalle de
pedido.

Laboratorios SQL
37
---2.Crear una tabla con los pedidos que pertenecen a un vendedor
realizados durante un año.

Laboratorios SQL
38

También podría gustarte