Sesión 4

Michael Andrés Calderón Ferreira
Michael Andrés Calderón FerreiraCoordinador de desarrollo de software en Corporación Universitaria Unitec
[70-461]
Querying Microsoft SQL Server 2012
/ITPROS-DC/ITProsDCITPROS DC
http://itpros-dc.com
COMPARTIR EL CONOCIMIENTO, NUESTRA PASIÓN
Esquema
Curso
• Module 1, “Introduction to Microsoft SQL Server 2014”
• Module 2, “Introduction to T-SQL Querying”
• Module 3, “Writing SELECT Queries”
• Module 4, “Querying Multiple Tables”
• Module 5, “Sorting and Filtering Data”
• Module 6, “Working with SQL Server 2014 Data Types”
• Module 7, “Using DML to Modify Data”
• Module 8, “Using Built-In Functions”
• Module 9, “Grouping and Aggregating Data”
• Module 10, “Using Subqueries”
Esquema
Curso
• Module 11, “Using Table Expressions”
• Module 12, “Using Set Operators”
• Module 13, “Using Window Ranking, Offset, and Aggregate Functions”
• Module 14, “Pivoting and Grouping Sets”
• Module 15, “Executing Stored Procedures”
• Module 16, “Programming with T-SQL”
• Module 17, “Implementing Error Handling”
• Module 18, “Implementing Transactions”
• Module 19, “Improving Query Performance”
• Module 20, “Querying SQL Server Metadata”
SESIÓN # 4
• Introducción a tipos de datos
• Tipo de dato cadena
• Tipo de dato fecha y hora
• Cuando convertir tipo de dato
• Funciones de fecha y hora
• Funciones de cadena
• Collation
• Concatenar cadenas
• Predicado LIKE
• DML
• MERGE
• IDENTITY
• SEQUENCES
Tipos de datos
Exact numerics: tinyint , smallint , int, bigint, money
Unicode character strings: nchar, nvarchar, ntext
Date and time: date, datetime, time
Character strings: char, varchar, text
• SQL Server asocia los tipos de datos a variables, columnas y/o expresiones.
• Los tipos de datos determinan cual será el dato de entrada:
• Cadenas, numeros, fechas, dinero, binarios, etc.
• Exact Numeric
Data type Range Storage (bytes)
tinyint 0 to 255 1
smallint -32,768 to 32,768 2
int 2^31 (-2,147,483,648) to
2^31-1 (2,147,483,647)
4
Bigint -2^63 - 2^63-1
(+/- 9 quintillion)
8
bit 1, 0 or NULL 1
decimal/numeric - 10^38 +1 through 10^38 – 1
when maximum precision is used
5-17
money -922,337,203,685,477.5808 to
922,337,203,685,477.5807
8
smallmoney - 214,748.3648 to 214,748.3647 4
¿Cuando convertir un tipo de dato?
• Escenarios de convertir tipos de datos
• Cuando un dato es movido, comparado o combinado con otro tipo de dato
• Durante la declaración de una variable
• Conversion implicita
• Cuando se esta comparando un tipo de dato con otro
• Conversión explicita
• Usar funciones CAST o CONVERT
• No todas las conversions son permitidas por SQL Server
WHERE <column of smallint type> = <value of int type>
CAST(unitprice AS int)
Character Data Types
• SQL Server soporta dos tipos de datos de cadena:
• Regular: CHAR, VARCHAR
• Almacena 1 byte por caracter
• Solo 256 caracteres posibles
• Unicode: NCHAR, NVARCHAR
• Almacena 2 bytes por caracter
• Soporta multiple lenguaje
Collation
• Aplicar esa coleccion de region
SELECT empid, lastname
FROM HR.employees
WHERE lastname COLLATE Latin1_General_CS_AS =
N'Funk';
Concatenar Cadenas
• SQL Server usa el signo (+) para concatenar cadenas
• Concatenar un valor NULL retorna un NULL
• SQL Server 2012 implantó la function CONCAT
• Convierte NULL en cadena vacia antes de concatenar
SELECT empid, lastname, firstname,
firstname + N' ' + lastname AS fullname
FROM HR.Employees;
SELECT custid, city, region, country,
CONCAT(city, ', ' + region, ', ' + country) AS location
FROM Sales.Customers
Funciones de cadena de caracteres
Function Syntax Remarks
SUBSTRING() SUBSTRING (expression , start , length) Returns part of an expression.
LEFT(), RIGHT() LEFT (expression , integer_value)
RIGHT (expression , integer_value)
LEFT() returns left part of string up to
integer_value. RIGHT() returns right part of string.
LEN(), DATALENGTH() LEN ( string_expression )
DATALENGTH ( expression )
LEN() returns the number of characters of the
specified string expression, excluding trailing
blanks. DATALENGTH() returns the number of
bytes used.
CHARINDEX() CHARINDEX ( expressionToFind, expressionToSearch ) Searches an expression for another expression
and returns its starting position if found. Optional
start position.
REPLACE() REPLACE ( string_expression , string_pattern , string_replacement ) Replaces all occurrences of a specified string
value with another string value.
UPPER(), LOWER() UPPER ( character_expression )
LOWER ( character_expression )
UPPER() returns a character expression with
lowercase character data converted to uppercase.
LOWER() converts uppercase to lowercase.
Predicado LIKE
• El predicado LIKE se usa para comprobar una cadena de caracteres con
base a un patron.
• Estos patrones se expresan con simbolos
• % (Percent) Representa una cadena de cualquier longitud
• _ (Underscore) Representa un unico caracter
SELECT categoryid, categoryname, description
FROM Production.Categories
WHERE description LIKE 'Sweet%'
Tipos de datos Fecha y Hora
• Versiones anteriores de SQL Server solo soportaban DATETIME y SMALLDATETIME
• DATE, TIME, DATETIME2, y DATETIMEOFFSET se introdujo en SQL Server 2008
• SQL Server 2012 añade mas funciones para trabajar con datos de fecha y hora
Tipo de dato Almacenamiento
(bytes)
Rango de dato Exactitud Formato de ingreso
recomendado
DATETIME 8 January 1, 1753 to
December 31, 9999
3-1/3 milliseconds 'YYMMDD
hh:mm:ss:nnn'
SMALLDATETIME 4 January 1, 1900 to
June 6, 2079
1 minute 'YYMMDD
hh:mm:ss:nnn'
DATETIME2 6 to 8 January 1, 0001 to
December 31, 9999
100 nanoseconds 'YYMMDD
hh:mm:ss.nnnnnn'
DATE 3 January 1, 0001 to
December 31, 9999
1 day 'YYYY-MM-DD'
TIME 3 to 5 100 nanoseconds 'hh:mm:ss:nnnnnnn'
DATETIMEOFFSET 8 to 10 January 1, 0001 to
December 31, 9999
100 nanoseconds 'YY-MM-DD
hh:mm:ss:nnnnnnn
[+|-]hh:mm'
Working with Date and Time Separately
• DATETIME, SMALLDATETIME, DATETIME2, y DATETIMEOFFSET incluyen la fecha y los datos de
tiempo
• Si solo se especifica la fecha, el tiempo establecido será media noche (todos ceros)
• Si solo se especifica la hora, la fecha establecida será (1 de enero de 1990)
DECLARE @DateOnly DATETIME = '20120212';
SELECT @DateOnly;
RESULT
-----------------------
2012-02-12 00:00:00.000
Funciones de fecha y hora
Function Return Type Remarks
GETDATE() datetime Devuelve la fecha y hora actual sistema de base de datos
como un valor de fecha y hora sin la base de datos de zona
horaria offset.
GETUTCDATE() datetime Devuelve la fecha y hora actual sistema de base de datos
como un valor de fecha y hora. La zona horaria base de
datos de desplazamiento no está incluido. Este valor
representa el tiempo UTC actual (Tiempo Universal
Coordinado).
SYSDATETIME() datetime2 Devuelve un valor datetime2 (7) que contiene la fecha y la
hora del equipo en el que se ejecuta la instancia de SQL
Server.
SYSDATETIMEOFFSET() datetimeoffset Devuelve un valor datetimeoffset (7) que contiene la fecha y
la hora del equipo en el que se ejecuta la instancia de SQL
Server. El desplazamiento de zona horaria está incluido.
SELECT CURRENT_TIMESTAMP();
SELECT SYSUTCDATETIME();
INSERT
INSERT INTO Sales.OrderDetails(
orderid, productid, unitprice, qty, discount)
VALUES
(12001,39,18,2,0.05),
(12002,39,18,5,0.10);
INSERT INTO Sales.OrderDetails(
orderid, productid, unitprice, qty, discount)
VALUES(12000,39,18,2,0.05);
• Inserta un unico valor
• Inserta multiple valores
INSERT CON SELECT
• Inserta los valores que son product de una consulta (Select)
INSERT INTO Sales.OrderHist(
orderid,custid,empid,orderdate)
SELECT orderid,custid,empid,orderdate
FROM Sales.Orders
WHERE orderdate < '20080101';
SELECT INTO
• Crea una nueva tabla
• Copia nombre de columnas, tipos de datos y valores nulos.
• NO copia restricciones o indices
SELECT orderid, custid, empid, orderdate, shippeddate
INTO Sales.OrderArchive
FROM Sales.Orders
WHERE orderdate < '20080101';
UPDATE
UPDATE Production.Products
SET unitprice = (unitprice * 1.04)
WHERE categoryid = 1 AND discontinued = 0;
• Actualiza todas las filas de una table o vista
• Conjunto se puede filtrar con una clausula WHERE
• Conjunto se puede filtrar con JOIN
• Solo las columnas especificadas en SET serán actualizadas
MERGE
• MERGE modifica los datos con base a una condicion
MERGE INTO schema_name.table_name AS TargetTbl
USING (SELECT <select_list>) AS SourceTbl
ON (TargetTbl.col1 = SourceTbl.col1)
WHEN MATCHED THEN
UPDATE SET col2 = SourceTbl.col2
WHEN NOT MATCHED THEN
INSERT (<column_list>)
VALUES (<value_list>);
DELETE
• DELETE sin clausula WHERE elimina todas las filas
• Use WHERE para especificar fila(s) a eliminar
DELETE FROM dbo.Nums;
DELETE FROM Sales.OrderDetails
WHERE orderid = 10248;
TRUNCATE TABLE
• TRUNCATE TABLE borra toda la tabla
• Libera almacenamiento fisico de la maquina
• Se puede devolver si el truncate es parte de una transaccion
• TRUNCATE TABLE producira un error si la table esta
referenciada por una restriccion de llave externa de
otra tabla
TRUNCATE TABLE dbo.Nums;
IDENTITY
CREATE TABLE Production.Products(
productid int IDENTITY(1,1) NOT NULL,
productname nvarchar(40) NOT NULL,
categoryid int NOT NULL,
unitprice money NOT NULL)
• IDENTITY genera numeros secuenciales automaticos para la insercion de registro
en una tabla.
• Puede especificar los valores de inicialización e incremento
• Solo una columna de una tabla puede tener la propiedad IDENTITY
• IDENTITY se omite en la sentencia INSERT
Sequences
• Agregado en SQL Server 2012
• Objetos independientes de la base de datos
• Mas flexible que la propiedad IDENTITY
• Se puede usar como valor por defecto
• Administrar con las sentencias CREATE/ALTER/DROP
-- Define a sequence
CREATE SEQUENCE dbo.InvoiceSeq AS INT START WITH 1
INCREMENT BY 1;
-- Retrieve next available value from sequence
SELECT NEXT VALUE FOR dbo.InvoiceSeq;
SELECT cache_size,
current_value, s.*
FROM sys.sequences as s
Sesión 4
Referencias
• http://www.microsoftvirtualacademy.com/training-courses/querying-microsoft-sql-server-2012-
databases-jump-start-spanish
• http://www.labitacorabd.blogspot.com
• http://www.sqlpass.org/
• http://www.mundosql.es/
1 de 26

