Successfully reported this slideshow.
Your SlideShare is downloading. ×
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Loading in …3
×

Check these out next

1 of 143 Ad
Advertisement

More Related Content

Advertisement

More from Antonios Chatzipavlis (20)

Advertisement

Using T-SQL

  1. 1. SQL Saturday Night Using T-SQL March 30, 2013 SQL Saturday Night #19
  2. 2. Η παρουσίαση αυτή θα καταγραφεί ώστε να είναι διαθέσιμη για όσους θέλουν να την ξαναδούν, ή δεν είχαν την δυνατότητα να την παρακολουθήσουν σε πραγματικό χρόνο. Εάν κάποιος από τους παραβρισκόμενους σε αυτή έχει το οποιοδήποτε πρόβλημα ή αντίρρηση να είναι μέρος της καταγραφή αυτής, παρακαλείται να αποχωρήσει άμεσα. Σε διαφορετική περίπτωση η παραμονή σε αυτή εκλαμβάνεται ως αποδοχή της καταγραφής. Η παρουσίαση αυτή διατίθεται δωρεάν, και θα αρχίσει σε 1 λεπτό…
  3. 3. Αυτή την στιγμή ο παρουσιαστής μιλάει και σας ζητάει να βεβαιώσετε ότι τον ακούτε. Εάν αυτό δεν είναι δυνατόν παρακαλείστε να αλλάξετε το χρώμα της κάρτας σας στο αντίστοιχο χρώμα ώστε να τον ενημερώσετε. Αυτό μπορεί να γίνει πατώντας την αντίστοιχη επιλογή που βρίσκεται στο πάνω δεξί μέρος του περιβάλλοντος του live meeting. Σας ευχαριστούμε για την συνεργασία.
  4. 4. Using T-SQL SQL Saturday Night # 19 – March 30, 2013
  5. 5. SP_WHO Sotiris Fivi Antonios Karras Panopoulou Chatzipavlis SQL Server Jr. DBA SQL Server Jr. DBA SQL Server Evangelist - Microsoft Student Partner - Microsoft Student Partner - MVP on SQL Server - N.T.U.A Student - N.T.U.A Student - MCSE on Data Platform - MCSA on SQL Server 2012 - Microsoft Trainer (MCT) - MCT Regional Leader
  6. 6. SOCIAL CONNECTIONS @antoniosch @sqlschool SQL School Greece www.sqlschool.gr help@sqlschool.gr
  7. 7. Agenda Using T-SQL
  8. 8. PRESENTATION TOPICS - 1 • Introduction to Microsoft SQL Server 2012 • SQL Server Management Studio • Introduction to T-SQL Querying • SELECT Statements / Queries • Querying Multiple Tables • Sorting and Filtering Data • Grouping and Aggregating Data
  9. 9. PRESENTATION TOPICS - 2 • Using Sub-queries • Using Views, Table Value Functions and Table Expressions • Using Set Operators • Using Stored Procedures • Using Window Functions • What’s New in SQL Server 2012
  10. 10. Introduction to Microsoft SQL Server 2012
  11. 11. SQL SERVER ARCHITECTURE • Services • Instances • Tools
  12. 12. SQL SERVER VERSIONS Umachandar Jayachandran former SQL Server MVP and currently a PM on the SQL Server Perf Team.
  13. 13. SQL SERVER VERSIONS
  14. 14. SQL SERVER VERSIONS Operating Version Release Year Code Name Company System 1.0 1989 OS2 Aston Tate, Microsoft, Sybase 1.1 1991 OS2 Aston Tate, Microsoft, Sybase 4.2 1992 Windows Microsoft 4.21 1994 SQLNT Windows Microsoft 6.0 1995 SQL95 Windows Microsoft 6.5 1996 Hydra Windows Microsoft 7.0 1998 Sphinx Windows Microsoft 2000 2000 Shiloh Windows Microsoft 2005 2005 Yukon Windows Microsoft 2008 2008 Katmai Windows Microsoft 2008 R2 2010 Kilimanjaro Windows Microsoft 2012 2012 Denali Windows Microsoft
  15. 15. SQL SERVER 2012 EDITIONS Main Editions Other Editions Enterprise Parallel Data Warehouse Standard Web Business Intelligence Developer Express Express LocalDB
  16. 16. SQL SERVER DATABASES Containers Boundaries Tables Security Accounts Views Permissions Procedures Default Collations Functions Users Roles Schemas
  17. 17. SQL SERVER SYSTEM DATABASES master The system configuration database. msdb The configuration database for the SQL Server Agent service and other system services. model Τhe template for new user databases. tempdb Used by the database engine to store temporary data such as work tables. Dropped and recreated each time SQL Server restarts resource Α hidden system configuration database that provides system objects to other databases. distribution The distribution database stores metadata and history data for all types of replication, and transactions for transactional replication.
  18. 18. SSMS SQL Server Management Studio
  19. 19. SQL SERVER MANAGEMENT STUDIO (SSMS) “SQL Server Management Studio is an integrated environment for accessing, configuring, managing, administering, and developing all components of SQL Server. SQL Server Management Studio combines a broad group of graphical tools with a number of rich script editors to provide access to SQL Server to developers and administrators of all skill levels. ”
  20. 20. Using SQL Server Management Studio
  21. 21. Introduction to T-SQL Querying
  22. 22. INTRODUCING TRANSACT-SQL (T-SQL) Is the language in which you will write your queries for SQL Server. Structure Query Language (SQL) Developed by IBM in 1970 Adopted as ANSI and ISO standards Widely used in industry SQL is declarative not procedural
  23. 23. CATEGORIES OF T-SQL STATEMENTS Data Manipulation Language (DML) Statement for querying and modify data SELECT, INSERT, UPDATE, DELETE Data Definition Language (DDL) Statements for Objects definitions CREATE, ALTER, DROP Data Control Language (DCL) Statements for security permissions GRANT, DENY, REVOKE
  24. 24. PREDICATES AND OPERATORS Predicates IN, BETWEEN, LIKE Operators Precedence 1 ( ) Parentheses Comparison Operators 2 *, /, % =, >, <, >=, <=, <>, !=, !>, !< 3 +, - Logical Operators 4 =, <, >, >=, <=, !=, !>, !< 5 NOT AND, OR, NOT 6 AND Arithmetic Operators 7 8 BETWEEN, IN, LIKE, OR = +, -, *, /, % Concatenation +
  25. 25. FUNCTIONS CATEGORIES • Rowset Functions • Mathematical Functions • Aggregate Functions • Metadata Functions • Ranking Functions • Security Functions • Configuration Functions • String Functions • Conversion Functions • System Functions • Cursor Functions • System Statistical • Date and Time Data Functions Types and Functions • Logical Functions • Text and Image Functions
  26. 26. VARIABLES • Local variables in T-SQL temporarily store a value of specific data type • Name begins with single @ sign • @@ reserved for system functions • Assigned a data type • Must be declared and used within the same batch • You can declare and initialize in the same statement (from SQL Server 2008 and later) DECLARE @variablename datatype [=init value] DECLARE @myVar INT = 20;
  27. 27. EXPRESSIONS • Combination of identifiers, values and operators evaluated to obtain a single result • Can be used in many situations like • SELECT clause • WHERE clause • SET clause SELECT YEAR(SalesOrderDate) + 1 … SELECT Quantity * UnitPrice …
  28. 28. CONTROL FLOW STATEMENTS • IF…ELSE • WHILE • BREAK • CONTINUE • BEGIN…END
  29. 29. ERRORS AND ERROR HANDLING • @@error system function • RAISERROR • THROW • TRY…CATCH
  30. 30. TRANSACTION CONTROL STATEMENTS • BEGIN TRANSACTION • COMMIT TRANSACTION • ROLLBACK TRANSACTION
  31. 31. T-SQL Elements
  32. 32. COMMENTS Block comments /* SELECT … other code… */ Inline comments -- inline comment DECLARE @myVar INT = 20; -- initial value
  33. 33. BATCHES AND BATCH SEPARATOR • Batches are sets of commands sent to SQL Server as a unit • Batches determine variable scope and name resolution • To separate statements into batches SQL Server uses the GO keyword • GO is not a SQL Server command! • We can define our batch separator • GO n time feature added in SQL Server 2005 and later. DECLARE @CustomerID NCHAR(5) = ‘ANTON’; SELECT CustomerID, CompanyName FROM Orders WHERE CustomerID = @CustomerID; GO CREATE TABLE T(c1 INT); GO CREATE VIEW V AS SELECT * FROM T; GO
  34. 34. SQL SERVER DATA TYPES • SQL Server defines a set of system data types for • storing data in columns, • holding values temporarily in variables, • for operating on data in expressions, • for passing parameters in stored procedures and functions • Data Types specify the • Type • Length • Precision • Scale
  35. 35. SQL SERVER DATA TYPES CATEGORIES • Exact numeric • Approximate numeric • Date & Time • Character string • Unicode character strings • Binary string • Other data types
  36. 36. EXACT NUMERIC DATA TYPES Data type Range Storage (bytes) tinyint 0 to 255 1 smallint -32,768 to 32,768 2 int 2^31 (-2,147,483,648) to 4 2^31-1 (2,147,483,647) bigint -2^63 - 2^63-1 8 (+/- 9 quintillion) bit 1, 0 or NULL 1 decimal - 10^38 +1 through 10^38 – 1 when 5-17 maximum precision is used numeric - 10^38 +1 through 10^38 – 1 when 5-17 maximum precision is used money -922,337,203,685,477.5808 to 8 922,337,203,685,477.5807 smallmoney - 214,748.3648 to 214,748.3647 4
  37. 37. APPROXIMATE NUMERIC DATA TYPES Data Type Range Storage (bytes) float(n) - 1.79E+308 to -2.23E-308, 0 and 2.23E- Depends on value of n, 4 308 to 1.79E+308 or 8 bytes real - 3.40E + 38 to -1.18E - 38, 0 and 1.18E - 4 38 to 3.40E + 38 • 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
  38. 38. DATE & TIME DATA TYPES • Older versions of SQL Server supported only DATETIME and SMALLDATETIME • DATE, TIME, DATETIME2, and DATETIMEOFFSET introduced in SQL Server 2008 • SQL Server 2012 adds new functionality for working with date and time data types
  39. 39. DATE & TIME DATA TYPES Storage Recommended Entry Data Type Date Range Accuracy (bytes) Format DATETIME 8 January 1, 1753 to 3-1/3 'YYMMDD December 31, 9999 milliseconds hh:mm:ss:nnn' SMALLDATETIME 4 January 1, 1900 to 1 minute 'YYMMDD June 6, 2079 hh:mm:ss:nnn' DATETIME2 6 to 8 January 1, 0001 to 100 'YYMMDD December 31, 9999 nanoseconds hh:mm:ss.nnnn nn' DATE 3 January 1, 0001 to 1 day 'YYYY-MM-DD' December 31, 9999 TIME 3 to 5 100 'hh:mm:ss:nnn nanoseconds nnnn' DATETIMEOFFSET 8 to 10 January 1, 0001 to 100 'YY-MM-DD December 31, 9999 nanoseconds hh:mm:ss:nnnn nnn [+|- ]hh:mm'
  40. 40. CHARACTER STRING DATA TYPES • One byte per character Data Type Range Storage CHAR(n) 1-8000 characters n bytes, padded Fixed Length VARCHAR(n) 1-8000 characters n+2 bytes Variable Length VARCHAR(MAX) 1-2^31-1 characters Actual length + 2 Variable Length • TEXT deprecated • Use VARCHAR(MAX) instead
  41. 41. UNICODE CHARACTER STRING DATA TYPES • Two bytes per character Data Type Range Storage NCHAR(n) 1-8000 characters 2*n bytes, padded Fixed Length NVARCHAR(n) 1-8000 characters (2*n)+2 bytes Variable Length NVARCHAR(MAX) 1-2^31-1 characters Actual length + 2 Variable Length • NTEXT deprecated • Use NVARCHAR(MAX) instead
  42. 42. BINARY STRING 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 • IMAGE deprecated • Use VARBINARY(MAX) instead
  43. 43. OTHER DATA TYPES Data Type Range Storage Remarks (bytes) 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 Represents position in a content hierarchy sql_variant 0-8000 bytes Depends on Can store data of various content data types table N/A N/A Not a storage data type, used for query and programmatic operations
  44. 44. DATA TYPES PRESENTENCE • Data type precedence determines which data type will be chosen when expressions of different types are combined • Data type with the lower precedence is converted to the data type with the higher precedence • Important for understanding implicit conversions • Conversion to type of lower precedence must be made explicitly (with CAST function) • Example (low to high): • CHAR -> VARCHAR -> NVARCHAR -> TINYINT -> INT -> DECIMAL -> TIME -> DATE -> DATETIME2 -> XML
  45. 45. DATA TYPES CONVERSION • Data type conversion scenarios • When data is moved, compared, or combined with other data • During variable assignment • Implicit conversion • When comparing data of one type to another • Transparent to user WHERE <column of smallint type> = <value of int type> • Explicit conversion • Uses CAST or CONVERT functions CAST(unitprice AS int) • Not all conversions allowed by SQL Server
  46. 46. SELECT Statement The Select Statement and Writing Queries
  47. 47. SELECT STATEMENT – MAIN CLAUSES • [ WITH <common_table_expression>] • SELECT select_list [ INTO new_table ] • [ FROM table_source ] [ WHERE search_condition ] • [ GROUP BY group_by_expression ] • [ HAVING search_condition ] • [ ORDER BY order_expression [ ASC | DESC ] ]
  48. 48. SELECT STATEMENT – LOGICAL PROCESSING • FROM • ON • JOIN • WHERE • GROUP BY • WITH CUBE or WITH ROLLUP • HAVING • SELECT • DISTINCT • ORDER BY • TOP
  49. 49. Select statement – Full statement
  50. 50. SELECT DISTINCT • Specifies that only unique rows can appear in the result set • Removes duplicates based on column list results, not source table • Provides uniqueness across set of selected columns • Removes rows already operated on by WHERE, HAVING, and GROUP BY clauses • Some queries may improve performance by filtering out duplicates prior to execution of SELECT clause
  51. 51. COLUMN ALIASES • Column aliases using AS SELECT orderid, unitprice, qty AS quantity FROM OrderDetails; • Column aliases using = SELECT orderid, unitprice, quantity = qty FROM OrderDetails; • Accidental column aliases SELECT orderid, unitprice quantity FROM OrderDetails;
  52. 52. TABLE ALIASES • Create table aliases in the FROM clause • Table aliases with AS SELECT custid, orderdate FROM dbo.Orders AS SO; • Table aliases without AS SELECT custid, orderdate FROM Sales.Orders SO; • Using table aliases in the SELECT clause SELECT SO.custid, SO.orderdate FROM Sales.Orders AS SO;
  53. 53. SELECT STATEMENT – CASE EXPRESSION Simple Case expression CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END Searched CASE expression CASE WHEN boolean_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END
  54. 54. SELECT Statement
  55. 55. Querying Multiple Tables Writing Join Queries
  56. 56. JOIN CLAUSE – INTRODUCTION • By using joins, you can retrieve data from two or more tables based on logical relationships between the tables. • Three types of Joins 1. Inner Joins, which use a comparison operator to match rows from two tables based on the values in common columns from each table 2. Outer Joins, in which all the rows of the specified table(s) are returned, not just the ones in which the joined columns match 3. Cross Joins, which produce the Cartesian product of the tables involved in the join (if there is no WHERE clause present) 4. Self Joins which you need to compare and retrieve data stored in the same table • Main Join Clause SELECT select_list FROM first_table join_type second_table [ON (join_condition)] [WHERE (search_condition)]
  57. 57. T-SQL JOIN SYNTAX CHOICES • ANSI SQL-92 • Tables joined by JOIN operator in FROM Clause • Preferred syntax SELECT ... FROM Table1 JOIN Table2 ON <on_predicate> • ANSI SQL-89 • Tables joined by commas in FROM Clause • Not recommended: accidental Cartesian products! SELECT ... FROM Table1, Table2 WHERE <where_predicate>
  58. 58. Join Multiple Tables
  59. 59. Sorting & Filtering Sorting and Filtering Data
  60. 60. SORTING/FILTERING – SORTING • You can sort data retrieved by a SELECT statement using the ORDER BY clause • ORDER BY clause syntax: ORDER BY order_by_expression [ COLLATE collation_name ] [ ASC | DESC ] [ ,...n ] [ <offset_fetch> ]
  61. 61. SORTING/FILTERING – COLLATION • Specifies that the ORDER BY operation should be performed according to the collation specified in collation_name • Using collations to sort data, depending on encoding or case sensitive/accent sensitive options
  62. 62. SORTING/FILTERING – TOP/OFFSET <offset_fetch> ::= { OFFSET { integer_constant | offset_row_count_expression } { ROW | ROWS } [ FETCH { FIRST | NEXT } {integer_constant | fetch_row_count_expression } { ROW | ROWS } ONLY ] } • Specifies the number of rows to return after the OFFSET clause has been processed. The value can be an integer constant or expression that is greater than or equal to one. • Both OFFSET and FETCH can use variables as input and thus are able to be optimized for specified values of those values using the OPTIMIZE FOR hint
  63. 63. SORTING/FILTERING – WORKING WITH NULL VALUES • NULL has three logical interpretations • Unknown value • Unavailable value • Not supported value • SET ANSI_NULLS { ON | OFF } • Setting ANSI_NULLS ON, causes the SELECT statements using WHERE column_name = NULL to return zero rows even if there are null values in column_name ( thus operators =, <> follow the ISO standard) • Option in future versions ANSI_NULLS will by default be set to ON
  64. 64. Sorting & Filtering
  65. 65. Grouping & Aggregating Grouping and Aggregating Data
  66. 66. AGGREGATE FUNCTIONS • Aggregate functions perform a calculation on a set of values and return a single value. • Deterministic in nature. They return the same value any time that they are called by using a specific set of input values. List of Aggregate Functions AVG MIN CHECKSUM_AVG SUM COUNT STDEV COUNT_BIG STDEVP GROUPING VAR GROUPING_ID VARP MAX
  67. 67. GROUP BY CLAUSE • Groups sets of rows, using the values of one or more columns or expressions. • Each group is represented by one and only one row. • Usually aggregates are used to provide the grouping criterion • Can filter the groups created using the HAVING keyword • A GROUP BY clause can include GROUPING SETS, CUBE AND ROLLUP keywords
  68. 68. DISTINCT & NULL WITH AGGREGATE FUNCTIONS • Use DISTINCT with aggregate functions to summarize only unique values • DISTINCT aggregates eliminate duplicate values, not rows (unlike SELECT DISTINCT) • Most aggregate functions ignore NULL • COUNT(<column>) ignores NULL • COUNT(*) counts all rows • NULL may produce incorrect results (such as use of AVG) • Use ISNULL or COALESCE to replace NULLs before aggregating
  69. 69. GROUPING SETS • GROUPING SETS subclause builds on T-SQL GROUP BY clause • Allows multiple groupings to be defined in same query SELECT <column list with aggregate(s)> FROM <source> GROUP BY GROUPING SETS( (<column_name>),--one or more columns (<column_name>),--one or more columns () -- empty parentheses if aggregating all rows );
  70. 70. GROUPING_ID • Multiple grouping sets present a problem in identifying the source of each row in the result set • NULLs could come from the source data or could be a placeholder in the grouping set • The GROUPING_ID function provides a method to mark a row with a 1 or 0 to identify which grouping set the row is a member of SELECT GROUPING_ID(Category)AS grpCat, GROUPING_ID(CustomerID) AS grpCust, Category, CustomerID, SUM(Qty) AS TotalQty FROM CategorySales GROUP BY CUBE(Category,CustomerID) ORDER BY Category, CustomerID;
  71. 71. Grouping & Aggregating
  72. 72. CUBE/ROLLUP • CUBE provides shortcut for defining grouping sets given a list of columns • All possible combinations of grouping sets created SELECT <column list with aggregate(s)> FROM <source> GROUP BY CUBE (<column_name>, <column_name>, ...); • ROLLUP provides shortcut for defining grouping sets, creates combinations assuming input columns form a hierarchy SELECT <column list with aggregate(s)> FROM <source> GROUP BY CUBE (<column_name>, <column_name>, ...);
  73. 73. PIVOT • Pivoting data is rotating data from a rows-based orientation to a columns-based orientation • Distinct values from a single column are projected across as headings for other columns - may include aggregation
  74. 74. PIVOT SYNTAX • Pivoting includes three phases: 1. Grouping determines which element gets a row in the result set 2. Spreading provides the distinct values to be pivoted across 3. Aggregation performs an aggregation function (such as SUM) Grouping SELECT Category, [2006],[2007],[2008] FROM ( SELECT Category, Qty, Orderyear FROM Sales.CategoryQtyYear) AS D PIVOT(SUM(QTY) FOR orderyear IN([2006],[2007],[2008]) Spreading ) AS pvt; Aggregation
  75. 75. UNPIVOT • Unpivoting data is rotating data from a columns-based orientation to a rows-based orientation • Spreads or splits values from one source row into one or more target rows • Each source row becomes one or more rows in result set based on number of columns being pivoted
  76. 76. UNPIVOT SYNTAX • Unpivoting includes three elements: • Source columns to be unpivoted • Name to be assigned to new values column • Name to be assigned to names columns SELECT category, qty, orderyear FROM CategorySales UNPIVOT(qty FOR orderyear IN([2006],[2007],[2008])) AS unpvt;
  77. 77. CUBE, ROLLUP PIVOT, UNPIVOT ,
  78. 78. Using Sub-queries What is and How to write Sub-queries
  79. 79. SUBQUERIES • Nesting queries within queries • Outer query : result set returned to caller • Inner query : result set returned to outer query • Types of subqueries based on return value: • Single –valued (scalar) • Multivalued • Table-valued
  80. 80. DEPENDENCY ON OUTER QUERY • Self-Contained Subqueries • Subquery not dependent on outer query • Can be evaluated by executing the subquery once and substituting the result into the WHERE clause of the outer query • Easier to debug • Correlated Subqueries • The subquery depends on the outer query for its values • The subquery is executed repeatedly, once for each row that might be selected by the outer query • Known as repeating subquery
  81. 81. USE • Anywhere an expression is allowed • Not in an ORDER BY clause • Subqueries within subqueries • Commonly used with (NOT) IN and EXISTS
  82. 82. EXISTS PREDICATE • Tests existence of rows. • Returns TRUE or FALSE • Usually * consists the SELECT list of the subquery, no reason to list column names • Enough to determine whether the subquery returns at least one row, so engine doesn’t need to process all rows
  83. 83. Using Subqueries
  84. 84. Views, TVFs, Table Expressions Using Views, Table Value Functions and Table Expressions
  85. 85. VIEWS A view is a virtual table whose contents (rows and columns) are defined by a query. • The rows and columns of data come from tables referenced in the query defining the view and are produced dynamically when the view is referenced. • Updatable view: modifying an underlying base table through the view • Indexed view: The view definition has been computed and the resulting data stored just like a table.
  86. 86. USE • To focus, simplify, and customize the perception each user has of the database. • As a security mechanism by allowing users to access data through the view, without granting the users permissions to directly access the underlying base tables. • To provide a backward compatible interface to emulate a table whose schema has changed.
  87. 87. OPTIONS • CHECK OPTION Prevent data modifications through the view that conflict with the views filter • ENCRYPTION Encrypt text of the CREATE VIEW statement in sys.syscomments • SCHEMABINDING Prevent modification of underlying views that would affect the view definition
  88. 88. Using Views
  89. 89. INLINE TABLE-VALUED FUNCTIONS • Table-valued functions (TVFs) are named table expressions with definitions stored in a database • TVFs return a virtual table to the calling query • SQL Server provides two types of TVFs • Inline, based on a single SELECT statement • Multi-statement, which creates and loads a table variable • Unlike views, TVFs support input parameters • Inline TVFs may be thought of as parameterized views
  90. 90. WRITING INLINE TVF • Table-valued functions are created by administrators and developers • Create and name function and optional parameters with CREATE FUNCTION • Declare return type as TABLE • Define inline SELECT statement following RETURN CREATE FUNCTION Sales.fn_LineTotal (@orderid INT) RETURNS TABLE AS RETURN SELECT orderid, CAST((qty * unitprice * (1 - discount)) AS DECIMAL(8, 2)) AS line_total FROM OrderDetails WHERE orderid = @orderid ;
  91. 91. Inline Table Value Functions
  92. 92. DERIVED TABLES • Derived tables are named query expressions created within an outer SELECT statement • Not stored in database – represents a virtual relational table • When processed, unpacked into query against underlying referenced objects • Allow you to write more modular queries SELECT <column_list> FROM ( <derived_table_definition> ) AS <derived_table_alias>; • Scope of a derived table is the query in which it is defined
  93. 93. Derived Tables
  94. 94. COMMON TABLE EXPRESSIONS • CTEs are named table expressions defined in a query • CTEs are similar to derived tables in scope and naming requirements • Unlike derived tables, CTEs support multiple definitions, multiple references, and recursion WITH <CTE_name> AS ( <CTE_definition> ) <outer query referencing CTE>;
  95. 95. WRITING CTE • Define the table expression in WITH clause • Assign column aliases (inline or external) • Pass arguments if desired • Reference the CTE in the outer query WITH CTE_year AS ( SELECT YEAR(orderdate) AS orderyear, customerid FROM Orders ) SELECT orderyear, COUNT(DISTINCT customerid) AS cust_count FROM CTE_year GROUP BY orderyear;
  96. 96. Common Table Expressions
  97. 97. Set Operators Using Set Operators
  98. 98. SET OPERATORS Set operators combine results from two or more queries into a single result set. • The number and the order of the columns must be the same in all queries. • The data types must be compatible • ORDER BY clause applied to result of operator • Names of columns in result are specified by the first query • NULLS are equal Input Query 1 set operator Input Query 2 [ORDER BY … ]
  99. 99. SET OPERATORS • UNION: returns all rows that belong to at least one of the input queries. • By default result set has no duplicates. To get result set with duplicates specify ALL option. • INTERSECT: returns any distinct values that are returned by both the left query and the right one. • EXCEPT: returns any distinct values from the left query that are not also found on the right query.
  100. 100. APPLY • Invoke a table-valued function for each row returned by an outer table expression of a query. • CROSS APPLY returns only rows from the outer table that produce a result set from the table- valued function. • OUTER APPLY returns both rows that produce a result set, and rows that do not, with NULL values in the columns produced by the table-valued function.
  101. 101. Union, Intersect, Except, Apply
  102. 102. Stored Procedures Using Stored Procedures
  103. 103. STORED PROCEDURES A stored procedure in SQL Server is a group of one or more Transact-SQL statements which can : • Accept input parameters and return multiple values in the form of output parameters to the calling program. • Contain programming statements that perform operations in the database. These include calling other procedures. • Return a status value to a calling program to indicate success or failure (and the reason for failure)
  104. 104. BENEFITS • Reduced server/client network traffic • Stronger security • Reuse of code • Easier maintenance • Improved performance
  105. 105. Using Stored Procedures
  106. 106. Window Functions Using Window Functions
  107. 107. SQL WINDOWING Window functions are functions applied to sets of rows defined by a clause called OVER They are used mainly for analytical purposes allowing you to calculate running totals, calculate moving averages, identify gaps and islands in your data, and perform many other computations These functions are based on the concept of windowing in standard SQL, which is both an ISO and ANSI standard The idea behind this concept is to allow you to apply various calculations to a set, or window, of rows and return a single value Window functions can help to solve a wide variety of querying tasks by helping you express set calculations more easily, intuitively, and efficiently than ever before
  108. 108. THE SYNTAX function_name(<arguments>) OVER( [ <window partition clause> ] [ <window order clause> [ <window frame clause> ] ] )
  109. 109. OVER CLAUSE OVER defines a window, or set, of rows to be used by a window function, including any ordering With a specified window partition clause, the OVER clause restricts the set of rows to those with the same values in the partitioning elements By itself, OVER() is unrestricted and includes all rows Multiple OVER clauses can be used in a single query, each with its own partitioning and ordering, if needed
  110. 110. WINDOW PARTITION CLAUSE The partitioning element allows you to restrict the window to only those rows that have the same values in the partitioning attributes as the current row. SELECT orderid, custid, val, SUM(val) OVER() AS sumall, SUM(val) OVER(PARTITION BY custid) AS sumcust FROM OrderValues AS O1;
  111. 111. WINDOW ORDER CLAUSE The ordering element defines the ordering for the calculation, if relevant, within the partition SELECT custid, orderid, val, RANK() OVER(ORDER BY val DESC) AS rnk_all, RANK() OVER(PARTITION BY custid ORDER BY val DESC) AS rnk_cust FROM Orders;
  112. 112. WINDOW FRAME CLAUSE Framing is another option that enables you to further restrict the rows in the window partition. SELECT empid, ordermonth, qty, SUM(qty) OVER(PARTITION BY empid ORDER BY ordermonth ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS runqty FROM EmpOrders;
  113. 113. CONCEPTUAL RELATIONSHIP BETWEEN WINDOW ELEMENTS Result set (OVER) Window partition (PARTITION BY) Frame (ROWS BETWEEN)
  114. 114. WINDOW AGGREGATE FUNCTIONS • Similar to grouped aggregate functions • SUM, MIN, MAX, etc. • Applied to windows defined by OVER clause • Window aggregate functions support partitioning, ordering, and framing SELECT custid, ordermonth, qty, SUM(qty) OVER(PARTITION BY custid) AS totalpercust FROM Sales.CustOrders;
  115. 115. WINDOW RANKING FUNCTIONS • Ranking functions require a window order clause • Partitioning is optional • To display results in sorted order still requires ORDER BY! Function Description RANK Returns the rank of each row within the partition of a result set. May include ties and gaps. DENSE_RANK Returns the rank of each row within the partition of a result set. May include ties. Will not include gaps. ROW_NUMBER Returns a unique sequential row number within partition based on current order. NTILE Distributes the rows in an ordered partition into a specified number of groups. Returns the number of the group to which the current row belongs.
  116. 116. WINDOW DISTRIBUTION FUNCTIONS • Window distribution functions perform statistical analysis on data, and require a window order clause • Rank distribution performed with PERCENT_RANK and CUME_DIST • Inverse distribution performed with PERCENTILE_CONT and PERCENTILE_DISC
  117. 117. WINDOW OFFSET FUNCTIONS • Window offset functions allow comparisons between rows in a set without the need for a self-join • Offset functions operate on an position relative to the current row, or to the start or end of the window frame Function Description LAG Returns an expression from a previous row that is a defined offset from the current row. Returns NULL if no row at specified position. LEAD Returns an expression from a later row that is a defined offset from the current row. Returns NULL if no row at specified position. FIRST_VALUE Returns the first value in the current window frame. Requires window ordering to be meaningful. LAST_VALUE Returns the last value in the current window frame. Requires window ordering to be meaningful.
  118. 118. Window Functions
  119. 119. What’s New in SQL Server 2012 Improvements of T-SQL in SQL Server 2012
  120. 120. USING SEQUENCES • Sequence objects added in SQL Server 2012 • Independent objects in database • More flexible than the IDENTITY property • Can be used as default value for a column • Manage with CREATE/ALTER/DROP statements • Retrieve value with the NEXT VALUE FOR clause -- Define a sequence CREATE SEQUENCE dbo.InvoiceSeq AS INT START WITH 1 INCREMENT BY 1; -- Retrieve next available value from sequence SELECT NEXT VALUE FOR dbo.InvoiceSeq;
  121. 121. USING MERGE TO MODIFY DATA • MERGE modifies data based on a condition • When the source matches the target • When the source has no match in the target • When the target has no match in the source MERGE INTO schema_name.table_name AS TargetTbl USING (SELECT <select_list>) AS SourceTbl ON (TargetTbl.col1 = SourceTbl.col1) WHEN MATCHED THEN UPDATE SET col2 = SourceTbl.col2 WHEN NOT MATCHED THEN INSERT (<column_list>) VALUES (<value_list>);
  122. 122. Conversion Functions
  123. 123. NEW CONVERSION FUNCTIONS • PARSE SELECT PARSE('Monday, 13 December 2010' AS datetime2 USING 'en-US') AS Result; Result : 2010-12-13 00:00:00.0000000 • TRY_CONVERT SELECT CASE WHEN TRY_CONVERT(float, 'test') IS NULL THEN 'Cast failed' ELSE 'Cast succeeded' END AS Result; • TRY_PARSE SELECT TRY_PARSE('AAAAA' AS datetime2 USING 'en-US') AS Result; Result : NULL
  124. 124. Date & Time Functions
  125. 125. DATEFROMPARTS • Returns a date value with the date portion set to the specified year, month and day, and the time portion set to the default. • If the arguments are not valid, then an error is raised. • If required arguments are null, then null is returned. SELECT DATEFROMPARTS ( 2010, 12, 31 ) AS Result; Result 2010-12-31
  126. 126. DATETIME2FROMPARTS • Returns a fully initialized datetime2 value. • If the arguments are not valid, an error is raised. • If required arguments are null, then null is returned. • If the precision argument is null, then an error is raised. SELECT DATETIME2FROMPARTS( 2010, 12, 31, 23, 59, 59, 0, 0 ); Result 2010-12-31 23:59:59.0000000
  127. 127. DATETIMEFROMPARTS • Returns a fully initialized datetime value. • If the arguments are not valid, then an error is raised. • If required arguments are null, then a null is returned. SELECT DATETIMEFROMPARTS( 2010, 12, 31, 23, 59, 59, 0 ); Result 2010-12-31 23:59:59.000
  128. 128. DATETIMEOFFSETFROMPARTS • Returns a fully initialized datetimeoffset data type. • The offset arguments are used to represent the time zone offset. • If the offset arguments are omitted, then the time zone offset is assumed to be 00:00. • If the offset arguments are specified, then both arguments must be present and both must be positive or negative. • If minute_offset is specified without hour_offset, an error is raised. • If other arguments are not valid, then an error is raised. • If required arguments are null, then a null is returned. • If the precision argument is null, then an error is raised. SELECT DATETIMEOFFSETFROMPARTS(2010,12,31,14,23,23,0,12,0,7); Result 2010-12-07 00:00:00.0000000 +00:00
  129. 129. EOMONTH • Returns the last day of the month that contains the specified date, with an optional offset. DECLARE @date DATETIME = '12/1/2011'; SELECT EOMONTH ( @date ) AS Result; GO Result 2011-12-31
  130. 130. SMALLDATETIMEFROMPARTS • Returns a smalldatetime value for the specified date and time. SELECT SMALLDATETIMEFROMPARTS ( 2010, 12, 31, 23, 59 ); Result 2011-01-01 00:00:00
  131. 131. TIMEFROMPARTS • Returns a fully initialized time value. • If the arguments are invalid, then an error is raised. • If any of the parameters are null, null is returned. • If the precision argument is null, then an error is raised. SELECT TIMEFROMPARTS ( 23, 59, 59, 0, 0 ) AS Result; Result 23:59:59.0000000
  132. 132. Logical Functions
  133. 133. CHOOSE • Returns the data type with the highest precedence from the set of types passed to the function • CHOOSE acts like an index into an array, where the array is composed of the arguments that follow the index argument. SELECT CHOOSE (3,'Manager','Director','Developer','Tester'); Result Developer
  134. 134. IIF • Returns the data type with the highest precedence from the types in true_value and false_value • IIF is a shorthand way for writing a CASE expression. DECLARE @a int = 45, @b int = 40; SELECT IIF ( @a > @b, 'TRUE', 'FALSE' ) AS Result; GO Result TRUE
  135. 135. String Functions
  136. 136. CONCAT • Returns a string that is the result of concatenating two or more string values. SELECT CONCAT ( 'Happy ', 'Birthday ', 11, '/', '25' ); Result Happy Birthday 11/25
  137. 137. FORMAT • Returns a value formatted with the specified format and optional culture. DECLARE @d DATETIME = '10/01/2011'; SELECT FORMAT ( @d, 'd', 'en-US' ) AS 'US English Result' ,FORMAT ( @d, 'd', 'en-gb' ) AS 'GB English Result' ,FORMAT ( @d, 'd', 'de-de' ) AS 'German Result'; US English Result : 10/1/2011 Result GB English Result : 01/10/2011 German Result : 01.01.2011
  138. 138. Questions & Answers
  139. 139. SUMMARY • Introduction to Microsoft SQL Server 2012 • SQL Server Management Studio • Introduction to T-SQL Querying • SELECT Statements / Queries • Querying Multiple Tables • Sorting and Filtering Data • Grouping and Aggregating Data
  140. 140. SUMMARY • Using Sub-queries • Using Views, Table Value Functions and Table Expressions • Using Set Operators • Using Stored Procedures • Using Window Functions • What’s New in SQL Server 2012
  141. 141. Thank you
  142. 142. SELECT KNOWLEDGE FROM SQL SERVER

×