Вы находитесь на странице: 1из 33

Asignatura :SQL server aplicado

Profesor: Guillermo Aguilera I


Carrera: Ingeniería en Conectividad y Redes

Guía 3 complementaria de
Implementación, Administración y
Soporte de
Microsoft SQL Server 2014.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
Module 2: Use and management of data using Transact-SQL.

A. Using SELECT to retrieve rows and columns

The following example shows three code examples. This first code example returns
all rows (no WHERE clause is specified) and all columns (using the *) from
the Producttable in the AdventureWorks2012 database.
SQLCopy

USE AdventureWorks2012;
GO
SELECT *
FROM Production.Product
ORDER BY Name ASC;
-- Alternate way.
USE AdventureWorks2012;
GO
SELECT p.*
FROM Production.Product AS p
ORDER BY Name ASC;
GO

This example returns all rows (no WHERE clause is specified), and only a subset of
the columns (Name, ProductNumber, ListPrice) from the Product table in
the AdventureWorks2012 database.

USE AdventureWorks2012;
GO
SELECT Name, ProductNumber, ListPrice AS Price
FROM Production.Product
ORDER BY Name ASC;
GO

This example returns only the rows for Product that have a product line of R and
that have days to manufacture that is less than 4.
SQLCopy

USE AdventureWorks2012;
GO
SELECT Name, ProductNumber, ListPrice AS Price
FROM Production.Product
WHERE ProductLine = 'R'
AND DaysToManufacture < 4
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
ORDER BY Name ASC;
GO
B. Using SELECT with column headings and calculations

The following examples return all rows from the Product table. The first example
returns total sales and the discounts for each product. In the second example, the
total revenue is calculated for each product.
SQLCopy

USE AdventureWorks2012;
GO
SELECT p.Name AS ProductName,
NonDiscountSales = (OrderQty * UnitPrice),
Discounts = ((OrderQty * UnitPrice) * UnitPriceDiscount)
FROM Production.Product AS p
INNER JOIN Sales.SalesOrderDetail AS sod
ON p.ProductID = sod.ProductID
ORDER BY ProductName DESC;
GO

This is the query that calculates the revenue for each product in each sales order.
SQLCopy

USE AdventureWorks2012;
GO
SELECT 'Total income is', ((OrderQty * UnitPrice) * (1.0 -
UnitPriceDiscount)), ' for ',
p.Name AS ProductName
FROM Production.Product AS p
INNER JOIN Sales.SalesOrderDetail AS sod
ON p.ProductID = sod.ProductID
ORDER BY ProductName ASC;
GO
C. Using DISTINCT with SELECT

The following example uses DISTINCT to prevent the retrieval of duplicate titles.
SQLCopy

USE AdventureWorks2012;
GO
SELECT DISTINCT JobTitle
FROM HumanResources.Employee
ORDER BY JobTitle;
GO
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
D. Creating tables with SELECT INTO

The following first example creates a temporary table named #Bicycles in tempdb.
SQLCopy

USE tempdb;
GO
IF OBJECT_ID (N'#Bicycles',N'U') IS NOT NULL
DROP TABLE #Bicycles;
GO
SELECT *
INTO #Bicycles
FROM AdventureWorks2012.Production.Product
WHERE ProductNumber LIKE 'BK%';
GO

This second example creates the permanent table NewProducts.


SQLCopy

USE AdventureWorks2012;
GO
IF OBJECT_ID('dbo.NewProducts', 'U') IS NOT NULL
DROP TABLE dbo.NewProducts;
GO
ALTER DATABASE AdventureWorks2012 SET RECOVERY BULK_LOGGED;
GO

SELECT * INTO dbo.NewProducts


FROM Production.Product
WHERE ListPrice > $25
AND ListPrice < $100;
GO
ALTER DATABASE AdventureWorks2012 SET RECOVERY FULL;
GO
E. Using correlated subqueries

The following example shows queries that are semantically equivalent and
illustrates the difference between using the EXISTS keyword and the IN keyword.
Both are examples of a valid subquery that retrieves one instance of each product
name for which the product model is a long sleeve logo jersey, and
the ProductModelID numbers match between the Product and ProductModel tables.
SQLCopy

USE AdventureWorks2012;
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
GO
SELECT DISTINCT Name
FROM Production.Product AS p
WHERE EXISTS
(SELECT *
FROM Production.ProductModel AS pm
WHERE p.ProductModelID = pm.ProductModelID
AND pm.Name LIKE 'Long-Sleeve Logo Jersey%');
GO