Recomendados

Sesión 6 por
Sesión 6Sesión 6
Sesión 6Michael Andrés Calderón Ferreira
284 vistas16 diapositivas
LENGUAJE DE CONSULTA ESTRUCTURADO por
LENGUAJE DE CONSULTA ESTRUCTURADOLENGUAJE DE CONSULTA ESTRUCTURADO
LENGUAJE DE CONSULTA ESTRUCTURADOMinerva136
6.6K vistas12 diapositivas
Introducción a sql por
Introducción a  sqlIntroducción a  sql
Introducción a sqlMarisol Henao
5.4K vistas11 diapositivas
XQuery y XPath for SQL Server 2012 itpros dc_chapter6 por
XQuery y XPath for SQL Server 2012 itpros dc_chapter6XQuery y XPath for SQL Server 2012 itpros dc_chapter6
XQuery y XPath for SQL Server 2012 itpros dc_chapter6Julián Castiblanco
1.7K vistas34 diapositivas
Procedimientos Almacenados por
Procedimientos AlmacenadosProcedimientos Almacenados
Procedimientos Almacenadosguesta403644
677 vistas7 diapositivas
MANUAL COMPLETO DE SQL por
MANUAL COMPLETO DE SQLMANUAL COMPLETO DE SQL
MANUAL COMPLETO DE SQLEdgar Sandoval
44.4K vistas75 diapositivas

