Exercise 2: Working with Data Basic DDL and DMLIn this exercise, you will create a new database and work with its data. This means you will create some tables, index those tables appropriately, and then insert and query data. For this purpose, you will use two different tools. The first tool, the Database Manager for SQL Azure, is a browser based Silverlight database administration tool that you can access from the Windows Azure portal. The other tool is SQL Server Management Studio, a tool normally associated with SQL Server management. You will see that this tool is equally useful for managing your SQL Azure databases. Task 1 – Creating a New Database- In the Windows Azure Management portal UI, select the Database option.
- Under Subscriptions, expand your project in the tree view on the left, select the server name where you wish to create a database and then click Create in the Database group of the ribbon.
.png)
Figure 10Creating a new database - In the Create Database dialog, set the Database name to HoLTestDB, select the WebEdition and set the Maximum size to 1 GB.
.png)
Figure 11Choosing database features In this hands-on lab, you create a database using the SQL Azure portal. Databases can also be created by executing a DDL query against your assigned server using the T-SQL CREATE DATABASE statement, specifying which SQL Azure database edition (Web or Business) to create as well as its maximum size. For example, to create a Business Edition database with a maximum size of 30GB, use the following T-SQL command: CREATE DATABASE HolTestDB (MAXSIZE = 30GB)Once a database reaches its maximum size, you cannot insert additional data until you delete some data to free storage space or increase its maximum size.
Task 2 – Managing your Database with the Database Manager for SQL AzureIn this task, you use the Database Manager for SQL Azure, a Silverlight client that runs in your browser, to connect to your SQL Azure database, create and populate a table, and then query its contents. - Expand the server node under your subscription, click the HoLTestDB database to select it, and then click Manage on the ribbon.
.png)
Figure 12Managing a database - You will be redirected to the SQL Azure Management Portal. Enter your Server Administrator username and password and then click Log on.
.png)
Figure 13Signing in to the SQL Azure Management Portal - Wait until you are connected to your database and the Administration page is shown.
.png)
Figure 14SQL Azure Management Portal Administration page - On the left pane, click Design option.
.png)
Figure 15SQL Azure Design view - Make sure Tables option is selected in the navigation menu and click New table.
.png)
Figure 16Creating a new table - In the table creation UI, set the Name of the table to People.
- Next, define three table columns using the information shown below and click Save.
Column | Type | Is Identity? | Is Required? | Is Primary Key? |
|---|
ID | Int | Yes | Yes | Yes | Name | nvarchar(50) | No | Yes | No | Age | Int | No | Yes | No |
.png)
Figure 17Creating the table schema - Once the table is saved, click Data in the navigation menu.
.png)
- Now, click Add Row and enter sample data for the Name and Age columns.
Name | Age |
|---|
Alexandra | 16 | Ian | 18 | Marina | 45 |
.png)
Figure 19Adding rows to the table - Repeat the previous step to add another two rows and then click Save to commit the data to the table.
.png)
- Next, click New Query in the ribbon.
- In the query window, enter the following T-SQL statement to select all the rows in the People table and then click Run. Verify that the results grid shows the rows that you entered previously.
.png)
Figure 21Querying the database
Task 3 – Managing your Database with SQL Server Management StudioIn this task, you use SQL Server Management Studio, a tool typically used for managing SQL Server, to connect to your SQL Azure server and administer it. - Open SQL Server Management Studio from Start | All Programs | Microsoft SQL Server 2008 R2 | SQL Server Management Studio. You will be presented with a logon dialog.
- In the Connect to Server dialog, enter your login information ensuring that you select SQL Server Authentication. SQL Azure currently only supports SQL Server Authentication.
Please replace server name with your server (e.g. REPLACE_SERVER_NAME.database.windows.net.) .png)
Figure 22Connecting to SQL Azure with SQL Server Management Studio - Click Connect.
- You should now see in your Object Explorer the structure of your database. Notice that your SQL Azure database is no different to an on-premises relational database.
.png)
Figure 23Object Explorer showing the HoLTestDB database - In Object Explorer, select the HoLTestDB database in the tree view and then click New Query on the toolbar.
.png)
Figure 24Creating a new query window - You now have a query window with an active connection to your account. You can test your connection by display the result of the @@version scalar function. To do this, type the following statement into the query window and press the Execute button. You will get back a scalar result that indicates the edition as Microsoft SQL Azure.
.png)
Figure 25Retrieving the SQL Azure version - Replace the previous query with the statement shown below and click Execute. Notice that the results grid shows the databases currently accessible.
SELECT * FROM sys.databases
.png)
Figure 26Query results showing the list of databases in your subscription - You can check that you are now in the context of your user database by executing the following query. Make sure that you replace the previous query.
.png)
Figure 27Querying the database currently in use - Do not close the query window. You will need it during the next task.
Task 4 – Creating Logins and Database UsersMuch like SQL Server, SQL Azure allows you to create additional logins and then assign those logins as users with permissions on a database. In this task, you will create a new login and then create a user that uses the new login in your HoLTestDB database. - Open a new query window connected to the master database. To do this, in Object Explorer, expand the System Databases node inside Databases and then select master. Then, click New Query on the toolbar.
.png)
Figure 28Querying the master database You cannot reuse the previous query window connected to the HoLTestDB database because you cannot change the database context without closing the current connection. The USE <database_name> command does not work with SQL Azure. Therefore, you need to open a new query window or disconnect and reconnect in order to change from the HoLTestDB to the master database. - Create a new login by executing the following statement:
CREATE LOGIN HoLUser WITH password='Password1'
You should choose your own password for this login account and use it where appropriate throughout the lab. If you do not choose a unique password, you should ensure that you remove this login when you finish the lab. To do this, execute the following statement in the master database: DROP LOGIN HoLUser - Go back to the query window connected to the HoLTestDB database. If you closed this window, open it again by selecting the HoLTestDB database in Object Explorer and then click New Query.
- In the query window, execute the following statement to create a new user in the HoLTestDB database for the login HoLUser.
-- Create a new user from the login and execute
CREATE USER HoLUser FROM LOGIN HoLUser
- Next, add the user to the db_owner role of your HoLTestDB database by executing the following:
-- Add the new user to the db_owner role and execute
EXEC sp_addrolemember 'db_owner', 'HoLUser'
By making your user a member of the db_owner role, you have granted a very extensive permission set to the user. In a real world scenario, you should be careful to ensure that you grant users only the smallest privilege set possible. - Change the user associated with the current connection to the newly created HoLUser. To do this, right-click the query window, point to Connection, and then select Change Connection.
.png)
Figure 29Changing the database connection properties - In the Connect to Database Engine dialog, replace the Login name with HoLUser and set the Password to the value that you chose earlier when you created the database user.
.png)
Figure 30Connecting to the database as a different user - Click Options to show additional connection settings. Switch to the Connection Properties tab and ensure that the name of the database for the connection isHoLTestDB. If the current value is different, you will need to type this rather than use the drop down list, then press the Connect button.
.png)
Figure 31Connecting to a specific database You are now connected to the database as the HoLUser database user. You will continue with this user for the remaining steps of this exercise.
Task 5 – Creating Tables, Indices, and Queries- In the query window, replace the current content with the following SQL query to create a Contact table and execute it.
CREATE TABLE [Contact](
[ContactID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
[Title] [nvarchar](8) NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[EmailAddress] [nvarchar](50) NULL,
[Phone] [nvarchar](30) NULL,
[Timestamp] [timestamp] NOT NULL
)
SQL Azure requires that every table have a clustered index. If you create a table without a clustered index, you will not be able to insert rows into the table until you have created one. Because the clustered index determines the order of rows on disk, and thus affects certain queries, you may choose to place the clustered index on a column other than the primary key column. - You will add an index on the EmailAddress field. To do this, execute the following query:
CREATE INDEX IX_Contact_EmailAddress
ON Contact(EmailAddress)
- Execute the following query to add a row to the new Contact table:
INSERT INTO [Contact]
([Title],[FirstName],[LastName],[EmailAddress],[Phone])
VALUES
('Mr','David','Alexander','davida@fabrikam.com','555-1234-5555')
- Now, query the data back out, but start by enabling the SHOWPLAN_ALL option to show the execution plan. To do that, execute the following query:
SET SHOWPLAN_ALL ON
GO
SELECT * FROM Contact WHERE EmailAddress ='davida@fabrikam.com'
GO
SET SHOWPLAN_ALL OFF
.png)
Figure 32Query execution plan for a small set - Next, you will add a large number of rows to the database and then examine the query plan again. To do this, execute the following query to create a stored procedure named AddData. This stored procedure will loop incrementing a counter each time through and add a new record with an email address with the pattern [Counter]davida@fabrikam.com:
CREATE PROCEDURE AddData
@NumRows int
AS
DECLARE @counter int
SELECT @counter = 1
WHILE (@counter < @NumRows)
BEGIN
INSERT INTO [Contact]
([Title],[FirstName],[LastName],[EmailAddress],[Phone])
VALUES
('Mr','David','Alexander',CAST(@counter as nvarchar)+'davida@fabrikam.com','555-1234-5555')
SELECT @counter = @counter + 1
END
- Now, insert 10,000 rows into the Contact table by executing the new stored procedure. Each row will have a unique email address. To do this, execute the following T-SQL statement:
It may take some time to generate the 10,000 rows. - Execute the following query again and examine the generated plan. Compare the result with the one obtained previously, when the table contained few rows.
SET SHOWPLAN_ALL ON
GO
SELECT * FROM Contact WHERE EmailAddress ='davida@fabrikam.com'
GO
SET SHOWPLAN_ALL OFF
.png)
Figure 33Query execution plan for a large set Notice that the second time around the query optimizer is likely to use the index that you defined: This is the Index Seek line in the query plan. - For the most part, you can use any tool that you might have previously used with SQL Server on-premises. For an example of this, look at the query plan graphically. In SQL Server Management Studio press Ctrl-L to display the Estimated Execution Plan.
.png)
Figure 34Showing the query execution plan graphically
| |