-- OR

USE AdventureWorks2012;
GO
SELECT DISTINCT Name
FROM Production.Product
WHERE ProductModelID IN
(SELECT ProductModelID
FROM Production.ProductModel
WHERE Name LIKE 'Long-Sleeve Logo Jersey%');
GO

The following example uses IN in a correlated, or repeating, subquery. This is a


query that depends on the outer query for its values. The query is executed
repeatedly, one time for each row that may be selected by the outer query. This
query retrieves one instance of the first and last name of each employee for which
the bonus in the SalesPerson table is 5000.00 and for which the employee
identification numbers match in the Employee and SalesPerson tables.
SQLCopy

USE AdventureWorks2012;
GO
SELECT DISTINCT p.LastName, p.FirstName
FROM Person.Person AS p
JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = p.BusinessEntityID WHERE 5000.00 IN
(SELECT Bonus
FROM Sales.SalesPerson AS sp
WHERE e.BusinessEntityID = sp.BusinessEntityID);
GO

The previous subquery in this statement cannot be evaluated independently of the


outer query. It requires a value for Employee.EmployeeID, but this value changes as
the SQL Server Database Engine examines different rows in Employee.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
A correlated subquery can also be used in the HAVING clause of an outer query. This
example finds the product models for which the maximum list price is more than
twice the average for the model.
SQLCopy

USE AdventureWorks2012;
GO
SELECT p1.ProductModelID
FROM Production.Product AS p1
GROUP BY p1.ProductModelID
HAVING MAX(p1.ListPrice) >= ALL
(SELECT AVG(p2.ListPrice)
FROM Production.Product AS p2
WHERE p1.ProductModelID = p2.ProductModelID);
GO

This example uses two correlated subqueries to find the names of employees who
have sold a particular product.
SQLCopy

USE AdventureWorks2012;
GO
SELECT DISTINCT pp.LastName, pp.FirstName
FROM Person.Person pp JOIN HumanResources.Employee e
ON e.BusinessEntityID = pp.BusinessEntityID WHERE pp.BusinessEntityID IN
(SELECT SalesPersonID
FROM Sales.SalesOrderHeader
WHERE SalesOrderID IN
(SELECT SalesOrderID
FROM Sales.SalesOrderDetail
WHERE ProductID IN
(SELECT ProductID
FROM Production.Product p
WHERE ProductNumber = 'BK-M68B-42')));
GO
F. Using GROUP BY

The following example finds the total of each sales order in the database.
SQLCopy

USE AdventureWorks2012;
GO
SELECT SalesOrderID, SUM(LineTotal) AS SubTotal
FROM Sales.SalesOrderDetail
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
GROUP BY SalesOrderID
ORDER BY SalesOrderID;
GO

Because of the GROUP BY clause, only one row containing the sum of all sales is
returned for each sales order.
G. Using GROUP BY with multiple groups

The following example finds the average price and the sum of year-to-date sales,
grouped by product ID and special offer ID.
SQLCopy

USE AdventureWorks2012;
GO
SELECT ProductID, SpecialOfferID, AVG(UnitPrice) AS [Average Price],
SUM(LineTotal) AS SubTotal
FROM Sales.SalesOrderDetail
GROUP BY ProductID, SpecialOfferID
ORDER BY ProductID;
GO
H. Using GROUP BY and WHERE

The following example puts the results into groups after retrieving only the rows
with list prices greater than $1000.
SQLCopy

USE AdventureWorks2012;
GO
SELECT ProductModelID, AVG(ListPrice) AS [Average List Price]
FROM Production.Product
WHERE ListPrice > $1000
GROUP BY ProductModelID
ORDER BY ProductModelID;
GO
I. Using GROUP BY with an expression

The following example groups by an expression. You can group by an expression if


the expression does not include aggregate functions.
SQLCopy

USE AdventureWorks2012;
GO
SELECT AVG(OrderQty) AS [Average Quantity],
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
NonDiscountSales = (OrderQty * UnitPrice)
FROM Sales.SalesOrderDetail
GROUP BY (OrderQty * UnitPrice)
ORDER BY (OrderQty * UnitPrice) DESC;
GO
J. Using GROUP BY with ORDER BY

