100% encontró este documento útil (1 voto)
153 vistas

SQL Server

Este documento contiene instrucciones SQL para realizar diversas operaciones sobre bases de datos y tablas, como agregar, modificar y consultar datos; usar joins, subconsultas y procedimientos almacenados; e importar datos de forma masiva. Se detallan comandos para manipular estructuras, datos y permisos a nivel de tablas, columnas y registros.

Cargado por

smith anton
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
100% encontró este documento útil (1 voto)
153 vistas

SQL Server

Este documento contiene instrucciones SQL para realizar diversas operaciones sobre bases de datos y tablas, como agregar, modificar y consultar datos; usar joins, subconsultas y procedimientos almacenados; e importar datos de forma masiva. Se detallan comandos para manipular estructuras, datos y permisos a nivel de tablas, columnas y registros.

Cargado por

smith anton
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 7

AGREGAR VARIABLES A LA TABLA:

INSERT INTO categorias


VALUES (9,'CUADERNOS', 'UTILES ESCOLARES')

AGREGAR VARIABLES A LA TABLA EN FORMA DESORDENADA:


INSERT INTO categorias(idcategoria, descripcion, nombrecategoria)
values (10, 'tecnología', 'computadora')

CAMBIAR DE NOMBRE COLUMNA:


EXEC sp_RENAME 'Empleado.dept','numdep','COLUMN'

AGRUPAR TABLAS:
ALTER TABLE Empleado ADD
CONSTRAINT FK_DEPARTAMENTO FOREIGN KEY (numdep) REFERENCES Departamento (numdep)

CAMBIAR TIPO DE DATOS:


alter table Empleado alter column sexo varchar(30) not null

CONSULTAR EL TIPO DE DATOS:


sp_help Empleado

MOSTRAR TODOS LOS DATOS DE LA TABLA categorías:


select * from categorías

MOSTRAR LA COLUMNA nombrecategoria DE LA TABLA categorías:


SELECT nombrecategoria from categorias

MOSTRAR LA COLUMNA idcategoría, nombrecategoria DE LA TABLA categorías:


select idcategoria, nombrecategoria from categorias

MOSTRAR LA COLUMNA idCliente, idpedido DE LA TABLAS clientes, detallesdepedidos:


select idCliente, idpedido from clientes, detallesdepedidos
MOSTRAR LOS CLIENTES QUE RESIDEN EN EL PAÍS DE Alemania (NombreCompañia,Dirección y CodPostal):
select NombreCompañia, Direccion, CodPostal
FROM clientes
where pais='Alemania'

LISTAR LOS PRODUCTOS CUYO PRECIO DE UNIDAD ESTE ENTRE 45 Y 90 SOLES (nombreProducto,
PrecioUnidad):
select nombreProducto, precioUnidad
from productos Between = entre
where precioUnidad between 45 and 90

LISTAR A LOS CLIENTES QUE NO TIENEN Fax. (nombre compañia, ciudad y país):
select NombreCompañia, ciudad, pais
from clientes
where Fax IS NULL
SELECCIONAR LOS CLIENTES (nombre de compañía, dirección y país), CUYO NOMBRE COMPAÑÍA
EMPIECEN CON LAS LETRAS A, B, C o D, PERTENEZCAN AL país de Alemania Y ORDENARLOS DE MANERA
ASCENDENTE POR EL CAMPO dirección:
SELECT NombreCompañia, Direccion, Pais
FROM Clientes
where NombreCompañia like ('[abcd]%') and Pais='Alemania'
order by Direccion asc

TOTAL DE EMPLEADOS NACIDOS ANTES DEL 1 DE ENERO DE 1960:


select count(IdEmpleado) as NroEmpleados
from Empleados
where FechaNacimiento < '1960-01-01'

MOSTRAR LA CANTIDAD DE CLIENTE POR PAÍS Y ORDENARLOS DE MANERA DESCENDENTE:


select Pais, COUNT(idCliente) as NroCliente
from clientes
group by pais
order by NroCliente desc

MOSTRAR LA CANTIDAD DE CLIENTE POR PAÍS DONDE DICHA CANTIDAD SEA MAYOR IGUAL 6:
select Pais, count(idCliente) as NroCliente
from clientes
group by pais
having count(idCliente)>=6

