0% found this document useful (0 votes)
99 views31 pages

Working With Data Types

This module provides an overview of working with different data types in SQL Server. It covers numeric, character, date/time, and other specialized data types. It discusses choosing the appropriate data type, implicit and explicit conversion between types, and common conversion issues. Lessons demonstrate working with data types through examples and conversions.

Uploaded by

Dip Madav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views31 pages

Working With Data Types

This module provides an overview of working with different data types in SQL Server. It covers numeric, character, date/time, and other specialized data types. It discusses choosing the appropriate data type, implicit and explicit conversion between types, and common conversion issues. Lessons demonstrate working with data types through examples and conversions.

Uploaded by

Dip Madav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Module 2

Working with Data


Types

Module Overview
Using Data Types
Working with Character Data
Converting Data Types
Working with Specialized Data Types

Lesson 1: Using Data Types


Introducing Data Types
Exact Numeric Data Types
Approximate Numeric Data Types
Date and Time Data Types
Unique Identifiers
NULL or NOT NULL Columns
Demonstration 1A: Working with Numeric Data Types

Introducing Data Types


Data types determine what can be stored

Constrain the type of data that an object can hold and the
permitted operations

Provide limits on the range of values

Data types apply to database columns, variables,

expressions, and parameters

Critical to choose appropriate data types

Assist with query optimization

Provide a level of self-documentation

Three basic sets of data types

System data types

Alias data types

User-defined data types

Exact Numeric Data Types


Wide variety of numeric types are supported
Vary in range, precision, and accuracy
Data Type

Notes

tinyint

8 bits (0 to 255)

smallint

16 bit integer (-32768 to 32767)

int

32 bit integer (-2147483648 to 2147483647)

bigint

64 bit integer (-2^63 to 2^63 1)

decimal

fixed precision and scale (-10^38+1 10^38-1)

numeric

functionally equivalent to decimal

smallmoney

fixed scale of 4 decimal places in 32 bits avoid

money

fixed scale of 4 decimal places in 64 bits - avoid

bit

values of 1, 0, or NULL

Approximate Numeric Data Types


Two approximate numeric types are supported
float is from float(1) to float(53)
float defaults to float(53)
real is fixed 4 byte storage
float and real not regularly used in business applications as they

are not precise

Data Type

Notes

float

approximate value with scale of up to 53 digits

real

ISO standard floating point with fixed storage of 32


bits

Date and Time Data Types


Rich set of options is available for storing date and time data
Need to be very careful of string literal formats of each
Large set of functions available for processing these data types
Data Type

Notes

date

0001-01-01 to 9999-12-31 with accuracy of 1 day

datetime2

same date storage as date data type plus time


storage as per time data type

datetime

1753-01-01 to 9999-12-31 with accuracy of 3.33


milliseconds

datetimeoffset

as per datetime2 plus timezone offset of -14:00 to


+14:00

smalldatetime

1900-01-01 to 2079-06-06 with 1 minute accuracy

time

00:00:00.0000000 to 23:59:59.9999999 with 100


nanosecond accuracy

Unique Identifiers
uniqueidentifier data type is typically used for storing

GUID values

GUID is globally unique identifier


Storage is essentially a 128-bit integer but standard

integer arithmetic is not supported

=, <>, <, >, <=, >= are supported along with NULL and

NOT NULL checking

IDENTITY cannot be used


New values from NEWID() function
Common error is to store these as strings

NULL or NOT NULL Columns


Determine whether a value must be provided
Can be defined on columns and parameters
Cannot be defined on variables
Are often inappropriately defined

CREATE
CREATE TABLE
TABLE Sales.Opportunity
Sales.Opportunity
(
(
OpportunityID
OpportunityID int NOT NULL,
Requirements
Requirements nvarchar(50)
nvarchar(50) NOT
NOT NULL,
NULL,
ReceivedDate
ReceivedDate date
date NOT
NOT NULL,
NULL,
LikelyClosingDate
LikelyClosingDate date
date NULL,
NULL,
SalespersonID
SalespersonID int NULL,
Rating
Rating int
int NOT
NOT NULL
NULL
);
);

Demonstration 1A: Working with Numeric Data Types


In this demonstration you will see:
How to work with NULL
How to insert GUIDs into a table

Lesson 2: Working with Character Data