The following example finds the average price of each type of product and orders
the results by average price.
SQLCopy

USE AdventureWorks2012;
GO
SELECT ProductID, AVG(UnitPrice) AS [Average Price]
FROM Sales.SalesOrderDetail
WHERE OrderQty > 10
GROUP BY ProductID
ORDER BY AVG(UnitPrice);
GO
K. Using the HAVING clause

The first example that follows shows a HAVING clause with an aggregate function. It
groups the rows in the SalesOrderDetail table by product ID and eliminates
products whose average order quantities are five or less. The second example
shows a HAVINGclause without aggregate functions.
SQLCopy

USE AdventureWorks2012;
GO
SELECT ProductID
FROM Sales.SalesOrderDetail
GROUP BY ProductID
HAVING AVG(OrderQty) > 5
ORDER BY ProductID;
GO

This query uses the LIKE clause in the HAVING clause.


SQLCopy

USE AdventureWorks2012 ;
GO
SELECT SalesOrderID, CarrierTrackingNumber
FROM Sales.SalesOrderDetail
GROUP BY SalesOrderID, CarrierTrackingNumber
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
HAVING CarrierTrackingNumber LIKE '4BD%'
ORDER BY SalesOrderID ;
GO
L. Using HAVING and GROUP BY

The following example shows using GROUP BY, HAVING, WHERE, and ORDER BY clauses
in one SELECT statement. It produces groups and summary values but does so after
eliminating the products with prices over $25 and average order quantities under 5.
It also organizes the results by ProductID.
SQLCopy

USE AdventureWorks2012;
GO
SELECT ProductID
FROM Sales.SalesOrderDetail
WHERE UnitPrice < 25.00
GROUP BY ProductID
HAVING AVG(OrderQty) > 5
ORDER BY ProductID;
GO
M. Using HAVING with SUM and AVG

The following example groups the SalesOrderDetail table by product ID and


includes only those groups of products that have orders totaling more
than $1000000.00 and whose average order quantities are less than 3.
SQLCopy

USE AdventureWorks2012;
GO
SELECT ProductID, AVG(OrderQty) AS AverageQuantity, SUM(LineTotal) AS
Total
FROM Sales.SalesOrderDetail
GROUP BY ProductID
HAVING SUM(LineTotal) > $1000000.00
AND AVG(OrderQty) < 3;
GO

To see the products that have had total sales greater than $2000000.00, use this
query:
SQLCopy

USE AdventureWorks2012;
GO
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
SELECT ProductID, Total = SUM(LineTotal)
FROM Sales.SalesOrderDetail
GROUP BY ProductID
HAVING SUM(LineTotal) > $2000000.00;
GO

If you want to make sure there are at least one thousand five hundred items
involved in the calculations for each product, use HAVING COUNT(*) > 1500 to
eliminate the products that return totals for fewer than 1500 items sold. The query
looks like this:
SQLCopy

USE AdventureWorks2012;
GO
SELECT ProductID, SUM(LineTotal) AS Total
FROM Sales.SalesOrderDetail
GROUP BY ProductID
HAVING COUNT(*) > 1500;
GO
N. Using the INDEX optimizer hint

The following example shows two ways to use the INDEX optimizer hint. The first
example shows how to force the optimizer to use a nonclustered index to retrieve
rows from a table, and the second example forces a table scan by using an index of
0.
SQLCopy

USE AdventureWorks2012;
GO
SELECT pp.FirstName, pp.LastName, e.NationalIDNumber
FROM HumanResources.Employee AS e WITH
(INDEX(AK_Employee_NationalIDNumber))
JOIN Person.Person AS pp on e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
GO

-- Force a table scan by using INDEX = 0.


USE AdventureWorks2012;
GO
SELECT pp.LastName, pp.FirstName, e.JobTitle
FROM HumanResources.Employee AS e WITH (INDEX = 0) JOIN Person.Person AS
pp
ON e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
GO
M. Using OPTION and the GROUP hints

The following example shows how the OPTION (GROUP) clause is used with a GROUP
BYclause.
SQLCopy

USE AdventureWorks2012;
GO
SELECT ProductID, OrderQty, SUM(LineTotal) AS Total
FROM Sales.SalesOrderDetail
WHERE UnitPrice < $5.00
GROUP BY ProductID, OrderQty
ORDER BY ProductID, OrderQty
OPTION (HASH GROUP, FAST 10);
GO
O. Using the UNION query hint

