Download presentation
Presentation is loading. Please wait.
Published byCarol Ami Phillips Modified over 8 years ago
1
Course 2778A Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Presentation: 60 minutes Lab: 60 minutes Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 This module helps students to : get started with databases and transact-SQL in SQL server 2008. After completing this module, students will be able to: Understand SQL Server 2008 Understand SQL Server Databases Understand the SQL Language Understand syntax Elements of T-SQL Work with T-SQL Scripts Use T-SQL Querying Tools Required materials To teach this module, you need the Microsoft Office PowerPoint® file 2778A_01.ppt. Important It is recommended that you use PowerPoint 2002 or a later version to display the slides for this course. If you use PowerPoint Viewer or an earlier version of PowerPoint, all the features of the slides might not be displayed correctly. Preparation tasks To prepare for this module: Read all of the materials for this module. Practice performing the demonstrations and the lab exercises. Work through the Module Review and Takeaways section and determine how you will use this section to reinforce student learning and promote knowledge transfer to on-the-job performance. Make sure that students are aware that there are additional information and resources for the module on the Course Companion CD.
2
Course 2778A Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Overview of SQL Server 2008 Overview of SQL Server Databases Overview and Syntax Elements of T-SQL Working with T-SQL Scripts Using T-SQL Querying Tools
3
Lesson 1: Overview of SQL Server 2008
Course 2778A Lesson 1: Overview of SQL Server 2008 Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Overview of Client/Server Architecture SQL Server Components SQL Server Management Tools SQL Server Database Engine Components
4
Overview of Client/Server Architecture
Course 2778A Overview of Client/Server Architecture Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Two-tier Multitier Explain the difference between single-user and client/server architecture applications. Remind students that client/server architecture involves the use of a client to connect to a server for processing. Be sure to mention that the 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, and is also known as a thick client. In a multitier system, an application server handles the business logic and communicates with the SQL database server. Question: What types of Client/Server architecture systems do you use at your current organization? Answers will vary, but will include multitier web applications and two-tier client line of business applications. References Chapter 7 - Client/Server Architecture: File-Server vs. Client/Server: SQL Database Server SQL Database Server OLE DB Components OLE DB Components Business Logic Business Logic Application Server Display Code Client Computer Display Code Client Computer
5
Course 2778A SQL Server Components Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Server Components Description SQL Server Database Engine Core service for storing and processing data Analysis Services Tools for creating and managing analytical processing Reporting Services Components for creating and deploying reports Integration Services Tools for moving, copying, and transforming data 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) and data mining applications. Reporting 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: The Database Engine also features these components: Full-Text Search Replication Service Broker Notification Services
6
SQL Server Management Tools
Course 2778A SQL Server Management Tools Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Management tools Description SQL Server Management Studio An environment to access, configure, manage, and administer SQL components SQL Server Configuration Manager An interface to provide management for SQL services, protocols, and client aliases SQL Server Profiler A GUI tool to profile and trace the Database Engine and Analysis Services Database Engine Tuning Advisor An application to create an optimal sets of indexes, indexed views, and partitions Business Intelligence Development Studio An IDE for creating Analysis Services, Reporting Services, and Integration Services solutions 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 Studio SQL 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 Manager SQL Server Configuration Manager provides basic configuration management for SQL Server services, server protocols, client protocols, and client aliases. SQL Server Profiler SQL 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 Advisor Database Engine Tuning Advisor helps create optimal sets of indexes, indexed views, and partitions. Business Intelligence Development Studio The 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:
7
SQL Server Database Engine Components
Course 2778A SQL Server Database Engine Components Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Components Description Protocols Ways to implement the external interface to the SQL Server Relational Engine Interface into the storage engine, composed of services to interact with the underlying database storage components and features Storage Engine Core of SQL Server, a highly scalable and available service for data storage, processing, and security SQLOS Operating system with a powerful API, which brings together all system components, enabling innovation of SQL Server’s scalability and performance, providing manageability and supportability features Explain to students that the Database Engine is the core service for storing, processing, and securing data. Explain how the Database Engine provides controlled access and rapid transaction processing to meet the requirements of the most demanding data consuming applications. Be sure to mention that they can use the Database Engine to create relational databases for online transaction processing or online analytical processing data. Protocols Used to implement the external interface to the SQL Server. To connect to SQL Server Database Engine you must have a network protocol enabled. Microsoft SQL Server can service requests on several protocols at the same time. Clients connect to SQL Server with a single protocol. If the client program does not know which protocol SQL Server is listening on, configure the client to sequentially try multiple protocols. Use SQL Server Configuration Manager to enable, disable, and configure network protocols. Relational Engine The relational engine provides an interface into the storage engine, which is composed of services to interact with the underlying database storage components and features. The main responsibilities of the relational engine are: Parsing the SQL statements. The parser scans an SQL statement and breaks it down into the logical units, such as keywords, parameters, operators, and identifiers. The parser also breaks down the overall SQL statement into a series of smaller logical operations. Optimizing the execution plans. Typically, there are many ways that the server could use data from the source tables to build the result set. The query optimizer determines what these various series of steps are, estimates the cost of each series, and chooses the series of steps that has the lowest cost. It then combines the specific steps with the query tree to produce an optimized execution plan. Executing the series of logical operations defined in the execution plan. After the query optimizer has defined the logical operations required to complete a statement, the relational engine steps through these operations in the sequence specified in the optimized execution plan. Processing Data Definition Language and other statements. These statements are not the typical SELECT, INSERT, UPDATE, or DELETE statements; these statements have special processing needs. Examples are the SET statements to set connection options, and the CREATE statements to create objects in a database. Formatting results. The relational engine formats the results returned to the client. The results are formatted as either a traditional, tabular result set or as an XML document. The results are then encapsulated in one or more Tabular Data Stream (TDS) packets and returned to the application. References: Components of the SQL Server Database Engine:
8
Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane.
Course 2778A Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane. Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Storage Engine The SQL Server 2008 database engine implements a highly scalable and available service for data storage, processing, and security to meet the requirements of the most demanding data systems. The primary responsibilities of the storage engine include: Providing features to improve ease of use for managing storage components Managing the data buffers and all I/O to the physical files Controlling concurrency, managing transactions, locking, and logging Managing the files and physical pages used to store data Recovering from system faults SQLOS The latest version of SQL Server features SQLOS - a user level highly configurable operating system with powerful API, enabling automatic locality and advanced parallelism. SQLOS attempts to hide the complexity of underlying hardware from high level programmers and at the same time it provides powerful and comprehensive set of features to programmers willing to take advantage of the hardware underneath the system. SQLOS provides operating system services such as a non preemptive scheduling, memory management, deadlock detection, exception handling, hosting for external components such as Common Language Runtime, CLR and other services. The goals of SQLOS include bringing all system components together, enabling further innovation of SQL Server’s scalability and performance, providing manageability and supportability features. It exposes cohesive API to developers so that they can easily exploit features of hardware and the operating system. SQLOS models its internals to simplify developing process as for high and as for low end platforms. SOS’s scheduling subsystem consists of scheduling nodes, schedulers, tasks, workers and system threads. A scheduling node provides an abstraction layer over group of CPUs. On NUMA systems scheduling node represents a single NUMA node. On SMP box there is one scheduling node. It is possible to change a number of nodes by editing Windows registry. As you would expect a node also is a collection of schedulers. A scheduler is an abstraction over a CPU. Schedulers deal with tasks that run by workers that get executed by system threads. Reference: SQL Server Overview: Components of the SQL Server Database Engine: Considerations for Installing the SQL Server Database Engine:
9
Lesson 2: Overview of SQL Server Databases
Course 2778A Lesson 2: Overview of SQL Server Databases Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Overview of Relational Databases What Is Normalization? The Normalization Process SQL Server Database Objects Overview of Data Types
10
Overview of Relational Databases
Course 2778A Overview of Relational Databases Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Relational databases store data in multiple interrelated tables The tables have one-to-many relationships 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: Relational Database Components: Database Engine Concepts: Relational Databases: Orders OrderID CustomerID EmployeeID OrderDate ShippedDate ShipVia Freight Order Details OrderID ProductID UnitPrice Quantity Products ProductID ProductName SupplierID UnitPrice UnitsInStock Discontinued
11
The process for removing redundant data from a database
Course 2778A What Is Normalization? Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 The process for removing redundant data from a database Benefits Accelerates sorting and indexing ü 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: SQL Database Normalization Rules: Allows more clustered indexes ü Helps UPDATE performance ü More compact databases ü Disadvantages Increase in tables to join Slower data retrieval Insertion of code in tables Difficulty in data model query
12
The Normalization Process
Course 2778A The Normalization Process Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 First Normal Form Second Normal Form Third Normal Form Order Details ProdCategory Product1 Product2 Order Details ProdCat_ID ProductID 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. Accounts Accountnumber Address PostCode Accounts Address PostCode City PostCode City State Orders Quantity Price Total Orders Quantity Price Customer ID Telephone Number 123 456 789 Customer ID First Name Surname 123 Robert Ingram 456 Jane Wright 789 Maria Fernandez
13
Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane.
Course 2778A Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane. Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 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: SQL Database Normalization Rules:
14
SQL Server Database Objects
Course 2778A SQL Server Database Objects Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Objects Notes Tables Contain all the data in SQL Server databases Views Act like a virtual table or a stored query Indexes Enable fast retrieval, built from one or more columns in table or view Triggers Execute a batch of SQL code when an insert, update or delete command is executed against a specific table Procedures Accept parameters, contain statements, and return values. Constraints Prevent inconsistent data from being placed in a column Rules Specify acceptable values that can be inserted in column Provide an overview of a number of database objects. 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. Note: DEFAULT keyword depreciated in SQL Server 2008 in CREATE TABLE and ALTER TABLE. CHECK keyword depreciated in SQL Server 2008 in CREATE TABLE and ALTER TABLE. 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 statements the same way a table is referenced. 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.
15
Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane.
Course 2778A Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane. Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Triggers A trigger is a database object that is attached to a table. In many aspects it is similar to a stored procedure. As a matter of fact, triggers are often referred to as a "special kind of stored procedure." The main difference between a trigger and a stored procedure is that the former is attached to a table and is only fired when an INSERT, UPDATE or DELETE occurs. You specify the modification action(s) that fire the trigger when it is created. Note: WITH APPEND clause on triggers depreciated in SQL Server Instead, re-create the whole trigger. Use CREATE TRIGGER WITH APPEND. 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). You can use the Transact-SQL EXECUTE statement to run a stored procedure. Stored procedures are different from functions in that they do not return values in place of their names and they cannot be used directly in an expression. Constraints The primary job of a constraint is to enforce a rule in the database. Together, the constraints in a database maintain the integrity of the database. For instance, we have foreign key constraints to ensure all orders reference existing products. You cannot enter an order for a product the database does not know about. Maintaining integrity is of utmost importance for a database, so much so that we cannot trust users and applications to enforce these rules by themselves. Once integrity is lost, you may find customers are double billed, payments to the supplier are missing, and everyone loses faith in your application. Rules A rule specifies the acceptable values that can be inserted into that column. Reference: Identifiers: Using Extended Properties on Database Objects: Database Engine Concepts:
16
Course 2778A Overview of Data Types Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 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, binary 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 are organized into the following categories: Exact numerics Unicode character strings Approximate numerics Binary strings Date and time Other data types Character strings
17
Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane.
Course 2778A Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane. Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Data types in SQL Server are organized into the following categories: Exact numerics bigint, numeric, bit, smallint, decimal, smallmoney, int, tinyint, money Unicode character strings nchar, nvarchar, ntext Approximate numerics float, real Binary strings binary, varbinary, image Date and time date, datetimeoffset, datetime2, smalldatetime, datetime, time Other data types cursor, timestamp, hierarchyid, uniqueidentifier, sql_variant, xml, table Character strings char, varchar, text In 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 xml References Data Types (Transact-SQL):
18
Lesson 3: Overview and Syntax Elements of T-SQL
Course 2778A Lesson 3: Overview and Syntax Elements of T-SQL Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 A History and Definition of ANSI SQL and T-SQL Categories of SQL Statements Introduction to Basic T-SQL Syntax Types of T-SQL Operators What Are T-SQL Functions? What Are T-SQL Variables? What Are T-SQL Expressions? Control-of-flow Statements
19
A History and Definition of ANSI SQL and T-SQL
Course 2778A A History and Definition of ANSI SQL and T-SQL Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Developed in the early 1970s Discuss ANSI SQL, and compare it to SQL Server T-SQL. History of SQL SQL 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 SQL The process of implementing a standard as defined by ANSI can take some time by vendors. An example is SQL-99. This was defined in 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 SQL Microsoft’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 SQL There 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: 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.
20
Categories of SQL Statements
Course 2778A Categories of SQL Statements Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 DML – Data Manipulation Language INSERT Table1 VALUES (1, 'Row #1') DCL – Data Control Language Discuss the various categories of SQL Statements. Data Manipulation Language (DML) DML is 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) DCL is 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) DDL is 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 Statements SQL 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): 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
21
Introduction to Basic T-SQL Syntax
Course 2778A Introduction to Basic T-SQL Syntax Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 There are four primary properties to the SELECT statement The number and attributes of the columns in the result set 1 The tables from which the result set data is retrieved 2 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: Transact-SQL Syntax Conventions (Transact-SQL): The conditions the rows in the source tables must meet 3 The sequence which the rows of the result set are ordered 4 SELECT ProductID, Name, ListPrice FROM Production.Product WHERE ListPrice > $40 ORDER BY ListPrice ASC
22
Types of T-SQL Operators
Course 2778A Types of T-SQL Operators Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Type Operators Arithmetic operators +, -, *, /, % Vacation + SickLeave AS 'Total PTO' Assignment operator = = 1 Comparison operators =, <, >, <>, !, >=, <= IF <> 0) … Logical operators AND, OR, NOT WHERE Department = ‘Sales' AND (Shift = 'Evening' OR Shift = 'Night') String concatenation operator + SELECT LastName + ', ' + FirstName AS Moniker 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, % integer Used 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 – AND Either term in a topic - OR First term without the second term - NOT String Concatenation String 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):
23
What Are T-SQL Functions?
Course 2778A What Are T-SQL Functions? Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Functions Notes Rowset Return objects that can be used as table references Examples: CONTAINSTABLE, OPENDATASOURCE, OPENQUERY Aggregate Operate on a collection but returns a single value Examples: AVG, CHECKSUM_AGG, SUM, COUN Ranking Return a ranking value for each row in a partition Examples: RANK, DENSE_RANK Scalar Operate on a single value and then return a single value Examples: CREATE FUNCTION dbo.ufn_CubicVolume Discuss several functions within T-SQL. Rowset Functions - Return an object that can be used like table references in an SQL statement Example: 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 value Example: 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 partition Example: GO SELECT 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.PostalCode FROM Sales.SalesPerson s INNER JOIN Person.Contact c ON s.SalesPersonID = c.ContactID INNER JOIN Person.Address a ON a.AddressID = c.ContactID WHERE TerritoryID IS NOT NULL AND SalesYTD <> 0; Scalar Functions - Operate on a single value and then return a single value SELECT ProductModelID, Name, dbo.ufnGetInventoryStock(ProductID)AS CurrentSupply FROM Production.Product WHERE 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):
24
What Are T-SQL Variables?
Course 2778A What Are T-SQL Variables? Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 A Transact-SQL local variable is an object that can hold a single data value of a specific type Variables in batches and scripts are typically used to: Explain to students that variables are designed to hold values. Remind students that the variable has a data type that is defined. Use of the declare and set are shown to create, then populate the value of a variable. A Transact-SQL local variable is an object that can hold a single data value of a specific type. Variables in batches and scripts are typically used: As a counter either to count the number of times a loop is performed or to control how many times the loop is performed. To hold a data value to be tested by a control-of-flow statement. To save a data value to be returned by a stored procedure return code or function return value. The DECLARE statement initializes a Transact-SQL variable by: Assigning a name. The name must have a as the first character. Assigning a system-supplied or user-defined data type and a length. For numeric variables, a precision and scale are also assigned. For variables of type XML, an optional schema collection may be assigned. Setting the value to NULL. Setting a Value in a Transact-SQL Variable When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement. To assign a variable a value by using the SET statement, include the variable name and the value to assign to the variable. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in a select list. If a variable is referenced in a select list, it should be assigned a scalar value or the SELECT statement should only return one row. If a SELECT statement returns more than one row and the variable references a nonscalar expression, the variable is set to the value returned for the expression in the last row of the result set. A variable can be set dynamically with code similar to the following: USE Northwind AS decimal(10, 4) UPDATE [Order Details] SET UnitPrice = UnitPrice * 1.1 WHERE OrderID = 10248 = (SELECT SUM(Quantity * UnitPrice) FROM [Order Details] WHERE OrderID = 10248) References: Transact-SQL Variables: Count the number of times a loop is performed Hold data to be tested by a control-of-flow statement Save data values to be returned by a function return value as <data_type> varchar(20) = 'ice cream' … WHERE Description
25
What Are T-SQL Expressions?
Course 2778A What Are T-SQL Expressions? Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Symbols and operators evaluated to obtain a single value Expressions can be combined if one of these is true: Explain to students that expressions are combination of symbols and operators that the SQL Server Database Engine evaluates to obtain a single data value. Remind students that simple expressions can be a single constant, variable, column, or scalar function. Operators can be used to join two or more simple expressions into a complex expression. Two expressions can be combined by an operator if they both have data types supported by the operator and at least one of these conditions is true: The expressions have the same data type. The data type with the lower precedence can be implicitly converted to the data type with the higher data type precedence. If the expressions do not meet these conditions, the CAST or CONVERT functions can be used to explicitly convert the data type with the lower precedence to either the data type with the higher precedence or to an intermediate data type that can be implicitly converted to the data type with the higher precedence. If there is no supported implicit or explicit conversion, the two expressions cannot be combined. References: Expressions (Transact-SQL): The expressions have the same data type The data type with the lower precedence can be converted to the data type with the higher precedence SELECT ProductID, Variable_N +2
26
Control-of-flow Statements
Course 2778A Control-of-flow Statements Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 These are the control-of-flow keywords: BEGIN...END BREAK GOTO CONTINUE Explain to students that T-SQL provides special words called control-of-flow language that control the flow of execution of T-SQL statements, statement blocks, user-defined functions, and stored procedures. Explain that, without control-of-flow language, separate T-SQL statements are performed sequentially, as they occur. Control-of-flow language permits statements to be connected, related to each other, and made interdependent using programming-like constructs. These control-of-flow words are useful when you need to direct T-SQL to take some kind of action. For example, use a BEGIN...END pair of statements when including more than one T- SQL statement in a logical block. Use an IF...ELSE pair of statements when a certain statement or block of statements needs to be executed IF some condition is met, and another statement or block of statements should be executed if that condition is not met. The control-of-flow statements cannot span multiple batches, user-defined functions, or stored procedures. WAITFOR blocks the execution of a batch, stored procedure, or transaction until a specified time or time interval is reached, or a specified statement modifies or returns at least one row. Uses of WAITFOR WAITFOR TIME '22:20'; WAITFOR DELAY '02:00'; References: Control-of-Flow: Conditional Statement Syntax: IF...ELSE WHILE RETURN WAITFOR IF Boolean_expression BEGIN { sql_statement | statement_block } END ELSE
27
Lesson 4: Working with T-SQL Scripts
Course 2778A Lesson 4: Working with T-SQL Scripts Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 What Are Batch Directives? Structured Exception Handling Commenting T-SQL Code
28
What Are Batch Directives?
Course 2778A What Are Batch Directives? Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 These control movement within a T-SQL file Present an overview of batch directives. Explain how batch directives control the movement and script execution within a T-SQL file. GO is a batch directive which signals to SQL Server to execute the batch. You use GO in sqlcmd to execute a query rather than the enter key. A transaction, by default, is automatically committed in SQL Server unless the transaction is placed within a BEGIN TRANSACTION clause. Provide an example of a IF…ELSE statement and how the statements are skipped. Explain how If is the first statement is printed, otherwise the second statement after the ELSE is printed Here is the full script: EXECUTE usp_GetList '%Bikes%', 700, @compareprice OUT, @cost OUTPUT BEGIN PRINT 'These products can be purchased for less than AS varchar(20)))+'.' END ELSE PRINT 'The prices for all products in this category exceed $'+ AS varchar(20)))+'.‘ GO References: ELSE (IF...ELSE): BEGIN PRINT 'These products can be purchased for less than AS varchar(20)))+'.' END ELSE PRINT 'The prices for all products in this category exceed $'+ AS varchar(20)))+'.‘ GO
29
Structured Exception Handling
Course 2778A Structured Exception Handling Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 TRY/CATCH BEGIN TRY -- Generate divide-by-zero error. SELECT 1/0; END TRY BEGIN CATCH -- Execute error retrieval routine. EXECUTE usp_GetErrorInfo; END CATCH; Discuss error handling and exception handling at a high level. A group of SQL statements are enclosed within a TRY statement. If an error is found control is passed to the CATCH block. The CATCH block follows immediately after the TRY block. Note that TRY/CATCH constructs can be nested. Either a TRY block or a CATCH block can contain nested TRY/CATCH constructs. For example, a CATCH block can contain an embedded TRY/CATCH construct to handle errors encountered by the CATCH code. RAISERROR allows the creation of an error message. These can be used within a TRY/CATCH to create and event that displays a customized message. References: TRY...CATCH (Transact-SQL): RAISERROR (Transact-SQL): RAISERROR RAISERROR (N'This is message %s %d.', -- Message text. 10, -- Severity, 1, -- State, N'number', -- First argument. 5); -- Second argument. -- The message text returned is: This is message number 5. GO
30
Commenting T-SQL Code There are two ways to comment code using T-SQL:
Course 2778A Commenting T-SQL Code Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Comments are statements about the meaning of the code When used, there is no execution performed on the text 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): -- (Comment) (Transact-SQL): Using Comments: There 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
31
Lesson 5: Using T-SQL Querying Tools
Course 2778A Lesson 5: Using T-SQL Querying Tools Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Tools for Querying SQL Server 2008 Databases An Introduction to SQL Server Management Studio What Is a SQL Server Solution? Creating SQL Server Solutions Executing Queries in SQL Server Management Studio Generating Reports in Microsoft Office Excel
32
Tools for Querying SQL Server 2008 Databases
Course 2778A Tools for Querying SQL Server 2008 Databases Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Tool Description SQL Server Management Studio Used for interactive creation of T-SQL scripts To access, configure, manage, and create many other SQL Server Objects Microsoft Office Excel A spreadsheet used by financial and business professional to retrieve data SQLCMD A command used by administrators for command line and batch files processing SQLCMD –S server\instance –i C:\script PowerShell An environment used by administrators for command line and batch processing Provide an overview of common application that are used to Querying SQL Server 2008. SQL Server Management Studio SQL Server Management Studio is the tool used for interactive creation of T-SQL scripts. It is also used to manage SQL Server 2008. Microsoft Office Excel® Excel is for use in analysis and reporting. SQLCMD SQLCMD is a command used by system administrator for using command line and batch files for processing. PowerShell PowerShell is an environment used by system administrator for using command line and batch files for processing. Explain the use and application of PowerShell. bcp utility The 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 Utility The 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. Question: Have you used any of these tools for querying SQL Server databases? Answers will vary. Discuss the experiences and normal uses of these tools. References: Query Tools: bcp Utility: sqlcmd Utility:
33
An Introduction to SQL Server Management Studio
Course 2778A An Introduction to SQL Server Management Studio Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Support for writing and editing queries or scripts Integrated source control for solution and script projects Provide an overview of SQL Server Management Studio and its use with SQL Server 2008. The features listed below highlight a portion of its capabilities: Support for writing and editing queries or scripts without requiring a connection to a server. Integrated source control for solution and script projects, supporting storing and maintaining copies of scripts as they evolve over time. Supports most administrative tasks for SQL Server. An integrated Web browser for quick browsing of MSDN or online help. SQL Server Management Studio also includes the following general features: A single, integrated environment for SQL Server Database Engine management and authoring. New management dialogs for managing objects in the SQL Server Database Engine, Analysis Services, Reporting Services, Notification Services, and SQL Server Compact 3.5 SP1, that allows you to execute your actions immediately, send them to a Code Editor, or script them for later execution. Non-modal and resizable dialogs allow access to multiple tools while a dialog is open. A common scheduling dialog that allows you to perform action of the management dialogs at a later time. Exporting and importing SQL Server Management Studio server registration from one Management Studio environment to another. Save or print XML Showplan or Deadlock files generated by SQL Server Profiler, review them later, or send them to administrators for analysis. A new error and informational message box that presents much more information, allows you to send Microsoft a comment about the messages, allows you to copy messages to the clipboard, and allows you to easily the messages to your support team. Integration of Help from online communities. A new activity monitor with filtering and automatic refresh. Integrated Database Mail interfaces. References: Features in SQL Server Management Studio: Supports most administrative tasks for SQL Server An integrated Web browser for quick browsing
34
What is a SQL Server Solution?
Course 2778A What is a SQL Server Solution? Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 SQL Server Management Studio provides two containers for managing database projects: 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: Introduction to Solutions, Projects, and Items: Solutions Projects A solution includes projects and files that define the solution A project is a set of files, plus related metadata When you create a project, a solution is created to contain it
35
Creating SQL Server Solutions
Course 2778A Creating SQL Server Solutions Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Solutions contain scripts, queries, connection information and files that you need to create your database solution Use these containers to: Provide an overview of creating SQL Server solutions. Explain how, when you create a project, SQL Server Management Studio creates a solution to contain it. You can only open one solution at a time. SQL Server Management Studio does not allow you to create folders within projects. To organize your work, create multiple projects. Use Solution Explorer to handle the details of file management while you focus on items that make up your database solution. Solutions and projects contain items that represent the scripts, queries, connection information and files that you need to create your database solution. Quick Demo - To create a new solution and project: On the File menu, point to New, and then click Project. In the New Project dialog box, click a type of project. Optionally modify the project name in the Name text box. Optionally modify the path for the solution in the Location text box. Optionally modify the solution name in the Solution Name text box. Click OK. References: Introduction to Solutions, Projects, and Items: How to: Create New Solutions: Implement source control on queries and scripts Manage settings for your solution Handle the details of file management Add items useful to multiple projects in to one solution Work on miscellaneous files independent from solutions
36
Executing Queries in SQL Server Management Studio
Course 2778A Executing Queries in SQL Server Management Studio Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Executing queries occurs when in a query session by: Create queries by interactively entering them in a query window Load a file that contains T-SQL and then execute commands or modify then execute Selecting the Execute Icon Pressing the F5 key Discuss how to execute a query. Explain how SQL Server Management Studio provides two ways to access and change data. SQL Server Management Studio provides two ways to access and change data: From the File menu or the New Query and Database Engine Query buttons in the toolbar, you can open a Database Engine Query window. In the Database Engine Query window you can interactively code Transact-SQL and XQuery statements to query databases and change the data. You can save the statements as script files that can then be run using the sqlcmd utility. The Database Engine Query Editor supports dynamic F1 help, auto-completion, code outlining, a Transact-SQL debugger, IntelliSense, and other productivity aids. In the Object Explorer, you can right-click tables or views and select menu items that let you select or edit rows. Quick Demo From the File menu or the New Query and Database Engine Query buttons in the toolbar, you can open a Database Engine Query window. In the Database Engine Query window enter the following query: USE AdventureWorks2008 GO UPDATE Person.Person SET Promotion = 0 WHERE PersonType = ‘EM’ Save the statements as script files. Open sqlcmd and display the /? screen to show the available switches. Point out common switches such as –S and –i and –o. Run using the sqlcmd utility. References: Query Tools:
37
Generating Reports in Microsoft Office Excel
Course 2778A Generating Reports in Microsoft Office Excel Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Connect to Database Server 1 Select Database and Table 2 Outline the steps needed to generate reports from SQL Server using Excel. 1) You can use an Office Data Connection (.odc) file to connect to a Microsoft SQL Server database from a Microsoft Office Excel 2007 file. 2) MS Query can also be used to customize the type of information you would like to retrieve. Quick Demo On the Data tab, in the Get External Data group, click From Other Sources, and then click From Microsoft Query. In the Choose Data Source dialog box, make sure that the Use the Query Wizard to create/edit queries check box is clear. Double-click the data source that you want to use. References: Connect to (import) SQL Server data: Use Microsoft Query to retrieve external data: Save Data Connection File 3 Import Data and Select Format 4
38
Lab: Using SQL Server Management Studio and SQLCMD Page 50
Course 2778A Lab: Using SQL Server Management Studio and SQLCMD Page 50 Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Exercise 1: Explore the components and execute queries in SQL Server Management Studio Exercise 2: Start and use sqlcmd Exercise 3: Generate a report from a SQL Server database using Microsoft Office Excel In this lab the students will explore and execute queries in SQL Server Management Studio, generate reports from the AdventureWorks2008 database, and use sqlcmd. Exercise 1 In this exercise, students explore SQL Server Management Studio and make changes to the environment, add projects to a solution. Students will then open and execute a query, then write a query to return all table rows. The student launches SQL Server Management Studio. The student views help content. The student customizes SQL Server Management Studio. The student creates a SQL Server solution. The student adds projects to an existing solution. The student opens and executes a query. The student writes a query to return all table rows. Exercise 2 In this exercise, students will start and use sqlcmd. The student starts the sqlcmd utility and connects to a default instance of SQL Server. The student runs Transact-SQL script files by using sqlcmd. The student runs Transact-SQL script files by using sqlcmd To save this output to a text file. The student reviews the output file. Exercise 3 In this exercise, students will generate a report from a SQL Server database using Microsoft Office Excel. The student launches Excel. The student creates a new data connection in the workbook. The student selects the data to import and its format. The student views the report. Logon information Virtual machine NY-SQL-01 User name Student Password Pa$$w0rd Estimated time: 60 minutes
39
Course 2778A Lab Scenario Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 You are the database administrator of Adventure Works. The Human Resources department requires that you generate several reports by using SQL Server You need to generate reports with a list of employee addresses sorted by departments or a list of addresses of employees residing in the United States. You also need to analyze the details of the newly hired employees by using a database diagram in SQL Server Management Studio. To do this, you will explore and execute queries in SQL Server Management Studio, generate reports from the AdventureWorks database, and examine the database diagram in SQL Server Management Studio.
40
Lab Review Why would we execute a T-SQL command using sqlcmd?
Course 2778A Lab Review Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Why would we execute a T-SQL command using sqlcmd? What tools did we use in the lab to query the database? How is Excel useful when querying SQL Server databases? Use the questions on the slide to guide the debriefing after students have completed the lab exercises. Question: Why would we execute a T-SQL command using SQLCMD? SQLCMD can be launched from the command line, in a script or through an application, allowing a SQL script to be launched programmatically or without the Management Studio. Question: What are the four main tools for querying SQL Server 2008 databases? SQL Server Management Studio, Microsoft Office Excel, and SQLCMD. PowerShell can also query SQL Server 2008 databases, but we did not use it in the lab. Question: How is Excel useful when querying SQL Server 2008 databases? Excel can collect large amounts of data and perform visualization, reporting, and analysis on the desktop.
41
Module Review and Takeaways
Course 2778A Module Review and Takeaways Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008 Review Questions Best Practices Tools Review Questions Point the students to the appropriate section in the course so that they are able to answer the questions presented in this section. Q: What examples of a third tier client server architecture have you seen at work? A: An example of third tier client/server architecture would be a client that connects to a web server that connects to SQL Server 2008 for access to the data. Q: Which server management tool do we use to create optimal sets of indexes and partitions? A: Database Engine Tuning Advisor helps create optimal sets of indexes, indexed views, and partitions. Q: How would you quickly create graphs and reports from SQL data? A: Connect to the SQL database from an Excel file. Q: What are the two main parts of the relational database server? A: The relational database server of SQL Server has two main parts: the relational engine and the storage engine. Best Practices for Getting Started Transact-SQL in SQL Server 2008 Help the students understand the best practices presented in this section. Ask students to consider these best practices in the context of their own business situations. Formatting Capitalize reserve words. Code should be indented properly. Naming Objects Objects should be placed in square brackets. [Customers] Retain the case of the table names as in the database. [OrderDetails] Include schema in object names. Sales.Customers Use ANSI SQL Comment Code Tools Point out the location from which each key tool can be installed. Let students review the function and usage of each tool on their own. Remind students that they can use this as a master list to help them gather all the tools required to facilitate their application support work. Microsoft SQL Server Management Studio Managing SQL server databases and tables. Start | All Programs | Microsoft SQL Server 2008 SQL Server Business Intelligence Development Studio Managing SQL server applications. Start | All Programs | Microsoft SQL Server 2008
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.