Está en la página 1de 3

UNIVERSIDAD NACIONAL DE TRUJILLO

ESCUELA DE ING. SISTEMAS

LABORATORIO SOBRE USO DE TRIGGER


DOCENTE: DR. LUIS BOY CHAVIL

SCRIPT DE LA BASE DE DATOS


--CREACION DE LA BDATOS BIBLIOTEKA
USE MASTER
CREATE DATABASE BIBLIOTEKA
GO
--TABLA ALUMNO
USE BIBLIOTEKA
GO
CREATE TABLE ALUMNO
(IdAlumno integer identity(1, 1) not null primary key,
Nombre varchar(60) not null
)
go
--TABLA PRESTAMO
CREATE TABLE PRESTAMO
(Autogenerado integer identity(1, 1) not null primary key,
IdAlumno integer not null,
Fecha date not null
)
go
--Relacion entre ALUMNO-PRESTAMO
alter table PRESTAMO
add
constraint R_Alumno_Prestamo
foreign key (IdAlumno)
references [ALUMNO](IdAlumno),
constraint D_Fecha
default(GetDate()) for Fecha
go

--TABLA LIBROSPRESTADOS
CREATE TABLE LIBROSPRESTADOS
(Autogenerado integer not null,
IdLibro integer not null,
Estado integer not null
)
go
--Relacion entre Prestamo_LibrosPrestados
alter table LIBROSPRESTADOS
add
constraint R_Prestamo_LibrosPrestados
foreign key (Autogenerado)
references [PRESTAMO](Autogenerado),
constraint K_Primaria
primary key (Autogenerado, IdLibro)
go
--TABLA LIBRO
CREATE TABLE LIBRO
(IdLibro integer identity(1, 1) not null primary key,
Titulo varchar(60) not null,
ncopias integer not null
)
go
--Relacion entre LIBRO-LibrosPrestados
alter table LIBROSPRESTADOS
add
constraint R_Libro_LibrosPrestados
foreign key (IdLibro)
references [LIBRO](IdLibro)
go

DIAGRAMA DE LA BASE DE DATOS

SCRIPT DE TRIGGER PARA REGISTRAR EL PRESTAMO DE UN LIBRO


--Trigger para actualizar el Nº de copias de LibrosPrestados
--cuando se registra el prestamo de un libro
use BIBLIOTEKA
go
create trigger T_Prestamos
on LIBROSPRESTADOS
for insert
AS
BEGIN
begin transaction
declare @IdLibro integer
declare @CuentaCopias integer
select @IdLibro=IdLibro
from inserted
select @CuentaCopias=ncopias
from LIBRO
where IdLibro=@IdLibro
if @CuentaCopias>0
begin
UPDATE LIBRO
set ncopias-=1
where IdLibro=@IdLibro
commit transaction
end
else
begin
rollback transaction
raiserror('No hay libro disponible', 16, 2)
end
END
go

SCRIPT DE TRIGGER PARA REGISTRA LA DEVOLUCION DE UN LIBRO


--Trigger para actualizar el Nº de copias de LibrosPrestados
--cuando se registra la devolucion de un Libro.

use BIBLIOTEKA
go
create trigger T_Devolucion
on LIBROSPRESTADOS
for Update
as
Begin
begin transaction
declare @IdLibro integer
declare @cuentaLibros integer
select IdLibro=@IdLibro
from deleted
select @cuentaLibros=ncopias
from LIBRO
where IdLibro=@IdLibro
UPDATE LIBRO
set ncopias+=1
where IdLibro=@IdLibro
commit transaction
End
go

También podría gustarte