You are on page 1of 13

--CONSULTA 1

select * into BCK_1 from Products where UnitsOnOrder<20 and UnitPrice <10 or
UnitsInStock < 7
--CONSULTA 2
select ShipCity,count(1)'ORDENES POR CIUDAD',ShipCountry,sum(freight)'FLETE'
into BCK_2 from orders
group by ShipCity,ShipCountry having count(1) between 20 and 40
--CONSULTA 3
select top 5 percent
OrderID,(sum(UnitPrice*Quantity))'SUBTOTAL',sum((UnitPrice*Quantity)*(1-
Discount))'VALOR REAL' into BCK_3 from [Order Details]
group by OrderID having sum(UnitPrice*Quantity)>2500
select * from BCK_1
select * from BCK_2
select * from BCK_3

--CONSULTA 1
select * from orders
select * from Customers
select * from Employees
select * from Categories
select * from Products
select * from [Order Details]
go
create view v_ordencompleta as
select
o.OrderID,c.CompanyName,e.LastName,e.FirstName,o.OrderDate,o.ShipName,o.Freig
ht,p.ProductName,p.UnitPrice,
d.Quantity,d.Discount,(d.UnitPrice*d.Quantity)*(1-d.Discount)'IMPORTE' from Orders
o
inner join Customers c on o.CustomerID=c.CustomerID
inner join Employees e on o.EmployeeID=e.EmployeeID
inner join [Order Details] d on o.OrderID=d.OrderID
inner join Products p on d.ProductID=p.ProductID
inner join Categories ca on p.CategoryID=ca.CategoryID
go
select LastName,count(OrderID)'Cantidad' from v_ordencompleta group by LastName
having LastName='Buchanan'
select top 1 OrderID,sum(Quantity)'Cantidad' from v_ordencompleta group by OrderID
order by sum(Quantity) desc
select top 1 year(OrderDate)'Ao',sum(Quantity)'Cantidad' from v_ordencompleta
group by year(OrderDate) order by sum(Quantity) desc
select top 1 CompanyName,count(1)'Cantidad Ordenes' from v_ordencompleta group
by CompanyName order by count(1) desc
select top 1 CompanyName, sum(IMPORTE)'Gasto' from v_ordencompleta group by
CompanyName order by sum(IMPORTE) desc
select top 1 ProductName,sum(Quantity)'Cantidad' from v_ordencompleta group by
ProductName order by sum(Quantity) desc
select top 1 ProductName,sum(importe)'Ingreso' from v_ordencompleta group by
ProductName order by sum(UnitPrice*Quantity) desc
go
create view v_producto as
select p.ProductName,s.CompanyName,c.CategoryName,p.UnitsInStock from Products
p
inner join Suppliers s on p.SupplierID=s.SupplierID
inner join Categories c on p.CategoryID=c.CategoryID
go
update Products set ProductName='Chai1' where ProductName='Chai'
update v_producto set ProductName='Chai' where ProductName='Chai1'
select * from Products
select * from v_producto
create table bco_Cliente(
codigo int identity(10001,1)primary key,
nombre varchar(80)unique not null,
fecha datetime default getdate(),
lineaCredito money default 0 check (lineaCredito>=0),
lineaDisponible money default 0 check (lineaDisponible>=0))
go
create table bco_Movimiento(
nro_Ope int identity primary key,
codCli int,
fechOpe datetime default getdate(),
cargo money default 0,
abono money default 0)

select * from bco_Cliente


select * from bco_Movimiento
--sin triggers --con triggers
insert bco_Cliente(nombre,lineaCredito) values ('AUQUI',1000)
go
--creando triggers
create trigger tg_NuevoCliente on bco_Cliente
after insert
as
insert bco_Movimiento (codCli,abono)
select codigo,lineaCredito from inserted
go
create trigger tg_NuevoMovimiento on bco_Movimiento
after insert
as
declare @codcli int,@cargo money,@abono money
select @codcli=codcli,@cargo=cargo,@abono=abono from inserted
update bco_Cliente set lineaDisponible=lineaDisponible+@abono-@cargo
where codigo=@codcli
go
--comprobando
select * from bco_Cliente
select * from bco_Movimiento

insert bco_Movimiento (codCli,abono) values (10003,350)


insert bco_Movimiento (codCli,cargo) values (10003,150)

select * from clientes


