Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Def.Son procesos que realizan una tarea especfica con una o ms tablas
de datos.USP (User Stored Procedure)
Ejemplos:
-- 1. Crear USP que muestre los productos almacenados u ordenados por
nombre.
Laboratorios SQL 1
--3.Crear USP que liste los productos segn 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 parmetros.
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 pas enviados en un ao
especfico.
createprocedure usp_Pedidos_Enviados
@PE varchar(15),
@Ao int
As
Select IdPedido,IdCliente, IdEmpleado,PasDestinatario,FechaEnvo from
Pedidos
whereYEAR(FechaEnvo)= @Ao and PasDestinatario =@PE
orderby IdPedido desc
return
---Prueba
execute usp_Pedidos_Enviados'Alemania',1996
Laboratorios SQL 3
--7. Listar Pedidos por el IdEmpleado.
CreateProc usp_Pedidos_Empleado
@IdEmple int
As
select P.IdPedido, P.FechaPedido,P.IdCliente,NombreCompaa,
E.Nombre +' '+ E.Apellidos as Empleado, P.PasDestinatario
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
---Prueba
Execute usp_Pedidos_Pas 'Alemania'
Laboratorios SQL 4
--9.Listar Pedidos_ListarTodos.
Create proc usp_Pedidos_ListarTodos
As
Select P.IdPedido, P.FechaPedido, P.PasDestinatario, P.IdCliente,
NombreCompaa,E.Nombre +' '+ E.Apellidos as Empleado, P.PasDestinatario
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 comn
en la tabla.
-------------------------------------------------------------------------
Laboratorios SQL 6
Funciones Estadsticas
AVG Promedio / Sum Suma / Max Mnimo
select PasDestinatario,
COUNT(*)As NPedidos,
AVG(Cargo)As PromedioCargo ,
MAX(Cargo)As MayorCargo,
MIN(Cargo)As MenorCargo ,
SUM(Cargo)As Totalcargo From Pedidos
Groupby PasDestinatario
Having PasDestinatario<>'Brail'or PasDestinatario <>'Argentina'
Having
Es una clasula que permite establecer una condicin de datos agrupados
1.select PasDestinatario,
COUNT(*)As NPedidos,
AVG(Cargo)As PromedioCargo ,
MAX(Cargo)As MayorCargo,
MIN(Cargo)As MenorCargo ,
SUM(Cargo)As Totalcargo From Pedidos
Group by PasDestinatario
Having COUNT(*)>=50 and AVG(Cargo)>=60
2.select PasDestinatario,
COUNT(*)As NPedidos,
AVG(Cargo)As PromedioCargo ,
MAX(Cargo)As MayorCargo,
MIN(Cargo)As MenorCargo ,
SUM(Cargo)As Totalcargo From Pedidos
Groupby PasDestinatario
Having PasDestinatario In('Brasil','Argentina')
---- Having not PasDestinatario In ('Brasil','Argentina')
Laboratorios SQL 7
3.Hacer una estadstica de los productos agrupados por sus categoras de
solo los productos que no esten suspendidos ,el resultado debe mostrar el
nombre de la categora.
select C.NombreCategora,
COUNT(*)As nProductos ,
SUM(P.UnidadesEnExistencia)As TotalStock,
AVG(P.PrecioUnidad)AS PromedoPrecio,
MAX(P.PrecioUnidad)As MayorPrecio,
MIN(P.PrecioUnidad)As MnimoPrecio
From Productos P Inner Join Categoras C -- unir(INNER JOIN) dos tablas
On P.IdCategora = C.IdCategora --con el campos en comn
Where P.Suspendido=0 -- el valor suspendido es dato tipo bye
Group by C.NombreCategora
Laboratorios SQL 8
-------------------------------------------------------------------------
Procedimientos Almacenados_Mantenimiento-
Empleados
---1.Listar empleados
Create procedure usp_Listar_Empleados
As
select
IdEmpleado,Nombre,Apellidos,Cargo,Tratamiento,Direccin,Ciudad,Pas
from Empleados
order by IdEmpleado
return
---2.Ubicar un empleado
Create procedure usp_Empleado_Buscar
@IdEmpl int
As
select
IdEmpleado,Nombre,Apellidos,Cargo,Tratamiento,Direccin,Ciudad,Pas,TelDo
micilio
from Empleados
where IdEmpleado=@IdEmpl
return
--Prueba
execute usp_Empleado_Buscar6---no olvidarse enviar el parmetro
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),
@Pas varchar (15)
As
Update Empleados set
Nombre=@Nombre,Apellidos=@Apellidos,Cargo=@Cargo,Tratamiento=@Trata,
TelDomicilio=@Tel,Direccin=@Dir,Ciudad=@Ciudad,Pas=@Pas
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,IdCategora,PrecioUnidad,UnidadesEnExistencia)
values(@NombreProducto,@IdProvee,@IdCate,@Precio,@stock)
set @IdProducto =@@IDENTITY
Laboratorios SQL 11
-------------------------------------------------------------------------
Procedimientos Almacenados_Mantenimiento -
Pedidos
--- 1.Adicionar Pedidos
Create procedure usp_Pedidos_Adicionar
@IdPed int output,variable que devuleva el cdigo del pedido
@IdCliente int,
@IdEmpleado int,
@Fecha_Pedido datetime,
@Cargo money,
@Destinatario varchar (40),
@Direccin varchar (60),
@Pas varchar (10)
as
insert into
Pedidos(IdCliente,IdEmpleado,FechaPedido,Cargo,Destinatario,DireccinDest
inatario,PasDestinatario)
values(@IdCliente,@IdEmpleado ,@Fecha_Pedido ,@Cargo,@Destinatario
,@Direccin,@Pas)
set @IdPed=@@IDENTITY
Laboratorios SQL 12
Select
IdPedido,IdCliente,IdEmpleado,FechaEntrega,FechaEnvo,FormaEnvo,Cargo,De
stinatario,DireccinDestinatario,CiudadDestinatario,ReginDestinatario,C
dPostalDestinatario,PasDestinatario From Pedidos
Where IdPedido=@IdPed
-------------------------------------------------------------------------
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 ao 1996.
Select IdCliente,NombreCompaa,NombreContacto,Pas from Clientes
Where IdCliente in
(select distinct IdCliente from Pedidos where YEAR(FechaPedido)=1996)
--Otra forma
Select distinct C.IdCliente,C.NombreCompaa,C.NombreContacto,C.Pas
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 relacin es muchos
a muchos,se necesita una tabla intermedia.
--- 3.Mostrar los productos que tienen un precio mayor a dos veces el
promedio de precio de todos los productos.
Laboratorios SQL 13
Select IdProducto,NombreProducto,CantidadPorUnidad from Productos
Where PrecioUnidad >=(select AVG(PrecioUnidad)from Productos)
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 Cdigo,NombreProducto as Producto,
(selectSUM(PrecioUnidad*Cantidad*(1-Descuento))
From[Detalles de pedidos]
whereIdProducto=Productos.IdProducto and Descuento>0)as Total
From[Productos]
Laboratorios SQL 14
---3.Mostrar los pases donde se enviaron el producto "pez espada"
durante los meses de Enero a Marzo del ao 1995.
-------------------------------------------------------------------------
Nota:EXISTSes una funcin SQL que devuelve verdadero cuando una
subconsulta retorna al menos una fila.
-------------------------------------------------------------------------
selectdistinctPasDestinatariofromdbo.Pedidos
whereEXISTS(Select*from[Detalles de pedidos]
whereIdProducto in
(SelectIdProductoFROMProductos whereNombreProducto='Pez
espada'))andFechaEnvoin('01/01/1995','31/03/1995')
--- 4.Mostar los Productos que tengan igual precio que "Te Dharamsa".
--- 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
Laboratorios SQL 15
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
INNERJOINProductos
on[Detalles de pedidos].IdProducto=Productos.IdProducto
GroupbyEmpleados.Apellidos,Productos.NombreProducto
HavingProductos.NombreProducto=@NomProdandEmpleados.Apellidos=@NomVendGO
-------------------------------------------------------------------------
Nota:Paraaplicar la condicin en los grupos utilizoHAVING no uso WHERE.
-------------------------------------------------------------------------
Execute usp_CantidadPedidosVendidos'Pez espada ','Davolio'
PRCTICA 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
SelectDistinctPasDestinatario
FromPedidos
WhereEXISTS(Select*From[Detalles de pedidos]
WhereIdProducto in(SelectIdProductoFromProductos
whereIdProducto=@IdPro))
--Prueba
executeUsp_Listar_Producto_xPais'1'
Laboratorios SQL 16
@IdProint,
@Cantint
As
SelectIdProducto,NombreProducto,PrecioUnidad,UnidadesEnExistenciafromProd
uctos
updateProductosSETUnidadesEnExistencia=UnidadesEnExistencia +@Cant
WHEREIdProducto=@IdPro
go
--Prueba
execUsp_Actualizar_Stock1,60
--- 3.Crear el Proc almcenado que elimine los pedidos entre 2 Fechas de
un Pas determinado.
CreateProcedure Usp_Eliminar_Entre_Fechas
@PaisChar(15),
@Fech1SmallDateTime,
@Fech2SmallDateTime
As
DeleteFromPedidos
WherePasDestinatario=@PaisandFechaPedidoin(@Fech1,@Fech2)
go
--Prueba
executeUsp_Eliminar_Entre_Fechas'Brasil','1995-08-01','1994-08-12'
Laboratorios SQL 17
CreateProcedureUsp_Adicionar_Empleado
@IdEmpleintoutput,
@ApellidosChar(30),
@Nombchar(15),
@CargoChar(15),
@Ciudadchar(15)
As
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 parmetro.
-- EXISTS .- es una funcin 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')
Laboratorios SQL 18
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.
@cateint=0 --no se asigna un texto a un nmero
as
updateProductos
setUnidadesEnExistencia=convert(int,
UnidadesEnExistencia+UnidadesEnExistencia*@porcentaje/100 )
whereIdCategora=@cate
return
----
executeusp_Productos_Actualizar10,1
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 nmero
as
updateProductos
setPrecioUnidad=PrecioUnidad+PrecioUnidad*@porcentaje/100
whereIdCategora=@cate
return
----
executeusp_Precios_Actualizar10,1
Creacin deuna Base de Datos
--Archivos: Archivo de datos primario(extensin.mdf), Archivo de datos
secundario(extensin.ndf)Transacciones(extensin.ldf)
--Tienen nombres : Fsicos
Lgicosnombre(administracion de la base datos)
USEMASTER
GO
createDATABASEMASTER_EMPRESA--Nombre lgico
on
PRIMARY--Se crea con valores por defecto
Laboratorios SQL 19
MAXSIZE=400MB,
FILEGROWTH=20)
Unin de tablas
CreateDatabaseBDMASTER
UseBDMASTER
--CREAR TABLAS --
CreateTableTabla01
(IdPedidointPrimaryKey,
IdClientechar (5)notnull,
MontoSmallmoneynotnull,
FechaSmallDateTime
)
go
CreateTableTabla02
(IdPedidointPrimaryKey,
IdClientechar (5)notnull,
MontoSmallmoneynotnull,
FechaSmallDateTime
Laboratorios SQL 20
)
go
CreateTableTabla03
(IdPedidointPrimaryKey,
IdClientechar (5)notnull,
MontoSmallmoneynotnull,
FechaSmallDateTime
)
go
Laboratorios SQL 21
select*fromTabla03)
go
select*intoTablaFinalfromTabla01
UNIONALL
(Select*fromTabla02
UNIONALL
select*fromTabla03)
--Establece que los datos que existe en una columna tambin debe existir
en la otra tabla.
---Prueba--
InsertIntoPedidos(IdCliente)values(5)
--error porque no existe el cliente(5)
Laboratorios SQL 22
InsertIntoClientesvalues(5)
InsertIntoClientesvalues(6)
InsertIntoClientesvalues(7)
InsertIntopedidos(IdCliente)values(5)
InsertIntopedidos(IdCliente)values(6)
InsertIntopedidos(IdCliente)values(7)
--otra forma
CreateTableComprobantes
(IdDocumentointIdentityPrimaryKey,
IdPediint
foreignkey(IdPedi)ReferencesPedidos(IdPedido)
)
Go
--Prueba--
InsertIntoComprobantes(IdPedi)values(2)
InsertIntoComprobantes(IdPedi)values(4)
InsertIntoComprobantes(IdPedi)values(5)
select*frompedidos
select*fromComprobantes
select*fromClientes
PRCTICA 02/11/11
Createprocusp_pedidos_mostrar
@mesint,
@anoint
As
SELECTP.IdPedido,P.FechaPedido,C.NombreCompaaasCliente,C.NombreContactoasContac
to,E.Apellidos+' '+E.NombreAsVendedor
FROMPedidosPInnerJoinClientesC
OnP.Idcliente=C.IdCliente
InnerJoinEmpleadosE
OnP.IdEmpleado=E.IdEmpleado
WHEREMONTH(FechaPedido)=@mesANDYEAR(FechaPedido)=@ano
OrderByC.NombreCompaa
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
---1.Crear una base de datos mediante un script T-SQL, con las siguientes
caractersticas:
Nombre : SysExamen
Archivo de Datos : SysExa_Dat
Tamao : 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 tamao del archivo de datos.
Laboratorios SQL 25
filegrowth=20)
go
selecttop 10
P.IdProductoasCdigo,P.NombreProductoasProducto,P.PrecioUnidadasPrecio,P.
SuspendidoasSituacin,C.NombreCategoraasCategoraintoProductosCaros
fromProductosPinnerjoinCategorasC
onP.IdCategora=C.IdCategora
orderbyP.PrecioUnidaddesc
select*fromProductosCaros
CreateDataBaseSysMaster
useSysMaster
--tabla clientes
createtableClientes
(IdClienteintprimaryKey,
NombreClientechar(40)notnull,
Direccinchar (50)notnull,
telchar (10)notnull,
)
go
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
CreatefunctionListadoPais(@paisvarchar(100))
--Formato de la tabla
(IdClientevarchar(5),NombreCompaavarchar(50),NombreContacto
varchar(100),Pasvarchar(15))
As
Laboratorios SQL 27
--Cuerpo de la instruccion "begin..end"
begin
--Inserto filas en la variable(tabla que sera retornada)
Insert@clientes
selectIdCliente,NombreCompaa,NombreContacto,Pas fromClientes
wherePas=@pais
Return-- Return indica que las filas insertadas en la variable son retornadas
end
---Prueba---
--Este tipo de funcin puede ser referenciada en el "from" de una consulta.
Select*fromdbo.ListadoPais('Argentina')
Laboratorios SQL 28
--- 3.FUNCIN CON VALOR DE TABLAEN LNEA
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')
IFOBJECT_ID(N'dbo.GetWeekDay',N'FN')ISNOTNULL
DROPFUNCTIONdbo.GetWeekDay;
CREATEFUNCTIONdbo.GetWeekDay(@Datedatetime)
RETURNSint
AS
BEGIN
RETURNDATEPART(weekday,@Date)
END
GO
Laboratorios SQL 29
---Prueba
SELECTdbo.GetWeekDay(CONVERT(DATETIME,'20020201',101))ASDayOfWeek;
GO
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 condicin establecidaal realizar una operacin de insercin
(INSERT),actualizacin (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 Caractersticas:
No aceptan parmetros o argumentos (pero podran 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 travs de
transacciones autnomas)
Laboratorios SQL 30
Pueden causar errores de mutaciones en las tablas, si se han escrito de manera
deficiente.
---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
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 Atencin al Cliente', 16, 10)
GO
---Prueba---
InsertintoClientes(IdCliente,NombreCompaa,NombreContacto)
Values('ISTBP','Instituto El Buen Cordero','Jaime Saucedo')
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,Limite
credito)
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','OTOO',3588,'JOSE'
,105,99999.99)
SELECT*FROMTransaccion_Clientes
SELECT*FROMRegistro_Operacion
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
Laboratorios SQL 36
--Crear usp utlizando una transacciones
createproceduresp_AdicionarUsuario
@CODIGOnchar(5),
@LOGInchar (30),
@PASSnchar (30),
@EMAILnchar (30),
@IdNivelbigint,
@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
lnea:'+CONVERT(varchar(255),ERROR_LINE())+'.'
--ROLLBACK.cancela los cambios propuestos en una transaccin 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