Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Use TSQL

Descargar como pdf o txt
Descargar como pdf o txt
Está en la página 1de 32

Use TSQL

-- INICIO DEL CURSO DE SQL SERVER --

-- Para leer una tabla

select * from Sales.Customers -- Tabla de Clientes

select * from Production.Products -- Tabla de Productos

-- Leer algunos campos de la tabla Clientes:

select custid, companyname, contactname, city, country

from Sales.Customers

-- Existen 6 cláusulas de base de datos:

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

-- SELECT -> seleccionar campos de una tabla

-- FROM -> apuntar a que tabla vamos a consultar

-- WHERE -> filtrar campos de búsqueda

-- GROUP BY -> agrupar datos

-- HAVING -> filtrar campos de (funciones de agregación)

-- ORDER BY -> ordenar los datos

-- OJO: Para texto en filtros usar -> ' ' y para números (van solos) ejm -> 7,8,9

-- Leer todos los clientes que son de Mexico:

select custid, companyname, contactname, contacttitle, city, country, phone

from Sales.Customers

where country = 'Mexico'

-- Leer los datos del cliente con código(custid) => 17

select custid, companyname, contactname, contacttitle, city, country, phone

from Sales.Customers

where custid = 17
-- Leer todos los clientes que son de Mexico, España y USA:

select * from Sales.Customers

where country in ('Mexico','Spain','USA') --se utiliza in para filtrar 2 o más valores.

-- Leer todos los clientes del custid del 1 al 10:

select * from Sales.Customers

where custid in (1,2,3,4,5,6,7,8,9,10)

-- Leer todos los clientes del custid del 20 al 50:

select * from Sales.Customers

where custid between 20 and 50

-- Leer todos los clientes del 20 al 50 y

-- traer solo a los que son del país de France, Spain, Brazil

select * from Sales.Customers

where custid between 20 and 50 and country in ('France','Spain','Brazil')

-- Leer todos los clientes que son del 35 al 80

select * from Sales.Customers

where custid >= 35 and custid <=80 ---> para evitar el doble filtro utilizar el between

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

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

---- DML -> select, insert, update, delete

---- DDL -> create, alter, drop

--- Para los ejemplos crearemos nuestro propio esquema de BD:

create schema Test -- Creamos el schema de BD llamado Test.

-- Tipos de Datos:
-- Texto -> varchar(50) "caracteres no definidos" , char(8) "caracteres definidos"

-- Números -> int "Número entero", decimal(18,5)

-- Fecha -> date, datetime, smalldatetime

-- OJO:

--> ejemplo dni 04678944 en texto -> llegará así -> 4678944 en número

-- Creando nuestra primera tabla - Alumnos:

create table Test.Alumnos

IdAlumno int,

Nombres varchar(50),

Edad int,

MesCumpleaños varchar(15)

select * from Test.Alumnos

--- Insertar registros a nuestra tabla de Test.Alumnos:

insert into Test.Alumnos values (1, 'Victor Custodio', 24, 'Febrero')

insert into Test.Alumnos values (2, 'Joaquín Silva', 25, 'Marzo')

insert into Test.Alumnos values (3, 'Daniel Huayta', 26, 'Abril')

insert into Test.Alumnos values (4, 'Jhon Cochachi', 27, 'Mayo')

insert into Test.Alumnos values (5, 'José Laurente', 28, 'Junio')

insert into Test.Alumnos values (6, 'Josep Agama', 21, 'Noviembre')

--- Actualizar la edad de José Laurente ---> 30 años

update Test.Alumnos set Edad=30

where IdAlumno=5

--- Eliminar a José Laurente


delete from Test.Alumnos

where IdAlumno=5

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

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

-- Uso del Like:

select * from Sales.Customers

where contactname like 'a%' --- empiecen con "A"

select * from Sales.Customers

where contactname like '%na' --- termine con "na"

select * from Sales.Customers

where contactname like '%on%' --- contenga la palabra "on"

select * from Sales.Customers

where contactname not like '%on%' --- no contenga la palabra "on"

--- USAMOS COMODINES =)

