1 / 37

Brian Alderman | MCT, CEO / Founder of MicroTechPoint

03 | SQL Server Data Types. Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager. Course Topics. Introduce data types Character data types Date and time data type Built-in functions. Module Overview. Data Types.

Download Presentation

Brian Alderman | MCT, CEO / Founder of MicroTechPoint

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 03 | SQL Server Data Types Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager

  2. Course Topics

  3. Introduce data types Character data types Date and time data type Built-in functions Module Overview

  4. Data Types

  5. SQL Server data types • SQL Server associates columns, expressions, variables, and parameters with data types • Data types determine what kind of data can be stored in the field: • Integers, characters, dates, money, binary strings, etc. • SQL Server supplies several built-in data types • Developers can also define custom types • Aliases in T-SQL • User-defined types in .NET code • Built-in data types are categorized as shown in the table below

  6. Numeric data types • Exact Numeric • Decimal/numeric are functionally equivalent and use precision and scale parameters: • Approximate Numeric • float(24) is the ISO synonym for float • In float(n), n is the number of bytes used to store the mantissa of the float number in scientific notation • Values of float are truncated when converted to integer types DECLARE @mydecimal AS DECIMAL(8,2)

  7. Binary stringdata types • Binary Strings

  8. Otherdata types

  9. Converting strings with PARSE • PARSE is new function in SQL Server 2012 that converts strings to date, time, and number types • PARSE example: SELECT PARSE('02/12/2012' AS datetime2 USING'en-US') AS parse_result;

  10. Character Data Types

  11. Character data types • SQL Server supports two kinds of character data types: • Regular: CHAR, VARCHAR • One byte stored per character • Only 256 possible characters – limits language support • Unicode: NCHAR, NVARCHAR • Two bytes stored per character • 65k characters represented – multiple language support • Precede characters with N' (National) • TEXT, NTEXT deprecated • Use VARCHAR(MAX), NVARCHAR(MAX) instead • CHAR, NCHAR are fixed length • VARCHAR, NVARCHAR are variable length • Character data is delimited with single quotes

  12. String concatenation • SQL Server uses the + (plus) sign to concatenate characters: • Concatenating a value with a NULL returns a NULL • SQL Server 2012 introduces CONCAT() function • Converts NULL to empty string before concatenation SELECT BusinessEntityID, FirstName, LastName, FirstName + N' ' + LastNameASFullName FROMPerson.Person; SELECT AddressLine1, City, StateProvinceID, CONCAT(AddressLine1, ', ' + City, ', ' + PostalCode) AS Location FROMPerson.Address

  13. Character string functions • Common functions that modify character strings

  14. The LIKE predicate • The LIKE predicate used to check a character string against a pattern • Patterns expressed with symbols • % (Percent) represents a string of any length • _ (Underscore) represents a single character • [<List of characters>] represents a single character within the supplied list • [<Character> - <character>] represents a single character within the specified range • [^<Character list or range>] represents a single character not in the specified list or range • ESCAPE Character allows you to search for a character that is also a wildcard character (%, _, [, ] for example) SELECTProductLine, Name,ProductNumber FROMProduction.Product WHERE Name LIKE 'Mountain%'

  15. Demo Character data types

  16. Date and Time Data Types

  17. Date and time data types • Older versions of SQL Server supported only DATETIME and SMALLDATETIME • DATE, TIME, DATETIME2, and DATETIMEOFFSET introduced in SQL Server 2008

  18. Date and time data types: literals • SQL Server doesn't offer an option for entering a date or time value explicitly • Dates and times are entered as character literals and converted explicitly or implicitly • For example, CHAR converted to DATETIME due to precedence • Formats are language-dependent, can cause confusion • Best practices: • Use character strings to express date and time values • Use language-neutral formats SELECTSalesOrderID, CustomerID, OrderDate FROMSales.SalesOrderHeader WHEREOrderDate= '20070825';

  19. Working with date and time separately • DATETIME, SMALLDATETIME, DATETIME2, and DATETIMEOFFSET include both date and time data • If only date is specified, time set to midnight (all zeroes) • If only time is specified, date set to base date(January 1, 1900) DECLARE @DateOnly DATETIME = '20120212'; SELECT@DateOnly; RESULT ----------------------- 2012-02-12 00:00:00.000

  20. Querying date and time values • Date values converted from character literals often omit time • Queries written with equality operator for date will match midnight • If time values are stored, queries need to account for time past midnight on a date • Use range filters instead of equality SELECTSalesOrderID, CustomerID, OrderDate FROMSales.SalesOrderHeader WHEREOrderDate = '20070825'; SELECT SalesOrderID, CustomerID, OrderDate FROMSales.SalesOrderHeader WHERE OrderDate >= '20070825' ANDOrderDate< '20070826';

  21. Date and time functions • Functions that return current date and time • Functions that return date and time from parts • Functions that modify date and time values • Functions that operate on date and time values • Functions that return part of dates and times SELECTDATEADD(day,1,'20120212'); SELECTEOMONTH('20120212'); SELECT CURRENT_TIMESTAMP(); SELECT SYSUTCDATETIME(); SELECT DATENAME(year,'20120212'); SELECT DAY('20120212'); SELECT DATEFROMPARTS(2012,2,12); SELECT DATETIME2FROMPARTS(2012,2,12,8,30,0,0,0);

  22. Converting with CAST • Converts a value from one data type to another • Can be used in SELECT and WHERE clauses • ANSI standard • Truncation can occur if converting to smaller data type • CAST Example: • Returns an error if data types are incompatible: SELECTCAST(SYSDATETIME() AS date) AS‘TodaysDate’; --attempt to convert datetime2 to int SELECTCAST(SYSDATETIME() ASint); Msg 529, Level 16, State 2, Line 1 Explicit conversion from data type datetime2 to int is not allowed.

  23. Converting with CONVERT • Converts a value from one data type to another • Can be used in SELECT and WHERE clauses • CONVERT is specific to SQL Server, not standards-based • Style specifies how input value is converted: • Date, time, numeric, XML, etc. Example: • SELEC SELECT CONVERT(CHAR(8), CURRENT_TIMESTAMP,112) AS ISO_style; ISO_style --------- 20120212

  24. Demo Date and time function data types

  25. Built-in Functions

  26. SQL Server 2012 built-in function types • SQL Server functions can be categorized by scope of input and type of output:

  27. Scalar functions • Operate on elements from a singlerow as inputs, return a single value as output. • Return a single (scalar) value • Can be used like an expressionin queries • May be deterministic ornon-deterministic • Collation depends on input valueor default collation of database Date and Time functions Mathematical functions Conversion functions Metadata functions Scalar Function Categories SELECTSalesOrderID, YEAR(OrderDate) ASOrderYear FROMSales.SalesOrderHeader; • Configuration • Conversion • Cursor • Date and Time • Logical • Mathematical • Metadata • Security • String • System • System Statistical • Text and Image SELECTABS(-1.0), ABS(0.0), ABS(1.0); SELECT CAST(SYSDATETIME() ASdate); SELECTDB_NAME() AScurrent_database;

  28. Window functions • Functions applied to a window, or set of rows • Include ranking, offset, aggregate and distribution functions SELECT TOP(5) ProductID, Name, ListPrice, RANK() OVER(ORDER BY ListPriceDESC) ASRankByPrice FROMProduction.Product ORDER BY RankByPrice; ProductID Name ListPriceRankByPrice --------- ---------------- --------- ----------- 749 Road-150 Red, 62 3578.27 1 750 Road-150 Red, 44 3578.27 1 751 Road-150 Red, 48 3578.27 1 752 Road-150 Red, 52 3578.27 1 753 Road-150 Red, 56 3578.271

  29. Writing logical tests with functions • ISNUMERIC tests whether an input expression is a valid numeric data type • Returns a 1 when the input evaluates to any valid numeric type, including FLOAT and MONEY, otherwise returns 0 SELECT ISNUMERIC('SQL') ASisnmumeric_result; isnmumeric_result ----------------- 0 SELECT ISNUMERIC(‘101.99')AS isnmumeric_result; isnmumeric_result ----------------- 1

  30. Performing conditional tests with IIF • IIF returns one of two values, depending on a logical test • Shorthand for a two-outcome CASE expression SELECTProductID, ListPrice, IIF(ListPrice > 50, 'high', 'low') ASPricePoint FROM Production.Product;

  31. Selecting items from a list with CHOOSE • CHOOSE returns an item from a list as specified by an index value • CHOOSE example: SELECT CHOOSE (3, 'Beverages', 'Condiments', 'Confections') AS choose_result; choose_result ------------- Confections

  32. Demo Built-in functions

  33. Summary • SQL Server associates columns, expressions, variables, and parameters with data types that determines what kind of data can be stored in the field • There are seven categories of built-in data types • SQL Server Data Type Categories • Exact numeric • Unicode characters • Approximate numeric • Binary strings • Date and time • Character strings • Other

  34. Summary • There are several character string functions available • LEFT(), RIGHT() • LEN(), DATALENGTH() • CHARINDEX() • REPLACE() • UPPER(), LOWER() • SUBSTRING() • The LIKE predicate used to check a character string against a pattern • % (Percent) represents a string of any length • _ (Underscore) represents a single character

  35. Summary • There are several date and time data types available • SMALLDATETIME • DATETIME • DATETIME2 • DATE • TIME • DATETIMEOFFSET • You can use the following date and time functions to return current date and time • GETDATE() • GETUTCDATE() • CURRENT_TIMESTAMP • SYSDATETIME() • STSUTCDATETIME() • SYSDATETIMEOFFSET()

  36. Summary • Built-in function types include • Scalar • Grouped Aggregate • Window • Other functions include • ISNUMERIC • IIF • CHOOSE

More Related