You are on page 1of 31

Database Fundamentals

Brian Alderman | MCT, CEO / Founder of


MicroTechPoint
Pete Harris | Microsoft Senior Content Publisher

Meet Brian Alderman |


@brianalderman

Chief Executive Office, Founder MicroTechPoint

Industry-recognized consultant
Noted author and conference speaker
Brians expertise and designs range across Microsoft
operating systems

More than 25 years of industry experience


Brian has been focused on helping IT Pros and Database Administrators (DBAs)
better understand core Microsoft technologies for over 25 years.
A frequent presenter at SharePoint Conferences around the world, he has authored
or contributed to several SharePoint, SQL Server, and other technical books, and is a
MCSE, MCT, and MCITP: SharePoint and SQL Server Administrator.
Brian has a BS and MS in Computer Information Systems where he graduated
summa cum laude from Regis University of Colorado Springs and lives in Scottsdale,
AZ where he enjoys playing golf year round and traveling around the world.

LinkedIn
/brianalderman

Blog
http://brianalderman.wordpress.
com

Meet Pete Harris | @SQLPete

Content Development Manager in Microsofts


Learning Experiences team
Focuses on SQL Server and Web training

With Microsoft since 1995


Part of the first team of developer training folks in the post-Microsoft
University era
Has built a variety of content and spoken to customers all over the
world

Course Modules
Database Fundamentals
01 | Introducing core database concepts (50 minutes)
Define databases, example of relational database tables, and introduce common database
terminology

02 | Relational Concepts (50 minutes)


Normalization, referential integrity, and constraints

03 | Creating databases and database objects (50 minutes)


Data types, database objects, DDL statements, and creating scripts

04 | Using DML statements (50 minutes)


DML statements, using the SELECT statement; using INSERT, UPDATE, and DELETE to
manage data; indexes and triggers

05 | SQL Server Administration Fundamentals (50 minutes)


SQL Server security; securing database and objects; performing database backups and database
restores

Click to edit
Master subtitle
style

04 | Uso de sentencias DML


Brian Alderman | MCT, CEO / Founder of
MicroTechPoint
Pete Harris | Microsoft Senior Content Publisher

Descripcin general del mdulo


La introduccin de las sentencias DML
Utilizacin de la sentencia SELECT
Modificacin de datos utilizando sentencias
DML
Los ndices y disparadores

Las declaraciones DML

Sentencias DML comunes


SELECT - recuperar datos
INSERT - agregar datos
ACTUALIZACIN - modificar datos
DELETE - eliminar los datos
BULK INSERT - Importar un archivo de datos

La instruccin SELECT

Uso de la instruccin SELECT bsica


La instruccin SELECT se utiliza para
recuperar filas y columnas de una tabla
SELECT * FROM tablename
La instruccin SELECT requiere el nombre de
la tabla y, o bien el * (recupera todas las
columnas)
o
nombres
de
columnas
especficos
Para limitar el nmero de filas devueltas
puede incluir la clusula WHERE de la
sentencia SELECT

Muestra instruccin SELECT


SELECT BusinessEntityID, JobTitle, Gender
FROM HumanResources.Employee
WHERE BusinessEntityID <= 50
Devuelve los siguientes resultados:
BusinessEntityID
Title
Gender
--------------------------------------1
Chief Executive Officer
M
2
Vice President of Engineering
F
3
Engineering Manager
M
4
Senior Tool Designer
M

WHERE mltiples clusulas


Puede combinar varias clusulas WHERE de una instruccin de
consulta para crear consultas ms especficas.

SELECT BusinessEntityID, Jobtitle, VacationHours


FROM HumanResources.Employee
WHERE JobTitle = Design Engineer AND
gender = F AND HireDate >= 2000-JAN-01
SELECT BusinessEntityID, Jobtitle, VacationHours
FROM HumanResources.Employee
WHERE VacationHours > 80 OR
BusinessEntityID <= 50

El uso de la clusula BETWEEN


Recuperacin de filas dentro de un rango de fechas utilizando
la clusula BETWEEN

SELECT BusinessEntityID, Jobtitle, VacationHours


FROM HumanResources.Employee
WHERE VacationHours BETWEEN 75 AND 100

Ordenar el conjunto de resultados


utilizando ORDER BY

Ordenar el conjunto de resultados mediante el ORDER BY para


especificar qu campo para ordenar por.
SELECT BusinessEntityID, Jobtitle, VacationHours
FROM HumanResources.Employee
WHERE VacationHours BETWEEN 75 AND 100
ORDER BY VacationHours

Usted puede ordenar en orden descendente


utilizando la clusula DESC.
SELECT BusinessEntityID, Jobtitle, VacationHours
FROM HumanResources.Employee
WHERE VacationHours BETWEEN 75 AND 100
ORDER BY VacationHours DESC

El uso de la clusula NOT


Escriba una consulta para devolver datos que especifica lo que
usted no desea que se devuelva

SELECT BusinessEntityID, Jobtitle, Gender


FROM HumanResources.Employee
WHERE NOT Gender = M

clusula UNION
La clusula UNION permite combinar las filas devueltas de varias
instrucciones SELECT en un nico conjunto de resultados