select * from Sales.Customers

where contactname like '_a_a%' --- empiecen con "A" en la segunda y cuarta letra

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

-- Uso de Operadores Matemáticos:

select (5+5*5/5)-1

select sum(Edad) as SumaEdades from Test.Alumnos ---> funciones de agregación lo veremos


la sgte clase.

-- Uso del Concat:

select concat('Hola',' - ','Cómo estás?')


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

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

--- Funciones Condicionales:

select iif((5+5) > 9, 'TRUE', 'FALSE')

-- Para colocar alias o sobrenombres a los campos:

select custid as Codigo,

companyname as Compañia,

contactname as NombreContacto,

city as Ciudad,

country as País,

iif(country='Mexico','EN ONDA','NADA') as CampoNuevo

from Sales.Customers

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

--- SEGMENTACIÓN DE CLIENTES:

-- EJEMPLOS:

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

--- TARJETA CLASICA:

--- Hombre, entre 20 y 25 años, soltero, 930 soles

--- TARJETA PLATINUM

--- TARJETA BLACK

--- Hombre, entre 20 y 25 años, soltero, 2000 a 3000 soles

-- SEGMENTOS

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

--- CLIENTE PLATINUM:

--- country in (UK,Germany,France) ; contacttitle like '%Manager%'

--- CLIENTE VIP:

--- country in (USA,Spain,Brazil) ; contacttitle like '%Sales%'


--- CLIENTE CLASICO:

--- los que nos cumplan las reglas de arriba :)

select custid, contactname, contacttitle, city, country,

case when country in ('UK','Germany','France') and contacttitle like


'%Manager%'

then 'CLIENTE PLATINUM'

when country in ('USA','Spain','Brazil') and contacttitle like '%Sales%'

then 'CLIENTE VIP'

else 'CLIENTE CLASICO'

end as Segmento_Cliente

from Sales.Customers

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

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

--- Dar Permisos de Administrador al usuario SA a nuestra BD TSQL =)

Alter authorization on database::TSQL to sa

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

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

--- CREANDO NUESTRO MODELO DE MATRICULA:

-- Automaticamente se crean los campos para que acepten nulos

create table Test.Alumnos

IdAlumno int,

Nombres varchar(50),

Edad int,

MesCumpleaños varchar(15)

select * from Test.Alumnos


--- Cambiaremos la estructura de la tabla:

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

--- Cambiar el IdAlumno para que no acepte nulos:

alter table Test.Alumnos

alter column IdAlumno int not null

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

-- Cambiar el IdAlumno como llave primaria:

alter table Test.Alumnos

add primary key (IdAlumno)

-- LLAVES:

-- Llaves Primarias (PK) -> Llave principal de la tabla y son únicas

-- Llaves Foraneas (FK)

create table Test.Profesor

( IdProfesor int primary key,

Nombres varchar(50) )

insert into Test.Profesor values (1,'Carlos Reyes')

insert into Test.Profesor values (2,'Mario Reyes')

select * from Test.Profesor

create table Test.Asignatura

( IdAsignatura int primary key,

Nombre varchar(50) )

insert into Test.Asignatura values (1,'SQL SERVER')

insert into Test.Asignatura values (2,'POWER BI')


select * from Test.Asignatura

create table Test.Matricula

IdMatricula int primary key,

IdAlumno int,

IdProfesor int,

IdAsignatura int,

Fecha date,

constraint FK_Alumno foreign key (IdAlumno) references Test.Alumnos(IdAlumno),

constraint FK_Profesor foreign key (IdProfesor) references Test.Profesor(IdProfesor),

constraint FK_Asignatura foreign key (IdAsignatura) references Test.Asignatura(IdAsignatura)

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

---- Con esto hemos cambiado de fecha a fecha y hora :D

alter table Test.Matricula

alter column Fecha datetime

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

insert into Test.Matricula values (1,4,1,1,GETDATE())

insert into Test.Matricula values (2,2,2,2,GETDATE())

insert into Test.Matricula values (3,4,2,1,GETDATE())

select * from Test.Matricula