Más contenido relacionado

La actualidad más candente

Otros Objetos de Esquemas Z051 Cap 12 por
Otros Objetos de Esquemas Z051 Cap 12Otros Objetos de Esquemas Z051 Cap 12
Otros Objetos de Esquemas Z051 Cap 12Alexander Calderón
736 vistas15 diapositivas
Presentación1 por
Presentación1Presentación1
Presentación1Diego Sanchez Hernandez
114 vistas27 diapositivas
Sesion06c - Sentencias SQL en PL-SQL (Oracle) por
Sesion06c - Sentencias SQL en PL-SQL (Oracle)Sesion06c - Sentencias SQL en PL-SQL (Oracle)
Sesion06c - Sentencias SQL en PL-SQL (Oracle)José Toro
1.3K vistas4 diapositivas
Sesión04 - Diccionario de datos (Oracle) por
Sesión04 - Diccionario de datos (Oracle)Sesión04 - Diccionario de datos (Oracle)
Sesión04 - Diccionario de datos (Oracle)José Toro
7.4K vistas5 diapositivas
Curso SQL - Leccion 12 por
Curso SQL - Leccion 12Curso SQL - Leccion 12
Curso SQL - Leccion 12Emmanuel Ortiz Gutierrez
219 vistas48 diapositivas
MANEJO DE SENTENCIAS DE DEFINICION por
MANEJO DE SENTENCIAS DE DEFINICIONMANEJO DE SENTENCIAS DE DEFINICION
MANEJO DE SENTENCIAS DE DEFINICIONSergio Perez
258 vistas7 diapositivas

La actualidad más candente(20)

