SlideShare una empresa de Scribd logo
1 de 26
[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
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/

Más contenido relacionado

La actualidad más candente

Otros Objetos de Esquemas Z051 Cap 12
Otros Objetos de Esquemas Z051 Cap 12Otros Objetos de Esquemas Z051 Cap 12
Otros Objetos de Esquemas Z051 Cap 12Alexander Calderón
 
Sesion06c - Sentencias SQL en PL-SQL (Oracle)
Sesion06c - Sentencias SQL en PL-SQL (Oracle)Sesion06c - Sentencias SQL en PL-SQL (Oracle)
Sesion06c - Sentencias SQL en PL-SQL (Oracle)José Toro
 
Sesión04 - Diccionario de datos (Oracle)
Sesión04 - Diccionario de datos (Oracle)Sesión04 - Diccionario de datos (Oracle)
Sesión04 - Diccionario de datos (Oracle)José Toro
 
MANEJO DE SENTENCIAS DE DEFINICION
MANEJO DE SENTENCIAS DE DEFINICIONMANEJO DE SENTENCIAS DE DEFINICION
MANEJO DE SENTENCIAS DE DEFINICIONSergio Perez
 
05 Sql Profundizacion
05 Sql Profundizacion05 Sql Profundizacion
05 Sql ProfundizacionKudos S.A.S
 
Base de Datos(Funciones, Vistas,Procedimientos Almacenados,Triggers)
Base de Datos(Funciones, Vistas,Procedimientos Almacenados,Triggers)Base de Datos(Funciones, Vistas,Procedimientos Almacenados,Triggers)
Base de Datos(Funciones, Vistas,Procedimientos Almacenados,Triggers)Universidad Nacional de Piura
 
Técnicas avanzadas de consultas con sql server 2014
Técnicas avanzadas de consultas con sql server 2014Técnicas avanzadas de consultas con sql server 2014
Técnicas avanzadas de consultas con sql server 2014JOSE AHIAS LOPEZ PORTILLO
 
TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM
TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM   TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM
TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM Kamisutra
 
Programación MySQL-Ejercicios
Programación MySQL-EjerciciosProgramación MySQL-Ejercicios
Programación MySQL-Ejerciciostestgrupocomex
 
Comandos mysql
Comandos mysqlComandos mysql
Comandos mysqlpolar
 
Breve resumen sobre consultas básicas en MySQL
Breve resumen sobre consultas básicas en MySQLBreve resumen sobre consultas básicas en MySQL
Breve resumen sobre consultas básicas en MySQLTotus Muertos
 
Manual basico del_lenguaje_sql
Manual basico del_lenguaje_sqlManual basico del_lenguaje_sql
Manual basico del_lenguaje_sqlTomas Castle
 
Evolucion de PostgreSQL hasta 9.4
Evolucion de PostgreSQL hasta 9.4Evolucion de PostgreSQL hasta 9.4
Evolucion de PostgreSQL hasta 9.4Anthony Sotolongo
 
Vistas En Sql Y My Sql
Vistas En Sql Y My SqlVistas En Sql Y My Sql
Vistas En Sql Y My SqlZiscko
 

La actualidad más candente (20)

Otros Objetos de Esquemas Z051 Cap 12
Otros Objetos de Esquemas Z051 Cap 12Otros Objetos de Esquemas Z051 Cap 12
Otros Objetos de Esquemas Z051 Cap 12
 
Presentación1
Presentación1Presentación1
Presentación1
 
Sesion06c - Sentencias SQL en PL-SQL (Oracle)
Sesion06c - Sentencias SQL en PL-SQL (Oracle)Sesion06c - Sentencias SQL en PL-SQL (Oracle)
Sesion06c - Sentencias SQL en PL-SQL (Oracle)
 
Sesión04 - Diccionario de datos (Oracle)
Sesión04 - Diccionario de datos (Oracle)Sesión04 - Diccionario de datos (Oracle)
Sesión04 - Diccionario de datos (Oracle)
 
Curso SQL - Leccion 12
Curso SQL - Leccion 12Curso SQL - Leccion 12
Curso SQL - Leccion 12
 
MANEJO DE SENTENCIAS DE DEFINICION
MANEJO DE SENTENCIAS DE DEFINICIONMANEJO DE SENTENCIAS DE DEFINICION
MANEJO DE SENTENCIAS DE DEFINICION
 
7.1. procedimientos almacenados
7.1.  procedimientos almacenados7.1.  procedimientos almacenados
7.1. procedimientos almacenados
 
05 Sql Profundizacion
05 Sql Profundizacion05 Sql Profundizacion
05 Sql Profundizacion
 
Base de Datos(Funciones, Vistas,Procedimientos Almacenados,Triggers)
Base de Datos(Funciones, Vistas,Procedimientos Almacenados,Triggers)Base de Datos(Funciones, Vistas,Procedimientos Almacenados,Triggers)
Base de Datos(Funciones, Vistas,Procedimientos Almacenados,Triggers)
 
Técnicas avanzadas de consultas con sql server 2014
Técnicas avanzadas de consultas con sql server 2014Técnicas avanzadas de consultas con sql server 2014
Técnicas avanzadas de consultas con sql server 2014
 
TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM
TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM   TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM
TRANSACCIONES, TRIGGERS, PROCEDIMIENTOS ALMACENADOS: DB2/IBM
 
Programación MySQL-Ejercicios
Programación MySQL-EjerciciosProgramación MySQL-Ejercicios
Programación MySQL-Ejercicios
 
Comandos mysql
Comandos mysqlComandos mysql
Comandos mysql
 
Sentencias create
Sentencias createSentencias create
Sentencias create
 
Breve resumen sobre consultas básicas en MySQL
Breve resumen sobre consultas básicas en MySQLBreve resumen sobre consultas básicas en MySQL
Breve resumen sobre consultas básicas en MySQL
 
Manual basico del_lenguaje_sql
Manual basico del_lenguaje_sqlManual basico del_lenguaje_sql
Manual basico del_lenguaje_sql
 
Tuning fondo-negro-2
Tuning fondo-negro-2Tuning fondo-negro-2
Tuning fondo-negro-2
 
Evolucion de PostgreSQL hasta 9.4
Evolucion de PostgreSQL hasta 9.4Evolucion de PostgreSQL hasta 9.4
Evolucion de PostgreSQL hasta 9.4
 
Vistas En Sql Y My Sql
Vistas En Sql Y My SqlVistas En Sql Y My Sql
Vistas En Sql Y My Sql
 
(In) seguridad web
(In) seguridad web(In) seguridad web
(In) seguridad web
 

Destacado

Dat202 Techdays Paris 2015: PowerBI un an après
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
 
Examen sybase - Administration base de donnees
Examen sybase - Administration base de donneesExamen sybase - Administration base de donnees
Examen sybase - Administration base de donneeswebreaker
 
To g chapter season 2 chapter 6.cv
To g chapter season 2 chapter 6.cvTo g chapter season 2 chapter 6.cv
To g chapter season 2 chapter 6.cvMax Kerkula
 
Projeto AN9 - Uberlândia
Projeto AN9 - UberlândiaProjeto AN9 - Uberlândia
Projeto AN9 - UberlândiaFilipe Detrey
 
Tuning Sql Server for SharePoint--- Community Day Belgium 2013
Tuning Sql Server for SharePoint--- Community Day Belgium 2013Tuning Sql Server for SharePoint--- Community Day Belgium 2013
Tuning Sql Server for SharePoint--- Community Day Belgium 2013Isabelle Van Campenhoudt
 
QUALITY MANAGEMENT
QUALITY MANAGEMENTQUALITY MANAGEMENT
QUALITY MANAGEMENTsmcci
 
SharePoint 2016 les nouveautés / yosTour Lyon / Etienne Bailly | Benoit Jester
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 JesterEtienne Bailly
 
Smci
SmciSmci
Smcismcci
 
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?
Microsoft BI demystified: SharePoint 2016 BI or for PowerBI v2?SPC Adriatics
 
Relational databases & NoSQL databases
Relational databases & NoSQL databasesRelational databases & NoSQL databases
Relational databases & NoSQL databasesCédric Villa
 
บทที่ ๔ สื่อการสอนและห้องเรียนภาษาไทยในฐานะภาษาต่างประเทศ
บทที่ ๔ สื่อการสอนและห้องเรียนภาษาไทยในฐานะภาษาต่างประเทศบทที่ ๔ สื่อการสอนและห้องเรียนภาษาไทยในฐานะภาษาต่างประเทศ
บทที่ ๔ สื่อการสอนและห้องเรียนภาษาไทยในฐานะภาษาต่างประเทศเจริญขวัญ นาคประดิษฐ์
 
SharePoint 2016 BI or PowerBI v2 - SharePoint Saturday Cambridge
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 Cambridgeserge luca
 
Dart structured web apps
Dart   structured web appsDart   structured web apps
Dart structured web appschrisbuckett
 
Présentation JSS2015 - Le Query Store de SQL Server 2016
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 2016Guillaume Nocent
 
PowerBI v2, Power to the People, 1 year later
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 laterserge luca
 
SQL Saturday 510 Paris 2016 - Query Store session - final
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 - finalPhilippe Geiger
 
Unbreakable Sharepoint 2016 With SQL Server 2016 availability groups
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 groupsIsabelle Van Campenhoudt
 

Destacado (20)

Dat202 Techdays Paris 2015: PowerBI un an après
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ès
 
Examen sybase - Administration base de donnees
Examen sybase - Administration base de donneesExamen sybase - Administration base de donnees
Examen sybase - Administration base de donnees
 
Cycle Power BI Part1
Cycle Power BI Part1Cycle Power BI Part1
Cycle Power BI Part1
 
To g chapter season 2 chapter 6.cv
To g chapter season 2 chapter 6.cvTo g chapter season 2 chapter 6.cv
To g chapter season 2 chapter 6.cv
 
Portfolio henderson a
Portfolio henderson aPortfolio henderson a
Portfolio henderson a
 
Projeto AN9 - Uberlândia
Projeto AN9 - UberlândiaProjeto AN9 - Uberlândia
Projeto AN9 - Uberlândia
 
Tuning Sql Server for SharePoint--- Community Day Belgium 2013
Tuning Sql Server for SharePoint--- Community Day Belgium 2013Tuning Sql Server for SharePoint--- Community Day Belgium 2013
Tuning Sql Server for SharePoint--- Community Day Belgium 2013
 
QUALITY MANAGEMENT
QUALITY MANAGEMENTQUALITY MANAGEMENT
QUALITY MANAGEMENT
 
SharePoint 2016 les nouveautés / yosTour Lyon / Etienne Bailly | Benoit Jester
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
 
Smci
SmciSmci
Smci
 
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?
Microsoft BI demystified: SharePoint 2016 BI or for PowerBI v2?
 
Relational databases & NoSQL databases
Relational databases & NoSQL databasesRelational databases & NoSQL databases
Relational databases & NoSQL databases
 
บทที่ ๔ สื่อการสอนและห้องเรียนภาษาไทยในฐานะภาษาต่างประเทศ
บทที่ ๔ สื่อการสอนและห้องเรียนภาษาไทยในฐานะภาษาต่างประเทศบทที่ ๔ สื่อการสอนและห้องเรียนภาษาไทยในฐานะภาษาต่างประเทศ
บทที่ ๔ สื่อการสอนและห้องเรียนภาษาไทยในฐานะภาษาต่างประเทศ
 
SharePoint 2016 BI or PowerBI v2 - SharePoint Saturday Cambridge
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
 
Dart structured web apps
Dart   structured web appsDart   structured web apps
Dart structured web apps
 
Présentation JSS2015 - Le Query Store de SQL Server 2016
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
 
PowerBI v2, Power to the People, 1 year later
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
 
Powerbi 365
Powerbi 365Powerbi 365
Powerbi 365
 
SQL Saturday 510 Paris 2016 - Query Store session - final
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
 
Unbreakable Sharepoint 2016 With SQL Server 2016 availability groups
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 Querying SQL Server 2012 (20)

Tsql
TsqlTsql
Tsql
 
Tsql
TsqlTsql
Tsql
 
Sentencias
SentenciasSentencias
Sentencias
 
Sql server(1)
Sql server(1)Sql server(1)
Sql server(1)
 
scrib,my plick,slide boom
scrib,my plick,slide boomscrib,my plick,slide boom
scrib,my plick,slide boom
 
scrib,my plick, slide boom
scrib,my plick, slide boomscrib,my plick, slide boom
scrib,my plick, slide boom
 
Expo
ExpoExpo
Expo
 
Lenguaje estructurado sql
Lenguaje estructurado sqlLenguaje estructurado sql
Lenguaje estructurado sql
 
Curso Developer SQL 2012 enfocado a la Certificación 70-641
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
 
Bdii 04 sql
Bdii 04 sqlBdii 04 sql
Bdii 04 sql
 
Lenguaje transact sql
Lenguaje transact sqlLenguaje transact sql
Lenguaje transact sql
 
Tema5 sql - dml
Tema5   sql - dmlTema5   sql - dml
Tema5 sql - dml
 
Introduccion al sql query
Introduccion al sql queryIntroduccion al sql query
Introduccion al sql query
 
Amnel
AmnelAmnel
Amnel
 
Database fundamental itprosdc_chapter2
Database fundamental itprosdc_chapter2Database fundamental itprosdc_chapter2
Database fundamental itprosdc_chapter2
 
(25/02) Desarrollador@S Invita - Introducción y novedades de SQL Server 2008
(25/02) Desarrollador@S Invita - Introducción y novedades de SQL Server 2008(25/02) Desarrollador@S Invita - Introducción y novedades de SQL Server 2008
(25/02) Desarrollador@S Invita - Introducción y novedades de SQL Server 2008
 
Consultas sql
Consultas sqlConsultas sql
Consultas sql
 
Cheat_MySQL.docx
Cheat_MySQL.docxCheat_MySQL.docx
Cheat_MySQL.docx
 
Deber de sql
Deber de sqlDeber de sql
Deber de sql
 
Base de datos - Clase 2
Base de datos - Clase 2Base de datos - Clase 2
Base de datos - Clase 2
 

Último

CLASE 2 MUROS CARAVISTA EN CONCRETO Y UNIDAD DE ALBAÑILERIA
CLASE 2 MUROS CARAVISTA EN CONCRETO  Y UNIDAD DE ALBAÑILERIACLASE 2 MUROS CARAVISTA EN CONCRETO  Y UNIDAD DE ALBAÑILERIA
CLASE 2 MUROS CARAVISTA EN CONCRETO Y UNIDAD DE ALBAÑILERIAMayraOchoa35
 
SOLICITUD-PARA-LOS-EGRESADOS-UNEFA-2022.
SOLICITUD-PARA-LOS-EGRESADOS-UNEFA-2022.SOLICITUD-PARA-LOS-EGRESADOS-UNEFA-2022.
SOLICITUD-PARA-LOS-EGRESADOS-UNEFA-2022.ariannytrading
 
Centro Integral del Transporte de Metro de Madrid (CIT). Premio COAM 2023
Centro Integral del Transporte de Metro de Madrid (CIT). Premio COAM 2023Centro Integral del Transporte de Metro de Madrid (CIT). Premio COAM 2023
Centro Integral del Transporte de Metro de Madrid (CIT). Premio COAM 2023ANDECE
 
sistema de construcción Drywall semana 7
sistema de construcción Drywall semana 7sistema de construcción Drywall semana 7
sistema de construcción Drywall semana 7luisanthonycarrascos
 
IPERC Y ATS - SEGURIDAD INDUSTRIAL PARA TODA EMPRESA
IPERC Y ATS - SEGURIDAD INDUSTRIAL PARA TODA EMPRESAIPERC Y ATS - SEGURIDAD INDUSTRIAL PARA TODA EMPRESA
IPERC Y ATS - SEGURIDAD INDUSTRIAL PARA TODA EMPRESAJAMESDIAZ55
 
Reporte de simulación de flujo del agua en un volumen de control MNVA.pdf
Reporte de simulación de flujo del agua en un volumen de control MNVA.pdfReporte de simulación de flujo del agua en un volumen de control MNVA.pdf
Reporte de simulación de flujo del agua en un volumen de control MNVA.pdfMikkaelNicolae
 
Calavera calculo de estructuras de cimentacion.pdf
Calavera calculo de estructuras de cimentacion.pdfCalavera calculo de estructuras de cimentacion.pdf
Calavera calculo de estructuras de cimentacion.pdfyoseka196
 
Diapositiva de Topografía Nivelación simple y compuesta
Diapositiva de Topografía Nivelación simple y compuestaDiapositiva de Topografía Nivelación simple y compuesta
Diapositiva de Topografía Nivelación simple y compuestajeffsalazarpuente
 
Hanns Recabarren Diaz (2024), Implementación de una herramienta de realidad v...
Hanns Recabarren Diaz (2024), Implementación de una herramienta de realidad v...Hanns Recabarren Diaz (2024), Implementación de una herramienta de realidad v...
Hanns Recabarren Diaz (2024), Implementación de una herramienta de realidad v...Francisco Javier Mora Serrano
 
TEXTURA Y DETERMINACION DE ROCAS SEDIMENTARIAS
TEXTURA Y DETERMINACION DE ROCAS SEDIMENTARIASTEXTURA Y DETERMINACION DE ROCAS SEDIMENTARIAS
TEXTURA Y DETERMINACION DE ROCAS SEDIMENTARIASfranzEmersonMAMANIOC
 
Topografía 1 Nivelación y Carretera en la Ingenierías
Topografía 1 Nivelación y Carretera en la IngenieríasTopografía 1 Nivelación y Carretera en la Ingenierías
Topografía 1 Nivelación y Carretera en la IngenieríasSegundo Silva Maguiña
 
Introducción a los sistemas neumaticos.ppt
Introducción a los sistemas neumaticos.pptIntroducción a los sistemas neumaticos.ppt
Introducción a los sistemas neumaticos.pptEduardoCorado
 
ECONOMIA APLICADA SEMANA 555555555544.pdf
ECONOMIA APLICADA SEMANA 555555555544.pdfECONOMIA APLICADA SEMANA 555555555544.pdf
ECONOMIA APLICADA SEMANA 555555555544.pdfmatepura
 
2. UPN PPT - SEMANA 02 GESTION DE PROYECTOS MG CHERYL QUEZADA(1).pdf
2. UPN PPT - SEMANA 02 GESTION DE PROYECTOS MG CHERYL QUEZADA(1).pdf2. UPN PPT - SEMANA 02 GESTION DE PROYECTOS MG CHERYL QUEZADA(1).pdf
2. UPN PPT - SEMANA 02 GESTION DE PROYECTOS MG CHERYL QUEZADA(1).pdfAnthonyTiclia
 
CICLO DE DEMING que se encarga en como mejorar una empresa
CICLO DE DEMING que se encarga en como mejorar una empresaCICLO DE DEMING que se encarga en como mejorar una empresa
CICLO DE DEMING que se encarga en como mejorar una empresaSHERELYNSAMANTHAPALO1
 
CENTROIDES Y MOMENTOS DE INERCIA DE AREAS PLANAS.pdf
CENTROIDES Y MOMENTOS DE INERCIA DE AREAS PLANAS.pdfCENTROIDES Y MOMENTOS DE INERCIA DE AREAS PLANAS.pdf
CENTROIDES Y MOMENTOS DE INERCIA DE AREAS PLANAS.pdfpaola110264
 
Flujo multifásico en tuberias de ex.pptx
Flujo multifásico en tuberias de ex.pptxFlujo multifásico en tuberias de ex.pptx
Flujo multifásico en tuberias de ex.pptxEduardoSnchezHernnde5
 
Flujo potencial, conceptos básicos y ejemplos resueltos.
Flujo potencial, conceptos básicos y ejemplos resueltos.Flujo potencial, conceptos básicos y ejemplos resueltos.
Flujo potencial, conceptos básicos y ejemplos resueltos.ALEJANDROLEONGALICIA
 
AMBIENTES SEDIMENTARIOS GEOLOGIA TIPOS .pptx
AMBIENTES SEDIMENTARIOS GEOLOGIA TIPOS .pptxAMBIENTES SEDIMENTARIOS GEOLOGIA TIPOS .pptx
AMBIENTES SEDIMENTARIOS GEOLOGIA TIPOS .pptxLuisvila35
 
Edificio residencial Becrux en Madrid. Fachada de GRC
Edificio residencial Becrux en Madrid. Fachada de GRCEdificio residencial Becrux en Madrid. Fachada de GRC
Edificio residencial Becrux en Madrid. Fachada de GRCANDECE
 

Último (20)

CLASE 2 MUROS CARAVISTA EN CONCRETO Y UNIDAD DE ALBAÑILERIA
CLASE 2 MUROS CARAVISTA EN CONCRETO  Y UNIDAD DE ALBAÑILERIACLASE 2 MUROS CARAVISTA EN CONCRETO  Y UNIDAD DE ALBAÑILERIA
CLASE 2 MUROS CARAVISTA EN CONCRETO Y UNIDAD DE ALBAÑILERIA
 
SOLICITUD-PARA-LOS-EGRESADOS-UNEFA-2022.
SOLICITUD-PARA-LOS-EGRESADOS-UNEFA-2022.SOLICITUD-PARA-LOS-EGRESADOS-UNEFA-2022.
SOLICITUD-PARA-LOS-EGRESADOS-UNEFA-2022.
 
Centro Integral del Transporte de Metro de Madrid (CIT). Premio COAM 2023
Centro Integral del Transporte de Metro de Madrid (CIT). Premio COAM 2023Centro Integral del Transporte de Metro de Madrid (CIT). Premio COAM 2023
Centro Integral del Transporte de Metro de Madrid (CIT). Premio COAM 2023
 
sistema de construcción Drywall semana 7
sistema de construcción Drywall semana 7sistema de construcción Drywall semana 7
sistema de construcción Drywall semana 7
 
IPERC Y ATS - SEGURIDAD INDUSTRIAL PARA TODA EMPRESA
IPERC Y ATS - SEGURIDAD INDUSTRIAL PARA TODA EMPRESAIPERC Y ATS - SEGURIDAD INDUSTRIAL PARA TODA EMPRESA
IPERC Y ATS - SEGURIDAD INDUSTRIAL PARA TODA EMPRESA
 
Reporte de simulación de flujo del agua en un volumen de control MNVA.pdf
Reporte de simulación de flujo del agua en un volumen de control MNVA.pdfReporte de simulación de flujo del agua en un volumen de control MNVA.pdf
Reporte de simulación de flujo del agua en un volumen de control MNVA.pdf
 
Calavera calculo de estructuras de cimentacion.pdf
Calavera calculo de estructuras de cimentacion.pdfCalavera calculo de estructuras de cimentacion.pdf
Calavera calculo de estructuras de cimentacion.pdf
 
Diapositiva de Topografía Nivelación simple y compuesta
Diapositiva de Topografía Nivelación simple y compuestaDiapositiva de Topografía Nivelación simple y compuesta
Diapositiva de Topografía Nivelación simple y compuesta
 
Hanns Recabarren Diaz (2024), Implementación de una herramienta de realidad v...
Hanns Recabarren Diaz (2024), Implementación de una herramienta de realidad v...Hanns Recabarren Diaz (2024), Implementación de una herramienta de realidad v...
Hanns Recabarren Diaz (2024), Implementación de una herramienta de realidad v...
 
TEXTURA Y DETERMINACION DE ROCAS SEDIMENTARIAS
TEXTURA Y DETERMINACION DE ROCAS SEDIMENTARIASTEXTURA Y DETERMINACION DE ROCAS SEDIMENTARIAS
TEXTURA Y DETERMINACION DE ROCAS SEDIMENTARIAS
 
Topografía 1 Nivelación y Carretera en la Ingenierías
Topografía 1 Nivelación y Carretera en la IngenieríasTopografía 1 Nivelación y Carretera en la Ingenierías
Topografía 1 Nivelación y Carretera en la Ingenierías
 
Introducción a los sistemas neumaticos.ppt
Introducción a los sistemas neumaticos.pptIntroducción a los sistemas neumaticos.ppt
Introducción a los sistemas neumaticos.ppt
 
ECONOMIA APLICADA SEMANA 555555555544.pdf
ECONOMIA APLICADA SEMANA 555555555544.pdfECONOMIA APLICADA SEMANA 555555555544.pdf
ECONOMIA APLICADA SEMANA 555555555544.pdf
 
2. UPN PPT - SEMANA 02 GESTION DE PROYECTOS MG CHERYL QUEZADA(1).pdf
2. UPN PPT - SEMANA 02 GESTION DE PROYECTOS MG CHERYL QUEZADA(1).pdf2. UPN PPT - SEMANA 02 GESTION DE PROYECTOS MG CHERYL QUEZADA(1).pdf
2. UPN PPT - SEMANA 02 GESTION DE PROYECTOS MG CHERYL QUEZADA(1).pdf
 
CICLO DE DEMING que se encarga en como mejorar una empresa
CICLO DE DEMING que se encarga en como mejorar una empresaCICLO DE DEMING que se encarga en como mejorar una empresa
CICLO DE DEMING que se encarga en como mejorar una empresa
 
CENTROIDES Y MOMENTOS DE INERCIA DE AREAS PLANAS.pdf
CENTROIDES Y MOMENTOS DE INERCIA DE AREAS PLANAS.pdfCENTROIDES Y MOMENTOS DE INERCIA DE AREAS PLANAS.pdf
CENTROIDES Y MOMENTOS DE INERCIA DE AREAS PLANAS.pdf
 
Flujo multifásico en tuberias de ex.pptx
Flujo multifásico en tuberias de ex.pptxFlujo multifásico en tuberias de ex.pptx
Flujo multifásico en tuberias de ex.pptx
 
Flujo potencial, conceptos básicos y ejemplos resueltos.
Flujo potencial, conceptos básicos y ejemplos resueltos.Flujo potencial, conceptos básicos y ejemplos resueltos.
Flujo potencial, conceptos básicos y ejemplos resueltos.
 
AMBIENTES SEDIMENTARIOS GEOLOGIA TIPOS .pptx
AMBIENTES SEDIMENTARIOS GEOLOGIA TIPOS .pptxAMBIENTES SEDIMENTARIOS GEOLOGIA TIPOS .pptx
AMBIENTES SEDIMENTARIOS GEOLOGIA TIPOS .pptx
 
Edificio residencial Becrux en Madrid. Fachada de GRC
Edificio residencial Becrux en Madrid. Fachada de GRCEdificio residencial Becrux en Madrid. Fachada de GRC
Edificio residencial Becrux en Madrid. Fachada de GRC
 

Querying SQL Server 2012

  • 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
  • 25.

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.