--- RESUMEN DE LA CLASE N° 1 ---

--- Claúsulas de Base de Datos:

--SELECT -> selecionar los campos a leer


--FROM -> apuntar a la tabla a consultar

--WHERE -> filtros de búsqueda

-- Para filtrar 1 valor ->"="

select custid, companyname, contactname, country, city

from Sales.Customers

where country = 'USA'

-- Para filtrar más de un valor en un campo: -> "IN"

select custid, companyname, contactname, country, city

from Sales.Customers

where country in ('USA','Mexico')

-- Para filtrar más de una condición: ->"AND"

select custid, companyname, contactname, country, city

from Sales.Customers

where country in ('USA','Mexico') and city in ('San Francisco','México D.F.')

-- Uso del OR

select custid, companyname, contactname, country, city

from Sales.Customers

where (country = 'USA' and city='San Francisco') or country ='Mexico'

-- Para filtros de rangos de números:

select custid, companyname, contactname, country, city

from Sales.Customers

where custid >= 5 and custid <= 50

select custid, companyname, contactname, country, city

from Sales.Customers

where custid between 5 and 50


--- Tipos de Datos:

-- Texto -> varchar(50) -> Se lee con comillas simples -> Ejm. country='Canada'

-- Número -> enteros -> int -> no lleva comillas simples -> Ejm. custid=5

-- Número -> decimal -> decimal(18,2) -> Ejm. VentaTotal > 500.50

-- Fecha -> date -> YYYY/MM/DD -> '2007/10/17' -> Se lee con comillas simples

-- Uso de la función Like

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

select * from Sales.Customers

where contactname like 'A%' --> inicien con la letra A

select * from Sales.Customers

where contactname like '%A' --> terminen con la letra A

select * from Sales.Customers

where contactname like '%ON%' --> contengan la palabra ON

--- Segmentación de Clientes --------------

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

--- Clásica -> Sueldo Mínimo, entre 25 años y 50 años.

--- Platinum ->

-------- N°1 -> Hombre, Soltero, >5000 soles, sin hijos

-------- N°2 -> Mujer, Soltera, >3000 soles, 2 hijos

--- Black

---- Uso del CASE:

select custid as CodigoCliente, contactname, contacttitle, country, city,

case when contacttitle like '%Manager%' and country in ('USA','UK','Spain')

then 'CLIENTE BLACK'


when contacttitle like '%Sales%' and country in ('Mexico','France')

then 'CIENTE PLATINUM'

else 'CLIENTE CLÁSICO'

end as Segmento_Cliente

from Sales.Customers

--- OTRA CONDICIONAL -> USO DEL IIF (IGUAL AL SI DEL EXCEL)

select custid as CodigoCliente, contactname, contacttitle, country, city,

IIF(contactname like 'A%','CLIENTE CON A','CLIENTE SIN A')

from Sales.Customers

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

USE TSQL ---> Nosotros le decimos que haga referencia a esa BD!!!

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

--- USO DE JOINS: ---

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

select top 3 * from Production.Products

select top 3 * from Production.Categories

--- Traer el nombre de la categoría del producto en la consulta

select A.*, B.categoryname, B.description

from Production.Products as A

inner join Production.Categories as B on A.categoryid = B.categoryid

------ CASO PRÁCTICO - REAL!!!

------------- TABLA_CLIENTES -> CLIENTES DEL BCP -> 5MM

------ PARA ESTE ANÁLISIS

------ CARLOS!!! No incluyas a los clientes que están en INFOCORP


---> HACES UN PROCESO -> SUBES TU EXCEL A UNA TABLA DE SQL SERVER -> TABLA_X

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

-- USO DE SUBCONSULTAS

--SELECT * FROM TABLA_CLIENTES

--WHERE DNI NOT IN (SELECT DNI FROM TABLA_X)

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

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

--- USO DEL GROUP BY ---

--- Hallar la cantidad de ordenes que hay por cliente (custid)

SELECT custid, COUNT(orderid) as ConteoOrdenes

FROM Sales.Orders

GROUP BY custid

