Mostrando entradas con la etiqueta trigger en sql server. Mostrar todas las entradas
Mostrando entradas con la etiqueta trigger en sql server. Mostrar todas las entradas

sábado, 14 de abril de 2012

Ejemplo de una base de datos en SQL server

Advertencia aun no esta editado totalmente


--se crea la base de datos
create database Tienda on primary
(
--se indica el nombre
name=Tiendasemsix,
--la ruta donde se alojará
filename='D:\Tiendasemsix.mdf',
--su tamaño(espacio en disco) inicial
size=4mb,
--el tamaño máximo que alcanzará
maxsize=10mb,
--y por último el crecimiento gradual
filegrowth=2
)
--ejemplo de una tabla
create table Nombre_de_la_tabla
(
Campo1 tipo_de_dato,--va una coma al final de cada delcración de un campo
Campo2 tipo_de_dato,
Campo3 tipo_de_dato--la línea del campo final no lleva coma
)

--creamos las tablas
--explicaremos una de ellas
--se crea la tabla
create table Cliente
(
--declaramos una llave primaria(primary key) de tipo entero(int),
-- la cual será autoincrementable(crece gradualmente en uno),
--al ser llave primaria no admite valores nulos pero dejamos
-- la instriccion "not null" como ejemplo
ID_Cliente int primary key identity(1,1) not null,
--una clave para el cliente de tipo varchar y de tamaño 50
Clave_Cliente varchar(50)not null,
Nombre varchar(50) not null,
RFC varchar(10) not null,
--un campo llamado saldo de tipo money, el ultimo campo no lleva como al final
Saldo money not null
)

create table Producto
(
ID_Producto int primary key identity(1,1) not null,
Clave_Producto varchar(50) not null,
Descripcion varchar(100) not null,
Costo_Unitario money not null,
Existencia int not null
)

create table Venta
(
ID_Venta int primary key identity(1,1) not null,
--esta es una llave foránea la cual hace referencia a otra tabla
ID_Cliente int not null foreign key(ID_Cliente)references Cliente(ID_Cliente),
ID_Producto int not null foreign key(ID_Producto)references Producto(ID_Producto),
No_Factura int not null,
Cantidad int not null,
Fecha date not null,
Total money not null,
Saldo money not null,
--este es un campo llamado Cancelado de tipo bit
--el cual tiene como valor definido false, también puede ser 0
Cancelado bit default('false')not null,
Tipo_Vta varchar(10)
)

Create table Corte_Caja
(
Fecha date not null,
Total money not null
)

Create table Pago
(
No_Factura int not null,
Monto money not null,
Fecha date not null,
No_Pago int not null,
Saldo_Anterior money ,
Saldo_Nuevo money
)

create table Devolucion
(
No_Factura int not null,
Fecha date not null
)

create procedure Nombre_del_procedimiento
(
--campos que recibe, inician con un @
@Campo1 tipo_de_dato,
@Campo2 tipo_de_dato,
@Campo3 tipo_de_dato--sin coma al final de la última línea
)
as
--inicio del procedimiento
begin
--cuerpo del procedimiento donde pueden ir uno o
--varios grupos de instrucciones
end
--fin del procedimiento
-----------------------------------------------------------VENTA
create procedure Realiza_Vta
(
      @Clave_Cliente varchar(50),
      @Clave_Producto varchar(50),
      @No_Factura int,
      @Cantidad int,
      @Tipo_Vta varchar(10)
)
AS
Begin
      declare @Total money
      if Exists(select *from Cliente where Clave_Cliente=@Clave_Cliente)
            begin
            if Exists(select *from Producto where Clave_Producto=@Clave_Producto)
                  begin
                        if (select Existencia from Producto Where Clave_Producto=@Clave_Producto)>=@Cantidad
                             begin
                              Begin transaction
                                   set @Total=(@Cantidad*(select Costo_Unitario from Producto where ID_Producto=(select ID_Producto from Producto where Clave_Producto=@Clave_Producto)))
                                   Insert into Venta(ID_Cliente,ID_Producto,No_Factura,Cantidad,Fecha,Total,Saldo,Tipo_Vta)values((select ID_Cliente from Cliente where Clave_Cliente=@Clave_Cliente),(select ID_Producto from Producto where Clave_Producto=@Clave_Producto),@No_Factura,@Cantidad,Getdate(),@Total,@Total,@Tipo_Vta)
                                   if @@ERROR>0
                                   goto error 
                             Commit transaction
                             end
                        else
                             begin
                                   goto errorc
                             end  
                  end
            else
                  begin
                        goto errorb
                  end
            end
      else
            begin
                  goto errora
            end