Unicode
Character Data Types
Understanding Collations
Implementing UTF-16 SC Collations
Demonstration 2A: Working with Character Data

Unicode
Is a worldwide character-encoding standard
Simplifies software localization
Improves multilingual character processing
Is implemented in SQL Server as double-byte for Unicode types
Requires N prefix on constants
Uses LEN() to return number of characters, DATALENGTH() to

return the number of bytes

DECLARE
DECLARE @Hello
@Hello nvarchar(10);
nvarchar(10);
SET
SET @Hello
@Hello =
= N'Hello';
N'Hello';
SET
SET @Hello
@Hello =
= N'
N'
';
';
SET
SET @Hello
@Hello =
= N'
N'
';
';

Character Data Types


Fixed length, variable length, and large character data types
Single byte and double byte (Unicode) data types
Data Type

Notes

char

Fixed length single-byte character data

nchar

Fixed length Unicode character data

varchar

Variable length single-byte character data

nvarchar

Variable length Unicode character data

varchar(max)

Large value single-byte character data

nvarchar(max)

Large value Unicode character data

text

Variable length single-byte character data


(deprecated: do not use for new work)

ntext

Variable length Unicode data (deprecated: do not


use for new work)

Understanding Collations
Collations in SQL Server control:

Code page that is used to store non-Unicode data

Rules that govern how SQL Server sorts and compares values
for non-Unicode types

SQL Server supports a large number of collations,

including case-sensitivity options

Collation settings can be determined at the instance,

database, and column levels

Comparisons between data stored in different collations

require specifying the collation to use for the comparison

SELECT
SELECT *
FROM
FROM Production.Product
Production.Product
WHERE
WHERE Name LIKE
LIKE N'%ball%'
N'%ball%' COLLATE
COLLATE
SQL_Latin1_General_Cp1_CS_AS;
SQL_Latin1_General_Cp1_CS_AS;

Implementing UTF-16 SC Collations


Unicode consortium lists values from 0x0000 to 0x10FFFF

Most values fit in a 16 bit word

SC (Supplementary Character) Collations provide support for


characters with codepoint values larger than 0xFFFF

Supported on nchar, nvarchar, nvarchar(max) and

sql_variant

Requires two consecutive 16 bit words (surrogate pairs)

Example:

Japanese_Bushu_Kakusu_100_CI_AS_SC

Demonstration 2A: Working with Character Data


In this demonstration you will see:
How to work with Unicode and non Unicode data
How to work with collations

Lesson 3: Converting Data Types


Using CAST, CONVERT, and PARSE
Using TRY_PARSE and TRY_CONVERT
Implicit Data Conversion
Common Conversion Issues
Demonstration 3A: Common Conversion Issues

Using CAST, CONVERT, and PARSE


CAST, CONVERT, and PARSE change an expression of one

data type to another in SQL Server

CAST is based on ANSI SQL standards


CONVERT allows specifying a style, PARSE allows

specifying a culture

SELECT
SELECT CAST(SYSDATETIME()
CAST(SYSDATETIME() AS nvarchar(30));
nvarchar(30));
SELECT
SELECT CONVERT(varchar(8),SYSDATETIME(),112);
CONVERT(varchar(8),SYSDATETIME(),112);
SELECT
SELECT CONVERT(char(8),
CONVERT(char(8), 0x4E616d65,
0x4E616d65, 0)
0)
AS
AS 'Style
'Style 0,
0, binary
binary to character';
character';
SELECT
SELECT PARSE('Monday,
PARSE('Monday, 13
13 December
December 2010'
2010' AS
AS
datetime2
datetime2 USING
USING 'en-US');
'en-US');

Using TRY_PARSE and TRY_CONVERT


Return the result of a data conversion, if possible
No error thrown on failure
Return NULL if the cast fails

SELECT
SELECT
CASE
CASE WHEN
WHEN TRY_PARSE('NotLikely'
TRY_PARSE('NotLikely' AS decimal
decimal
USING
USING
'sr-Latn-CS')
'sr-Latn-CS') IS
IS NULL
NULL
THEN
THEN 'Not
'Not Decimal'
Decimal'
ELSE
ELSE 'Decimal'
'Decimal'
END
END AS
AS Result
Result ;;

Implicit Data Conversion


When data isn't explicitly converted between types,

implicit data conversion is attempted and is based on data