--- Traeme todos los clientes con su conteo de ordenes

select A.custid,COUNT(b.orderid) as ConteoOrdenes

from Sales.Customers as A

left join Sales.Orders as B on A.custid = B.custid

group by A.custid

order by 2

--- Resumen de la Sesión N° 2 ---

-- Uso de Joins

select O.orderid, O.orderdate, O.custid, C.contactname, C.country

from Sales.Orders as O

inner join Sales.Customers as C on O.custid=C.custid

-- Claúsulas de BD
-- Quiero hallar la cantidad de ordenes por año:

select year(orderdate) as Año, COUNT(orderid) as ConteoOrdenes

from Sales.Orders

where year(orderdate) in (2007,2008)

group by year(orderdate)

-- Quiero hallar el monto de la venta total de ordenes por año

select * from Sales.Orders where orderid=10248

select * from Sales.OrderDetails where orderid=10248

select YEAR(orderdate) as Año, sum(unitprice * qty) as VentaTotal

from Sales.Orders as O

inner join Sales.OrderDetails as OD on O.orderid=OD.orderid

group by YEAR(orderdate)

select YEAR(orderdate) as Año, OD.orderid, sum(unitprice * qty) as VentaTotal

from Sales.Orders as O

inner join Sales.OrderDetails as OD on O.orderid=OD.orderid

group by YEAR(orderdate),OD.orderid

-- Quiero hallar la cantidad de clientes(custid) que he tenido por Año, Mes

-- Utilizar Tabla: Sales.Orders

-- Respuesta x Zoom: La cantidad de clientes que hubo en Abril(4) del 2008

select YEAR(orderdate) as Año, MONTH(orderdate) as Mes, COUNT(custid) as Conteo

from Sales.Orders

group by YEAR(orderdate), MONTH(orderdate)

order by YEAR(orderdate), MONTH(orderdate)


-- Quiero hallar la suma de precio unitario por categoría (categoryid)

-- Respuesta -> La suma de unitprice de la categoría 7

select categoryid , SUM(unitprice) as SumaUnitPrice

from Production.Products

group by categoryid

-- Quiero hallar la cantidad de productos(productid)

-- que hay por Supplier(Companyname)

select S.companyname, COUNT(productid) as ConteoProductos

from Production.Products as P

inner join Production.Suppliers as S on P.supplierid=S.supplierid

group by S.companyname

-- Uso del CAST -> Conversión de Datos:

select productname, unitprice,

cast(unitprice as int) as Entero,

cast(unitprice as decimal(18,2)) as '2_Decimal',

cast(GETDATE() as date) as Fecha

from Production.Products

---------

-- Uso de Tablas Temporales

create table #Tablita (id int)

insert into #Tablita values (2)

select * from #Tablita

-- Crear tabla a traves de un resultado

-- Uso del into


select categoryid , SUM(unitprice) as SumaUnitPrice

into #TablaEjemplo

from Production.Products

group by categoryid

select * from #TablaEjemplo

-- Insertando datos de consulta a una tabla

insert into #TablaEjemplo

select categoryid , SUM(unitprice) as SumaUnitPrice

from Production.Products

group by categoryid

select * from #TablaEjemplo

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

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

-- Uso de Vistas

--- Solo sirve para hacer consultas con SELECT!!!

create view Vista_ResultadoSuppliers

as

select S.companyname, COUNT(productid) as ConteoProductos

from Production.Products as P

inner join Production.Suppliers as S on P.supplierid=S.supplierid

group by S.companyname

select * from Vista_ResultadoSuppliers

---- Uso de Tablas Derivadas

select * from
(

select orderid, orderdate as Fecha, shipcountry, shipcity

from Sales.Orders

where YEAR(orderdate) =2008 and shipcountry='USA'

) as Tablon

--- Uso de la Función Ranking -> RANK()

-- Realizar un ranking de productos por preciounitario de forma desc

select *,

RANK() OVER(order by unitprice desc) as RankByUnitPrice

from Production.Products

--- Explicación del ORDER BY -> última claúsula de BD!

