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
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)
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.
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.
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.
If time permits, also introduce LTRIM, RTRIM, REPLICATE.
The FORMAT function is mentioned in the workbook, though not on this slide.
For more information on LIKE, go to Books Online at
LIKE (Transact-SQL)
http://go.microsoft.com/fwlink/?LinkID=402731
Point out which data types consume the least storage.
Note that all function arguments are required! DATETIME2FROMPARTS() requires eight arguments.
EOMONTH was new in 2012.
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
Note: The code samples are for illustration only, they will not run with the course database.