The following example uses the MERGE UNION query hint.


SQLCopy

USE AdventureWorks2012;
GO
SELECT BusinessEntityID, JobTitle, HireDate, VacationHours,
SickLeaveHours
FROM HumanResources.Employee AS e1
UNION
SELECT BusinessEntityID, JobTitle, HireDate, VacationHours,
SickLeaveHours
FROM HumanResources.Employee AS e2
OPTION (MERGE UNION);
GO
P. Using a simple UNION

In the following example, the result set includes the contents of


the ProductModelIDand Name columns of both the ProductModel and Gloves tables.
SQLCopy

USE AdventureWorks2012;
GO
IF OBJECT_ID ('dbo.Gloves', 'U') IS NOT NULL
DROP TABLE dbo.Gloves;
GO
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
-- Create Gloves table.
SELECT ProductModelID, Name
INTO dbo.Gloves
FROM Production.ProductModel
WHERE ProductModelID IN (3, 4);
GO

-- Here is the simple union.


USE AdventureWorks2012;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID NOT IN (3, 4)
UNION
SELECT ProductModelID, Name
FROM dbo.Gloves
ORDER BY Name;
GO
Q. Using SELECT INTO with UNION

In the following example, the INTO clause in the second SELECT statement specifies
that the table named ProductResults holds the final result set of the union of the
designated columns of the ProductModel and Gloves tables. Note that
the Glovestable is created in the first SELECT statement.
SQLCopy

USE AdventureWorks2012;
GO
IF OBJECT_ID ('dbo.ProductResults', 'U') IS NOT NULL
DROP TABLE dbo.ProductResults;
GO
IF OBJECT_ID ('dbo.Gloves', 'U') IS NOT NULL
DROP TABLE dbo.Gloves;
GO
-- Create Gloves table.
SELECT ProductModelID, Name
INTO dbo.Gloves
FROM Production.ProductModel
WHERE ProductModelID IN (3, 4);
GO

USE AdventureWorks2012;
GO
SELECT ProductModelID, Name
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
INTO dbo.ProductResults
FROM Production.ProductModel
WHERE ProductModelID NOT IN (3, 4)
UNION
SELECT ProductModelID, Name
FROM dbo.Gloves;
GO

SELECT ProductModelID, Name


FROM dbo.ProductResults;
R. Using UNION of two SELECT statements with ORDER BY

The order of certain parameters used with the UNION clause is important. The
following example shows the incorrect and correct use of UNION in
two SELECT statements in which a column is to be renamed in the output.
SQLCopy

USE AdventureWorks2012;
GO
IF OBJECT_ID ('dbo.Gloves', 'U') IS NOT NULL
DROP TABLE dbo.Gloves;
GO
-- Create Gloves table.
SELECT ProductModelID, Name
INTO dbo.Gloves
FROM Production.ProductModel
WHERE ProductModelID IN (3, 4);
GO

/* INCORRECT */
USE AdventureWorks2012;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID NOT IN (3, 4)
ORDER BY Name
UNION
SELECT ProductModelID, Name
FROM dbo.Gloves;
GO

/* CORRECT */
USE AdventureWorks2012;
GO
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID NOT IN (3, 4)
UNION
SELECT ProductModelID, Name
FROM dbo.Gloves
ORDER BY Name;
GO
S. Using UNION of three SELECT statements to show the effects of ALL
and parentheses

The following examples use UNION to combine the results of three tables that all
have the same 5 rows of data. The first example uses UNION ALL to show the
duplicated records, and returns all 15 rows. The second example
uses UNION without ALL to eliminate the duplicate rows from the combined results
of the three SELECTstatements, and returns 5 rows.

The third example uses ALL with the first UNION and parentheses enclose the
second UNION that is not using ALL. The second UNION is processed first because it is
in parentheses, and returns 5 rows because the ALL option is not used and the
duplicates are removed. These 5 rows are combined with the results of the
first SELECT by using the UNION ALL keywords. This does not remove the duplicates
between the two sets of 5 rows. The final result has 10 rows.
SQLCopy

USE AdventureWorks2012;
GO
IF OBJECT_ID ('dbo.EmployeeOne', 'U') IS NOT NULL
DROP TABLE dbo.EmployeeOne;
GO
IF OBJECT_ID ('dbo.EmployeeTwo', 'U') IS NOT NULL
DROP TABLE dbo.EmployeeTwo;
GO
IF OBJECT_ID ('dbo.EmployeeThree', 'U') IS NOT NULL
DROP TABLE dbo.EmployeeThree;
GO