fin1:
goto fin2              
error:
rollback transaction
print 'Ha ocurrido un error'
goto fin2
errora:
print 'No existe el cliente'
goto fin2
errorb:
print 'No existe el producto'
goto fin2
errorc:
print 'Cantidad de productos insuficientes para vender'
fin2:
End
-----------------------------------------------------------------------------------venta editado--------------------

create procedure Realiza_Vta
(
      @Clave_Cliente varchar(50),
      @Clave_Producto varchar(50),
      @No_Factura int,
      @Cantidad int,
      @Tipo_Vta varchar(10)
)
AS
Begin
      declare @Total money
      if Exists(select *from Cliente where Clave_Cliente=@Clave_Cliente)
            begin
            if Exists(select *from Producto where Clave_Producto=@Clave_Producto)
                  begin
                        if (select Existencia from Producto Where Clave_Producto=@Clave_Producto)>=@Cantidad
                             begin
                             Begin transaction
                                   set @Total=(@Cantidad*(select Costo_Unitario from Producto where ID_Producto=(select ID_Producto from Producto where Clave_Producto=@Clave_Producto)))
                                   Insert into Venta(ID_Cliente,ID_Producto,No_Factura,Cantidad,Fecha,Total,Saldo,Tipo_Vta)values((select ID_Cliente from Cliente where Clave_Cliente=@Clave_Cliente),(select ID_Producto from Producto where Clave_Producto=@Clave_Producto),@No_Factura,@Cantidad,Getdate(),@Total,@Total,@Tipo_Vta)
                                   if @@ERROR>0
                                   goto error 
                                   Commit transaction
                             end
                        else
                             begin
                                   goto errorc
                             end  
                  end
            else
                  begin
                        goto errorb
                  end
            end
      else
            begin
                  goto errora
            end
fin1:
return     
error:
rollback transaction
print 'Ha ocurrido un error'
goto fin2
errora:
print 'No existe el cliente'
goto fin2
errorb:
print 'No existe el produto'
goto fin2
errorc:
print 'Productos insuficientes para realizar la venta'
fin2:
End

--------------------------------------------------------------------------------------------------------------------
create trigger Nombre_del_trigger
on Tabla_con_la_cual_se_activa after|before|for insert|update|delete
as
--inicio del trigger
begin
--cuerpo del grupo de instrucciones
end
--final


create trigger Inserta_Vta_Trg
on Venta After insert
As
Begin
Begin Transaction
      if (select Tipo_Vta from inserted)='CONTADO'
            begin
                  if Exists(select *from Corte_Caja where Fecha=(select Fecha From inserted))
                        begin
                        update Corte_Caja set Total=Total+(select Saldo from inserted) where Fecha=(select Fecha From inserted)
     
                        if @@ERROR>0
                        goto error
                        end
                  else
                        begin
                        Insert into Corte_Caja(Fecha,Total)values(Getdate(),(select Saldo from inserted))
                        if @@ERROR>0
                        goto error
                        end
            end
      else
            begin
            update Cliente set Saldo=Saldo+(select Saldo from inserted) where ID_Cliente=(select ID_Cliente from Inserted)
     
            if @@ERROR>0
            goto error
            end
            update Producto set Existencia=Existencia-(Select Cantidad from inserted) where ID_Producto=(select ID_Producto from inserted)
     
      if @@ERROR>0
            goto error
      Commit Transaction     
      fin1:
goto fin2  
error:
Rollback Transaction
print 'ha ocurrido un error'

