Presentation is loading. Please wait.

Presentation is loading. Please wait.

Working with SQL Server 2016 Data Types

Similar presentations


Presentation on theme: "Working with SQL Server 2016 Data Types"— Presentation transcript:

1 Working with SQL Server 2016 Data Types
20761B 6: Working with SQL Server 2016 Data Types Module 6 All demonstrations in this module use a Microsoft Azure® SQL Database running a copy of the AdventureWorksLT database. Before attempting to run these demos, ensure you have a copy of AdventureWorksLT running on an Azure instance. For detailed steps on creating a copy of the AdventureWorksLT database in Azure see: D:\Creating an AdventureWorks Database on Azure.docx. Working with SQL Server 2016 Data Types

2 Lesson 1: Introducing SQL Server 2016 Data Types
20761B Lesson 1: Introducing SQL Server 2016 Data Types 6: Working with SQL Server 2016 Data Types Demonstration: SQL Server Data Types Note that character and date/time datatypes will be covered in later lessons.

3 SQL Server supplies built-in data types
SQL Server Data Types 6: Working with SQL Server 2016 Data Types SQL Server associates columns, expressions, variables and parameters with data types Data types determine the kind of data that can be held in a column or variable Integers, characters, dates, decimals, binary strings, and so on SQL Server supplies built-in data types Developers can also define custom data types Point out that approximate numeric data types (also referred to as floating point numbers) are typically used in scientific applications; business applications most commonly use exact numeric types. SQL Server Data Type Categories Exact numeric Unicode character strings Approximate numeric Binary strings Date and time Other Character strings