type precedence

Not all data types can be implicitly converted to all other

data types

DECLARE
DECLARE
DECLARE
DECLARE
DECLARE
DECLARE

@Salary
@Salary decimal(18,2)
decimal(18,2) == 78000.00;
78000.00;
@Annual
@Annual int
int == 50000;
50000;
@XmlData
@XmlData xml;
xml;

SET
SET @Salary
@Salary == @Annual;
@Annual;
SET
SET @Salary
@Salary +=
+= @Annual;
@Annual;
SET
SET @XmlData
@XmlData == '<Customers>
'<Customers>
<Customer
<Customer CustomerID="10"/>
CustomerID="10"/>
</Customers>';
</Customers>';

Common Conversion Issues


Many common issues arise during data type conversions

Inappropriate values for the target data type

Value is out of range for the target data type

Value is truncated while being converted (sometimes silently)

Value is rounded while being converted (sometimes silently)

Value is changed while being converted (sometimes silently)

Assumptions are made about internal storage formats for data


types

Some datetime conversions are non-deterministic and depend


on language settings

Some parsing issues are hard to understand

Demonstration 3A: Common Conversion Issues


In the following demonstration you will see:
How to convert date data types explicitly
How language settings can affect date conversions
How data can be truncated during data type conversion
Issues that can arise with implicit conversion

Lesson 4: Working with Specialized Data Types


timestamp and rowversion
Alias Data Types
Other Data Types
Demonstration 4A: rowversion Data Type

timestamp and rowversion


rowversion assists in creating systems based on optimistic

concurrency

timestamp and rowversion both automatically change value

whenever a row is modified

rowversion replaces the timestamp data type


Each new value is always larger than the previous value and is

unique within the database

Alias Data Types


CREATE TYPE can be used to create alias types
Alias types are subtypes of existing system data types
Alias types can include the details of nullability
Alias types are often used to maintain consistency across

data type usage in an application

CREATE
CREATE TYPE
TYPE ProductNumber
ProductNumber
FROM
FROM nvarchar(20)
nvarchar(20) NOT
NOT NULL;
NULL;
GO
GO
CREATE
CREATE TABLE
TABLE Production.ProductConversion
Production.ProductConversion
(
( ProductConversionID
ProductConversionID int
int NOT
NOT NULL
NULL IDENTITY(1,1),
IDENTITY(1,1),
FromProduct
FromProduct ProductNumber,
ProductNumber,
ToProduct
ToProduct ProductNumber
ProductNumber
);
);

Other Data Types


Data Type

Notes

binary

Is a fixed length binary data

varbinary

Is a variable length binary data

varbinary(max)

Is a long variable length binary data

image

Is a long variable length binary data deprecated


use varbinary(max) instead

hierarchyid

Represents a position in a tree hierarchy

sql_variant

Stores values of various other data types

xml

Is XML data stored in an internal format

cursor

Is used for variables that need to hold a reference


to a cursor

table

Holds an entire resultset

geometry,
geography

Are used to hold spatial data

Demonstration 4A: rowversion Data Type


In this demonstration you will see:
How to use the rowversion data type

Lab 2: Working with Data Types


Exercise 1: Choosing Appropriate Data Types
Exercise 2: Writing Queries With Data Type Conversions
Challenge Exercise 3: Designing and Creating Alias Data

Types (Only if time permits)

Logon information

Virtual machine

10776A-MIA-SQL1

User name

AdventureWorks\Administrator

Password

Pa$$w0rd

Estimated time: 45 minutes

Lab Scenario
A new developer has sought your assistance in deciding
which data types to use for three new tables she is
designing. She presents you with a list of organizational
data requirements for each table. You need to decide on
appropriate data types for each item.
You need to export some data from your existing system
but while being exported, some of the columns need to be
converted to alternate data types.
If you have time, there is another issue that your manager
would like you to address. She is concerned about a lack of
consistency in the use of data types across the
organization. At present, she is concerned about email
addresses and phone numbers. You need to review the
existing data types being used in the MarketDev database
for this and create new data types that can be used in
applications, to avoid this inconsistency.

Lab Review
What data type should I use to store the number of

seconds since midnight?

Which of the following columns are likely to be nullable:

YTD_Sales, DateOfBirth?

Module Review and Takeaways


Review Questions
Best Practices

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy