Writing Queries UsingMicrosoft® SQL Server 2008®       Transact-SQL       Introduction
IntroductionJason Yousef, MSSenior Database EngineerA+, N+, MCSA, MCITP SQL Admin, MCITP SQL BIJYousef@goodhandsit.comhttp...
Module 1 Getting Started                        SQL Server Release History                           Version          Year...
Overview of Client/Server Architecture              Two-tier                     Multitier                                ...
SQL Server Components Server Components                           DescriptionSQL Server DB Engine      Core service for st...
SQL Server Management ToolsManagement tools                        Description  SQL Server              An environment to ...
demo
RDBMS - Overview of Relational                  Databases• Relational databases store data in multiple interrelated tables...
What Is Normalization?             The process for removing redundant data from a databaseBenefits      Accelerates sorti...
The Normalization Process• First Normal Form     Order Details      Order Details    ProdCategory       ProdCat_ID    Prod...
demo
Overview of Data Types Each column, variable, expression, parameter has a data type A data type specifies the type of data...
Integer Data Types• The four integer data types are:• Tinyint: Range of values: 0 through 255, precision: 3,  scale: 0, le...
Currency Data Types• Money: Range of values: –214,748.3648  through 214,748.3647, precision: 10, scale: 0,  length: 4• Sma...
Date and Time Data Types• Smalldatetime: date range: January 1, 1900, through June 6, 2079, time  resolution: 1 minute, le...
Character data types
demo
ANSI SQL – T-SQL•A History and Definition of ANSI SQL and T-SQL• Developed in the early 1970s• ANSI-SQL defined by the Ame...
Categories of SQL Statements• DML – Data Manipulation Language          INSERT Table1 VALUES (1, Row #1) • DCL – Data Cont...
Basic T-SQL SyntaxThere are four primary properties to the SELECT statement 1   The number and attributes of the columns i...
Types of T-SQL Operators            Type                      Operators                         • +, -, *, /, %• Arithmeti...
What Are T-SQL Functions? Functions                              NotesRowset       • Return objects that can be used as ta...
Commenting T-SQL Code• Comments are statements about the meaning of the code• When used, there is no execution performed o...
demo
Querying SQL Server 2008 Databases          Tool                              Description• SQL Server               • Used...
What is a SQL Server Solution?    SQL Server Management Studio provides two containers for    managing database projects:A...
demo
Upcoming SlideShare
Loading in...5
×

SQL Server Developer 70-433

437

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
437
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Welcome and title
  • Welcome Note, History..Started SQL server since 1999, on sql 2000, Only knew about the DBA roles, went to network administration, managed SQL 2005 server as part of the network, back to SQL dev, and business intelligence in 2008.
  • Prior to version 7.0 the code base for MS SQL Server was sold by Sybase SQL Server to Microsoft.In the last ten years since release of Microsoft's previous SQL Server product (SQL Server 2000), advancements have been made in performance, the client IDE tools, and several complementary systems that are packaged with SQL Server 2005. These include: an ETL tool (SQL Server Integration Services or SSIS), a Reporting Server, an OLAP and data mining server (Analysis Services), and several messaging technologies, specifically Service Broker and Notification Services.
  • difference between single-user and client/server architecture applications. client/server architecture involves the use of a client to connect to a server for processing. Microsoft® SQL Server® 2008 can be run in both modes. You can use SQL Server as a development tool on a workstation where the Server and all its components installed locally. You can also use SQL Server in a Client/Server Application where the databases are stored on a server and you use an application that connects to the server for backend process. Explain how client/server systems are constructed so that the database can reside on a central computer, known as a server, and be shared among several users. Users access the server through a client or server application. In a two-tier client/server system, users run an application on their local computer, known as a client, that connects over a network to the server running SQL Server. The client application runs both business logic and the code to display output to the user.In a multitier system, an application server handles the business logic and communicates with the SQL database server.OLE DB (Object Linking and Embedding, Database, sometimes written as OLEDB or OLE-DB) is an API designed by Microsoft for accessing data from a variety of sources in an uniform mannerhttp://en.wikipedia.org/wiki/OLE_DBReferencesChapter 7 - Client/Server Architecture: http://go.microsoft.com/fwlink/?LinkID=127206File-Server vs. Client/Server: http://go.microsoft.com/fwlink/?LinkID=127207
  • Anybody installed SQL server before?Explain to students that they can use the Feature Selection page of the SQL Server Installation Wizard to select the components to include in an installation of SQL Server. Mention that, by default, none of the features in the tree are selected.SQL Server Database Engine includes the Database Engine, the core service for storing, processing, and securing data, Replication, full-text search, and tools for managing relational and XML data.Analysis Services includes the tools for creating and managing online analytical processing (OLAP) Online analytical processing,and data mining applications. http://en.wikipedia.org/wiki/OlapReporting Services includes server and client components for creating, managing, and deploying tabular, matrix, graphical, and free-form reports. Reporting Services is also an extensible platform that you can use to develop report applications.Integration Services is a set of graphical tools and programmable objects for moving, copying, and transforming data. SQL Server provides a enterprise extraction, transformation, and loading (ETL) platform called SQL Server Integration Services (SSIS) with the features, tools, and functionality to build both classic and innovative kinds of ETL-based applications. Similar to Data Transformation Services (DTS), it provides functions for moving data from one place to another and manipulating that data at run time. Full-Text Search is the functionality you need to issue full-text queries against plain character-based data in SQL Server tables. Full-text queries could include words and phrases or multiple forms of a word or phrase. Full-Text Search allows fast and flexible indexing for keyword-based query of text data stored in a Microsoft SQL Server database. Replication is a set of technologies for copying and distributing data and database objects from one database to another, and then synchronizing between databases to maintain consistency. Using replication, you can distribute data to different locations and to remote or mobile users over local and wide area networks, dial-up connections, wireless connections, and the Internet. SQL Server provides three types of replication, each with different capabilities: transactional replication, merge replication, and snapshot replication.Service Broker provides the SQL Server Database Engine native support for messaging and queuing applications. This makes it easier for developers to create sophisticated applications that use the Database Engine components to communicate between disparate databases. Notification Services is a platform for developing applications that generate and send notifications, and it is also an engine that runs those applications. Question: Have you used any of these SQL Server components before?Answers will vary.References:Editions and Components of SQL Server 2008: http://go.microsoft.com/fwlink/?LinkID=127208
  • Explain to students that they can use the Feature Selection page of the SQL Server Installation Wizard to select the SQL Server Management Tools to include in an installation of SQL Server. SQL Server Management StudioSQL Server Management Studio is an integrated environment to access, configure, manage, and administer SQL server components. Management Studio lets developers and administrators of all skill levels use SQL Server. SQL Server Configuration ManagerSQL Server Configuration Manager provides basic configuration management for SQL Server services, server protocols, client protocols, and client aliases.SQL Server ProfilerSQL Server Profiler is a profiling and tracing tool. It provides a graphical user interface to profile and trace an instance of the Database Engine or Analysis Services.Database Engine Tuning AdvisorDatabase Engine Tuning Advisor helps create optimal sets of indexes, indexed views, and partitions.Business Intelligence Development StudioThe Business Intelligence Development Studio is an integrated development environment (IDE) for creating Analysis Services, Reporting Services, and Integration Services solutions.Have you used any of these SQL Server management tools before? References:Editions and Components of SQL Server 2008: http://go.microsoft.com/fwlink/?LinkID=127208
  • ANY QUESTIONS?DemoSQL Server Management Studio (SSMS)SQL Server Configuration ManagerSQL Server ProfilerDatabase Engine Tuning AdvisorBusiness Intelligence Development Studio (BIDS)
  • Explain how a relational database is a complex database that stores data in multiple tables that are interrelated. Usually the tables in a relational database have one-to-many relationships. An example of a relational database might have one table that stores customer orders and another that stores the line items for each order, and each order table would have one or more line items in the order details table. Another example might be a customers table and an orders table. Each customer may place multiple orders.It is important to explain that the relational database server of SQL Server has two main parts: the relational engine and the storage engine. The two engines work independently, interacting with each other through native data access components such as Object Linking and Embedding, Database (OLE DB). Additionally you can describe the database objects of the relational database.Tables - Tables are the main form for collection of information. Tables are objects that contain all the data in SQL Server databases. Each table represents a type of object that is meaningful to its users.Indexes - An index is an on-disk structure associated with a table or view that speeds retrieval of rows from the table or view. An index contains keys built from one or more columns in the table or view. These keys are stored in a B-tree structure that enables SQL Server to find the row or rows associated with the key values quickly and efficiently. There are clustered and non-clustered indexes.Views - A view can be thought of as either a virtual table or a stored query. The data accessible through a view is not stored in the database as a distinct object. What is stored in the database is a SELECT statement. The result set of the SELECT statement forms the virtual table returned by the view. A user can use this virtual table by referencing the view name in Transact-SQL (T-SQL) statements the same way a table is referenced.Stored Procedures - Stored procedures in Microsoft SQL Server are similar to procedures in other programming languages in that they can: Accept input parameters and return multiple values in the form of output parameters to the calling procedure or batch. Contain programming statements that perform operations in the database, including calling other procedures. Return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure). References:Databases: http://go.microsoft.com/fwlink/?LinkID=127213Relational Database Components: http://go.microsoft.com/fwlink/?LinkID=127214Database Engine Concepts: http://go.microsoft.com/fwlink/?LinkID=127215Relational Databases: http://go.microsoft.com/fwlink/?LinkID=127216
  • In this slide, discuss the high-level definition of the first three normalizations. These are the norms generally implemented in industry. Explain that Normalization is the process of organizing data in a database. Explain how this includes creating tables and establishing relationships between those tables according to rules designed both to protect the data and to make the database more flexible by eliminating redundancy and inconsistent dependency.It is important to explain that reasonable normalization of the logical database design yields best performance. A greater number of narrow tables is characteristic of a normalized database. A greater number of wide tables is characteristic of a denormalized database. A highly normalized database is routinely associated with complex relational joins, which can hurt performance. However, the SQL Server optimizer is very efficient at selecting rapid, efficient joins, as long as effective indexes are available.The benefits of normalization include:• Accelerates sorting and index creation, because tables are narrower.• Allows more clustered indexes, because there are more tables.• Fewer indexes per table, helping UPDATE performance.• Fewer NULLs and less redundant data, increasing database compactness.The disadvantages of normalization More tables to join: By spreading out your data into more tables, you increase the need to join tables. Data retrieval and queries may run slower because of the joins. Tables contain codes instead of real data: Repeated data is stored as codes rather than meaningful data. Therefore, there is always a need to go to the lookup table for the value. Data model is difficult to query against: The data model is optimized for applications, not for ad hoc querying.Question: Have you ever implemented normalization before? Did you find that it improved SQL Server performance? Answers will vary. Discuss the ways that normalization will improve or hurt server performance.References:Normalization: http://go.microsoft.com/fwlink/?LinkID=127217SQL Database Normalization Rules: http://go.microsoft.com/fwlink/?LinkID=127218
  • Provide an overview of the normalization process. Explain how redundant data wastes disk space and creates maintenance problems. If data that exists in more than one place must be changed, the data must be changed in exactly the same way in all locations. A customer address change is much easier to implement if that data is stored only in the Customers table and nowhere else in the database.Explain how, with SQL Server, reasonable normalization often helps rather than hurts performance. As normalization increases, so does the number and complexity of joins required to retrieve data. As a rough rule of thumb, Microsoft suggests carrying on the normalization process unless this causes many queries to have four-way or greater joins. There are a few rules for database normalization. Each rule is called a "normal form." If the first rule is observed, the database is said to be in "first normal form." If the first three rules are observed, the database is considered to be in "third normal form." Although other levels of normalization are possible, third normal form is considered the highest level necessary for most applications.First Normal Form• Eliminate repeating groups in individual tables.• Create a separate table for each set of related data.• Identify each set of related data with a primary key.A design that is unambiguously in First Normal Form makes use of two tables: a Customer table and a Customer Telephone Number table.Second Normal Form• Create separate tables for sets of values that apply to multiple records.• Relate these tables with a foreign key.Third Normal Form• Eliminate fields that do not depend on the key.• Transitive dependencies must be eliminated, so all records must rely only on the primary key.Fourth Normal Form• Concerned with a more general type of dependency known as a multivalued dependency.• If and only if, for every one of its non-trivial multivalued dependencies X ->-> Y, X is a superkey.Fifth Normal Form• Also known as Project-join normal form (PJ/NF)• If and only if it is in Fourth Normal Form and every join dependency in it is implied by the candidate keys.Sixth Normal Form• A table is in sixth normal form if and only if it satisfies no non-trivial (in the formal sense) join dependencies at all• Sixth normal form is intended to decompose relation variables to irreducible components. References:Normalization: http://go.microsoft.com/fwlink/?LinkID=127217SQL Database Normalization Rules: http://go.microsoft.com/fwlink/?LinkID=127218
  • ANY QUESTIONS?DemoRDBMSUsing SQL Server Management Studio (SSMS)1-NormalizationSELECT TOP 10 * FROM [AdventureWorks].[Sales].[SalesOrderHeader] SELECT TOP 10 * FROM [AdventureWorks].[Sales].[SalesOrderDetail]-------SELECT top 10 * FROM [AdventureWorks].[Person].[CountryRegion] SELECT top 10 * FROM [AdventureWorks].[Person].[StateProvince] SELECT top 10 * FROM [AdventureWorks].[Person].[ContactType] SELECT top 10 * FROM [AdventureWorks].[Person].[Contact] SELECT top 10 * FROM [AdventureWorks].[Person].[AddressType] SELECT top 10 * FROM [AdventureWorks].[Person].[Address]2-database objects (Tables, Views,Indexes,Triggers,Procedures.Constraints,Rules)The best way to use rules in SQL Server is not to use them! Microsoft has told us the end is nigh for rules:CREATE RULE will be removed in a future version of Microsoft SQL Server. Avoid using CREATE RULE in new development work, and plan to modify applications that currently use it. We recommend that you use check constraints instead. Check constraints are created by using the CHECK keyword of CREATE TABLE or ALTER TABLE.So, taking their advice, let’s go over how to use CHECK constraints instead. Think of a check constraint as a digital bouncer; just as a bouncer only lets people “on the list” into an exclusive club, a check constraint will only allow data that evaluates to TRUE for its conditions to be input. Now, bouncers aren’t perfect and neither are check constraints. This SQL Server TechCenter page gives some examples of check constraint shortcomings.http://technet.microsoft.com/en-us/library/ms188064.aspx
  • Provide an overview of data types. In SQL Server, each column, local variable, expression, and parameter has a related data type. A data type is an attribute that specifies the type of data that the object can hold: integer data, character data, monetary data, date and time data, binary strings, and so on.SQL Server supplies a set of system data types that define all the types of data that can be used with SQL Server. You can also define your own data types in Transact-SQL or the Microsoft .NET Framework. Alias data types are based on the system-supplied data types. User-defined types obtain their characteristics from the methods and operators of a class that you create by using one of the programming languages support by the .NET Framework. SQL Server provides data type synonyms for International Organization for Standardization (ISO) compatibility. When two expressions that have different data types, collations, precision, scale, or length are combined by an operator, the characteristics of result are determined by the following: The data type of the result is determined by applying the rules of data type precedence to the data types of the input expressions. The collation of the result is determined by the rules of collation precedence when the result data type is char, varchar, text, nchar, nvarchar, or ntext. The precision, scale, and length of the result depend on the precision, scale, and length of the input expressions. Data types in SQL Server are organized into the following categories:Exact numericsbigint, numeric, bit, smallint, decimal, smallmoney, int, tinyint, moneyUnicode character stringsnchar, nvarchar, ntextApproximate numerics float, real Binary stringsbinary, varbinary, imageDate and timedate, datetimeoffset, datetime2, smalldatetime, datetime, time Other data types cursor, timestamp, hierarchyid, uniqueidentifier, sql_variant, xml, tableCharacter strings char, varchar, textIn SQL Server, based on their storage characteristics, some data types are designated as belonging to the following groups: Large value data types: varchar(max), nvarchar(max), and varbinary(max) Large object data types: text, ntext, image, varchar(max), nvarchar(max), varbinary(max), and xmlReferencesData Types (Transact-SQL): http://go.microsoft.com/fwlink/?LinkID=127223
  • http://msdn.microsoft.com/en-us/library/ms187752.aspx
  • http://msdn.microsoft.com/en-us/library/ms187752.aspx
  • http://msdn.microsoft.com/en-us/library/bb677335.aspx
  • http://msdn.microsoft.com/en-us/library/ms187752.aspx
  • ANY QUESTIONS?Demo Data Typeshttp://msdn.microsoft.com/en-us/library/ms187752.aspx
  • Discuss ANSI SQL, and compare it to SQL Server T-SQL. History of SQLSQL was developed by IBM in the early 1970s. SQL was adopted as a standard by American National Standards Institute (ANSI) in 1986 and ISO in 1987.Definition of ANSI SQLThe process of implementing a standard as defined by ANSI can take some time by vendors. An example is SQL-99. This was defined in 1999. This created an addition known as Common Table Expressions. This was implemented in the SQL Server 2005 version of T-SQL. ANSI SQL is defined by the American National Standards Institute. It is known as SQL/PSM or SQL/Persistent Stored Modules. These standards are considered open standards.Definition of T-SQL, or Transact SQLMicrosoft’s implementation of SQL is known as T-SQL. It is the language that is used to create queries for SQL Server. Other implementations of SQLThere are other implementations of SQL such as Oracle’s PL/SQL, Procedural Language/SQL and IBM’s SQL Procedural Language.Question: Have you used any other implementation of SQL besides T-SQL?Answers will vary. May include Oracle, IBM, or open source implementations.References:Using Common Table Expressions: http://go.microsoft.com/fwlink/?LinkID=127224
  • Discuss the various categories of SQL Statements.Data Manipulation Language (DML)DMLis the category of SQL statements that included changes to the data within the database. These include the UPDATE, DELETE, and INSERT statements.Data Control Language (DCL)DCLis the category of SQL statements that are associated with rights to objects within the database. These include GRANT, REVOKE, and DENY.Data Definition Language (DDL)DDLis the category of SQL statements that are associated with the implementation, changing, or deletion of objects for or within a database. These include CREATE, TRUNCATE, DROP, and ALTER.Transactional Control Language (TCL)TCL is abbreviation of Transactional Control Language. It is used to manage different transactions occurring within a database. These include COMMIT, SAVE POINT, ROLLBACK.SQL Select StatementsSQL Queries are often considered part of the DML. But when started with a SELECT there are no changes to the data used in the query.REFRENCES:GRANT (Transact-SQL): http://go.microsoft.com/fwlink/?LinkID=127225
  • Discuss the basic elements of T-SQL.Explain how the SELECT statement retrieves data from SQL Server and returns it to the user in one or more result sets. A result set is a tabular arrangement of the data from the SELECT. Like an SQL table, the result set is made up of columns and rows.The full syntax of the SELECT statement is complex, but most SELECT statements describe four primary properties of a result set: 1) The number and attributes of the columns in the result set. The following attributes must be defined for each result set column: The data type of the column.The size of the column, and for numeric columns, the precision and scale.The source of the data values returned in the column.2) The tables from which the result set data is retrieved, and any logical relationships between the tables.3) The conditions that the rows in the source tables must meet to qualify for the SELECT. Rows that do not meet the conditions are ignored.4) The sequence in which the rows of the result set are ordered.References:Query Fundamentals: http://go.microsoft.com/fwlink/?LinkID=127226Transact-SQL Syntax Conventions (Transact-SQL): http://go.microsoft.com/fwlink/?LinkID=127227
  • Present an overview of the various types of T-SQL operators. Explain how operators provide various ways of manipulating and comparing information.Arithmetic Operators Are + addition,- subtraction, * multiplication, / division, % integerUsed for mathematic functions.Assignment Operators = Assigns the value to a variable.Comparison Operators = equal to, < less than , > greater than, <> not equal to, ! not These can be used in formats such as >= or <=Comparison operators test whether two expressions are the same. Comparison operators can be used on all expressions except expressions of the text, ntext, or image data types. Logical Operators Logical Operators are used to specify how multiple search terms are combined in a search query. Logical operators also create more complicated search expressions from simpler ones, and thus refine your search. The following table shows you how to use each of the available operators.Operate on a single value and then return a single value. Scalar functions can be used wherever an expression is valid.Both terms in the same topic – ANDEither term in a topic - ORFirst term without the second term - NOTString ConcatenationString concatenation is done with the +An operator in a string expression that concatenates two or more character or binary strings, columns, or a combination of strings and column names into one expression (a string operator). References:Transact-SQL Reference (Transact-SQL): http://go.microsoft.com/fwlink/?LinkID=127228
  • Discuss several functions within T-SQL. Rowset Functions - Return an object that can be used like table references in an SQL statementExample: SELECT select_list FROM table AS FT_TBL INNER JOIN CONTAINSTABLE(table, column, contains_search_condition) AS KEY_TBL ON FT_TBL.unique_key_column = KEY_TBL.[KEY] Aggregate Functions - Operate on a collection of values but return a single, summarizing valueExample: SELECT AVG(VacationHours)as 'Average vacation hours', SUM (SickLeaveHours) as 'Total sick leave hours' FROM HumanResources.Employee WHERE Title LIKE 'Vice President%'; Ranking Functions - Return a ranking value for each row in a partitionExample:GOSELECT c.FirstName, c.LastName ,ROW_NUMBER() OVER (ORDER BY a.PostalCode) AS 'Row Number‘ ,RANK() OVER (ORDER BY a.PostalCode) AS 'Rank‘ ,DENSE_RANK() OVER (ORDER BY a.PostalCode) AS 'Dense Rank‘ ,NTILE(4) OVER (ORDER BY a.PostalCode) AS 'Quartile‘ ,s.SalesYTD, a.PostalCodeFROM Sales.SalesPerson s INNER JOIN Person.Contact c ON s.SalesPersonID = c.ContactID INNER JOIN Person.Address a ON a.AddressID = c.ContactIDWHERE TerritoryID IS NOT NULL AND SalesYTD <> 0; Scalar Functions - Operate on a single value and then return a single valueExample:SELECT ProductModelID, Name, dbo.ufnGetInventoryStock(ProductID)AS CurrentSupplyFROM Production.ProductWHERE ProductModelID BETWEEN 75 and 80; The above list is a small sample of what is available in T-SQL. Additional user-defined functions are also available. Scalar functions can be used wherever an expression is valid.References:Functions (Transact-SQL): http://go.microsoft.com/fwlink/?LinkID=127229
  • Provide a definition and example of how to comment T-SQL Code. Comments are nonexecuting text strings in program code (also known as remarks). Comments can be used to document code or temporarily disable parts of Transact-SQL statements and batches being diagnosed. Using comments to document code makes future program code maintenance easier. Comments are often used to record the program name, the author name, and the dates of major code changes. Comments can be used to describe complicated calculations or explain a programming method.Microsoft SQL Server supports two types of commenting characters: * -- (double hyphens)These comment characters can be used on the same line as code to be executed, or on a line by themselves. Everything from the double hyphens to the end of the line is part of the comment. For a multiple-line comment, the double hyphens must appear at the beginning of each comment line. * /* ... */ (forward slash-asterisk character pairs)These comment characters can be used on the same line as code to be executed, on lines by themselves, or even within executable code. Everything from the open comment pair (/*) to the close comment pair (*/) is considered part of the comment. For a multiple-line comment, the open-comment character pair (/*) must begin the comment, and the close-comment character pair (*/) must end the comment. No other comment characters should appear on any lines of the comment. Multiple-line /* */ comments cannot span a batch. The complete comment must be contained within a batch. For example, in SQL Query Analyzer and the osql utility, the GO command signals the end of a batch. When the utilities read the characters GO in the first two bytes of a line, they send all the code since the last GO command to the server as one batch. If a GO occurs at the start of a line between the /* and */ delimiters, then an unmatched comment delimiter will be sent with each batch and they will trigger syntax errors. /* will comment out the remaining code.References:/*...*/ (Comment) (Transact-SQL): http://go.microsoft.com/fwlink/?LinkID=127237-- (Comment) (Transact-SQL): http://go.microsoft.com/fwlink/?LinkID=127238Using Comments: http://go.microsoft.com/fwlink/?LinkID=127239
  • ANY QUESTIONS?Demooperators, functions, commentingOperators: SELECT *FROM [AdventureWorks].[HumanResources].[EmployeePayHistory]WHERE [Rate] > 10 AND [Rate] < 19ORDER BY Rate DESCSELECT *FROM [AdventureWorks].[HumanResources].[EmployeePayHistory]WHERE [Rate] BETWEEN 10 AND 19ORDER BY Rate DESC--Between is inclusive-----------------SELECT *FROM [AdventureWorks].[Person].[Address]WHERE [City] = 'Orlando'SELECT *FROM [AdventureWorks].[Person].[Address]WHERE [City] LIKE '%Or%'SELECT *FROM [AdventureWorks].[Person].[Address]WHERE [City] LIKE 'Or%'Functions: --Rowset Functions SELECT top 10 * from Person.Contact c --Aggregate Functions - Operate on a collection of values but return a single, summarizing valueSELECT AVG(VacationHours)as 'Average vacation hours', SUM (SickLeaveHours) as 'Total sick leave hours' FROM HumanResources.Employee WHERE Title LIKE 'Vice President%'; --Ranking Functions - Return a ranking value for each row in a partitionSELECT c.FirstName, c.LastName ,ROW_NUMBER() OVER (ORDER BY a.PostalCode) AS 'Row Number' ,RANK() OVER (ORDER BY a.PostalCode) AS 'Rank' ,DENSE_RANK() OVER (ORDER BY a.PostalCode) AS 'Dense Rank' ,NTILE(4) OVER (ORDER BY a.PostalCode) AS 'Quartile' ,s.SalesYTD, a.PostalCodeFROM Sales.SalesPerson s INNER JOIN Person.Contact c ON s.SalesPersonID = c.ContactID INNER JOIN Person.Address a ON a.AddressID = c.ContactIDWHERE TerritoryID IS NOT NULL AND SalesYTD <> 0; --Scalar Functions - Operate on a single value and then return a single valueSELECT ProductModelID, Name, dbo.ufnGetStock(ProductID)AS CurrentSupplyFROM Production.ProductWHERE ProductModelID BETWEEN 75 and 80; --Table Functionsselect * from dbo.ufnGetContactInformation(1101) Commenting: -- /* ... */
  • Microsoft Office Excel®Excel is for use in analysis and reporting.SQLCMDSQLCMD is a command used by system administrator for using command line and batch files for processing.PowerShellPowerShell is an environment used by system administrator for using command line and batch files for processing.Explain the use and application of PowerShell.http://tinyurl.com/q3h66zhttp://www.simple-talk.com/sql/database-administration/why-this-sql-server-dba-is-learning-powershell/bcp utilityThe bcp utility bulk copies data between an instance of Microsoft SQL Server and a data file in a user-specified format. The bcp utility can be used to import large numbers of new rows into SQL Server tables or to export data out of tables into data files. Except when used with the queryout option, the utility requires no knowledge of Transact-SQL. To import data into a table, you must either use a format file created for that table or understand the structure of the table and the types of data that are valid for its columns.sqlps UtilityThe sqlps utility starts a PowerShell session with the SQL Server PowerShell provider and cmdlets loaded and registered. You can enter PowerShell commands or scripts that use the SQL Server PowerShell components to work with instances of SQL Server and their objects.
  • Describe a SQL Server Solution. Explain how Microsoft SQL Server Management Studio provides two containers for managing database projects such as scripts, queries, data connections, and files: solutions and projects.Explain how a project is a set of files, plus related metadata such as connection information. The files in a project depend on which Microsoft SQL Server component the project is for. For example, a SQL Server project may contain data definition language (DDL) queries defining objects in a database. A solution includes one or more projects, plus files and metadata that help define the solution as a whole. Microsoft Visual SourceSafe® provide version control. SQL Server Management Studio does not support Microsoft Visual Studio® or Microsoft Business Intelligence Development Studio solutions or projects. Solutions and projects contain items that represent the scripts, queries, connection information and files that you need to create your database solution. Use these containers to: Manage settings for your solution as a whole or for individual projects. Use Solution Explorer to handle the details of file management while you focus on items that make up your database solution. Add items that are useful to multiple projects in the solution or to the solution without referencing the item in each project.References:Developing Solutions and Projects in SQL Server Management Studio: http://go.microsoft.com/fwlink/?LinkID=127244Introduction to Solutions, Projects, and Items: http://go.microsoft.com/fwlink/?LinkID=127245
  • ANY QUESTIONS?Demo SSMS solutions & projects ,Excell, SQLCMD
  • SQL Server Developer 70-433

    1. 1. Writing Queries UsingMicrosoft® SQL Server 2008® Transact-SQL Introduction
    2. 2. IntroductionJason Yousef, MSSenior Database EngineerA+, N+, MCSA, MCITP SQL Admin, MCITP SQL BIJYousef@goodhandsit.comhttp://asqlb.blogspot.com http://tinyurl.com/JYousef @Huslayer
    3. 3. Module 1 Getting Started SQL Server Release History Version Year Release Name Codename 1.0 SQL Server 1.0 1989 - (OS/2) (16bit) 1.1 SQL Server 1.1 1991 - (OS/2) (16bit) 4.21 1993 SQL Server 4.21 SQLNT (WinNT) 6.0 1995 SQL Server 6.0 SQL95 6.5 1996 SQL Server 6.5 Hydra 7.0 1998 SQL Server 7.0 Sphinx SQL Server 7.0 - 1999 Plato OLAP Tools 8.0 2000 SQL Server 2000 Shiloh SQL Server 2000 8.0 2003 Liberty 64-bit Edition 9.0 2005 SQL Server 2005 Yukon 10.0 2008 SQL Server 2008 Katmai Matrix (aka 10.25 2010 SQL Azure CloudDB) 10.5 2010 SQL Server 2008 R2 Kilimanjaro (aka KJ) 11.0 2012 SQL Server 2012 Denali http://en.wikipedia.org/wiki/Microsoft_SQL_Server
    4. 4. Overview of Client/Server Architecture Two-tier Multitier SQL Database Server SQL Database Server OLE DB ComponentsOLE DB Components Business Logic Display Code Application Server Business Logic Display Code Client Computer
    5. 5. SQL Server Components Server Components DescriptionSQL Server DB Engine Core service for storing and processing data Tools for creating and managing analyticalAnalysis Services processingReporting Services Components for creating and deploying reportsIntegration Services Tools for moving, copying, and transforming dataThe Database Engine also features these components: • Full-Text Search • Replication • Service Broker • Notification Services
    6. 6. SQL Server Management ToolsManagement tools Description SQL Server An environment to access, configure, Management Studio manage, and administer SQL SSMS components SQL Server An interface to provide management for Configuration SQL services, protocols, and client Manager aliases A GUI tool to profile and trace the SQL Server Profiler Database Engine and Analysis Services Database Engine An application to create an optimal sets Tuning Advisor of indexes, indexed views, and partitions Business Intelligence An IDE for creating Analysis Services, Development Studio Reporting Services, and Integration BIDS Services solutions
    7. 7. demo
    8. 8. RDBMS - Overview of Relational Databases• Relational databases store data in multiple interrelated tables• The tables have one-to-many relationships Orders Order Details OrderID OrderID Products CustomerID ProductID ProductID EmployeeID ProductName UnitPrice OrderDate SupplierID Quantity ShippedDate UnitPrice ShipVia UnitsInStock Freight Discontinued
    9. 9. What Is Normalization? The process for removing redundant data from a databaseBenefits  Accelerates sorting and indexing  Allows more clustered indexes  Helps UPDATE performance  More compact databasesDisadvantages • Increase in tables to join • Slower data retrieval • Insertion of code in tables • Difficulty in data model query
    10. 10. The Normalization Process• First Normal Form Order Details Order Details ProdCategory ProdCat_ID Product1 ProductID Product2• Second Normal Form Accounts Accounts PostCode Accountnumber Address PostCode Address PostCode City PostCode City State• Third Normal Form Orders Orders Quantity Quantity Price Price Total
    11. 11. demo
    12. 12. Overview of Data Types Each column, variable, expression, parameter has a data type A data type specifies the type of data the object can hold: integers, characters, monetary data, date and time, binaryData types are organized into the following categories: • Exact numerics • Unicode character strings • Approximate numerics • Binary strings • Date and time • Other data types • Character strings
    13. 13. Integer Data Types• The four integer data types are:• Tinyint: Range of values: 0 through 255, precision: 3, scale: 0, length: 1• Smallint: Range of values: –32, 768 (–2^15), through 32, 767 (2^15 – 1), precision: 5, scale: 0, length: 2• Int: Range of values: –2,147,483,648 (–2^31), through 2,147,483,647 (2^31 – 1) precision: 10, scale: 0, length: 4• Bigint: Range of values: –9,223,372,036,854,775,808 (–2^63), through 9,223,372,036,854,775,807 (2^63 – 1), precision: 19, scale: 0, length: 8
    14. 14. Currency Data Types• Money: Range of values: –214,748.3648 through 214,748.3647, precision: 10, scale: 0, length: 4• Smallmoney: Range of values: – 922,337,203,685,477.5808 through 922,337,203,685,477.5807, precision: 19, scale: 0, length: 8
    15. 15. Date and Time Data Types• Smalldatetime: date range: January 1, 1900, through June 6, 2079, time resolution: 1 minute, length: 4.• Datetime: date range: January 1, 1753, through December 31, 9999, time resolution: 3.33 milliseconds, length: 8• date stores only date values with a range of 0001-01-01 through 9999-12- 31.• time stores only time values with a range of 00:00:00.0000000 through 23:59:59.9999999.• datetime2 has a larger year and second range. 2007-05-08 12:35:29. 1234567• datetimeoffset lets you consider times in different zones. 2007-05-08 12:35:29.1234567 +12:15
    16. 16. Character data types
    17. 17. demo
    18. 18. ANSI SQL – T-SQL•A History and Definition of ANSI SQL and T-SQL• Developed in the early 1970s• ANSI-SQL defined by the American National Standards Institute• Microsoft implementation is T-SQL, or Transact SQL• Other implementations include PL/SQL and SQL Procedural Language.
    19. 19. Categories of SQL Statements• DML – Data Manipulation Language INSERT Table1 VALUES (1, Row #1) • DCL – Data Control Language GRANT CONNECT TO guest; GRANT CONTROL SERVER TO user_name; • DDL – Data Definition Language CREATE USER user_name • TCL - Transactional Control Language COMMIT TRANSACTION Inner2; • DQL - SQL Select Statements SELECT ProductID, Name, ListPrice FROM Production.Product
    20. 20. Basic T-SQL SyntaxThere are four primary properties to the SELECT statement 1 The number and attributes of the columns in the result set 2 The tables from which the result set data is retrieved 3 The conditions the rows in the source tables must meet 4 The sequence which the rows of the result set are ordered SELECT ProductID, Name, ListPrice FROM Production.Product WHERE ListPrice > $40 ORDER BY ListPrice ASC
    21. 21. Types of T-SQL Operators Type Operators • +, -, *, /, %• Arithmetic operators Vacation + SickLeave AS Total PTO • =• Assignment operator SET @MyCounter = 1 • =, <, >, <>, !, >=, <=• Comparison operators IF (@MyProduct <> 0) … • AND, OR, NOT• Logical operators WHERE Department = ‘Sales AND (Shift = Evening OR Shift = Night)• String concatenation • + SELECT LastName + , + FirstName operator AS Moniker
    22. 22. What Are T-SQL Functions? Functions NotesRowset • Return objects that can be used as table references Examples: CONTAINSTABLE, OPENDATASOURCE, OPENQUERYAggregate • Operate on a collection but returns a single value Examples: AVG, CHECKSUM_AGG, SUM, COUNRanking • Return a ranking value for each row in a partition Examples: RANK, DENSE_RANKScalar • Operate on a single value and then return a single value Examples: CREATE FUNCTION dbo.ufn_CubicVolume
    23. 23. Commenting T-SQL Code• Comments are statements about the meaning of the code• When used, there is no execution performed on the textThere are two ways to comment code using T-SQL:• The use of a beginning /* and ending */ creates comments /* This is a comment */• The double dash comments to the end of line --This is a comment
    24. 24. demo
    25. 25. Querying SQL Server 2008 Databases Tool Description• SQL Server • Used for interactive creation of T-SQL scripts Management Studio • To access, configure, manage, and create SSMS many other SQL Server Objects • A spreadsheet used by financial and• Microsoft Office Excel business professional to retrieve data • A command used by administrators for• SQLCMD command line and batch files processing SQLCMD –S serverinstance –i C:script • An environment used by administrators for• PowerShell command line and batch processing
    26. 26. What is a SQL Server Solution? SQL Server Management Studio provides two containers for managing database projects:A solution includes projects and files that define the solutionA project is a set of files, plus related metadataWhen you create a project, a solution is created to contain it
    27. 27. demo

    ×