SELECCIONAR LOS PEDIDOS QUE SE REALIZARON EN AGOSTO DE CUALQUIER AÑO POR LOS EMPLEADOS
CON CÓDIGO (idempleado) 2 y 5 Y CUYO CÓDIGO DE CLIENTES COMIENCEN CON LAS LETRAS DE LA A
HASTA LA G:
select *
from pedidos
where month(FechaPedido)=08 and IdEmpleado in (2,5) and IdCliente like ('[a-g]%')

MOSTRAR LOS 5 MEJORES PRODUCTOS CON PRECIO DE UNIDAD:


select top 5 nombreProducto, precioUnidad
from productos
order by precioUnidad desc

QUE PRODUCTO TIENE PRECIO DE UNIDAD SUPERIOR AL PRODUCTO “PEZ ESPADA”:


select nombreProducto, precioUnidad, suspendido
from productos
where precioUnidad >
(select precioUnidad
from productos
where nombreProducto='PEZ ESPADA'
)
SUBCONSULTAS:

 LISTAR LOS CAMPOS nombrecategoria y descripción DE LA TABLA Categoria, DE LOS PRODUCTOS CUYO
precioUnidad ESTE ENTRE 45 y 55. TODA ESTA INFORMACIÓN DEBE SER ORDENADA DE MANERA
DESCENDENTE POR EL CAMPO nombrecategoria.
select nombrecategoria,descripcion
from categorias
where idcategoria in (
select idcategoria
from productos
where precioUnidad between 45 and 55
)
order by nombrecategoria desc

 LISTAR LOS CAMPOS nombreproducto, categoriaproducto, preciounidad y unidadesenexistencia DE TODOS


LOS PRODUCTOS VENDIDOS EN UNA CANTIDAD MAYOR E IGUAL A 100:
select nombreProducto, categoriaProducto, precioUnidad, unidadesEnExistencia
from productos
WHERE idproducto in (
select idproducto
from detallesdepedidos
where cantidad>= 100
)

 LISTAR LOS CAMPOS nombreproducto y categoriaproducto DE AQUELLOS PRODUCTOS QUE PERTENECEN A


LA CATEGORÍA BEBIDAS:
select nombreProducto, categoriaProducto
from productos
where idCategoria in (
select idcategoria
from categorias
where nombrecategoria = 'bebidas'
)

 MOSTRAR LOS CLIENTES (nombrecompañia, telefono) QUE HAYAN PASADO AL MENOS UN PEDIDO EN EL
AÑO 1996
select NombreCompañia,Telefono
from clientes
where idCliente in (
select idCliente
from Pedidos
where year(FechaPedido)=1996
)
INSERTAR, ELIMINAR Y ACTUALIZAR DATOS

 Añadir un nuevo departamento: Número de departamento “G11”, nombre del departamento “GESTION
HUMANA” y numero de dirección “000080”:
insert into Departamento(numdep, nombredep, numdirec)
values ('G11', 'GESTION HUMANA', 000080)

 REDUCIR EL SALARIO DE LOS EMPLEADOS EN 1000 SOLES:


update Empleados
set sueldoBasico = sueldoBasico – 1000

 Asignar a los empleados del Tratamiento “Srta.” a “Sra.”:


update Empleados update clientes
set Tratamiento ='Sra.' set Ciudad = 'Peru'
where Tratamiento = 'Srta.' where idCliente = 'ALFKI'

 Eliminar al empleado de apellido “Soler”:


delete from Empleados
where Apellidos='Solar'

 Mostrar los campos “Nombre y Apellidos” y “Cargo” de empleados de sexo masculino:


select concat(Nombre,' ',Apellidos) as 'Nombre y Apellidos', cargo, Tratamiento
from Empleados
where Tratamiento like '%r.'

 Mostrar los campos “nombreproducto” y la última letra del campo “categoría producto” de la tabla
productos:
select nombreProducto, right(categoriaProducto,1) as categoriaProducto
from productos

 De la tabla Clientes mostrar el campo “nombrecompañia” en mayúsculas y el campo “direccion” en


minúsculas:
select upper(NombreCompañia) NombreCompañia, lower(Direccion) Direccion
from clientes

JOIN
 Mostrar el nombre de los productos y sus unidades en existencia de aquellos productos que
pertenecen a la categoría Bebidas y con unidades en existencia menor a 25:
select nombreProducto, unidadesEnExistencia
from productos A inner join categorias B on A.idcategoria=B.idcategoria
where nombrecategoria='bebidas' and unidadesEnExistencia<25

 Mostrar el nombre del empleado y cuantos pedidos realizo:

select Nombre, count(idPedido) as 'NroPedido'


