01 ManagementStudio Lab

29
7/27/2019 01 ManagementStudio Lab http://slidepdf.com/reader/full/01-managementstudio-lab 1/29 Using the SQL Server Management Studio in SQL Server 2012 ***Special Note*** All SQL scripts needed for this Lab are now located on the Course Materials Page: http://sharepoint.ssw.com.au/Training/UTSSQL/ After completing this lab, you will be able to: Use the new SQL Server Management Studio to perform basic SQL Server administration tasks. Use the new query interface in SQL Server Management Studio Generate scripts from database objects Manage scripts and database connections using Solution Explorer This lab focuses on the concepts in this module and as a result may not comply with Microsoft security recommendations. Exercise 0: Lab Setup From the Session Menu on the login screen, choose the UTS.NET session Enter the username and password you were given (not your UTS username/password) Your VMware image will start up automatically. If it does not, run the command vmware from a terminal window Objectives Note Estimated time to complete this lab: 60 minutes

Transcript of 01 ManagementStudio Lab

Page 1: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 1/29

Using the SQL Server Management

Studio in SQL Server 2012

***Special Note***All SQL scripts needed for this Lab are now located on the

Course Materials Page:http://sharepoint.ssw.com.au/Training/UTSSQL/ 

After completing this lab, you will be able to:

Use the new SQL Server Management Studio to perform basic SQL Server administration tasks.

Use the new query interface in SQL Server Management Studio

Generate scripts from database objects

Manage scripts and database connections using Solution Explorer 

This lab focuses on the concepts in this module and as a result may not comply with Microsoft securityrecommendations.

Exercise 0:

Lab Setup

From the Session Menu on the login screen, choose the UTS.NET session

Enter the username and password you were given (not your UTS username/password)

Your VMware image will start up automatically. If it does not, run the command vmware from a

terminal window

ObjectivesNote Estimated time tocomplete this lab: 60minutes

Page 2: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 2/29

2 Using the SQL Server Management Studio in SQL Server 2012

Exercise 1:

Exploring the Environment

In this exercise, you will become familiar with the new SQL Server 2012 administration tool, currently calledSQL Server Management Studio.

SQL Server Management Studio is a new tool built originally for SQL Server 2005 and upgraded for SQLServer 2008 and then 2012. It combines the functionality of the Enterprise Manager snap-in and the QueryAnalyzer. Although this is the main tool for administering one or more SQL Servers, you can also use the SQLServer Management Studio for executing queries and scripts, and for managing SQL Server projects. (One of the key enhancements with SQL Server management Studio 2008 is the addition of IntelliSense when writingSQL Queries.)

The SQL Server Management Studio tool is based on the Microsoft Development Environment used in VisualStudio 2010 to create applications. If you are not already familiar with Visual Studio 2010, using the SQLServer Management Studio tool will help you learn to use the new Microsoft Development Environment for Visual Studio 2010.

Task 1: Open SQL Server Management Studio and connect to your server

.1 From the Windows task bar, select Start | All Programs | Microsoft SQL Server 2012 | SQL Server

Management Studio.

.2 When the Connect to Server dialog box opens, verify that Database Engine is selected as the Server type,and verify that Windows Authentication is selected as the authentication method.

Figure 1: The Connect to Server dialog

.3 Click the Options button to display additional connection options.

.4 Click the Connection Properties tab. Note that the following options are available:

You can configure the network protocol to use for this connection, which might be differentthan the protocol you use for other connections.

You can configure a connection timeout, which controls how long to wait for the connection to be made.

You can configure an execution timeout to specify how long to wait for response from a query.

.5 Click Options again to hide the additional options tabs.

.6 Click Connect.

Page 3: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 3/29

Using the SQL Server Management Studio in SQL Server 2012 3

 Note the various areas of the SQL Server Management Studio:

The lower left pane is the Object Explorer, which looks like the tree view on the left side of SQL Server 2000Enterprise Manager. Above that is the Registered Servers pane, containing a list of servers to whichManagement Studio can connect. If you don’t see the Registered Servers pane, click View->Registered

Servers.

The right side of the SQL Server Management Studio contains the tools for managing projects. On the top rightis the Solution Explorer. Below that is the Properties Window. If the Solution Explorer is not visible, you canchoose to display it by selecting View | Solution Explorer. If the Properties window is not visible, you canalso enable that window from the View menu, or by right-clicking on any object in the Solution Explorer window and choosing Properties Window. At the moment, the Solution Explorer is blank because no solutionis currently loaded.

The location of all of these windows and browsers can be changed, and you can remove the ones you don’t wantor need. You can undock and move windows by double-clicking on the window’s title bar. There are optionsavailable for changing the layout and resetting the default layout from the Tools | Options menu.

If you close any of the windows, you can restore them from the View menu.

Task 3: Use TSQL to execute a stored procedure

1. Click the leftmost button (New Query) on the standard toolbar, and then select New SQLServer Query to open a SQL Query Window. When asked to connect to the server, click Connect.

2. The query window appears in the center portion of the SQL Server Management Studio, and is tabbed withthe Start Page. All additional query windows will be tabbed as well.

3. In the query window, enter the following code:

EXEC sp_who

4. Press F5 or click the Execute button on the toolbar  to execute the query.

 Note that you can disconnect from SQL Server without closing the query window by using the Query |Connection | Disconnect menu option. Alternatively, you can add a Disconnect or Disconnect All button to thetoolbar. Right-click on the toolbar and choose Customize. Go to the Commands tab and select Query in theleftmost list box. You can then drag any command from the rightmost list onto an existing toolbar. Click Close to dismiss this dialog box.

Task 4: Open and use a script file from a project

1. Download and save all the .sql scripts from

http://

2. Open ServerProperties.sql by clicking File->Open->File… and browse to the file

3. Type the following code into the SQL query window

USE master

SELECT SERVERPROPERTY('ServerName')

SELECT SERVERPROPERTY('Edition')

SELECT SERVERPROPERTY('ProductVersion')

SELECT SERVERPROPERTY('ProductLevel')

4. To execute the batch, press F5 or click the Execute button on the toolbar. If prompted, reconfirm your server name and authentication mode in the Connect to SQL Server dialog box.

Page 4: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 4/29

4 Using the SQL Server Management Studio in SQL Server 2012

5. You can also run a sub-set of the query by highlighting the relevant rows using your mouse. Then Hit F5 torun just those highlighted commands.

 Note the edition and version number of the SQL Server you are connected to. You may have to scroll down tosee all of the results.

Page 5: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 5/29

Using the SQL Server Management Studio in SQL Server 2012 5

Exercise 2:

Attaching a Database

In this exercise, you will attach the AdventureWorks database using the “Attach Database” option in the SQLServer Management Studio Object Explorer.

Attaching a database means making all the database files available to your SQL Server, just as if you hadcreated the database on the current server. Detaching a database allows you to move the physical files andreattach those files from a new physical location, or to make a copy of the files to use on another server (perhapsa test or development server).

Because the primary file contains the locations of all the other files in a database, if all the files are in their original location (as stored in the primary file) you only need to specify the primary file when attaching thedatabase. SQL Server will read the information in the primary file and attach all the associated files for thedatabase.

However, if the files are not all in the original location, the information stored in the primary file may not besufficient for SQL Server to find and attach all the database files. You will then need to specify the exact

 physical location of each database file that is not in the location it was when the database was detached.When a database is detached, SQL Server will do a checkpoint in the database, so all the committed transactionsare written to the disk files.

Task 1: If the database is already attached, detach it