SELECT BusinessEntityID, Jobtitle, HireDate


FROM HumanResources.Employee
WHERE JobTitle = 'Design Engineer'
UNION
SELECT BusinessEntityID, Jobtitle, HireDate
FROM HumanResources.Employee
WHERE HireDate BETWEEN '2005-01-01' AND
'2005-12-31'

Clausulas EXCEPT e INTERSECT


La clusula EXCEPT devuelve los valores distintos de la consulta a la
izquierda que no se encuentran en la consulta derecha
SELECT ProductID
FROM Production.Product
EXCEPT
SELECT ProductID
FROM Production.WorkOrder ;
La clusula INTERSECT devuelve los valores distintos devueltos por
las consultas situadas a los lados izquierdo y derecho del operando
se cruzan
SELECT ProductID
FROM Production.Product
INTERSECT
SELECT ProductID
FROM Production.WorkOrder ;

clusula JOIN
La clusula JOIN le permite combinar los datos
relacionados de mltiples tablas en un conjunto de
resultados
INNER JOINS utiliza un operador de comparacin para
que coincida con filas de dos tablas en funcin de
valores de una columna comn que existe en ambas
tablas
OUTER JOINS (izquierda, derecha, o total) incluye
registros de una o ambas tablas, incluso si no tienen
valores coincidentes

CROSS JOINS devolver todas las filas de la tabla


izquierda con todas las filas de la tabla derecha. WHERE

Muestra global
SQL Server proporciona funciones de
agregado para ayudar con el resumen de
los grandes volmenes de datos
SELECT COUNT (DISTINCT SalesOrderID) AS UniqueOrders,
AVG(UnitPrice) AS Avg_UnitPrice,
MIN(OrderQty)AS Min_OrderQty,
MAX(LineTotal) AS Max_LineTotal
FROM Sales.SalesOrderDetail;

Demo query generator

Demo
Uso de la instruccin SELECT

Insertar datos
Usted puede agregar una nueva fila a una tabla utilizando la
sentencia INSERT
INSERT INTO Production.UnitMeasure
VALUES (N'FT', N'Feet', '20080414')
Puede agregar varias filas a una tabla utilizando la sentencia INSERT
INSERT INTO Production.UnitMeasure
VALUES (N'FT2', N'Square Feet ', '20080923'),
(N'Y', N'Yards', '20080923'),
(N'Y3', N'Cubic Yards', '20080923'
BULK INSERT se puede utilizar para importar un archivo de datos en
una tabla con un formato especificado por el usuario.

instruccin Update
La instruccin UPDATE se utiliza para modificar los datos que ya est
almacenado en una tabla
UPDATE Sales.SalesPerson
SET Bonus = 6000, CommissionPct = .10, SalesQuota = NULL
WHERE sales.SalesPerson.BusinessEntityID = 289

Instruccin DELETE
La sentencia DELETE se utiliza para eliminar filas
de una tabla
DELETE FROM Production.UnitMeasure
WHERE Production.UnitMeasure.Name = Feet
Una instruccin DELETE sin una clusula WHERE
har que todas las filas que se eliminarn
DELETE FROM Sales.SalesPersonQuotaHistory;

Demo
Modificacin de datos
utilizando sentencias DML

Indexes and triggers

ndices de SQL Server


Los ndices le permiten acelerar la recuperacin
de los datos almacenados en una tabla o vista
El optimizador de consultas de SQL Server
evala cada mtodo para recuperar los datos y
selecciona el mtodo ms eficiente que puede
ser un recorrido de tabla o el uso de uno o ms
ndices, si existen.
Los ndices ms comnmente usados incluyen
clustered
nonclustered
unique

Creacin de un desencadenador DML


Los Triggers se utilizan para hacer cumplir
las reglas de negocio cuando se modifican
los datos
Este desencadenador DML muestra un
mensaje al usuario cuando se intenta
agregar o cambiar datos en la tabla de
clientes
CREATE TRIGGER Reminder1
ON Sales.Customer
AFTER INSERT, UPDATE
AS RAISERROR ('Notify Customer Relations', 16,
10);

Resumen
La instruccin SELECT es el uso para
recuperar datos de una o ms tablas
almacenadas en una base de datos
El comando SELECT debe indicar qu
columnas y qu tabla que desea recuperar
los datos de la hora de ejecutar la consulta.
Opcionalmente, la instruccin SELECT puede
incluir la clusula WHERE para definir las
condiciones que se utilizan para determinar
qu filas se devolvern

Resumen
Otros argumentos que se pueden utilizar
para controlar lo que se devuelve datos
incluyen;
BETWEEN
NOT
UNION
EXCEPT
INTERSECT
JOIN (INNER, OUTER, CROSS)

Resumen
Comandos DML que se pueden usar para
administrar la tabla y ver datos incluyen
INSERT
BULK INSERT
UPDATE
DELETE
Los ndices se utilizan para acelerar la
recuperacin de datos de las tablas y vistas
Los disparadores se utilizan para hacer
cumplir las reglas de negocio cuando se
modifican los datos

2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are
or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes
only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to
changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the
accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR
STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

You might also like