4 Exact Numeric Data Types
20761B Numeric Data Types 6: Working with SQL Server 2016 Data Types Exact Numeric Data Types Data Type Range Storage (bytes) tinyint 0 to 255 1 smallint -32,768 to 32,768 2 int 231 (-2,147,483,648) to (2,147,483,647) 4 bigint (+/- 9 quintillion) 8 bit 1, 0 or NULL decimal/numeric through 1038 – 1 when maximum precision is used 5-17 money -922,337,203,685, to 922,337,203,685, smallmoney -214, to 214, Note that not all content from the tables is printed in the workbook—use the links provided to show the references in the SQL Server 2016 Technical Documentation. Point out that numeric data types should be selected on the data they will need to store; storage considerations should be secondary. The int data type has often been the default choice amongst the integer data types, but might not always be most suitable. 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. Float mantissa value: The default value for the optional float mantissa (the number of bits used to store the mantissa of the float number in scientific notation) is 53. float(53) is a synonym for double precision (the double data type in various programming languages including C# and VB.Net). For more information, see the following topics in the SQL Server 2016 Technical Documentation: Decimal and Numeric (Transact SQL) Precision, Scale, and Length (Transact-SQL) Data Types (Transact-SQL) Float and Real (Transact-SQL)

5 Binary String Data Types
6: Working with SQL Server 2016 Data Types Binary string data types The image data type is also a binary string type but is marked for removal in a future version of SQL Server; varbinary(max) should be used instead Data Type Range Storage (bytes) binary(n) 1 to 8000 bytes n bytes varbinary(n) n bytes + 2 varbinary(max) 1 to 2.1 billion (approx.) bytes See the binary and varbinary (Transact-SQL) topic in the SQL Server 2016 Technical Documentation. Note that all data, regardless of the data type, is held in a binary format in SQL Server. Unlike other data types, the binary string data types store and retrieve binary data without modification or implicit formatting.

6 Other Data Types Data Type Range Storage (bytes) Remarks xml 0-2 GB
6: Working with SQL Server 2016 Data Types Data Type Range Storage (bytes) Remarks xml 0-2 GB Stores XML in native hierarchical structure uniqueidentifier Auto-generated 16 Globally unique identifier (GUID) hierarchyid n/a Depends on content Represents position in a hierarchy rowversion 8 Previously called timestamp geometry Shape definitions in Euclidian geometry geography Shape definitions in round-earth geometry sql_variant bytes Can store data of various other data types in the same column cursor Not a storage datatype—used for cursor operations table Not a storage data type—used for query operations Rowversion: note that, in previous versions of SQL Server, this data type was called timestamp, even though no date/time information was stored. For more information on XML, see Course Some of these types (cursors, sql_variant, and so on) are only listed for completeness. Don't get bogged down in details here. There's no need to get into design discussions at this stage, but you might wish to point out that the use of sql_variant probably means poor analysis of the problem and a lack of normalization. Students familiar with other RDBMS systems may be aware that some of them offer table (or its equivalent) as a storage data type. In SQL Server 2016, XML or JSON offer the equivalent functionality.

7 20761B Data Type Precedence 6: Working with SQL Server 2016 Data Types Data type precedence determines which data type will be chosen when expressions of different types are combined By default, the data type with the lower precedence is converted to the data type with the higher precedence It is important to understand implicit conversions Conversion to a data type of lower precedence must be made explicitly (using CAST or CONVERT functions) Example precedence (low to high) CHAR -> VARCHAR -> NVARCHAR -> TINYINT -> INT -> DECIMAL -> TIME -> DATE -> DATETIME2 -> XML Not all combinations of data type have a conversion (implicit or explicit) Note that not all the SQL Server data types are included in the precedence example—see Data Type Precedence (Transact-SQL) in the SQL Server 2016 Technical Documentation for a full list.

8 When are Data Types Converted?
20761B When are Data Types Converted? 6: Working with SQL Server 2016 Data Types Data type conversion scenarios When data is moved, compared to or combined with other data During variable assignment Implicit conversion When comparing data of one data type to another Transparent to the user Explicit conversion Uses CAST or CONVERT functions Code samples are fragments for illustration only. Note that conversion functions will be covered later in the course. Questions in workbook: In the example, which data type will be converted? To which data type will it be converted? 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. WHERE <column of smallint type> = <value of int type> CAST(unitprice AS INT)

9 Lesson 2: Working with Character Data
20761B Lesson 2: Working with Character Data 6: Working with SQL Server 2016 Data Types Demonstration: Working with Character Data Question You have the following query: SELECT FirstName FROM HumanResources.Employees WHERE FirstName LIKE N'[^MA]%' Will the query return an employee with the first name ‘Matthew’? Answer No.

10 20761B Character Data Types 6: Working with SQL Server 2016 Data Types SQL Server supports two kinds of character data as fixed-width or variable-width data: Single-byte: char and varchar One byte stored per character Only 256 possible characters—limits language support Multibyte: nchar and nvarchar Multiple bytes stored per character (usually two bytes, but sometimes up to four) More than 65,000 characters represented—multiple language support Precede character string literals with N (National) text and ntext data types are deprecated, but may still be used in older systems In new development, use varchar(max) and nvarchar(max) instead For a detailed discussion of Unicode character support, including a discussion on Unicode characters occupying more than two bytes (the Supplementary Characters section), see Collation and Unicode Support in the SQL Server 2016 Technical Documentation.

11 Collation Collation is a collection of properties for character data
20761B Collation 6: Working with SQL Server 2016 Data Types Collation is a collection of properties for character data Character set Sort order Case sensitivity Accent sensitivity When querying, collation awareness is important for comparison Is the database case-sensitive? If so: 'Funk‘ does not equal 'funk‘ SELECT * FROM HR.Employee does not equal SELECT * FROM HR.employee Add COLLATE clause to control collation comparison For some students, it may be helpful to point out that all character data is stored as binary data, and that data type and collation determine how the binary data is interpreted by the database engine for comparison and display. SELECT empid, lastname FROM HR.employees WHERE lastname COLLATE Latin1_General_CS_AS = N'Funk';

12 20761B String Concatenation 6: Working with SQL Server 2016 Data Types The + (plus) operator and the CONCAT function can both be used to concatenate strings in SQL 2016 Using CONCAT Converts input values to strings and converts NULL to empty string Using + (plus) No conversion of NULL or data type SELECT custid, city, region, country, CONCAT(city, ', ' + region, ', ' + country) AS location FROM Sales.Customers It might be helpful to students to discuss how the example CONCAT query takes advantage of the different NULL handling behavior of CONCAT and + to eliminate redundant commas in the result. Note that the ISNULL and COALESCE functions, covered later in the course, were often previously used to convert NULLs to empty strings. CONCAT now handles that. Note that the behavior of + when concatenating NULL values is actually dependent on the session parameter CONCAT_NULL_YIELDS_NULL (ON by default). However, setting CONCAT_NULL_YIELDS_NULL to any value other than ON is marked for deprecation, so this will become less important in future. SELECTcustid, city, region, country, CONCAT(city, ', ' + region, ', ' + country) AS location FROM Sales.Customers; SELECT empid, lastname, firstname, firstname + N' ' + lastname AS fullname FROM HR.Employees;

13 Character String Functions
20761B Character String Functions 6: Working with SQL Server 2016 Data Types Common functions that modify character strings 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 up to integer value. LEN, DATALENGTH LEN (string_expression) DATALENGTH (expression) LEN returns the number of characters in string_expression, excluding trailing spaces. DATALENGTH returns the number of bytes used. CHARINDEX CHARINDEX (expressionToFind, expressionToSearch) Searches expressionToSearch for expressionToFind and returns its start position if found. REPLACE REPLACE (string_expression , string_pattern , string_replacement) Replaces all occurrences of string_pattern in string_expression with string_replacement. UPPER, LOWER UPPER (character_expression) LOWER (character_expression) UPPER converts all characters in a string to uppercase. LOWER converts all characters in a string to lowercase. If time permits, also introduce LTRIM, RTRIM, REPLICATE and STUFF. Note: the FORMAT function is mentioned in the workbook, though not on this slide.

14 20761B The LIKE Predicate 6: Working with SQL Server 2016 Data Types The LIKE predicate can be used to check a character string for a match with a pattern Patterns are 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 characters that would otherwise be treated as part of a pattern - %, _, [, and ]) Note that SQL Server does not natively provide support for more complex pattern-matching tools such as regular expressions. SELECT categoryid, categoryname, description FROM Production.Categories WHERE description LIKE 'Sweet%';