--- asc -> ascendente

--- desc -> descendente

select * from Sales.Customers

order by custid desc

--- Hallar el ranking de categorías con más productos

select categoryid,

COUNT(productid) as ConteoProductos,

RANK() OVER(order by COUNT(productid) desc) as RankByConteo

from Production.Products

group by categoryid

--- Hallando el desempate con otra condición

select categoryid,

COUNT(productid) as ConteoProductos,

RANK() OVER(order by COUNT(productid) desc,categoryid asc) as


RankByConteo
from Production.Products

group by categoryid

-- Uso de Subqueries -> O SubConsultas:::

select custid,contactname,address,city,country

from Sales.Customers

where custid in (select custid from Lista_Negra) -- Solo Lista Negra

select custid,contactname,address,city,country

from Sales.Customers

where custid not in (select custid from Lista_Negra) -- Descartando a Lista Negra

-- Creando una lista negra:

create table Lista_Negra (custid int)

insert into Lista_Negra values (1),(17),(22),(48),(55)

select * from Lista_Negra

-----

-- USO DE CLAÚSULAS DE BASE DE DATOS - APRENDIDAS :

SELECT custid, count(orderid) as ConteoOrdenes

FROM Sales.Orders

WHERE shipcountry in ('USA','Mexico','France')

GROUP BY custid

ORDER BY 1 asc

--- Uso del HAVING!!!!

--- Hallar solo a los clientes(custid) que tengan más de 12 ordenes

SELECT custid, count(orderid) as ConteoOrdenes


FROM Sales.Orders

WHERE shipcountry in ('USA','Mexico','France')

GROUP BY custid

HAVING count(orderid) > 12

ORDER BY 1 asc

--- Hallar la cantidad de productos que hay por categoryid

--- Solo quedate con las categorías que tienen más de 6 productos

select categoryid, COUNT(productid) as ConteoProductos

from Production.Products

group by categoryid

having COUNT(productid) > 6

order by COUNT(productid) asc

--- Solución de la PC N° 1 ---

--- 1ra Solución ---

select o.custid,o.orderid, sum(od.unitprice * od.qty) as VentaTotal

into #TablaBase

from Sales.Orders as o

inner join Sales.OrderDetails as od on o.orderid=od.orderid

group by o.custid,o.orderid

order by o.custid

select custid, MAX(VentaTotal) as MaxVentaTotal

into #TablaMax

from #TablaBase

group by custid

order by 1
select * from #TablaBase where custid=1

select * from #TablaMax where custid=1

select a.custid, b.orderid,a.MaxVentaTotal

from #TablaMax as a

inner join #TablaBase as b on a.MaxVentaTotal=b.VentaTotal and a.custid=b.custid

order by 1

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

--- Solución Óptima

select custid, orderid, VentaTotal from

select o.custid,o.orderid, sum(od.unitprice * od.qty) as VentaTotal,

RANK() over(partition by custid order by sum(od.unitprice * od.qty) desc) as


RankByVentaTotal

from Sales.Orders as o

inner join Sales.OrderDetails as od on o.orderid=od.orderid

group by o.custid,o.orderid

) as Resultado

where RankByVentaTotal = 1

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

---------

-- Uso de Having!!!!

select orderid,

count(productid) as ConteoProd ,

SUM(qty*unitprice) as VentaTotal,

MAX(qty*unitprice) as VentaTotalMAX

from Sales.OrderDetails
group by orderid

having count(productid) > 5

order by 1 desc

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

--- Ejercicio ---

-- Hallar la cantidad de ordenes que hay por shipcountry,año y mes ....

-- Pero solo mencionar a los meses que tienen más de 5 ordenes

select shipcountry,

YEAR(orderdate) as Año,

MONTH(orderdate) as Mes,

COUNT(orderid) as ConteoOrdenes

from Sales.Orders

group by shipcountry,YEAR(orderdate),MONTH(orderdate)

having COUNT(orderid) > 5

--- Ejemplo de ROW_NUMBER

select shipcountry,

YEAR(orderdate) as Año,