SELECT pp.LastName, pp.FirstName, e.JobTitle


INTO dbo.EmployeeOne
FROM Person.Person AS pp JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
GO
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
SELECT pp.LastName, pp.FirstName, e.JobTitle
INTO dbo.EmployeeTwo
FROM Person.Person AS pp JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
GO
SELECT pp.LastName, pp.FirstName, e.JobTitle
INTO dbo.EmployeeThree
FROM Person.Person AS pp JOIN HumanResources.Employee AS e
ON e.BusinessEntityID = pp.BusinessEntityID
WHERE LastName = 'Johnson';
GO
-- Union ALL
SELECT LastName, FirstName, JobTitle
FROM dbo.EmployeeOne
UNION ALL
SELECT LastName, FirstName ,JobTitle
FROM dbo.EmployeeTwo
UNION ALL
SELECT LastName, FirstName,JobTitle
FROM dbo.EmployeeThree;
GO

SELECT LastName, FirstName,JobTitle


FROM dbo.EmployeeOne
UNION
SELECT LastName, FirstName, JobTitle
FROM dbo.EmployeeTwo
UNION
SELECT LastName, FirstName, JobTitle
FROM dbo.EmployeeThree;
GO

SELECT LastName, FirstName,JobTitle


FROM dbo.EmployeeOne
UNION ALL
(
SELECT LastName, FirstName, JobTitle
FROM dbo.EmployeeTwo
UNION
SELECT LastName, FirstName, JobTitle
FROM dbo.EmployeeThree
);
GO
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Module 4: Backup and Recovery on Microsoft SQL Server


2014.

En cuanto a los tipos de respaldo se refiere, SQL Server ofrece varias opciones: Completo,
Diferencial y Bitácora de Transacciones

1. El respaldo completo no necesita mucha explicación ya que involucra respaldar


todas y cada una las páginas que forman parte de la base de datos y aquellas
asociadas con la bitácora de transacciones que se generaron mientras el respaldo
estuvo activo. La desventaja de los respaldos completos es que si la base de datos
es muy grande, entonces pueden requerir bastante tiempo y espacio.

2. El respaldo diferencial consiste en respaldar todas las páginas que han sufrido
cambios desde el último respaldo completo y para poder que funcione tienes que
haber tomado un respaldo completo anteriormente. Dado que se respaldan
solamente las páginas que han cambiado desde el último respaldo completo, los
respaldos diferenciales generalmente son más rápidos que los completos.

Nota: La base de datos Maestra no puede respaldarse diferencialmente.

3. El respaldo de la Bitácora de Transacciones o Transaction Log solamente puede


hacerse cuando el modelo de recuperación de la base de datos es FULL o Bulk-
logged y se realiza principalmente con el fin de reducir la cantidad de datos que
pudieran perderse en caso de una falla y reducir el tamaño del archivo que
almacena la bitácora. Cuando realizas un respaldo de la bitácora, SQL Server
respalda todas la páginas nuevas desde el último respaldo completo, diferencial, o
desde el último respaldo de la bitácora. Esto significa que cada respaldo de la
Bitácora de Transacciones captura todas las transacciones asociadas con un punto
en el tiempo.

Ejercicio 15: Cree en el servidor una carpeta Backup. Luego realice el respaldo de la base de datos
dbreserva, sobre esta(realice las instrucciones del profesor).
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Ejercicio 16: Elimine la base de datos dbreserva y realice la recuperación del respaldo respectivo.

Ejercicio 17: Realice el ingreso de los siguientes registros, sobre la tabla pasajero, tabla país, tabla
aerolinea

Tabla país: Ingreso los países de Holanda, Francia y Venezuela

Tabla pasajero: Ingrese dos pasajeros nuevos

Tabla aerolínea: Agragar nueva Aerolínea de Chile:Lan Chile

- Realice un respaldo de tipo diferencial, sobre la base de datos dbreserva.

-Elimine la base de datos dbreserva.

- Realice la restauración de la base de datos dbreserva(respaldo Full) y de manera posterior el


respaldo Diferencial.

Limitaciones y restricciones

 Las copias de seguridad que se crean en una versión más reciente de SQL Server no se