go
create trigger tg_BorrarClientes on clientes
for delete
as
if (select count(1)from deleted)>3
begin
raiserror('No borrar ms de 3',15,1)
rollback transaction
end
else
begin
raiserror('Borrado Correcto',16,1)
commit
end

select country,count(1) from clientes group by country order by count(1) desc

delete from clientes where country='Argentina'


-----examen final -----
use Northwind
---numero 1---
select*from Orders
go

select OrderID, CustomerID, (Freight * 0.50) as 'FLETE',


ShipName, ShipAddress, ShipCity, ShipCountry
from Orders
where ShipRegion is null and
ShipCountry in ('france','germany','belgium')
and EmployeeID not between 1 and 5
and ShipCity like 'm%'
and ShipAddress like '12%'
go

----numero 2----
select*from Shippers
go

-----numero 3------

select*from Products
go

create procedure pa_examen3 as


select od.OrderID, p.ProductName,
((od.UnitPrice*od.Quantity)*(1-od.Discount)) AS 'VALOR TOTAL'
from [Order Details] AS OD
JOIN Products AS P ON p.ProductID=od.ProductID
go

exec pa_examen3
go

------numero 4------
create procedure

------ numero 5-----


select * into BCK_PRODUCTO
from Products

-PROCEDIMIENTOS ALMACENADOS
/*Crear un procedimiento almacenado al cual llamara pa_Listaproductos
el cual almacenara el codigo de producto, el nombre del producto para aquellos
productos
que no esten descontinuados*/
create proc pa_ListaProductos as
select ProductID,ProductName from Products
where Discontinued=0
order by ProductName
go
pa_ListaProductos --o
exec pa_ListaProductos
go
-- datos de los procedimientos almacenados
exec sp_helptext pa_ListaProductos
go
select * from sys.procedures
go
--sel
select * from sys.tables
go
/*Se le pide crear un procedimiento almacenado al cual llamara "pa_ListaClientes"
mediante el cual generara una copia total de la tabla customers a una tabla llamada
clientes*/
alter proc pa_ListaClientes as
if(select count(1) from sys.tables
where name='Clientes')>0
drop table Clientes
select * into clientes from Customers
select 'Se actualizo correctamente la tabla Clientes'
go
drop proc pa_ListaClientes
drop table clientes
exec pa_ListaClientes
select * from clientes
/* Crear un procedimiento almacenado al cual llamara "pa_ValorProducto" que
selecione
el codigo de la orden el nombre del producto y el total aplicando el descuento
como "VALOR TOTAL" de cada uno de los productos que componen la orden */
create procedure pa_ValorProducto as
select od.OrderID, p.ProductName,
((od.UnitPrice*od.Quantity)*(1-od.Discount)) AS 'VALOR TOTAL'
from [Order Details] AS OD
JOIN Products AS P ON p.ProductID=od.ProductID
go
exec pa_ValorProducto
go
/*INGRESANDO VALORES MEDIANTE UN
PROCEDIMIENTO ALMACENADO*/
/* SALUDO*/
alter proc saludo
@nombre varchar(20), @apellido varchar(20)
as
select 'Hola mi nombre es '+@nombre+' '+ @apellido+' mucho gusto'
go
exec saludo Gilmar, Bayona

--LA SUMA DE 2 NUMEROS