MONTH(orderdate) as Mes,

COUNT(orderid) as ConteoOrdenes,

RANK() over(partition by shipcountry

order by COUNT(orderid) desc) as RankByConteo,

ROW_NUMBER() over(partition by shipcountry

order by COUNT(orderid) desc) as


RowNumberByConteo

from Sales.Orders

group by shipcountry,YEAR(orderdate),MONTH(orderdate)

having COUNT(orderid) > 5


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

--- Ejemplo de Partition By

select productid,productname,categoryid,unitprice,

RANK() over(partition by categoryid order by unitprice desc) as RankingByUnitPrice,

ROW_NUMBER() over(partition by categoryid order by unitprice desc) as


RowNumByUnitPrice

from Production.Products

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

---Uso de Cte's

;with cte_ejemplo as

select productid,productname,categoryid,unitprice,

RANK() over(partition by categoryid order by unitprice desc) as


RankingByUnitPrice,

ROW_NUMBER() over(partition by categoryid order by unitprice desc)


as RowNumByUnitPrice

from Production.Products

),

cte_test2 as

select * from Production.Products where categoryid in (6,7,8)

),

cte_test3 as

select * from Sales.Customers where custid between 1 and 5

select * from cte_test2


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

--- DIFERENCIA ENTRE UNION Y UNION ALL!!!! -----

-- Uso del UNION -> tienen que tener la misma estructura

select country, region, city from Sales.Customers

UNION --- se encarga de eliminar la duplicidad de datos a nivel de filas

select country, region, city from HR.Employees

select country, region, city from Sales.Customers

UNION ALL--- muestra toda la unión de todos los registros de ambas tablas (incluído
duplicados)

select country, region, city from HR.Employees

--- Uso del INTERSECT

select country, region, city from Sales.Customers

INTERSECT

select country, region, city from HR.Employees

--- Uso del EXCEPT

select country, region, city from Sales.Customers -- solo va leer esto ---> excluyendo el
resultado de abajo

EXCEPT

select country, region, city from HR.Employees

----

----- CROSS JOIN!!!!!

-- Cumple la funcionalidad de un Plano Cartesiano -> TODO "XY"

select * from Sales.Customers -- 91 clientes

select * from Production.Products -- 77 productos


select * from Sales.Customers

cross join Production.Products ---> 91 x 77 -> 7007 filas

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

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

---- USO DE VARIABLES!!!

declare @var int ---> Declarando una variable

set @var = 18 ---> Seteando un valor a nuestra variable

select * from Sales.Customers where custid=@var

---- USO DE PROCEDIMIENTOS ALMACENADOS!!!! ---> SP :: Stored Procedure

create procedure sp_miprimersp2021

as

begin --- Inicio

select * from Sales.Customers where custid = 17

select custid,COUNT(orderid) as ConteoOrdenes

from Sales.Orders where custid = 17

group by custid

end --- Fin

exec sp_miprimersp2021

----- PASO N° 2

alter procedure sp_miprimersp2021


as

begin --- Inicio

declare @var int

set @var=28

select * from Sales.Customers where custid = @var

select custid,COUNT(orderid) as ConteoOrdenes

from Sales.Orders where custid = @var

group by custid

end --- Fin

exec sp_miprimersp2021

---- PASO N° 3

--- Usando variables dinámicas

alter procedure sp_miprimersp2021 (@var int)

as

begin --- Inicio

--declare @var int

--set @var=28

select * from Sales.Customers where custid = @var

select custid,COUNT(orderid) as ConteoOrdenes

from Sales.Orders where custid = @var

group by custid

end --- Fin


exec sp_miprimersp2021 75

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

-- Ejercicio N° 1 - SP

create procedure sp_ejercicio1 (@supplierid int)

as

begin

select * from Production.Products where supplierid = @supplierid

end

exec sp_ejercicio1 3

create procedure sp_ejercicio4 (@fecini date, @fecfin date)

as

begin

select custid, COUNT(orderid) as ConteoOrdenes

from Sales.Orders

where orderdate between @fecini and @fecfin

group by custid

end