15 Lesson 3: Working with Date and Time Data
20761B Lesson 3: Working with Date and Time Data 6: Working with SQL Server 2016 Data Types Demonstration: Working with Date and Time Data

16 Date and Time Data Types
20761B Date and Time Data Types 6: Working with SQL Server 2016 Data Types Older versions of SQL Server support only datetime and smalldatetime data types SQL Server 2008 introduced date, time, datetime2 and datetimeoffset data types SQL Server 2012 added further functionality for working with date and time data types Emphasize that datetime2, date, time, and datetimeoffset are recommended for new development because they are compliant with the ANSI SQL standard, offer better accuracy, and support a wider range of dates. The storage size for datetime2, date, and datetimeoffset can vary because these types can be defined with an optional scale parameter that limits their precision (and therefore the storage they require). Data Type Storage (bytes) Date Range (Gregorian Calendar) Accuracy Recommended Entry Format datetime 8 January 1, 1753 to December 31, 9999 Rounded to increments of .000, .003, or .007 seconds YYYYMMDD hh:mm:ss[.mmm] smalldatetime 4 January 1, 1900 to June 6, 2079 1 minute datetime2 6 to 8 January 1, 0001 to December 31, 9999 100 nanoseconds YYYYMMDD hh:mm:ss[.nnnnnnn] date 3 1 day YYYY-MM-DD time 3 to 5 n/a – time only hh:mm:ss[.nnnnnnn] datetimeoffset 8 to 10 YYYY-MM-DDThh:mm:ss[.nnnnnnn][{+|-}hh:mm]

17 Entering Date and Time Data Types Using Strings
20761B Entering Date and Time Data Types Using Strings 6: Working with SQL Server 2016 Data Types SQL Server doesn't offer a means to enter a date or time value as a literal value 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, and can cause confusion Best practices: Use character strings to express date and time values Use language-neutral formats SQL Server 2012 added the PARSE function to parse date string literals and indicate the culture. For example: SELECT PARSE('7/17/2011' AS DATE USING 'en-US') AS dt; Go to PARSE (Transact-SQL) at: PARSE (Transact-SQL) PARSE, TRY_PARSE and TRY_CONVERT will be covered in a later module. Note: the range of values for the offset in datetimeoffset is +/- 14 hours (time zones). For more information, see: datetimeoffset (Transact-SQL) SELECT orderid, custid, empid, orderdate FROM Sales.Orders WHERE orderdate = ' ';

18 Working Separately with Date and Time
20761B Working Separately with Date and Time 6: Working with SQL Server 2016 Data Types datetime, smalldatetime, datetime2, and datetimeoffset include both date and time data If only date is specified, time set to midnight (all zeros) If only time is specified, date set to base date (January 1, 1900) AS datetime2 = ' '; AS Result; AS time = '12:34:56'; SELECT AS datetime2) AS Result;

19 Querying Date and Time Values
20761B Querying Date and Time Values 6: Working with SQL Server 2016 Data Types 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 Consider discussing the disadvantages of using a BETWEEN predicate (either missing a day or including data from an additional day) instead of >= and < as part of discussing the second example. SELECT orderid, custid, empid, orderdate FROM Sales.Orders WHERE orderdate= ' '; SELECT orderid, custid, empid, orderdate FROM Sales.Orders WHEREorderdate >= ' ' ANDorderdate < ' ';

20 Date and Time Functions
20761B Date and Time Functions 6: Working with SQL Server 2016 Data Types To get system date and time values For example, GETDATE, GETUTCDATE, SYSDATETIME To get date and time parts For example, DATENAME, DATEPART To get date and time values from their parts For example, DATETIME2FROMPARTS, DATEFROMPARTS To get date and time difference For example, DATEDIFF, DATEDIFF_BIG To modify date and time values For example, DATEADD, EOMONTH To validate date and time values For example, ISDATE Note that, for functions that construct date and time data types from parts, all arguments are required. For example, DATETIME2FROMPARTS requires eight arguments. Not all date and time functions are available in all versions of SQL Server. SQL Server 2016 adds the DATEDIFF_BIG function, which works in the same way as DATEDIFF but returns a bigint data type.


Download ppt "Working with SQL Server 2016 Data Types"

Similar presentations


Ads by Google