pueden restaurar en versiones anteriores de SQL Server.

 En SQL Server 2014, puede restaurar una base de datos de usuario a partir de una copia de
seguridad de la base de datos creada utilizando SQL Server 2005 o una versión
posterior. Sin embargo, las copias de seguridad las bases de datos maestra,
de modelos y msdb creadas utilizando SQL Server 2005 o SQL Server 2008 no pueden
restaurarse con SQL Server 2014.

Requisitos previos
 En el modelo de recuperación optimizado para cargas masivas de registros o completa,
para poder restaurar una base de datos, se debe realizar una copia de seguridad del
registro de transacciones activo (conocido como final del registro). Para obtener más
información, vea Realizar copia de seguridad de un registro de transacciones (SQL Server).
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Usar SQL Server Management Studio


Para restaurar una copia de seguridad diferencial de la base de datos
1. Después de conectarse a la instancia adecuada de Motor de base de datos de SQL Server
de Microsoft, en el Explorador de objetos, haga clic en el nombre del servidor para expandir
el árbol de servidores.
2. Expanda Bases de datos. En función de la base de datos, seleccione una base de datos de
usuario o expanda Bases de datos del sistema y, a continuación, seleccione una base de
datos del sistema.
3. Haga clic con el botón secundario en la base de datos, seleccione Tareas,
seleccione Restaurar y, a continuación, haga clic en Base de datos.
4. En la página General, use la sección Origen para especificar el origen y la ubicación de los
conjuntos de copias de seguridad que se deben restaurar. Seleccione una de las siguientes
opciones.
5. Restaure el backup Full de la base de datos dbreserva.
6. Realice la restauración .

Nota : Si se va a restaurar una recuperación Full + Diferencial, la restauración de la base de datos


Full, se debe hacer en modalidad (RESTORE WITH NORECOVERY)

Ver siguiente nota técnica para realizar la restauración:


Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Presentación: Ver presentación de Backup and Recovery


sobre Microsoft SQL Server 2014.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Planes de Mantenimiento sobre Microsoft SQL Server


2012-2014:

Usar el Asistente para planes de


mantenimiento
SE APLICA A: SQL Server (versiones 2012, 2014 , 2016 y 2019).

En este tema se describe cómo crear un plan de mantenimiento de un solo servidor o


multiservidor mediante el Asistente para planes de mantenimiento de SQL Server 2017. El
Asistente para planes de mantenimiento crea un plan de mantenimiento que el Agente
Microsoft SQL Server puede ejecutar periódicamente. Esto permite realizar diversas tareas
de administración de bases de datos, incluidas copias de seguridad, comprobaciones de
integridad de la base de datos o actualizaciones de las estadísticas de la base de datos a
intervalos especificados.

Limitaciones y restricciones

 Para crear un plan de mantenimiento multiservidor, debe configurar un entorno


multiservidor con un servidor maestro y uno o varios servidores de destino. Debe
crear y mantener planes de mantenimiento multiservidor en el servidor maestro.
Puede ver planes en servidores de destino.

NOTA: Para crear o administrar planes de mantenimiento, debe ser miembro del rol fijo de
servidor sysadmin . El Explorador de objetos solo muestra el nodo Planes de mantenimiento para
los usuarios que son miembros del rol fijo de servidor sysadmin .
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

II. Opciones que se pueden aplicar sobre


un plan de mantenimiento.
Como crear un plan de mantenimiento
para tus bases de datos usando las
herramientas de SQL SERVER.