exec sp_ejercicio4 '2007-05-12','2007-10-12'

---- Resumen de la Sesión N° 4 ---

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

-- Uso de Procedimientos Almacenados

create procedure SP_INFO2008 (@custid int) -- variable dinámica


as

begin

declare @año int -- declarando una variable fija

set @año = 2008 -- dando un valor a mi variable

select * from Sales.Orders

where YEAR(orderdate) = @año and custid = @custid

end

exec SP_INFO2008 14

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

create procedure SP_INFO2008_Country (@country varchar(20)) -- variable dinámica

as

begin

declare @año int -- declarando una variable fija

set @año = 2008 -- dando un valor a mi variable

select * from Sales.Orders

where YEAR(orderdate) = @año and shipcountry = @country

end

exec SP_INFO2008_Country 'UK'

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

--- Crear un procedimiento que inserte las ordenes de un cliente específico (@custid)

--- a una Tabla RESULTADO (custid, orderid)


create table Resultado1 (custid int, orderid int)

select * from Resultado1

---

create procedure SP_INSERCIONORDEN (@custid int)

as

begin

--- Paso 1

DELETE FROM Resultado1 where custid = @custid

--- Paso 2

--- INSERTAR REGISTROS DIRECTAMENTE DE UN SELECT***

INSERT INTO Resultado1 (custid, orderid)

select custid, orderid

from Sales.Orders where custid = @custid

end

exec SP_INSERCIONORDEN 35

select * from Resultado1

-----

--- Tabla Sales.OrderDetails y Production.Products

select od.orderid, od.productid, p.productname, od.qty*od.unitprice as Venta

from Sales.OrderDetails as od

inner join Production.Products as p on od.productid=p.productid

--- OrderID, ProductID, NombreProduct, Venta

------------
select *, RANK() OVER(partition by categoryid

order by unitprice desc) as RankingByUnitprice

from Production.Products

--- USO DE LAG AND LEAD!!!!

USE AdventureWorks

SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear,

LAG(SalesQuota, 2,0) OVER (ORDER BY YEAR(QuotaDate)) AS PRevious2daQuota,