from Empleados A inner join Pedidos B on A.IdEmpleado = B.IdEmpleado
group by Nombre
 Seleccionar las categorías que tengan más 5 productos y el precio de unidad de cada producto sea
mayor igual a 15. Mostrar el nombre de la categoría y el número de productos:
select A.nombrecategoria, count(B.idCategoria) as cantidad
from categorias A inner join productos B on A.idcategoria = B.idCategoria
where precioUnidad >= 15
group by nombrecategoria
having count(B.idCategoria)>5

 Mostar el total pagado por cada orden de compras solo del mes de enero del 1996:

select A.IdPedido, SUM(B.preciounidad*B.cantidad)as Total


from Pedidos A inner join detallesdepedidos B on A.IdPedido=B.idpedido
where month(A.FechaPedido)=1 and year(A.FechaPedido)=1996
group by A.IdPedido

PROCEDIMIENTOS ALMACENADOS

 Crear un procedimiento almacenado que cuente los productos que empiezan con un determinado
carácter:
Ejemplo: Los productos que empiezan con “T”
CREATE PROCEDURE Cantidad_Producto
@nombre varchar(5)
as
select count(*) as [Cantidad Productos]
from productos
where nombreProducto like @nombre+'%'

---ejecutar
exec Cantidad_Producto 't'

 Realizar un procedimiento almacenado que devuelva el precio mayor y el precio menor de según
la categoría:
create procedure Precio_Producto
@NombreCategoria varchar(40)
as

select @NombreCategoria nombrecategoria, max(precioUnidad) [Precio Mayor],


min(precioUnidad) [Precio Menor]
from productos A inner join categorias B on A.idCategoria= B.idcategoria
where nombrecategoria = @NombreCategoria

---ejecutar
exec Precio_Producto 'bebidas'
 Realizar un procedimiento que permita eliminar el cliente según su
identificación (idcliente). Si el cliente realizo algún pedido mostrar el
siguiente mensaje “No se puede eliminar al cliente” caso contrario se
procede a eliminar al cliente y mostrar el siguiente mensaje “Cliente
eliminado”:

CREATE PROCEDURE ELIMINAR_CLIENTE


@CuestomerID char(5)
as
IF
EXISTS (SELECT * FROM Pedidos WHERE IdCliente = @CuestomerID)
PRINT 'NO SE PUEDE ELIMINAR AL CLIENTE'
ELSE
BEGIN
delete from clientes
where idCliente = @CuestomerID
PRINT 'CLIENTE FUE ELIMINADO'
END

-----EJECUTAR
EXEC ELIMINAR_CLIENTE 'ANATR'

 crear un procedimiento almacenado que muestre los productos que se


encuentra en un rango de precio. Ejemplo: Productos con un rango de precio
de unidad entre 10 y 20:

CREATE PROCEDURE RANGO_PRECIO


@MINI FLOAT,
@MAXI FLOAT
AS
SELECT *
FROM productos A
WHERE A.precioUnidad BETWEEN @MINI AND @MAXI
ORDER BY precioUnidad
GO

----EJECUTAR
EXEC RANGO_PRECIO 10,50
CARGA MASIVA

 Crear un archivo.txt que contenga la misma estructura de la tabla


Categorías y crear un procedimiento almacenado que realice dicha carga

bulk insert categorias


from 'E:\categoria.csv'
with
(
fieldterminator = ';',
rowterminator = '\n'
)

https://www.youtube.com/watch?v=3X0nyc5JGl8
Contraseña de manuales de instalación: CEDHINFO
https://drive.google.com/drive/u/1/folders/14jyE6FV6jYluZmBEd7wnUDJ-AAIpLvLW
https://www.youtube.com/watch?v=RajH5hTgL-M
https://www.youtube.com/watch?v=_V5cey9V9dw&t=310s
https://www.youtube.com/watch?v=TmH_794b2I4
https://www.youtube.com/watch?v=3V8mNlKbDAQ
http://cvosoft.com/sistemas_sap_abap/recursos_tecnicos_abap/que-es-sap-pm.php
https://www.youtube.com/watch?v=dVHdyyuLjiA

PLANIFICADO: todo aquello que se identifica mediante una actividad preventiva (ANOMALIAS)
NO PLANIFICADO: Siempre es una falla.
EMERGIACIA: Se sale de los alineamientos de mantenimiento. Ocurre a equipos críticos que
pueden parar la producción

También podría gustarte