alter PROC pa_suma1
@n1 int, @n2 int
as
select 'la suma de '+ltrim(str(@n1))+' mas '+ltrim(str(@n2))+' es = ', @n1+@n2
go
exec pa_suma1 2,4
/*INGRESANDO UNA TRANSPORTISTA (Shippers) NUEVA*/
SELECT * FROM Shippers
GO
create proc pa_NuevoShipper
@companyname nvarchar(40),
@phone nvarchar(40)
as
insert Shippers(CompanyName,Phone)
values(@companyname,@phone)
go
--Probando
exec pa_NuevoShipper UNMSM,4565432
/*VALIDANDO LO DATOS*/
ALTER proc pa_NuevoShipper
@companyname nvarchar(40)=NULL,
@phone nvarchar(40)=NULL
with encryption
as
if @companyname is null or @phone is null
begin
raiserror('Debe ingresar los valores faltantes...',15,1)
return
end
insert Shippers(CompanyName,Phone)
values(@companyname,@phone)
SELECT 'NUEVO SHIPPER REGISTRADO'
go
--PROBANDO
EXEC pa_NuevoShipper rrr, 4567897
select * from Shippers
go
exec sp_helptext pa_nuevoshipper
--JALANDO DATOS CON PARAMETROS
/*SELECCIONAR LOS DATOS DE UN EMPLEADO INGRESANDO SU CODIGO
MEDIANTE UN PA*/
CREATE PROC pa_empleado
@id int
as
SELECT * FROM Employees
WHERE EmployeeID=@id
GO
--probando
exec pa_empleado 4
--------VALORES OUTPUT------------
create proc pa_suma2
@n1 int, @n2 int, @r3 int output
as
set @r3 = @n1+@n2
go
--probando
declare @rpta int
exec pa_suma2 6,7,@rpta output
select 'La suma es =',@rpta
go
select * from Shippers
--OTRO EJEMPLO
create proc pa_AgregarS
@nombre nvarchar(40) output
as
select top (1) @nombre=CompanyName from Shippers
order by ShipperID desc
go
select * from Shippers
declare @recibir nvarchar(40)
exec pa_AgregarS @recibir output
select 'el nombre es=', @recibir
--llamando desde otro procedimiento almacenado
create proc pa_AgregarShipper
@telefono as nvarchar(24)
as
begin
declare @recibir as nvarchar(40)
exec pa_AgregarS @recibir output
insert Shippers values (@recibir,@telefono)
end
go
--probando todo
exec pa_AgregarShipper 44444
select * from Shippers
insert Shippers (CompanyName, Phone) values ('USDG',11111)
drop table bco_Cliente
--DESENCADENADORES O TRIGGERS
create table bco_Cliente (
codigo int identity(1001,1) primary key,
nombre varchar(80) unique not null,
fecha datetime default getdate(),
lineaCredito money default 0 check(lineaCredito>=0),
lineaDisponible money default 0 check(lineaDisponible>=0) )
go
create table bco_Movimiento (
--nro_Ope bigint identity primary key,
nro_Ope int identity primary key,
--codCli int references bco_Cliente,
codCli int,
fechaOpe datetime default getdate(),
cargo money default 0,
abono money default 0 )
go
select * from bco_Cliente
select * from bco_Movimiento
go
--SIN TRIGGERS
insert bco_Cliente(nombre,lineaCredito)values('Mark Vitto',5000)
go
--CREANDO TRIGGERS
create trigger tg_NuevoCliente on bco_Cliente
for insert
as
insert bco_Movimiento (codCli,abono)
select codigo,lineaCredito from inserted
go
--PROBANDO LUEGO DEL TRIGGER DE INSERT
insert bco_Cliente(nombre,lineaCredito)values('KEIKO',10000)
go
--TRIGGER PARA MOVIMIENTO
create trigger tg_NuevoMovimiento on bco_Movimiento
for insert
as
declare @codcli int, @cargo money, @abono money
select @codcli=codCli,@cargo=cargo,@abono=abono from inserted
update bco_Cliente set lineaDisponible=lineaDisponible+@abono-@cargo
where codigo=@codcli
go
--
select * from bco_Cliente
select * from bco_Movimiento
go
--PROBAR CON NUEVO CLIENTE Y MOVIMIENTOS
insert bco_Cliente(nombre,lineaCredito)values('Gilmar Bayona',1000)
go
--gasto
insert bco_Movimiento(codCli,cargo)values(1003,350)
insert bco_Movimiento(codCli,abono)values(1003,150)
go
select * into bck_cliente from Customers
go
--PARA BORRAR (EN ESTE CASO DATOS DE LA TABLA CLIENTES)
alter trigger tg_BorrarClientes on BCK_CLIENTE
for delete as
if (select COUNT(1) from deleted)>3
begin
raiserror('NO se permite Borrar mas de 3 clientes',15,1)
rollback
end
else
BEGIN
raiserror('BORRADO CORRECTO',16,1)
commit
END
go
SELECT * FROM BCK_CLIENTE
select COUNT(1) from BCK_CLIENTE where Country='UK'
select COUNTRY,COUNT(1) from BCK_CLIENTE GROUP BY Country ORDER
BY COUNT(1) DESC
--ELIMINANDO
DELETE BCK_CLIENTE WHERE Country ='Italy'
--REPONER
SELECT * INTO BCK_CLIENTE
FROM Customers
GO
DROP TABLE BCK_CLIENTE