LAG(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS PreviousQuota,

SalesQuota AS CurrentQuota,

LEAD(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS NextQuota,

LEAD(SalesQuota, 2,0) OVER (ORDER BY YEAR(QuotaDate)) AS NextQuota

FROM Sales.SalesPersonQuotaHistory

WHERE BusinessEntityID = 275 and YEAR(QuotaDate) IN ('2007','2008')

----------

--- PIVOT Y UNPIVOT --> En el otro archivo.

--------

CREATE PROCEDURE SP_TEST (@TipoCarga int, @FechaReproceso date)

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

--NOMBRE : SP_TEST

--SCHEMA : STG

--TABLAS AFECTADAS : ODS.TEST

--TABLAS FUENTES : STG.TEST

--OBJETIVO : Realizar la Carga de Datos a la tabla ....

--TIPO : SQL

--VERSIONES :

--#Version Desarrollador Fecha Descripcion


-- 1.0 Creyes 00/00/2000 Se creo script para......

--PARAMETROS : @TipoCarga (0 = CargaCero, 1 = CargaIncremental, 2 = Carga Reproceso)

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

AS

BEGIN TRY

IF @TipoCarga=0

---- Carga Inicial o conocida como la Primera Carga

IF @TipoCarga=1

---- Tabla_Test -> FechaCarga

---- Carga Incremental

--INSERT INTO TABLA_TEST

--SELECT * FROM TABLA_ORIGEN

--WHERE FECHACARGA > GETDATE() -1

-- ID - REGISTRO - FECHACARGA - FECHAMOD

-- 1 - xxrtt - 02/01/2018 - 08/01/2020

IF @TipoCarga=2 and @FechaReproceso='02/01/2020'

--- Carga Reproceso

--INSERT INTO TABLA_TEST

--SELECT * FROM TABLA_ORIGEN

--WHERE FECHACARGA > @FechaReproceso

END TRY

BEGIN CATCH

INSERT INTO LOG_ERRORS


VALUES (SUSER_SNAME(), ERROR_NUMBER(), ERROR_STATE(),
ERROR_SEVERITY(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_MESSAGE(), GETDATE());

END CATCH

GO

USE master; --- invocar una BD

GO

CREATE DATABASE EmpData4;

GO

USE EmpData4;

GO

CREATE TABLE EmpInfo(

EmpID INT PRIMARY KEY, ---> Llave primaria (solo aceptará ID únicos)

FirstName NVARCHAR(50) NOT NULL,

LastName NVARCHAR(50) MASKED WITH (FUNCTION = 'default()') NOT NULL,

Birthdate DATE MASKED WITH (FUNCTION = 'default()') NOT NULL,

CurrentFlag BIT MASKED WITH (FUNCTION = 'default()') NOT NULL,

SalesLastYear MONEY MASKED WITH (FUNCTION = 'default()') NOT NULL,

EmailAddress NVARCHAR(50),

SickLeave INT,

SalesYTD MONEY,

NatID NVARCHAR(15),

PhoneNumber NVARCHAR(25));

GO

INSERT INTO EmpInfo

SELECT e.BusinessEntityID, sp.FirstName, sp.LastName,

e.BirthDate, e.CurrentFlag, sp.SalesLastYear,

sp.EmailAddress, e.SickLeaveHours, sp.SalesYTD,


e.NationalIDNumber, sp.PhoneNumber

FROM AdventureWorks.HumanResources.Employee e

INNER JOIN AdventureWorks.Sales.vSalesPerson sp ON e.BusinessEntityID =


sp.BusinessEntityID

WHERE sp.CountryRegionName = 'United States';

select * from EmpInfo

-- Creamos un usuario al cual le asignaremos los permisos para que vea nuestra tabla EmpInfo

CREATE USER usuario_test WITHOUT LOGIN

GRANT SELECT ON OBJECT::dbo.EmpInfo TO usuario_test

GO

select * from EmpInfo

EXECUTE AS USER = 'usuario_test';

SELECT PhoneNumber FROM EmpInfo where PhoneNumber like '%7'

REVERT;

--- Aplicar una máscara cuando el tipo de datos es un correo electrónico:

ALTER TABLE EmpInfo

ALTER COLUMN EmailAddress NVARCHAR(50) MASKED WITH (FUNCTION = 'email()') NULL;

--- Aplicar una máscara aleatoria si es un tipo de datos INT:

ALTER TABLE EmpInfo

ALTER COLUMN SickLeave INT MASKED WITH (FUNCTION = 'random(1, 50)') NOT NULL;

--- Aplicar una máscara aleatoria si es un tipo de datos Money:

ALTER TABLE EmpInfo


ALTER COLUMN SalesYTD MONEY MASKED WITH (FUNCTION = 'random(101, 999)') NOT
NULL;

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

--- Máscara parcial -- Funciona mejor para los datos como números de tarjetas de crédito o ID -
--

--- Aplicando una máscara parcial reemplazando los 5 primeros caracteres por 'xxxxx'

ALTER TABLE EmpInfo

ALTER COLUMN NatID NVARCHAR(15) MASKED WITH (FUNCTION = 'partial(0, "xxxxx", 4)') NOT
NULL;

--- Aplicando una máscara parcial si es un Celular, solo mostrando los 4 primeros caracteres:

ALTER TABLE EmpInfo

ALTER COLUMN PhoneNumber NVARCHAR(25) MASKED WITH (FUNCTION = 'partial(4, "xxx-


xxxxxx", 0)') NULL

--- Aplicando una máscara parcial si es un Celular, solo mostrando los 4 primeros caracteres:

ALTER TABLE EmpInfo

ALTER COLUMN PhoneNumber NVARCHAR(25) MASKED WITH (FUNCTION = 'partial(2, "%-


%%%-%%", 2)') NULL

SELECT OBJECT_NAME(object_id) TableName,

name ColumnName,

masking_function MaskFunction

FROM sys.masked_columns

ORDER BY TableName, ColumnName

También podría gustarte