Sesion06c - Sentencias SQL en PL-SQL (Oracle) por José Toro
Sesion06c - Sentencias SQL en PL-SQL (Oracle)Sesion06c - Sentencias SQL en PL-SQL (Oracle)
Sesion06c - Sentencias SQL en PL-SQL (Oracle)
José Toro1.3K vistas
Sesión04 - Diccionario de datos (Oracle) por José Toro
Sesión04 - Diccionario de datos (Oracle)Sesión04 - Diccionario de datos (Oracle)
Sesión04 - Diccionario de datos (Oracle)
José Toro7.4K vistas
MANEJO DE SENTENCIAS DE DEFINICION por Sergio Perez
MANEJO DE SENTENCIAS DE DEFINICIONMANEJO DE SENTENCIAS DE DEFINICION
MANEJO DE SENTENCIAS DE DEFINICION
Sergio Perez258 vistas
05 Sql Profundizacion por Kudos S.A.S
05 Sql Profundizacion05 Sql Profundizacion
05 Sql Profundizacion
Kudos S.A.S2.2K vistas
TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM por Kamisutra
TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM   TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM
TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM
Kamisutra11.6K vistas
Programación MySQL-Ejercicios por testgrupocomex
Programación MySQL-EjerciciosProgramación MySQL-Ejercicios
Programación MySQL-Ejercicios
testgrupocomex51.8K vistas
Comandos mysql por polar
Comandos mysqlComandos mysql
Comandos mysql
polar988 vistas
Breve resumen sobre consultas básicas en MySQL por Totus Muertos
Breve resumen sobre consultas básicas en MySQLBreve resumen sobre consultas básicas en MySQL
Breve resumen sobre consultas básicas en MySQL
Totus Muertos14.1K vistas
Manual basico del_lenguaje_sql por Tomas Castle
Manual basico del_lenguaje_sqlManual basico del_lenguaje_sql
Manual basico del_lenguaje_sql
Tomas Castle515 vistas
Vistas En Sql Y My Sql por Ziscko
Vistas En Sql Y My SqlVistas En Sql Y My Sql
Vistas En Sql Y My Sql
Ziscko14K vistas

Destacado

Dat202 Techdays Paris 2015: PowerBI un an après por
Dat202 Techdays Paris 2015: PowerBI un an aprèsDat202 Techdays Paris 2015: PowerBI un an après
Dat202 Techdays Paris 2015: PowerBI un an aprèsIsabelle Van Campenhoudt
621 vistas31 diapositivas
Examen sybase - Administration base de donnees por
Examen sybase - Administration base de donneesExamen sybase - Administration base de donnees
Examen sybase - Administration base de donneeswebreaker
1.3K vistas1 diapositiva
Cycle Power BI Part1 por
Cycle Power BI Part1Cycle Power BI Part1
Cycle Power BI Part1Isabelle Van Campenhoudt
1.6K vistas34 diapositivas
To g chapter season 2 chapter 6.cv por
To g chapter season 2 chapter 6.cvTo g chapter season 2 chapter 6.cv
To g chapter season 2 chapter 6.cvMax Kerkula
406 vistas31 diapositivas
Portfolio henderson a por
Portfolio henderson aPortfolio henderson a
Portfolio henderson aAutumn Henderson
321 vistas18 diapositivas
Projeto AN9 - Uberlândia por
Projeto AN9 - UberlândiaProjeto AN9 - Uberlândia
Projeto AN9 - UberlândiaFilipe Detrey
479 vistas16 diapositivas

Destacado(20)

Examen sybase - Administration base de donnees por webreaker
Examen sybase - Administration base de donneesExamen sybase - Administration base de donnees
Examen sybase - Administration base de donnees
webreaker1.3K vistas
To g chapter season 2 chapter 6.cv por Max Kerkula
To g chapter season 2 chapter 6.cvTo g chapter season 2 chapter 6.cv
To g chapter season 2 chapter 6.cv
Max Kerkula406 vistas
Projeto AN9 - Uberlândia por Filipe Detrey
Projeto AN9 - UberlândiaProjeto AN9 - Uberlândia
Projeto AN9 - Uberlândia
Filipe Detrey479 vistas
QUALITY MANAGEMENT por smcci
QUALITY MANAGEMENTQUALITY MANAGEMENT
QUALITY MANAGEMENT
smcci725 vistas
SharePoint 2016 les nouveautés / yosTour Lyon / Etienne Bailly | Benoit Jester por Etienne Bailly
SharePoint 2016 les nouveautés / yosTour Lyon / Etienne Bailly | Benoit JesterSharePoint 2016 les nouveautés / yosTour Lyon / Etienne Bailly | Benoit Jester
SharePoint 2016 les nouveautés / yosTour Lyon / Etienne Bailly | Benoit Jester
Etienne Bailly1.7K vistas
Smci por smcci
SmciSmci
Smci
smcci295 vistas
Microsoft BI demystified: SharePoint 2016 BI or for PowerBI v2? por SPC Adriatics
Microsoft BI demystified: SharePoint 2016 BI or for PowerBI v2?Microsoft BI demystified: SharePoint 2016 BI or for PowerBI v2?
Microsoft BI demystified: SharePoint 2016 BI or for PowerBI v2?
SPC Adriatics244 vistas
Relational databases & NoSQL databases por Cédric Villa
Relational databases & NoSQL databasesRelational databases & NoSQL databases
Relational databases & NoSQL databases
Cédric Villa237 vistas
SharePoint 2016 BI or PowerBI v2 - SharePoint Saturday Cambridge por serge luca
SharePoint 2016 BI or PowerBI v2 - SharePoint Saturday CambridgeSharePoint 2016 BI or PowerBI v2 - SharePoint Saturday Cambridge
SharePoint 2016 BI or PowerBI v2 - SharePoint Saturday Cambridge
serge luca239 vistas
Dart structured web apps por chrisbuckett
Dart   structured web appsDart   structured web apps
Dart structured web apps
chrisbuckett1.3K vistas
Présentation JSS2015 - Le Query Store de SQL Server 2016 por Guillaume Nocent
Présentation JSS2015 - Le Query Store de SQL Server 2016Présentation JSS2015 - Le Query Store de SQL Server 2016
Présentation JSS2015 - Le Query Store de SQL Server 2016
Guillaume Nocent381 vistas
PowerBI v2, Power to the People, 1 year later por serge luca
PowerBI v2, Power to the People, 1 year laterPowerBI v2, Power to the People, 1 year later
PowerBI v2, Power to the People, 1 year later
serge luca1.4K vistas
SQL Saturday 510 Paris 2016 - Query Store session - final por Philippe Geiger
SQL Saturday 510 Paris 2016 - Query Store session - finalSQL Saturday 510 Paris 2016 - Query Store session - final
SQL Saturday 510 Paris 2016 - Query Store session - final
Philippe Geiger411 vistas
Unbreakable Sharepoint 2016 With SQL Server 2016 availability groups por Isabelle Van Campenhoudt
Unbreakable Sharepoint 2016 With SQL Server 2016 availability groupsUnbreakable Sharepoint 2016 With SQL Server 2016 availability groups
Unbreakable Sharepoint 2016 With SQL Server 2016 availability groups