End
-------------------------------------------------------PAGO------------------------------------------------------
create procedure Realiza_Pago
(
      @No_Factura int,
      @Monto money,
      @Comprobacion int output
)
as
Begin
      Begin Transaction
      set @Comprobacion=0
      insert into Pago(No_Factura,Monto,Fecha,No_Pago)values(@No_Factura,@Monto,getdate(),((select count(No_Pago) from Pago where No_Factura=@No_Factura)+1))
      if @@ERROR>0
                        goto error
      Commit Transaction
      noerror:
      set @Comprobacion=1
      goto fin
      error:
      Rollback Transaction
      set @Comprobacion=0
      fin:
End



create trigger Inserta_Pago_Trg
on Pago after insert
as
Begin
      Begin Transaction
      declare @Saldo_Anterior money,@Saldo_Nuevo money
      if (select No_Pago from inserted)>1
            begin
            set @Saldo_Anterior=(select Saldo_Nuevo from Pago where No_Factura=(select No_Factura from inserted) and No_Pago=((select No_Pago from inserted)-1))
            end
      else
            begin
            set @Saldo_Anterior=(select Saldo from Venta Where No_Factura=(select No_Factura from inserted))
            end

set @Saldo_Nuevo=@saldo_Anterior-(select Monto from inserted)
update Pago set Saldo_Anterior=@Saldo_Anterior,Saldo_Nuevo=@Saldo_Nuevo where No_Pago=(select No_Pago from inserted)
if @@ERROR>0
                  goto error 
      update Cliente set Saldo=Saldo-(select Monto from inserted)where ID_Cliente=(Select ID_Cliente from Venta where No_Factura=(select No_Factura from inserted))
      if @@ERROR>0
                        goto error
      update Venta set Saldo =@Saldo_Nuevo where No_Factura=(select No_Factura from inserted)
      if @@ERROR>0
                        goto error
      if exists(select Total from Corte_Caja where Fecha=(select Fecha from Inserted))
            begin
            update Corte_Caja set Total=Total+(select Monto from inserted) where Fecha=(select Fecha from inserted)
            if @@ERROR>0
                        goto error
            end
      else
            begin
            insert into Corte_Caja(Fecha,Total)values(getdate(),(select Monto from inserted))
            if @@ERROR>0
                        goto error
            end
      Commit Transaction          
noerror:
goto fin         
error:
Rollback Transaction
print 'se ha producido un error'        
fin:
End
---------------------------------------------------------devolucion-----------------------------------
create procedure Realiza_Devolucion
(
@No_Factura int,
@Comprobacion int output
)
as
begin
Begin Transaction
set @Comprobacion=0
insert into Devolucion(No_Factura,Fecha)values(@No_Factura,getdate())
if @@error>0
goto error
Commit Transaction
noerror:
set @Comprobacion=1
goto fin
error:
Rollback Transaction
set @Comprobacion=0
fin:
end

create trigger Inserta_Devolucion_Trg
On Devolucion after insert
as
begin
      Begin Transaction
      update Producto set Existencia=Existencia+(select Cantidad from Venta where No_Factura=(select No_Factura from inserted)) where ID_Producto=(select ID_Producto from Venta where No_Factura=(select No_Factura from inserted))
      if @@error>0
            goto error
      if (select Tipo_Vta from Venta where No_Factura=(select No_Factura from inserted))='CONTADO'
            begin
            if Exists(select *from Corte_Caja where Fecha=(select Fecha from inserted))
                  begin
                  update Corte_Caja set Total=Total-(select Saldo from Venta where No_Factura=(select No_Factura from inserted))where Fecha=(select Fecha from inserted)
                  if @@ERROR>0
                  goto error
                  end
            else
                  begin
                  Insert into Corte_Caja(Fecha,Total)values(Getdate(),((select Saldo from Venta where No_Factura=(select No_Factura from inserted))*(-1)))
                  if @@ERROR>0
                  goto error
                  end
            end
      else
            begin
                  update Cliente set Saldo=Saldo-(select Saldo from Venta where No_Factura=(select No_Factura from inserted)) where ID_Cliente=(select ID_Cliente from Venta where No_Factura=(select No_Factura from inserted))
                  if @@error>0
                        goto error
            end  
update Venta Set Cancelado='true' where No_Factura=(select No_Factura from inserted)
if @@error>0
goto error
Commit Transaction
noerror:
goto fin   
error:
Rollback Transaction
print 'Ha ocurrido un error'
fin:
end