What are the different data types and functions in SQL Server 2012
Comments
Content
03 | SQL Server Data Types
Querying Microsoft SQL Server 2012 Jump Start
01 | Introducing SQL Server 2012
SQL Server types of statements; other SQL statement elements; basic SELECT statements
02 | Advanced SELECT Statements
DISTINCT, Aliases, scalar functions and CASE, using JOIN and MERGE; Filtering and sorting data, NULL
values
03 | SQL Server Data Types
Introduce data types, data type usage, converting data types, understanding SQL Server function types
04 | Grouping and Aggregating Data
Aggregate functions, GROUP BY and HAVING clauses, subqueries; self-contained, correlated, and EXISTS; Views, inline-table
valued functions, and derived tables
| Lunch Break
Eat, drink, and recharge for the afternoon session
Exact numeric
Unicode characters
Approximate numeric
Binary strings
Date and time
Other
Character strings
Data type
Range
Storage (bytes)
DECLARE
tinyint @mydecimal
0 toAS
255DECIMAL(8,2)
smallint
int
1
-32,768 to 32,768
2^31 (-2,147,483,648) to
2^31-1 (2,147,483,647)
2
4
Data Type
Range
float(n)
Bigint
- 1.79E+308 to -2.23E-308, 0 and 2.23E-308 to
-2^63 - 2^63-1
1.79E+308
Depends on value of n, 4 or 8
8
bytes
bit
- 3.40E + 38 to -1.18E - 38, 0 and 1.18E - 38 to
3.40E + 38 1, 0 or NULL
4
real
(+/- 9 quintillion)
Storage (bytes)
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
Data Type
Range
Storage (bytes)
binary(n)
1-8000 bytes
n bytes
varbinary(n)
1-8000 bytes
n bytes + 2
varbinary(MAX)
1-2.1 billion (approx) bytes
actual length + 2
Data Type
Range
Storage
(bytes)
Remarks
rowversion
Auto-generated
8
Successor type to timestamp
uniqueidentifier
Auto-generated
16
Globally unique identifier
(GUID)
xml
0-2 GB
0-2 GB
Stores XML in native hierarchical
structure
cursor
N/A
N/A
Not a storage data type
hierarchyid
N/A
Depends on
content
Represents position in a
hierarchy
sql_variant
0-8000 bytes
Depends on
content
Can store data of various data
types
table
N/A
N/A
Not a storage data type, used
for query and programmatic
operations
Converting strings with PARSE
PARSE element
Comment
String_value
Formatted nvarchar(4000) input
Data_type
Requested data type ouput
Culture
Optional string in .NET culture form:
en-US, es-ES, ar-SA, etc.
SELECT PARSE('02/12/2012' AS datetime2 USING 'en-US')
AS parse_result;
Data Type
Range
Storage
CHAR(n),
NCHAR(n)
1-8000 characters
n bytes, padded
2*n bytes, padded
VARCHAR(n), NVARCHAR(n)
1-8000 characters
n+2 bytes
(2*n) +2 bytes
VARCHAR(MAX),
NVARCHAR(MAX)
1-2^31-1 characters
Actual length + 2
SELECT BusinessEntityID, FirstName, LastName,
FirstName + N' ' + LastName AS FullName
FROM Person.Person;
SELECT AddressLine1, City, StateProvinceID,
CONCAT(AddressLine1, ', ' + City, ', ' + PostalCode) AS
Location
FROM Person.Address
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 bytes used.
SELECT SalesOrderID, CustomerID, OrderDate
DATE
'YYYYMMDD'
'20120212'
FROM Sales.SalesOrderHeader
'YYYY-MM-DD'
'2012-02-12'
WHERE OrderDate
= '20070825';
TIME
'hh:mm:ss.nnnnnnn'
'12:30:15.1234567'
DATETIMEOFFSET
DECLARE @DateOnly DATETIME = '20120212';
SELECT @DateOnly;
RESULT
----------------------2012-02-12 00:00:00.000
SELECT SalesOrderID, CustomerID, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate = '20070825';
SELECT SalesOrderID, CustomerID, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate >= '20070825'
AND OrderDate < '20070826';
• Functions that modify
return date
dateof
and
and
time
time
from
values
parts
part
dates
and
times
Function
Function
Function
Function
DATEADD()
DATEFROMPARTS()
GETDATE()
Syntax
Syntax
Syntax
Return Type
Remarks
Return Type
Remarks
Return
Remarks
DATEADD(datepart,
interval,
date)
Adds
interval
to date,
Type
DATEFROMPARTS(year,
month,
day)
date
datetime
Current
date and
time.
No time
zonereturns
offset.same
datatype as date
DATENAME()
DATENAME(datepart, date)
nvarchar
Use 'year', 'month', 'day' as datepart
EOMONTH()
EOMONTH(start_date,
interval)
Returns
last
day of
month as start date,
DATETIMEFROMPARTS()
DATETIMEFROMPARTS(year,
month,
day,
hour,
datetime
GETUTCDATE()
datetime
Current
date
and
time in
UTC.
optional offset
minute,
seconds, milliseconds)
DATEPART()
DATEPART(datepart,
date)
int
Usewith
'year',
'month', 'day' as datepart
CURRENT_TIMESTAMP()
datetime
Current
date
and
time.
No time zone
offset.
SWITCHOFFSET()
SWITCHOFFSET(datetimeoffset,month, day,Changes
offset
DATETIME2FROMPARTS()
DATETIME2FROMPARTS(year,
hour, time zone
Datetime2
ANSI
standard.
time_zone)
DAY()
DAY(datevalue)minute,
int precision)
seconds, fractions,
SYSDATETIME()
datetime2
Current date and
time. No
time zone
TODATETIMEOFFSET()
TODATETIMEOFFSET(expression,
Converts
intooffset
datetimeoffset
DATETIMEOFFSETFROMPARTS()
DATETIMEOFFSETFROMPARTS(year,
month,
day, datetime2
datetime
MONTH()
MONTH(datevalue)
int
time_zone)
hour, minute, seconds, fractions, hour_offset,
STSUTCDATETIME()
datetime2
Current date and time in UTC.
minute_offset, precision)
YEAR()
YEAR(datevalue)
int
SMALLDATETIMEFROMPARTS()
SMALLDATETIMEFROMPARTS(year,
month,
day, hour,
SYSDATETIMEOFFSET()
datetimeoffset
Current date
and time.
Includessmalldatetime
time zone offset
minute)
SELECT CURRENT_TIMESTAMP();
Syntax
Remarks
DATENAME(year,'20120212');
SELECT SYSUTCDATETIME();
SELECT DAY('20120212');
DATEDIFF()
DATEDIFF(datepart, start_date, end_date)
Returns the difference in dateparts
Function
SELECT
between two dates
SELECT DATEFROMPARTS(2012,2,12);
ISDATE()
ISDATE(expression)
Determines whether a datetime or
SELECT DATETIME2FROMPARTS(2012,2,12,8,30,0,0,0);
smalldate time is a valid value
SELECT CAST(SYSDATETIME() AS date) AS ‘TodaysDate’;
--attempt to convert datetime2 to int
SELECT CAST(SYSDATETIME() AS int);
Msg 529, Level 16, State 2, Line 1
Explicit conversion from data type datetime2 to int is
not allowed.
Converting with CONVERT
SELECT CONVERT(CHAR(8), CURRENT_TIMESTAMP,112) AS ISO_style;
ISO_style
--------20120212
Function Category
Description
Scalar
Operate on a single row, return a
single value
Grouped Aggregate
Take one or more values but return a
single, summarizing value
Window
Operate on a window (set) of rows
Rowset
Return a virtual table that can be
used subsequently in a T-SQL
statement
Date and Time functions
Scalar Function
Categories
SELECT SalesOrderID, YEAR(OrderDate) AS
• Configuration
OrderYear
• Conversion
FROM Sales.SalesOrderHeader;
• Cursor
• Date and Time
• Logical
Mathematical functions
• Mathematical
SELECT ABS(-1.0), ABS(0.0), ABS(1.0);
• Metadata
• Security
Conversion functions
• String
SELECT CAST(SYSDATETIME() AS date); • System
• System Statistical
• Text and Image
Metadata functions
SELECT DB_NAME() AS current_database;
SELECT TOP(5) ProductID, Name, ListPrice,
RANK() OVER(ORDER BY ListPrice DESC) AS RankByPrice
FROM Production.Product
ORDER BY RankByPrice;