Similar a Sesión 4

Tsql por
TsqlTsql
TsqlNelson Rubio
1.3K vistas15 diapositivas
Tsql por
TsqlTsql
TsqlNelson Rubio
989 vistas15 diapositivas
Sentencias por
SentenciasSentencias
SentenciasJohannaLopez102476
1 vista84 diapositivas
Sql server(1) por
Sql server(1)Sql server(1)
Sql server(1)Helver Gilberto Parra Gonzalez
66 vistas14 diapositivas
scrib,my plick, slide boom por
scrib,my plick, slide boomscrib,my plick, slide boom
scrib,my plick, slide boomkevineliaslopezguillen10
324 vistas16 diapositivas
scrib,my plick,slide boom por
scrib,my plick,slide boomscrib,my plick,slide boom
scrib,my plick,slide boomkevineliasguillen
200 vistas16 diapositivas

Similar a Sesión 4(20)

Curso Developer SQL 2012 enfocado a la Certificación 70-641 por Henry Troncoso
Curso Developer SQL 2012 enfocado a la Certificación 70-641Curso Developer SQL 2012 enfocado a la Certificación 70-641
Curso Developer SQL 2012 enfocado a la Certificación 70-641
Henry Troncoso1.1K vistas
Cheat_MySQL.docx por dcam4
Cheat_MySQL.docxCheat_MySQL.docx
Cheat_MySQL.docx
dcam41 vista

Último

1 PDF TODO 36MB 628p.pdf por
1 PDF TODO 36MB 628p.pdf1 PDF TODO 36MB 628p.pdf
1 PDF TODO 36MB 628p.pdfFRANCISCOJUSTOSIERRA
16 vistas628 diapositivas
REGLAMENTO A LEY DE TRANSPORTE TERRESTRE TRANSITO Y SEGURIDAD VIAL.pdf por
REGLAMENTO A LEY DE TRANSPORTE TERRESTRE TRANSITO Y SEGURIDAD VIAL.pdfREGLAMENTO A LEY DE TRANSPORTE TERRESTRE TRANSITO Y SEGURIDAD VIAL.pdf
REGLAMENTO A LEY DE TRANSPORTE TERRESTRE TRANSITO Y SEGURIDAD VIAL.pdfAinnatHtezil
6 vistas97 diapositivas
0 EFECTO FRICCIÓN.pdf por
0 EFECTO FRICCIÓN.pdf0 EFECTO FRICCIÓN.pdf
0 EFECTO FRICCIÓN.pdfFRANCISCOJUSTOSIERRA
10 vistas1 diapositiva
PROTOCOLO MANEJO DE RESIDUOS ORGÁNICOS por
PROTOCOLO MANEJO DE RESIDUOS ORGÁNICOSPROTOCOLO MANEJO DE RESIDUOS ORGÁNICOS
PROTOCOLO MANEJO DE RESIDUOS ORGÁNICOSINGENIERIAJFB
11 vistas8 diapositivas
Calculista Estructuras Constitución por
Calculista Estructuras ConstituciónCalculista Estructuras Constitución
Calculista Estructuras Constituciónarquitecto valparaiso
6 vistas25 diapositivas
Ley del Mono Viña del Mar por
Ley del Mono Viña del MarLey del Mono Viña del Mar
Ley del Mono Viña del Mararquitecto valparaiso
8 vistas21 diapositivas

Último(20)

REGLAMENTO A LEY DE TRANSPORTE TERRESTRE TRANSITO Y SEGURIDAD VIAL.pdf por AinnatHtezil
REGLAMENTO A LEY DE TRANSPORTE TERRESTRE TRANSITO Y SEGURIDAD VIAL.pdfREGLAMENTO A LEY DE TRANSPORTE TERRESTRE TRANSITO Y SEGURIDAD VIAL.pdf
REGLAMENTO A LEY DE TRANSPORTE TERRESTRE TRANSITO Y SEGURIDAD VIAL.pdf
AinnatHtezil6 vistas
PROTOCOLO MANEJO DE RESIDUOS ORGÁNICOS por INGENIERIAJFB
PROTOCOLO MANEJO DE RESIDUOS ORGÁNICOSPROTOCOLO MANEJO DE RESIDUOS ORGÁNICOS
PROTOCOLO MANEJO DE RESIDUOS ORGÁNICOS
INGENIERIAJFB11 vistas
evaluacion n°3 (página 2 de 3).pdf por matepura
evaluacion n°3 (página 2 de 3).pdfevaluacion n°3 (página 2 de 3).pdf
evaluacion n°3 (página 2 de 3).pdf
matepura12 vistas
MINEDU guia_prevención atención acoso estudiantes.pdf por GustavoRojasVega
MINEDU guia_prevención atención acoso estudiantes.pdfMINEDU guia_prevención atención acoso estudiantes.pdf
MINEDU guia_prevención atención acoso estudiantes.pdf
GustavoRojasVega10 vistas
evaluacion n°3 (página 1 de 3).pdf por matepura
evaluacion n°3 (página 1 de 3).pdfevaluacion n°3 (página 1 de 3).pdf
evaluacion n°3 (página 1 de 3).pdf
matepura5 vistas
S6_TAREA_SET_C_GEOTC1201.pdf por matepura
S6_TAREA_SET_C_GEOTC1201.pdfS6_TAREA_SET_C_GEOTC1201.pdf
S6_TAREA_SET_C_GEOTC1201.pdf
matepura8 vistas
Práctica individual con evaluación entre compañeros - Jose Alonso Vasquez Fon... por JosAlonsoVsquezFonse2
Práctica individual con evaluación entre compañeros - Jose Alonso Vasquez Fon...Práctica individual con evaluación entre compañeros - Jose Alonso Vasquez Fon...
Práctica individual con evaluación entre compañeros - Jose Alonso Vasquez Fon...
Prueba_de_desarrollo II_Mecanica_de_Materiales PROF CHULLO.pdf por MatematicaFisicaEsta
Prueba_de_desarrollo II_Mecanica_de_Materiales  PROF CHULLO.pdfPrueba_de_desarrollo II_Mecanica_de_Materiales  PROF CHULLO.pdf
Prueba_de_desarrollo II_Mecanica_de_Materiales PROF CHULLO.pdf

Sesión 4

  • 1. [70-461] Querying Microsoft SQL Server 2012 /ITPROS-DC/ITProsDCITPROS DC http://itpros-dc.com COMPARTIR EL CONOCIMIENTO, NUESTRA PASIÓN
  • 2. Esquema Curso • Module 1, “Introduction to Microsoft SQL Server 2014” • Module 2, “Introduction to T-SQL Querying” • Module 3, “Writing SELECT Queries” • Module 4, “Querying Multiple Tables” • Module 5, “Sorting and Filtering Data” • Module 6, “Working with SQL Server 2014 Data Types” • Module 7, “Using DML to Modify Data” • Module 8, “Using Built-In Functions” • Module 9, “Grouping and Aggregating Data” • Module 10, “Using Subqueries”
  • 3. Esquema Curso • Module 11, “Using Table Expressions” • Module 12, “Using Set Operators” • Module 13, “Using Window Ranking, Offset, and Aggregate Functions” • Module 14, “Pivoting and Grouping Sets” • Module 15, “Executing Stored Procedures” • Module 16, “Programming with T-SQL” • Module 17, “Implementing Error Handling” • Module 18, “Implementing Transactions” • Module 19, “Improving Query Performance” • Module 20, “Querying SQL Server Metadata”
  • 4. SESIÓN # 4 • Introducción a tipos de datos • Tipo de dato cadena • Tipo de dato fecha y hora • Cuando convertir tipo de dato • Funciones de fecha y hora • Funciones de cadena • Collation • Concatenar cadenas • Predicado LIKE • DML • MERGE • IDENTITY • SEQUENCES
  • 5. Tipos de datos Exact numerics: tinyint , smallint , int, bigint, money Unicode character strings: nchar, nvarchar, ntext Date and time: date, datetime, time Character strings: char, varchar, text • SQL Server asocia los tipos de datos a variables, columnas y/o expresiones. • Los tipos de datos determinan cual será el dato de entrada: • Cadenas, numeros, fechas, dinero, binarios, etc.
  • 6. • Exact Numeric Data type Range Storage (bytes) tinyint 0 to 255 1 smallint -32,768 to 32,768 2 int 2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bigint -2^63 - 2^63-1 (+/- 9 quintillion) 8 bit 1, 0 or NULL 1 decimal/numeric - 10^38 +1 through 10^38 – 1 when maximum precision is used 5-17 money -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 smallmoney - 214,748.3648 to 214,748.3647 4
  • 7. ¿Cuando convertir un tipo de dato? • Escenarios de convertir tipos de datos • Cuando un dato es movido, comparado o combinado con otro tipo de dato • Durante la declaración de una variable • Conversion implicita • Cuando se esta comparando un tipo de dato con otro • Conversión explicita • Usar funciones CAST o CONVERT • No todas las conversions son permitidas por SQL Server WHERE <column of smallint type> = <value of int type> CAST(unitprice AS int)
  • 8. Character Data Types • SQL Server soporta dos tipos de datos de cadena: • Regular: CHAR, VARCHAR • Almacena 1 byte por caracter • Solo 256 caracteres posibles • Unicode: NCHAR, NVARCHAR • Almacena 2 bytes por caracter • Soporta multiple lenguaje
  • 9. Collation • Aplicar esa coleccion de region SELECT empid, lastname FROM HR.employees WHERE lastname COLLATE Latin1_General_CS_AS = N'Funk';
  • 10. Concatenar Cadenas • SQL Server usa el signo (+) para concatenar cadenas • Concatenar un valor NULL retorna un NULL • SQL Server 2012 implantó la function CONCAT • Convierte NULL en cadena vacia antes de concatenar SELECT empid, lastname, firstname, firstname + N' ' + lastname AS fullname FROM HR.Employees; SELECT custid, city, region, country, CONCAT(city, ', ' + region, ', ' + country) AS location FROM Sales.Customers
  • 11. Funciones de cadena de caracteres Function Syntax Remarks SUBSTRING() SUBSTRING (expression , start , length) Returns part of an expression. LEFT(), RIGHT() LEFT (expression , integer_value) RIGHT (expression , integer_value) LEFT() returns left part of string up to integer_value. RIGHT() returns right part of string. LEN(), DATALENGTH() LEN ( string_expression ) DATALENGTH ( expression ) LEN() returns the number of characters of the specified string expression, excluding trailing blanks. DATALENGTH() returns the number of bytes used. CHARINDEX() CHARINDEX ( expressionToFind, expressionToSearch ) Searches an expression for another expression and returns its starting position if found. Optional start position. REPLACE() REPLACE ( string_expression , string_pattern , string_replacement ) Replaces all occurrences of a specified string value with another string value. UPPER(), LOWER() UPPER ( character_expression ) LOWER ( character_expression ) UPPER() returns a character expression with lowercase character data converted to uppercase. LOWER() converts uppercase to lowercase.
  • 12. Predicado LIKE • El predicado LIKE se usa para comprobar una cadena de caracteres con base a un patron. • Estos patrones se expresan con simbolos • % (Percent) Representa una cadena de cualquier longitud • _ (Underscore) Representa un unico caracter SELECT categoryid, categoryname, description FROM Production.Categories WHERE description LIKE 'Sweet%'
  • 13. Tipos de datos Fecha y Hora • Versiones anteriores de SQL Server solo soportaban DATETIME y SMALLDATETIME • DATE, TIME, DATETIME2, y DATETIMEOFFSET se introdujo en SQL Server 2008 • SQL Server 2012 añade mas funciones para trabajar con datos de fecha y hora Tipo de dato Almacenamiento (bytes) Rango de dato Exactitud Formato de ingreso recomendado DATETIME 8 January 1, 1753 to December 31, 9999 3-1/3 milliseconds 'YYMMDD hh:mm:ss:nnn' SMALLDATETIME 4 January 1, 1900 to June 6, 2079 1 minute 'YYMMDD hh:mm:ss:nnn' DATETIME2 6 to 8 January 1, 0001 to December 31, 9999 100 nanoseconds 'YYMMDD hh:mm:ss.nnnnnn' DATE 3 January 1, 0001 to December 31, 9999 1 day 'YYYY-MM-DD' TIME 3 to 5 100 nanoseconds 'hh:mm:ss:nnnnnnn' DATETIMEOFFSET 8 to 10 January 1, 0001 to December 31, 9999 100 nanoseconds 'YY-MM-DD hh:mm:ss:nnnnnnn [+|-]hh:mm'
  • 14. Working with Date and Time Separately • DATETIME, SMALLDATETIME, DATETIME2, y DATETIMEOFFSET incluyen la fecha y los datos de tiempo • Si solo se especifica la fecha, el tiempo establecido será media noche (todos ceros) • Si solo se especifica la hora, la fecha establecida será (1 de enero de 1990) DECLARE @DateOnly DATETIME = '20120212'; SELECT @DateOnly; RESULT ----------------------- 2012-02-12 00:00:00.000
  • 15. Funciones de fecha y hora Function Return Type Remarks GETDATE() datetime Devuelve la fecha y hora actual sistema de base de datos como un valor de fecha y hora sin la base de datos de zona horaria offset. GETUTCDATE() datetime Devuelve la fecha y hora actual sistema de base de datos como un valor de fecha y hora. La zona horaria base de datos de desplazamiento no está incluido. Este valor representa el tiempo UTC actual (Tiempo Universal Coordinado). SYSDATETIME() datetime2 Devuelve un valor datetime2 (7) que contiene la fecha y la hora del equipo en el que se ejecuta la instancia de SQL Server. SYSDATETIMEOFFSET() datetimeoffset Devuelve un valor datetimeoffset (7) que contiene la fecha y la hora del equipo en el que se ejecuta la instancia de SQL Server. El desplazamiento de zona horaria está incluido. SELECT CURRENT_TIMESTAMP(); SELECT SYSUTCDATETIME();
  • 16. INSERT INSERT INTO Sales.OrderDetails( orderid, productid, unitprice, qty, discount) VALUES (12001,39,18,2,0.05), (12002,39,18,5,0.10); INSERT INTO Sales.OrderDetails( orderid, productid, unitprice, qty, discount) VALUES(12000,39,18,2,0.05); • Inserta un unico valor • Inserta multiple valores
  • 17. INSERT CON SELECT • Inserta los valores que son product de una consulta (Select) INSERT INTO Sales.OrderHist( orderid,custid,empid,orderdate) SELECT orderid,custid,empid,orderdate FROM Sales.Orders WHERE orderdate < '20080101';
  • 18. SELECT INTO • Crea una nueva tabla • Copia nombre de columnas, tipos de datos y valores nulos. • NO copia restricciones o indices SELECT orderid, custid, empid, orderdate, shippeddate INTO Sales.OrderArchive FROM Sales.Orders WHERE orderdate < '20080101';
  • 19. UPDATE UPDATE Production.Products SET unitprice = (unitprice * 1.04) WHERE categoryid = 1 AND discontinued = 0; • Actualiza todas las filas de una table o vista • Conjunto se puede filtrar con una clausula WHERE • Conjunto se puede filtrar con JOIN • Solo las columnas especificadas en SET serán actualizadas
  • 20. MERGE • MERGE modifica los datos con base a una condicion MERGE INTO schema_name.table_name AS TargetTbl USING (SELECT <select_list>) AS SourceTbl ON (TargetTbl.col1 = SourceTbl.col1) WHEN MATCHED THEN UPDATE SET col2 = SourceTbl.col2 WHEN NOT MATCHED THEN INSERT (<column_list>) VALUES (<value_list>);
  • 21. DELETE • DELETE sin clausula WHERE elimina todas las filas • Use WHERE para especificar fila(s) a eliminar DELETE FROM dbo.Nums; DELETE FROM Sales.OrderDetails WHERE orderid = 10248;
  • 22. TRUNCATE TABLE • TRUNCATE TABLE borra toda la tabla • Libera almacenamiento fisico de la maquina • Se puede devolver si el truncate es parte de una transaccion • TRUNCATE TABLE producira un error si la table esta referenciada por una restriccion de llave externa de otra tabla TRUNCATE TABLE dbo.Nums;
  • 23. IDENTITY CREATE TABLE Production.Products( productid int IDENTITY(1,1) NOT NULL, productname nvarchar(40) NOT NULL, categoryid int NOT NULL, unitprice money NOT NULL) • IDENTITY genera numeros secuenciales automaticos para la insercion de registro en una tabla. • Puede especificar los valores de inicialización e incremento • Solo una columna de una tabla puede tener la propiedad IDENTITY • IDENTITY se omite en la sentencia INSERT
  • 24. Sequences • Agregado en SQL Server 2012 • Objetos independientes de la base de datos • Mas flexible que la propiedad IDENTITY • Se puede usar como valor por defecto • Administrar con las sentencias CREATE/ALTER/DROP -- Define a sequence CREATE SEQUENCE dbo.InvoiceSeq AS INT START WITH 1 INCREMENT BY 1; -- Retrieve next available value from sequence SELECT NEXT VALUE FOR dbo.InvoiceSeq; SELECT cache_size, current_value, s.* FROM sys.sequences as s

Notas del editor

  1. Note that not all content from the tables is printed in the workbook – use the provided links to show the references in Books Online. Point out that the int is the primary integer data type in SQL Server. Decimal precision: The maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision of 38, with the default set at 18. Decimal scale: The maximum number of decimal digits that can be stored to the right of the decimal point. See the following topics in Books Online: Decimal and Numeric (Transact SQL) Precision, Scale, and Length (Transact-SQL) Data Types (Transact-SQL) Float and Real (Transact-SQL)
  2. For more information on XML, see Course 20464C. Some of these types (cursors, sql_variant, and so on) are only listed for completeness. Don't get bogged down in details here. While there's no need to get into design discussions at this stage, you may wish to point out that the use of sql_variant probably means poor analysis of the problem and a lack of normalization.
  3. Code samples are fragments for illustration only. Note that conversion functions will be covered later in the course. Questions in workbook: Which data type will be converted? To which type? The char will be converted to an int. Why does SQL Server attempt to convert the character variable to an integer and not the other way around? The data type with the lower precedence is converted to the higher.
  4. SELECT custid, city, region, country,   CONCAT(city, ', ' + region, ', ' + country) AS location FROM Sales.Customers Note that the ISNULL and COALESC functions, covered later in the course, were often previously used to convert NULLs to empty strings. CONCAT now handles that.
  5. If time permits, also introduce LTRIM, RTRIM, REPLICATE. The FORMAT function is mentioned in the workbook, though not on this slide.
  6. For more information on LIKE, go to Books Online at LIKE (Transact-SQL) http://go.microsoft.com/fwlink/?LinkID=402731
  7. Point out which data types consume the least storage.
  8. Note that all function arguments are required! DATETIME2FROMPARTS() requires eight arguments. EOMONTH was new in 2012.
  9. Go to INSERT (Transact-SQL) in Books Online at INSERT (Transact-SQL) http://go.microsoft.com/fwlink/?LinkID=402734 Go to Table Value Constructor (Transact-SQL) in Books Online at Table Value Constructor (Transact-SQL) http://go.microsoft.com/fwlink/?LinkID=402735
  10. Note: The code samples are for illustration only, they will not run with the course database.