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
Module 6 Working with SQL Server 2016 Data Types

2 Working with Date and Time Data
Module Overview 6: Working with SQL Server 2016 Data Types Working with Date and Time Data

3 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.

4 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 which 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

5 Exact 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 Books Online. 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 may 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 Books Online: Decimal and Numeric (Transact SQL) Precision, Scale, and Length (Transact-SQL) Data Types (Transact-SQL) Float and Real (Transact-SQL)

6 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 Books Online. 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.

7 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 may 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.

8 20761A 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 Books Online for a full list.

9 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)

10 Demonstration: SQL Server Data Types
6: Working with SQL Server 2016 Data Types In this demonstration, you will see how to: Convert data types Emphasize to students that this functionality is identical between Azure SQL Server and a locally-installed version. Preparation Steps 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 Start the MSL-TMG1, 20761A-MIA-DC, and 20761A-MIA-SQL virtual machines. Demonstration Steps Convert Data Types Ensure that the 20761A-MIA-DC, and 20761A-MIA-SQL virtual machines are running, and then log on to 20761A-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd. Start SQL Server Management Studio and connect to your Azure instance of the AdventureWorksLT database engine instance using SQL Server authentication. If the New Firewall Rule dialog box appears, click Sign In, enter your Azure credentials, and then click Sign in. In the New Firewall Rule dialog box, ensure Add my client IP is selected, and then click OK. If the Microsoft SQL Server Management Studio dialog box appears, click OK. Open the Demo.ssmssln solution in the D:\Demofiles\Mod06\Demo folder. If the Solution Explorer pane is not visible, on the View menu, click Solution Explorer. Expand Queries, and double-click the 11 – Demonstration A.sql script file. In the Available Databases list, click AdventureWorksLT. Select the code under the comment Step 2, and then click Execute. Select the code under the comment Step 3, and then click Execute. Select the code under the comment Step 4, and then click Execute. Keep SQL Server Management Studio open for the next demonstration.

11 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.

12 20761A 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 Multi-byte: 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 Books Online.

13 Collation Collation is a collection of properties for character data
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';

14 20761A 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;

15 Character String Functions
6: Working with SQL Server 2016 Data Types Common functions which 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. The FORMAT function is mentioned in the workbook, though not on this slide.

16 20761A 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%';

17 Demonstration: Working with Character Data
6: Working with SQL Server 2016 Data Types In this demonstration, you will see how to: Manipulate character data Preparation Steps Complete the previous demonstration in this module. Alternatively, start the MSL-TMG1, 20761A-MIA-DC, and 20761A-MIA-SQL virtual machines, log on to 20761A-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd, and connect to your Azure copy of the AdventureWorksLT database. Demonstration Steps Manipulate Character Data Ensure that you have completed the previous demonstration in this module. Alternatively, start the MSL-TMG1, 20761A-MIA-DC, and 20761A-MIA-SQL virtual machines, log on to 20761A-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd. If SQL Server Management Studio is not already open, start it and connect to your Azure instance of the AdventureWorksLT database engine instance using SQL Server authentication, and then open the Demo.ssmssln solution in the D:\Demofiles\Mod06\Demo folder. In Solution Explorer, open the 21 – Demonstration B.sql script file. In the Available Databases list, click AdventureWorksLT. Select the code under the comment Step 2, and then click Execute. Select the code under the comment Step 3, and then click Execute. Select the code under the comment NOTE: this will return no results, and then click Execute. Select the code under the comment Step 4, and then click Execute. Select the code under the comment Step 5, and then click Execute. Select the code under the comment Step 6, and then click Execute. Select the code under the comment end FORMAT example, and then click Execute. Select the code under the comment Step 7, and then click Execute. Keep SQL Server Management Studio open for the next demonstration.

18 Lesson 3: Working with Date and Time Data
6: Working with SQL Server 2016 Data Types Demonstration: Working with Date and Time Data

19 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]

20 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 = ' ';

21 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;

22 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 < ' ';

23 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.

24 Demonstration: Working with Date and Time Data
6: Working with SQL Server 2016 Data Types In this demonstration, you will see how to: Query date and time values Preparation Steps Complete the previous demonstration in this module. Alternatively, start the MSL-TMG1, 20761A-MIA-DC and 20761A-MIA-SQL virtual machines, log on to 20761A-MIA-SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd, and connect to your Azure copy of the AdventureWorksLT database.. Demonstration Steps Query Data and Time Values Ensure that you have completed the previous demonstration in this module. Alternatively, start the MSL-TMG1, 20761A-MIA-DC, and 20761A-MIA-SQL virtual machines, then log on to 20761A-MIA- SQL as ADVENTUREWORKS\Student with the password Pa$$w0rd. If SQL Server Management Studio is not already open, start it and connect to your Azure instance of the AdventureWorksLT database engine instance using SQL Server authentication, and then open the Demo.ssmssln solution in the D:\Demofiles\Mod06\Demo folder. In Solution Explorer, open the 31 – Demonstration C.sql script file. In the Available Databases list, click AdventureWorksLT. Select the code under the comment Step 2, and then click Execute. Select the code under the comment Step 3, and then click Execute. Select the code under the comment Step 4, and then click Execute. Select the code under the comment Step 5, and then click Execute. Select the code under the comment Step 6, and then click Execute. Select the code under the comment Step 7, and then click Execute. Close SQL Server Management Studio without saving any files.

25 Lab: Working with SQL Server 2016 Data Types
Exercise 4: Writing Queries That Use Character Functions Remind students that without an ORDER BY, the lab exercises may return results in a different order to the supplied lab answers. If they want to check results, they can add an ORDER BY clause, both to their solution and the provided one. This will affect all labs! Exercise 1: Writing Queries That Return Date and Time Data Before you start using different date and time functions in business scenarios, you should practice on sample data. Exercise 2: Writing Queries That Use Date and Time Functions The sales department wants to have different reports that focus on data during specific time frames. The sales staff would like to analyze distinct customers, distinct products, and orders placed near the end of the month. You should write the SELECT statements using the different date and time functions. Exercise 3: Writing Queries That Return Character Data Members of the marketing department would like to have a more condensed version of a report for when they talk with customers. They want the information that currently exists in two columns displayed in a single column. Exercise 4: Writing Queries That Use Character Functions The marketing department want to address customers by their first and last names. In the Sales.Customers table, there is only one column named contactname—it has both elements separated by a comma. You will have to prepare a report to show the first and last names separately. Logon Information Virtual machine: 20761A-MIA-SQL User name: ADVENTUREWORKS\Student Password: Pa$$w0rd Estimated Time: 90 Minutes

26 20761A Lab Scenario 6: Working with SQL Server 2016 Data Types You are an Adventure Works business analyst who will be writing reports using corporate databases stored in SQL Server You have been given a set of business requirements for data and you will write T-SQL queries to retrieve the specified data from the databases. You will need to retrieve and convert character, and date and time data into various formats.

27 Module Review and Takeaways
6: Working with SQL Server 2016 Data Types Review Question(s) Review Question(s) Question Will SQL Server be able to successfully and implicitly convert an int data type to a varchar? Answer No, int has a higher type precedence than varchar. What data type is suitable for storing Boolean flag information, such as TRUE or FALSE? The bit data type. What logical operators are useful for retrieving ranges of date and time values? >=, <


Download ppt "Working with SQL Server 2016 Data Types"

Similar presentations


Ads by Google