1. In the Object Explorer, expand the WIN-8CACK3FIVKF tree node (if it's not already expanded) and thenDatabases folders.

2. If the AdventureWorks database is in the list, right-click on it. Otherwise, skip to the Attach the

AdventureWorks database task below.

3. Point to Tasks, and then click Detach.

4. In the Detach Databases dialog box, click OK .

.7

.8 Figure: Detach the AdventureWorks database if it is already attached to your server

.9 AdventureWorks may remain in the Databases list until the list is refreshed.

Page 6: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 6/29

Page 7: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 7/29

Using the SQL Server Management Studio in SQL Server 2012 7

Figure: The database properties window lets you examine all of the properties for the current

database

3. Click each of the categories in the left pane to see what properties are read-only and which are updateable.

AdventureWorks is a case and accent-sensitive database because a case and accent sensitive collation wasspecified when the database was created. This means that all the data in all the tables is case-sensitive.

The ANSI SQL standard says that regular (non-delimited) identifiers are not case sensitive. However, becauseSQL Server stores the metadata in tables, all of your object names (tables, columns, stored procedures, views,etc.) will also be case sensitive.

When you are typing queries, you must match the case of the table and column names exactly.

4. Click OK to close the Database Properties window.

Task 2: Write a query to examine some data

1. Open GroupBy.sql file. This adds the following SQL to the query window:

USE AdventureWorks

GO

SELECT City, StateProvinceID, CustomerCount = count(*)

FROM Person.AddressGROUP BY City, StateProvinceID

HAVING count(*) > 1

ORDER BY count(*) DESC

GO

2. Select the query you just entered, and then press F5 or click the Execute button on the toolbar  to execute thequery.

Note

Page 8: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 8/29

8 Using the SQL Server Management Studio in SQL Server 2012

Even though the GO is not necessary for SQL Server to execute the queries, or for you to select and runindividual batches, using GO is the only way that the query tool knows how to separate the batches.

Exercise 4:

Creating a new databaseIn this exercise, you will create a new database using a SQL Server Management Studio template. You willthen investigate the default properties of a new database.

Task 1: Create a new database using TSQL

1. Click the New Query button

A new query window will open. Enter the following SQL.

-- =============================================

-- Create database

-- =============================================

IF DB_ID (N'NewDB') IS NOT NULL

DROP DATABASE NewDB

GO

CREATE DATABASE NewDB

GO

2. Press F5 or click the Execute button on the toolbar , and click Connect if necessary.

Task 2: Explore your new database

1. In the Object Browser, expand Databases if necessary.

2. Right-click on Databases and click Refresh. A NewDB folder will appear.

3. Right-click on the NewDB folder and click Properties.

4. Explore the properties dialog box to see what properties exist for a newly created database.

Because the Properties window is not modal, you can open a separate Properties window for each database,making it easier to compare the two.

5. Close the Properties window(s) when you’re done.

Exercise 5:

Setting up Database Access

In this exercise, you will add two new logins to SQL Server, and add those logins to a role in your new database.

SQL Server 2012 simplifies the administration of SQL Server security by separating the implicit link betweenusers and the database objects that they own. Earlier versions of SQL Server required that you first drop or reassign all database objects that the users owned, which significantly complicated the process. SQL Server 2012 includes a new object permission model that addresses this issue.

By breaking the link between users and database objects, administration is simplified as follows:

Users can be dropped without having to drop or reassign database objects.

Users are associated with a default schema that is the owner of objects that the user creates.

Note

Page 9: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 9/29

Using the SQL Server Management Studio in SQL Server 2012 9

Schemas can be owned by roles, allowing multiple users to administer database objects withoutrequiring database-wide permissions.

Task 1: Create two new logins

1. Open a new query window and enter the following code. Alternatively, you can open the SQL scriptLogins.sql. 

USE master

GO

EXEC sp_addlogin NewUser1, pa$$word123, NewDB

EXEC sp_addlogin NewUser2, pa$$word123, NewDB

GO

EXEC sp_helplogins

GO

2. Press F5, or click the Execute button on the toolbar , to execute the query. If prompted, respond to theConnect to SQL Server dialog box.

You should now have two new logins, each with a password of ‘pa$$word123’ and a default database of 

 NewDB. Note by default SQL Server 2012 enforces password policy on logins. (refer to ms-help://MS.SQLCC.v10/MS.SQLSVR.v10.en/s10de_4deptrbl/html/c0040c0a-a18f-45b9-9c40-0625685649b1.htm )

Task 2: Add the new logins as database users

1. This step will add both of your new logins to the NewDB database. The login NewUser1 will be given adefault schema of DemoSchema. The login NewUser2 will not be given a specific default schema, so itsdefault schema will be dbo. Load the DbUsers.sql script.

USE NewDB

GO

CREATE USER NewUser1

WITH DEFAULT_SCHEMA = DemoSchemaGO

CREATE USER NewUser2

GO

2. Select the code you just entered, and press F5 or click the Execute button on the toolbar  to execute theselected statements.

In SQL Server 2012, you use CREATE USER to map a Server login to a database user instead of sp_grantdbaccess (this was used previous versions). Optionally, you can specify a login name using this syntax:

CREATE USER <user_name>

[FOR LOGIN <Login_name>][WITH DEFAULT_SCHEMA schema_name]

If no login name is specified, then the user is associated with the login of the same name as that of the<user_name>. If no such login exists the CREATE USER fails. (However, if the name specified wereinterpreted to be a Windows login in the form DOMAIN\loginname, the CREATE USER would not fail.)

The <login_name> can be a Windows login, a Windows group or a SQL Login.

 Note that you can give a user a default schema, even though the schema has not been created yet. The defaultschema is the schema name that will automatically be assumed when a query is run, if a schema is not explicitly

Page 10: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 10/29

10 Using the SQL Server Management Studio in SQL Server 2012

specified. The default schema applies to all DML and DDL statements: SELECT, INSERT, UPDATE andDELETE, as well as CREATE TABLE and ALTER TABLE.

Task 3: Create a database role and add users to it.

1. In this step, you will create a database role named DemoUsers and you will create a schema of the samename, owned by that role. The two commands you will use are the equivalent of sp_addrole. You’ll add

 both new users to that role. This code is in the SQL script RolesAndSchemas.sql. Load this code.

USE NewDB

GO

CREATE ROLE DemoUsers

GO

CREATE SCHEMA DemoUsers AUTHORIZATION DemoUsers

GO

EXEC sp_addrolemember DemoUsers, NewUser1

EXEC sp_addrolemember DemoUsers, NewUser2

EXEC sp_addrolemember db_datareader, DemoUsers

GO

2. Select the code you just entered, and press F5, or click the Execute Button on the toolbar , to execute theselected statements.

 Note that you can make a role a member of another role. In this case, you made the user-defined roleDemoUsers a member of the predefined database role db_datareader.

Task 4: Create a schema and a table owned by the schema

1. In this step, you will add a schema owned by the role DemoUsers. You’ll verify that the schema was created by looking in the schemas table. This code is in the SQL script Schemas.sql. Load this code:

USE NewDB

GO

CREATE SCHEMA DemoSchema AUTHORIZATION DemoUsers

GO

SELECT * FROM sys.schemas

GO

2. Select the code you just entered, and press F5 or click the Execute button on the toolbar  to execute theselected statements. In your results, you should see all of the predefined database roles, as well as any user-defined roles created with sp_addrole, which automatically creates a corresponding schema. You’ll seeguest and INFORMATION_SCHEMA, which were users in SQL Server 2000. You should see your newly defined schemas DemoUsers and DemoSchema and a system schema called sys. There is also aschema dbo, as well as a user dbo that you can see if you run sp_helpuser.

In SQL Server 2012, all system tables are in a hidden resource database but are visible through the sys schema,

which is a logical schema available in every database

3. In this step, you’ll create two tables and insert a row of identifying data into each one. The tables will havethe same name, but one will be in the DemoSchema schema and the other will be in the dbo (built-in)schema. This code is in the SQL script NewTable.sql. Load this code:

Page 11: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 11/29

Using the SQL Server Management Studio in SQL Server 2012 11

USE NewDB

GO

CREATE TABLE DemoSchema.DemoTable

(version varchar(20) )

INSERT INTO DemoSchema.DemoTable SELECT 'DemoSchema schema'

GO

CREATE TABLE dbo.DemoTable

(version varchar(20) )

INSERT INTO dbo.DemoTable SELECT 'DBO schema'

GO

4. Select the code you just entered, and press F5 or click the Execute button on the toolbar  to execute theselected statements.

Task 5: Grant permissions to a role

1. In this step, you’ll grant permission to the DemoUsers role to create new tables. This code is in the SQLscript Permission.sql. Load this code:

USE NewDB

GO

GRANT CREATE TABLE to DemoUsers

GO

2. Select the code you just entered, and press F5 or click the Execute button on the toolbar  to execute theselected statements.

Task 6: Test access after logging in as different users

1. Disconnect from the database, if necessary: select the Query | Connection | Disconnect menu item. (If youhaven’t connected yet, this item will be unavailable.)

.10

.11 Figure: Disconnect from the active database

2. To see what happens when a user has a default schema defined, open the following script, which can befound in the SQL script UserDemo1.sql under Exercise 5 in the Solution Explorer.

Page 12: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 12/29

12 Using the SQL Server Management Studio in SQL Server 2012

USE NewDB

GO

SELECT * FROM DemoTable

GO

CREATE TABLE DemoTable1 (message varchar(30))

INSERT INTO DemoTable1 SELECT 'Created by NewUser1'

GOEXEC sp_help DemoTable1

GO

3. Press F5 or click the Execute button on the toolbar  to execute the script. When you are prompted to supplyyour connection information, choose SQL Server Authentication. Enter NewUser1 for the user name, andpa$$word123 for the password. Click Connect.

Because the user NewUser1 was given the default schema of DemoSchema, SQL Server will automatically look first for an object called DemoTable in DemoSchema when resolving the SELECT statement.

SQL Server will also use DemoSchema as the owner of the new table DemoTable1, as you can see when youexecute sp_help DemoTable1.

You can change the connection information for any open query using the File | Change Connection menu item.4. Disconnect again: select the Query | Connection | Disconnect menu item.

5. To see what happens when a default schema was not specified when the user was created, open the followingscript. It can be found in the SQL script UserDemo2.sql.

USE NewDB

SELECT * FROM DemoTable

GO

CREATE TABLE DemoTable2

(message varchar(30))

INSERT INTO DemoTable2 SELECT 'Created by NewUser2'

GO

6. Press F5 or click the Execute button on the toolbar  to execute the script. When you are prompted to supplyyour connection information, choose SQL Server Authentication. Enter NewUser2 for the user name, and“pa$$word” for the password. Click Connect.

You did not specify a default schema when you created the NewUser2 user, so dbo is used as the defaultschema. Because NewUser2 is a member of the DemoUsers role, which in turn is a member of thedb_datareader role, NewUser2 can read from the DemoTable in the dbo schema. However, NewUser2 does nothave permission to create a table in the dbo schema, so an error message is generated.

SQL Server will always first check the default schema defined for a user when accessing an object, and then itwill check for an object in the dbo schema.

In previous versions of SQL Server, users and schemas were treated as synonymous. For backwardcompatibility, if you use the system stored procedure sp_grantdbaccess, SQL Server 2012 will create both a user and a schema of the same name, and the schema will be a user’s default schema. This means that sp_ grantdbaccess NewUser is equivalent to the following code.

CREATE USER NewUser

WITH DEFAULT SCHEMA NewUser

CREATE SCHEMA NewUser AUTHORIZATION NewUser

Page 13: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 13/29

Using the SQL Server Management Studio in SQL Server 2012 13

In SQL Server 2012, users and schemas are two different things.

A user is an identifier for the person using a database. A user can belong to roles, and can be granted permissions, either directly or through roles they belong to.

A schema is a namespace which contains a set of objects and is owned by a user or a role.

A user is never added to a schema; schemas contain objects, not users. Users can be assigned a default schemathat may or may not exist. A user’s default schema is used for name resolution.

In order to create an object in a schema, the following conditions must be satisfied:

The schema must exist.

The user creating the object must have CREATE TABLE permission, either directly or throughrole membership.

The user creating the object must be the owner of the schema, must be a member of the role thatowns the schema, must have ALTER rights on the schema, or must have the ALTER ANYSCHEMA permission in the database.

Page 14: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 14/29

14 Using the SQL Server Management Studio in SQL Server 2012

Exercise 6:

PIVOT and UNPIVOT Operators

It is often useful to view relational data in multiple dimensions. For some time now, SQL Server has supportedthe CUBE and ROLLUP operators. These operators allow data to be viewed in different dimensions and allowaggregations to be displayed along those dimensions.

Since the 2005 release of SQL Server introduces support for the PIVOT and UNPIVOT operators. Theseoperators are less complex to understand and implement than CUBE and ROLLUP, while still allowing theflexibility to view data along different dimensions. For example, with the PIVOT operator it is almost effortlessto rotate rows into columns to look at Product data along different dimensions such as supplier, currentinventory, and amounts.

In this exercise, you will learn how to use the PIVOT and UNPIVOT operators, apply them in several queries,and compare their output.

Task 1: Creating a Management Studio Project.12 Click Start | All Programs | Microsoft SQL Server 2012 | SQL Server Management Studio. If asked to

connect, enter localhost in the Server Name text box, and select Windows Authentication in theAuthentication drop-down list.

.13 Click File | New | Project.

.14In the New Project dialog box, click SQL Server Scripts.

.15 Change the Name of the project to TSQLLab.

.16 Change the Location to C:\SQL Labs\User Projects.

.17 Clear the Create directory for Solution checkbox.

.18 Click OK to save the project.

Task 2: Connecting to the Adventure Works Database

1. In the Solution Explorer, right-click Queries and then click New Query.

Note: If you are prompted for connection information, type “localhost” for the server name, verify thatWindows Authentication is selected for the authentication mode, and click Connect.

2. Under  Queries, right-click the new script file and click Rename.

3. Rename the script to PIV_UNPIV.sql.

4. Type the following code in the query editor.

USE AdventureWorks

GO

5. Press F5 to execute the statement.

Task 3: Create a table and populate it with data

1. In the query editor, type the following code to create and populate a table.

Page 15: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 15/29

Using the SQL Server Management Studio in SQL Server 2012 15

CREATE TABLE SalesOrderTotalsMonthly

(

CustomerID int NOT NULL,

OrderMonth int NOT NULL,

SubTotal money NOT NULL

)

GO

INSERT SalesOrderTotalsMonthly

SELECT CustomerID, DATEPART(m, OrderDate), SubTotal

FROM Sales.SalesOrderHeader

WHERE CustomerID IN (11001, 11002, 11004, 11006)

To see the capabilities of the PIVOT operator, you are creating a worktable containing the customer ID, themonth an order was taken, and the subtotal due on the order. This table will be used in subsequent queries.

2. Select the statements you just typed.

3. Press F5 to execute the statements.

Task 4: Create a query that uses the PIVOT operator

1. In the query editor, type the following query that will pivot the table so that the sales for each month areoutput by customer.

SELECT * FROM SalesOrderTotalsMonthly

PIVOT (SUM(SubTotal) FOR OrderMonth IN

([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])) AS a

2. Select the statements you just typed.

3. Press F5 to execute the query.

You should see a column for each month across the top of the results. Each row represents a single customer.The customer's total order amounts for a given month are displayed.

You can do a simple select on the SalesOrderTotalsMonthly table to compare the output of the PIVOT resultsand the original table data.

Task 5: Create a worktable to PIVOT results by Year

1. In the query editor, type the following code to create and populate another worktable.

Page 16: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 16/29

16 Using the SQL Server Management Studio in SQL Server 2012

CREATE TABLE SalesOrderTotalsYearly

(

CustomerID int NOT NULL,

OrderYear int NOT NULL,

SubTotal money NOT NULL

)GO

INSERT SalesOrderTotalsYearly

SELECT CustomerID, YEAR(OrderDate), SubTotal

FROM Sales.SalesOrderHeader

WHERE CustomerID IN (11001, 11002, 11004, 11006, 11035)

2. Select the statements you just typed.

3. Press F5 to execute the statements.

In this case, you are creating a worktable that contains the sales by year for the specified customers. You can

now use the PIVOT operator to pivot information based on the year an order was taken.

Task 6: PIVOT results by year and by Customer

1. In the query editor, type the following queries that will pivot the table so that each year's sales are output bycustomer.

SELECT * FROM SalesOrderTotalsYearly

PIVOT (SUM(SubTotal) FOR OrderYear IN ([2001], [2003], [2004])) AS a

GO

SELECT * FROM SalesOrderTotalsYearly

PIVOT (SUM(SubTotal) FOR CustomerID in ([11001], [11002], [11004], [11006])) AS a

2. Select the queries you just typed.3. Press F5 to execute the query.

The PIVOT operator is used in two different queries. Each result set is pivoted in a different direction. The firstresult set shows customer orders by year. In this case, each year is shown as a separate column. Remember thatin the original table all years where sales occurred were stored in a single column.

The second result set shows subtotal amounts so that each customer’s data appears as a separate column in theresult set.

Task 7: Create a worktable to show the difference between the PIVOT and UNPIVOT operators

1. In the query editor, type the following queries that will create a worktable and pivot the table so that eachyear’s sales are output by customer.

Page 17: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 17/29

Using the SQL Server Management Studio in SQL Server 2012 17

CREATE TABLE YearlySalesPivot

(

OrderYear int NOT NULL,

[1] money NULL,

[2] money NULL,

[4] money NULL,[6] money NULL

)

GO

INSERT YearlySalesPivot

SELECT * FROM SalesOrderTotalsYearly

PIVOT (SUM(SubTotal) FOR CustomerID IN ([11001], [11002], [11004], [11006])) AS a

2. Select the statements you just typed.

3. Press F5 to execute the statements. If you receive the message, "Warning: Null value is eliminated by anaggregate or other SET operation," you can safely ignore it.

In addition to the PIVOT operator, there is an UNPIVOT operator which allows you to normalize pre-pivoteddata. To compare the output of these two operators, you will create a worktable to hold the pivoted output froma query. This stored output will then be un-pivoted and compared with the original pivoted results stored in thetable.

Task 8: Compare UNPIVOT and PIVOT results

1. In the Query Editor, type the following queries.

SELECT * FROM YearlySalesPivot

UNPIVOT (SubTotal FOR CustomerID IN ([1], [2], [4], [6])) AS a

ORDER BY CustomerID

-- Displays unpivoted results

SELECT * FROM YearlySalesPivot

-- Displays pivoted results stored in the worktable

2. Select the queries you just typed.

3. Press F5 to execute the query.

Task 9: Drop worktables

1. In the query editor, type the following code to drop the worktables you created.

DROP TABLE YearlySalesPivot

DROP TABLE SalesOrderTotalsYearly

DROP TABLE SalesOrderTotalsMonthly

2. Select the statements you just typed.

3. Press F5 to execute the statements.

Page 18: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 18/29

18 Using the SQL Server Management Studio in SQL Server 2012

Exercise 7:

Common Table Expressions and Recursive Queries

A Common Table Expression (CTE) is a temporary result set derived from a simple query. A CTE can be usedin many of the same ways you use a derived table. CTEs can also contain references to themselves. This allowsdatabase developers to write recursive queries. CTEs can also be used in place of views.

Task 1:Add a new script in SQL Server Management Studio

1. Using SQL Server Management Studio, open the TSQLLab project created in the previous exercise, if it'snot still open.

2. Right-click Queries in the Solution Explorer and click New Query.

3. When prompted for connection information, type “localhost” for the server name, verify that theauthentication method is set to Windows Authentication, and click Connect.

4. Right-click the script file and click Rename.

5. Rename the script as CTE_REC.sql

Task 2: Using a CTE as a Derived Table

1. The initial example will be a simple use of CTE to make you familiar with the syntax. In the CTE_REC.sqlscript, type the following code.

USE AdventureWorks

GO

WITH SalesCTE(ProductID, SalesOrderID)

AS

(

SELECT ProductID, COUNT(SalesOrderID)

FROM Sales.SalesOrderDetailGROUP BY ProductID

)

SELECT * FROM SalesCTE

--All Products and the number of times that they

--were ordered

2. Select the statements you just typed.

3. Press F5 to execute the query.

Task 3: Filtering a CTE used as a Derived Table

1. In the CTE_REC.sql script, type the following query.

Page 19: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 19/29

Using the SQL Server Management Studio in SQL Server 2012 19

WITH SalesCTE(ProductID, SalesOrderID)

AS

(

SELECT ProductID, COUNT(SalesOrderID)

FROM Sales.SalesOrderDetailGROUP BY ProductID

)

SELECT * FROM SalesCTE

WHERE SalesOrderID > 50

--All Products that were ordered more than 50 times

2. Select the query you just typed.

3. Press F5 to execute the query.

Just as you might filter the result set returned by a view, you can filter the result set contained in a CommonTable Expression.

Task 4: Aggregating with CTEs1. In the CTE_REC.sql script, type the following query.

WITH SalesCTE(ProductID, SalesOrderID)

AS

(

SELECT ProductID, COUNT(SalesOrderID)

FROM Sales.SalesOrderDetail

GROUP BY ProductID

)

SELECT AVG(SalesOrderID)

FROM SalesCTE

WHERE SalesOrderID > 50--Average number of times a Product was ordered

--for all Products that appeared on an order

--more than 50 times

2. Select the query you just typed.

3. Press F5 to execute the query.

Performing aggregations or other computations on the data returned by a Common Table Expression is similar to doing so for data from a standard table.

Task 5: Using CTEs Recursively

The most powerful use of Common Table Expressions is to create recursive queries. Since Common TableExpressions allow references to themselves in the same query, a recursive query is relatively straightforward tocreate.

First, create a new table in the database.

1. Type the following statements in the CTE_REC.sql script.

Page 20: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 20/29

20 Using the SQL Server Management Studio in SQL Server 2012

CREATE TABLE CarParts

(

CarID int NOT NULL,

Part varchar(15),

SubPart varchar(15),

Qty int)

GO

INSERT CarParts

VALUES (1, 'Body', 'Door', 4)

INSERT CarParts

VALUES (1, 'Body', 'Trunk Lid', 1)

INSERT CarParts

VALUES (1, 'Body', 'Car Hood', 1)

INSERT CarParts

VALUES (1, 'Door', 'Handle', 1)

INSERT CarParts

VALUES (1, 'Door', 'Lock', 1)INSERT CarParts

VALUES (1, 'Door', 'Window', 1)

INSERT CarParts

VALUES (1, 'Body', 'Rivets', 1000)

INSERT CarParts

VALUES (1, 'Door', 'Rivets', 100)

INSERT CarParts

VALUES (1, 'Door', 'Mirror', 1)

You are creating a table that holds parts and subparts for cars, often called a bill of materials. Bill of materialstables, organization charts, and other hierarchical data structures can easily benefit from the use of recursiveCommon Table Expressions.

 Notice that a given part such as a Body may contain multiple sub parts. For example, there are 1000 rivets in a body, and each door also contains 100 rivets.

2. Select the statements you just typed.

3. Press F5 to execute the query.

4. In the CTE_REC.sql script, type the following query.

Page 21: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 21/29

Using the SQL Server Management Studio in SQL Server 2012 21

WITH CarPartsCTE(SubPart, Qty)

AS

(

-- Anchor Member (AM):

-- SELECT query that doesn’t refer back to CarPartsCTE

SELECT SubPart, QtyFROM CarParts

WHERE Part = 'Body'

UNION ALL

-- Recursive Member (RM):

-- SELECT query that refers back to CarPartsCTE

SELECT CarParts.SubPart, CarPartsCTE.Qty * CarParts.Qty

FROM CarPartsCTE

INNER JOIN CarParts ON CarPartsCTE.SubPart = CarParts.Part

WHERE CarParts.CarID = 1

)

-- Outer Query

SELECT SubPart, SUM(Qty) AS q

FROM CarPartsCTEGROUP BY SubPart

Recursive CTEs are constructed from at least two queries. One is a non-recursive query, also referred to as theanchor member (AM). The other is the recursive query, also referred to as the recursive member (RM). Thesequeries are separated by the UNION ALL operator.

5. Select the query you just typed.

6. Press F5 to execute the query.

The query above lists the total quantities of parts required to create a car body. The Common Table Expressionis initially populated with data from the simple query, “SELECT SubPart, Qty FROM CarParts WHERE Part ='Body'”. Then, the set operator UNION ALL combines the results of the first query with the results of a

recursive query that multiplies subpart quantities by the number of parts in which they are used. Note that thesecond query contains a recursive reference in the INNER JOIN statement to the Common Table Expressionnamed CarPartsCTE.

Task 6: Drop worktables

1. In the query editor, type the following code to drop the table you created.

DROP TABLE CarParts

4. Select the statement you just typed.

5. Press F5 to execute the statements.

Exercise 8:

DDL Triggers and EventData()

In previous versions of SQL Server, you can define AFTER triggers only for Data Manipulation Language(DML) statements — INSERT, UPDATE, and DELETE. SQL Server 2005 allows you to define triggers for Data Definition Language (DDL), and you can optionally define the scope to be an entire database or even anentire server, not just a single object.

Page 22: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 22/29

22 Using the SQL Server Management Studio in SQL Server 2012

Within a trigger, you can get data regarding the event that initiated it by accessing the EventData() function.This function returns a variable that uses the new xml data type. Each event’s schema inherits the Server Events

 base schema.

In this exercise you will create DDL triggers and use EventData() to capture information about the callingevent.

Task 1: Add a new script in SQL Server Management Studio

1. Using SQL Server Management Studio, open the TSQLLab project created in the first exercise, if it's notstill open.

2. Right-click Queries in the Solution Explorer and click New Query.

3. When prompted for connection information, type “localhost” for the server name, verify that theauthentication method is set to Windows Authentication, and click Connect.

4. Right-click the script file and click Rename.

5. Rename the script DDL_EventData.sql

Task 2: Creating a DDL Trigger

1. In the DDL_EventData.sql script, type the following code.

USE AdventureWorks

GO

CREATE TABLE DDLTest

(

a int NOT NULL

)

GO

CREATE TRIGGER safety

ON DATABASEFOR DROP_TABLE

AS

PRINT 'You must disable Trigger "safety" to drop tables!'

ROLLBACK 

GO

The code above first creates a table, and then creates a DDL trigger that will fire when a user attempts to dropany database table.

2. Select the statements you just typed.

3. Press F5 to execute the query.

4. In the DDL_EventData.sql script, type the following query.

DROP TABLE DDLTest

5. Select the statement you just typed.

6. Press F5 to execute the query.

You will receive the following message:

Page 23: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 23/29

Using the SQL Server Management Studio in SQL Server 2012 23

 You must disable Trigger "safety" to drop tables!

Msg 3609, Level 16, State 2, Line 1

 Transaction ended in trigger. Batch has been aborted.

The DDL trigger returns an error message and prevents any table in the database from being dropped by rolling

 back the transaction.

Task 3: Alter the DDL Trigger to use EventData()

1. In the DDL_EventData.sql script, type the following code.

CREATE TABLE EventLog

(

PostTime datetime,

DBUser nvarchar(100),

Event nvarchar(100),

 TSQL nvarchar(2000)

)

GO

ALTER TRIGGER safety

ON DATABASE

FOR DDL_DATABASE_LEVEL_EVENTS

AS

DECLARE @data xml

SET @data = EventData()

INSERT EventLog (PostTime, DBUser, Event, TSQL)

VALUES (GETDATE(), CONVERT(nvarchar(100), CURRENT_USER),

CONVERT(nvarchar(100), @data.query('data(//EventType)')),

CONVERT(nvarchar(2000), @data.query('data(//TSQLCommand)')))

GO

--Test the trigger

CREATE TABLE Foo (a INT)

DROP TABLE Foo

GO

SELECT *

FROM EventLog

The EventData() function returns information about server or database events. This function returns an xml-typed variable.

2. Select the statements you just typed.

3. Press F5 to execute the query.

First, the code creates a log table to catch the event information. Second, the code alters the trigger to writeevent data to the log table. The code stores the time, user, event, and T-SQL associated with the event in the logtable. Finally, the code tests the altered trigger. Since the altered trigger does not include ROLLBACK, the“foo” table is successfully deleted.

Task 4: Drop worktables and trigger

1. In the query editor, type the following DDL to drop the worktables you created.

Page 24: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 24/29

24 Using the SQL Server Management Studio in SQL Server 2012

DROP TRIGGER safety

ON DATABASE

DROP TABLE DDLTest

DROP TABLE EventLog

2. Select the statement you just typed.3. Press F5 to execute the DDL statements.

Page 25: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 25/29

Using the SQL Server Management Studio in SQL Server 2012 25

Exercise 9:

Event Handling

Previous versions of SQL Server require that you include error handling code after every statement that might produce an error. SQL Server 2005 introduces two new constructs, TRY and CATCH. These two constructsallow you to handle transaction abort errors that would otherwise have resulted in the termination of a batch,

 provided that those errors do not cause severance of the connection.

In this exercise, you will learn how to use TRY and CATCH blocks in T-SQL.

Task 1: Add a new script in SQL Server Management Studio

1. Using SQL Server Management Studio, open the TSQLLab project created in the first exercise, if it's notstill open.

2. Right-click Queries in the Solution Explorer and click New Query.

3. When prompted for connection information, type “localhost” for the server name, verify that theauthentication method is set to Windows Authentication, and click Connect.

4. Right-click the script file and click Rename.

5. Rename the script TRY_CATCH.sql

Task 2: Creating worktables

1. In the TRY_CATCH.sql script, type the following code.

USE AdventureWorks

GO

CREATE TABLE ExceptionT1

(

a int NOT NULL PRIMARY KEY)

CREATE TABLE ExceptionT2

(

a int NOT NULL REFERENCES ExceptionT1(a)

)

GO

INSERT INTO ExceptionT1 VALUES (1)

INSERT INTO ExceptionT1 VALUES (3)

INSERT INTO ExceptionT1 VALUES (4)

INSERT INTO ExceptionT1 VALUES (6)

2. Select the statements you just typed.3. Press F5 to execute the query.

These statements create one table with a primary key and a second table with a foreign key that limits values tothose contained in the primary key column of the first table.

Task 3: Invoking a run-time error

When the SET XACT_ABORT option is set to OFF, only the Transact-SQL statement that raised the error isrolled back and the transaction continues processing.

1. In the TRY_CATCH.sql script, type the following query.

Page 26: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 26/29

26 Using the SQL Server Management Studio in SQL Server 2012

SET XACT_ABORT OFF

BEGIN TRAN

INSERT INTO ExceptionT2 VALUES (1)

INSERT INTO ExceptionT2 VALUES (2) /* Foreign Key Error */

INSERT INTO ExceptionT2 VALUES (3)

COMMIT TRANGO

2. Select the statements you just typed.

3. Press F5 to execute the query.

You should receive an error like the following:

Msg 547, Level 16, State 0, Line 1

INSERT statement conflicted with FOREIGN KEY constraint 'FK__ExceptionT2__a__5E1FF51F'. The conflict

occurred in database 'AdventureWorks', table 'ExceptionT1', column 'a'.

 The statement has been terminated.

 Now, view the resulting table values.

4. In the TRY_CATCH.sql script, type the following query.

SELECT *

FROM ExceptionT1

GO

SELECT *

FROM ExceptionT2

5. Select the statements you just typed.

6. Press F5 to execute the query.The first table, which you populated originally, has all four records. The second table has two records,corresponding to valid primary key values. When SET XACT_ABORT is OFF, the error is handled, butsubsequent statements execute successfully and the transaction is successfully committed.

Task 4: Using the TRY/CATCH construct and invoking a run-time error

1. In the TRY_CATCH.sql script, type the following code.

Page 27: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 27/29

Using the SQL Server Management Studio in SQL Server 2012 27

SET XACT_ABORT OFF

BEGIN TRY

BEGIN TRAN

INSERT INTO ExceptionT2 VALUES (4)

INSERT INTO ExceptionT2 VALUES (5) /* Foreign Key Error */

INSERT INTO ExceptionT2 VALUES (6)COMMIT TRAN

PRINT 'Transaction committed'

END TRY

BEGIN CATCH

ROLLBACK 

PRINT 'Transaction rolled back'

END CATCH

GO

2. Select the statements you just typed.

3. Press F5 to execute the query.

 Notice that the results pane displays 'Transaction rolled back'.

4. In the TRY_CATCH.sql script, type the following query.

SELECT *

FROM ExceptionT1

GO

SELECT *

FROM ExceptionT2

5. Select the statements you just typed.

6. Press F5 to execute the query. Notice that the same two records are in ExceptionT2, even though two of the second INSERT statements wouldnot have violated the foreign key constraint. When an unconditional ROLLBACK statement is issued in aCATCH block, the entire transaction is terminated and rolled back on any error raised in the TRY block,regardless of the SET XACT_ABORT setting.

Task 5: Drop worktables

1. In the query editor, type the following DDL to drop the worktables you created.

DROP TABLE ExceptionT2

DROP TABLE ExceptionT1

2. Select the statement you just typed.

3. Press F5 to execute the DDL statements.

Page 28: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 28/29

28 Using the SQL Server Management Studio in SQL Server 2012

Exercise 3: Performing basic database management using Powershell

Scenario

Microsoft SQL Server 2012 supports Windows PowerShell, which is a powerful scripting shell that letsadministrators and developers automate server administration and application deployment. The WindowsPowerShell language supports more complex logic than Transact-SQL scripts, giving SQL Server administratorsthe ability to build robust administration scripts. Windows PowerShell scripts can also be used to administer other Microsoft server products. This gives administrators a common scripting language across servers.

SQL Server provides a Windows PowerShell module named sqlps that is used to import the SQL Server components into a Windows PowerShell 2.0 environment or script. The sqlps module loads two WindowsPowerShell snap-ins that implement:

A SQL Server provider, which enables a simple navigation mechanism similar to file system paths. You can build paths similar to file system paths, where the drive is associated with a SQL Server management objectmodel, and the nodes are based on the object model classes. You can then use familiar commands such as cd anddir  to navigate the paths similar to the way you navigate folders in a command prompt window. You can useother commands, such as ren or del , to perform actions on the nodes in the path.

A set of cmdlets, which are commands used in Windows PowerShell scripts to specify a SQL Server action. TheSQL Server cmdlets support actions such as running a sqlcmd script containing Transact-SQL or XQuerystatements.

The Microsoft SQL Server 2012 PowerShell components can be used to manage instances of SQL Server 2000or later. Instances of SQL Server 2005 must be running SP2 or later. Instances of SQL Server 2000 must berunning SP4 or later. When the Microsoft SQL Server 2012 PowerShell components are used with earlier versions of SQL Server, they are limited to the functionality available in those versions.

1. In SQL Server Management Studio, right-click on the local server in Object Explorer and select StartPowershell.

2. As the Powershell interface opens, you will be already connected to the SQL Server Instance

3. Type the following command to retrieve the version of SQL Server that you are connected to:

Invoke-Sqlcmd -Query "SELECT @@VERSION;" -QueryTimeout 3

Invoke-Sqlcmd commandlet

 The Invoke-Sqlcmd cmdlet lets you run your sqlcmd script files in aWindows PowerShell environment. Much of what you can do withsqlcmd can also be done using Invoke-Sqlcmd.

4. Type the following command to enlist the databases within the instance

Cd databases

foreach ($database in (Get-ChildItem)) {Write-Host $database.Name}

Page 29: 01 ManagementStudio Lab

7/27/2019 01 ManagementStudio Lab

http://slidepdf.com/reader/full/01-managementstudio-lab 29/29

Using the SQL Server Management Studio in SQL Server 2012 29

7. In the Powershell command prompt you will now use the Backup-SQLDatabase commandlet to take a backupof each database installed. You can do using a pre-created sample backup script or type the following command.

To execute the script type:

C:\Labfiles\Setup\Manageability\Scripts\Ps-BackupDatabases.ps1

Or type out the full script text as listed below:

cd SQLSERVER:\SQL\[SERVER_NAME]\Default\Databases

$Backupdate = Get-Date -Format MMddyy

foreach($database in (Get-ChildItem)) {

$dbName = $database.Name

$bakFile = "c:\LabFiles\" + $dbName + "_" + $Backupdate + ".bak"

Backup-SqlDatabase -Database $dbName -BackupFile $bakFile -Initialize }

As the Powershell execution performs the database backup a progress bar is displayed.

8. Browse to c:\Labfiles 

9.  Notice that .BAK files have been created using the format defined in the above script.