SQL Server nos permite crear un plan de mantenimiento de nuestras bases de datos de
forma muy sencilla sin embargo es poco común que existan en la mayoría de los entornos
sencillamente por desconocimiento técnicos de los administradores de sistemas o por no
saber cómo nuestras bases de datos se ven afectadas a medida que se realizan operaciones
sobre ella lo cual reduce el rendimiento y a su vez los tiempo de respuesta en operaciones
CRUD y especialmente en las consultas. Una vez más, más allá de que el usuario tenga que
esperar un segundo más en una consulta se trata de como la disminución del rendimiento de
nuestras aplicaciones afecta de forma global el desempeño de nuestra aplicación, cuanto
tiempo (horas o minutos laborables) nos hace perder y los costos económicos asociados a
ello, cuanto espacio estamos ocupando de manera innecesaria en nuestros servidores y cuál
sería el costo económico de perder parte de nuestros datos en caso de un fallo grave en
nuestros discos.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
Sea que tengas una aplicación SharePoint, Dynamic CRM, Dynamic NAV, un aplicación
hecha a medida, etc. vas a necesitar de un plan de mantenimiento ya que todas estas
aplicaciones se ven afectadas de la misma manera. De una manera muy resumida el
problema está cuando empezamos a agregar y eliminar información a nuestra base de datos,
esto produce que aumente el porcentaje de fragmentación de la base de datos y de los
índices por lo que la ruta que consideraba el SQL server era la mejora para realizar
determinada consulta ya no lo es, para ello SQL server se basa en plan de ejecución que en
base a ciertas estadísticas le permiten saber cuál es la mejor forma de atacar un consulta,
pero estas estadísticas si no se actualizan en base al estado actual de la base de datos van
quedando obsoletas y mientras mas desfragmentación exista mas cuesta realizar
operaciones de escritura.

Con un poco de análisis de nuestras necesidades podemos llevar a cabo un plan de


mantenimiento en pocos minutos. Veamos cómo hacerlo en SSMS.

En SQL Server Managment Studio podremos ver la carpeta Managment y dentro de ella
Maintenance Plans, para usar el ayudante seleccionamos Maintenance Plans Wizard
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
Hacemos clic en Next

Le damos un nombre a nuestro plan de mantenimiento ya que podremos crear tantos como
queramos para distintas base de datos o conjunto de ellas.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Escogemos las tareas de mantenimiento que queremos realizar.

Shrink Database: Reduce espacio de la base de datos y los archivos de log.

Update Statistic: Asegura que el optimizador de consultas tiene la información actualizada


acerca de la distribución de los datos en la base de datos, esto permite que el optimizador
realice mejores cálculos acerca de cómo realizar alguna consulta.

Reorganized Index: Desfragmenta y comprime los índices físicos (Clustered Index) y no


físicos.

Rebuild Index: Reconstruye las paginas índices permitiendo la reorganización de los datos
y búsquedas más rápidas.

Check Database Integrity: Confirma la integridad de los datos y índices de la base de


datos.

History Cleanup: Elimina información histórica sobre copias de respaldos y


restauraciones.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Maintenance Cleanup: Elimina archivos dejados por la ejecución de los planes de


mantenimiento.

Escogemos el orden en que se ejecutan las tareas.


Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Para cada tarea se nos pedira que escojamos la base de datos, podemos escoger una, varias
o todas.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Para cada tarea sera necesario escoger las opciones que correspondan.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Después de configurar todas las tareas se creara el plan de ejecucion.


Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes
Podremos ver en el diseñador el plan de mantenimiento que hemos creado.

En la parte superior del diseñador en el icono con forma de calendario podemos configurar
la programación de un nuestro plan de mantenimiento.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Finalmente lo mismo que hemos realizado con el SSMS lo podemos realizar con SQL
Server Integration Services y el SQL Server Business Intelligence Development Studio.

Cuando creemos un proyecto podremos ver que en las herramientas tenemos


una sección dedicada a tareas del plan de mantenimiento. Solo es necesario arrastrar las
tareas que queremos ejecutar.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Si hace clic derecho> Editar sobre cualquier tarea la podemos configura exactamente igual
como lo hacíamos con SSMS.
Asignatura :SQL server aplicado
Profesor: Guillermo Aguilera I
Carrera: Ingeniería en Conectividad y Redes

Con esto generaremos un paquete de SSIS que podremos ejecutar cada vez que queramos.

Como hemos visto crear un plan de mantenimiento es relativamente sencillo, obviamente


cada escenario necesitara de realizar una análisis de cuáles son nuestras necesidades y
como puede impactar el plan de mantenimiento a nuestra aplicación sobre todo si estamos
hablamos de producto out of the box.

Actividad: Restaurar la base de Datos AventuraWorks y realizar planes de


Mantenimiento que contemplen las siguientes actividades:
1)Backup Full a las 00:00 de Lunes a Viernes
2)Backup diferencial desde las 08:00 hrs. A 20:00 hrs. De Lunes a Viernes
3)Plan de mantenimiento, que contemple las actividades siguientes en el mismo
orden que se plantean:

- Shrink, Reorganized Index,Rebuild Index,Check Database Integrity.

Вам также может понравиться