Using the Query Analyzer Using the Query Analyzer Objectives Explore the Query Analyzer user interface. Learn how to use the menu items and toolbars to work with SQL Server data and objects. Use object searching to locate objects across multiple databases. Use templates to create queries and SQL Server objects. Use the Transact-SQL Debugger to debug stored procedures. Use the graphical tools for optimizing queries and indexes. Learn how to get help using the Help menu items. Microsoft SQL Server 2000 Professional Skills Development 6-1
Using the Query Analyzer Query Analyzer Features The SQL Server 2000 Query Analyzer is fast becoming the development environment of choice for creating SQL Server objects and for writing Transact-SQL queries. It has been beefed up considerably from previous versions of SQL Server, with advanced features that are very similar to the development and debugging environment present in Visual Studio and VBA. The Query Analyzer gives you a robust graphical user interface that allows you to create, test, debug, and optimize your Transact-SQL statements. Here s a list of some of the Query Analyzer features you will find useful: You can have multiple connections open at the same time, each with its own security and database contexts. You can configure fonts and color-coding of Transact-SQL syntax, much like the Visual Basic Editor. The Object Browser allows you to explore your database objects, and also gives you access to templates. Templates are predefined files that include the basic Transact-SQL statements needed to create objects and perform common tasks. The Search object allows you to search for database objects and explore their structure. The Transact-SQL Debugger allows you to step through stored procedure code, also much like in the Visual Basic Editor. You can display and manipulate the values of variables and parameters. You can study and troubleshoot queries by displaying a graphical diagram of the execution plan for your Transact-SQL statements. You can run the Index Tuning Wizard, which analyzes Transact-SQL statements and their underlying tables to determine whether additional indexes will improve performance. In this chapter you ll learn how to use the tools in the Query Analyzer by exploring them through the menu structure. Many, but not all, of the commands you ll learn about are also available on the toolbar, which you can customize by adding or removing toolbar buttons. Customizing the Toolbar Although the Query Analyzer menu structure is fixed, the toolbar allows you to add or subtract buttons, so the tasks you perform most frequently can be easily accessible. 6-2 Microsoft SQL Server 2000 Professional Skills Development
Query Analyzer Features Try It Out! 1. To add or remove a toolbar button, right-click on the toolbar. This loads the Customize Toolbar dialog box, as shown in Figure 1. 2. Select the toolbar button in the left list box and click the Add button to move it to the right. 3. In the right-hand pane, you can remove existing buttons or change their order by selecting them and choosing the Move Up or Move Down buttons. Figure 1. Customizing the Query Analyzer toolbar. Microsoft SQL Server 2000 Professional Skills Development 6-3
Using the Query Analyzer The File Menu Items The File menu items provide options for connecting and disconnecting from SQL Server; opening, closing, and saving both scripts and result sets; printing queries or result sets; and quitting the Query Analyzer entirely. Figure 2 shows the available options. Figure 2. The File menu items. Multiple Connections One of the most useful features in the File menu is the ability to open multiple connections, either to different databases or using different security contexts. Try It Out! Take these steps to open multiple connections: 1. Choose File Connect from the menu. 6-4 Microsoft SQL Server 2000 Professional Skills Development
The File Menu Items 2. When the Connect to SQL Server dialog box is loaded, type in a user name and password, as shown in Figure 3. Click OK when finished. Figure 3. Creating a new connection in the Query Analyzer. 3. If necessary, repeat the process until you have two separate connection windows. Each connection will display its connection information in its title bar, as shown in Figure 4, where the Administrator is connected to the master database, and Bullwinkle is connected to the Shark database. Figure 4. The Query Analyzer with two connections. Opening Scripts To load Transact-SQL scripts into the Query Analyzer, select File Open and find the script you want to load. For example, most of the sample queries shown in this chapter can be found in the script file called QueryAnalyzer.sql. Microsoft SQL Server 2000 Professional Skills Development 6-5
Using the Query Analyzer You ll find script files like this one for many of the chapters in this course. Scripts that create objects can be used to recreate whole databases or just selected objects. Saving Scripts and Result Sets You can save queries and scripts that you create in the Query Analyzer by choosing File Save from the menu. If your cursor is active in the top pane, then you get the Save or Save As options. When you save, a default extension of.sql will be added to the base file name. If your cursor is active in the bottom pane, you get different Save options for the result set, as shown in Figure 5. The default file format is.csv, but you can change the extension if you like. The default format is ANSI (your choices are ANSI, Unicode, and OEM), and you can choose between comma-delimited and tab-delimited styles. Figure 5. Saving the result set as a.csv comma-delimited file. Saving scripts is a very handy way of documenting and preserving work you ve done. It s a lot easier to revise or reuse a script file than to redo something from scratch. As you ll see, SQL Server doesn t even require you to type in Transact-SQL to create scripts; they can be created simply by rightclicking on objects. But loading and saving scripts in the Query Analyzer gives you a lot of flexibility. Being able to save results in a standard, commaseparated format allows you to inspect or work with that data later as needed. 6-6 Microsoft SQL Server 2000 Professional Skills Development
The Edit Menu Items The Edit Menu Items The Edit menu items contain the usual commands for cutting, copying, pasting, finding, and replacing text strings. The Undo command will undo typing, one letter at a time. All actions have keyboard shortcut keys assigned, which are displayed in the right column of the menu list, as shown in Figure 6. Figure 6. The Edit menu commands. Goto, Bookmarks The Go to Line (CTRL+G) option allows you to type in a line number, which comes in handy for moving around in large scripts. You can also set and clear bookmarks by selecting Edit Bookmarks from the menu and choosing from the following list of actions as shown in Figure 7. Figure 7. The options available in the Edit Bookmarks fly-out menu. Microsoft SQL Server 2000 Professional Skills Development 6-7
Using the Query Analyzer Templates The Edit Insert Template command displays a list of built-in templates that ship with SQL Server 2000, as shown in Figure 8. Figure 8. Inserting a template. Double-click the category you re interested in to display a list of individual templates, as shown in Figure 9. Figure 9. Selecting a template. 6-8 Microsoft SQL Server 2000 Professional Skills Development
The Edit Menu Items Click Open when you ve selected the desired template. This displays the template file in the SQL pane of the Query Analyzer, as shown in Figure 10. Figure 10. The template loaded in the Query Analyzer. Microsoft SQL Server 2000 Professional Skills Development 6-9
Using the Query Analyzer You can t do much with this template until you replace all of the template parameters or placeholders. Chevrons (< >) are not valid Transact-SQL syntax, and you need to replace all of the text within the chevrons with valid Transact- SQL. Choose Edit Replace Template Parameters from the menu, and fill in values as shown in Figure 11. Click Replace All when you re finished. Figure 11. Filling in the parameters with the Replace Template Parameters dialog box. 6-10 Microsoft SQL Server 2000 Professional Skills Development
The Edit Menu Items If you need to add additional columns to the table, you can do so after you ve replaced the parameters in the template. Figure 12 shows the completed procedure. The presence of these generic parameters is the principal difference between templates and scripts. Figure 12. The Query Analyzer after filling in the template parameters. Advanced The Advanced menu option loads an additional fly-out menu showing further options, all for formatting text in the Query Analyzer window, as shown in Figure 13. You may want to take the time to memorize the keyboard shortcuts for items on this list that you will use frequently. You can waste a lot of time typing Transact-SQL if you fail to make use of these very handy options. Figure 13. Advanced menu options. Microsoft SQL Server 2000 Professional Skills Development 6-11
Using the Query Analyzer Query Menu Items The Query menu items are grouped into several sections because they encompass different kinds of activities, as shown in Figure 14. Several items, such as changing database context and parsing/executing queries, are also represented by default toolbar buttons. Figure 14. The Query menu items. Executing Queries Think of the Parse option as a syntax checker it will check the syntax of a query or of a highlighted section of text. The Execute option will actually run the query. The Cancel Executing Query option is used to cancel a longrunning query. Displaying Query Plans and Index Tuning The following grouping lumps together the Display Estimated Execution Plan option and the Index Tuning Wizard. Displaying the execution plan shows you how SQL Server proposes to execute a specific query. There are usually a number of different ways that the desired results of a query can be achieved. SQL Server evaluates its options based on the amount and variation 6-12 Microsoft SQL Server 2000 Professional Skills Development
Query Menu Items of data in the affected tables, and on what indexes are available. The execution plan shows you the decision that SQL Server has made about how to run the query most efficiently. Figure 15 shows the query plan for a query that joins the tblproduct and the tblorderdetail tables. If you linger the mouse over any of the elements you will see the breakdown in cost for that element. Figure 15. The estimated execution plan for a query. Microsoft SQL Server 2000 Professional Skills Development 6-13
Using the Query Analyzer If you want to improve performance of the query, load the Index Tuning Wizard by choosing Query Index Tuning Wizard from the menu. The Index Tuning Wizard will run based on the current query shown in the Query Analyzer window. You can also specify the database and tables you want it to inspect, as shown in Figure 16. Figure 16. Selecting tables for the Index Tuning Wizard. 6-14 Microsoft SQL Server 2000 Professional Skills Development
Query Menu Items The Index Tuning Wizard will then display its recommendations, as shown in Figure 17. Figure 17. Indexes recommended by the Index Tuning Wizard. The Index Tuning Wizard will then create any recommended indexes for you, if you wish. Configuring Result Sets Your three choices for configuring the result set of a query are: Results in Text Results in Grid Results to File Microsoft SQL Server 2000 Professional Skills Development 6-15
Using the Query Analyzer The default setting is Results in Grid since it takes less time for the Query Analyzer to display. If you choose Results to File, you will be prompted for a file name and location. The default extension is.rpt, but you can change this to any other extension you choose. You can also choose between ANSI, Unicode, and OEM formats for the data. Figure 18 shows the first few rows of the output in fixed-width format. Figure 18. The output from saving a query to a file. The Show Options The next grouping of menu options each adds an additional pane to the lower portion of the Query Analyzer window. Show Execution Plan: Displays the execution plan used by the query. The difference between this option and the Display Estimated Execution Plan described earlier is that it is executed concurrently with the query, instead of before the query executes. Show Server Trace: Displays a trace window where you can see the individual Transact-SQL statements that were run and the resources they consumed, as shown in Figure 19. This is the same kind of information that is displayed when you run a trace in SQL Server Profiler. Show Client Statistics: Displays client statistics, such as the number of rows affected, average fetch time, and number of fetches. Many of these options may show up as zeros if the query is not complex or does not return much data. 6-16 Microsoft SQL Server 2000 Professional Skills Development
Query Menu Items Figure 19. The Trace window displays Transact-SQL information. Microsoft SQL Server 2000 Professional Skills Development 6-17
Using the Query Analyzer Connection Options Choose Current Connection Properties to bring up the dialog box shown in Figure 20. You can configure connection properties for each connection as needed. The defaults shown here reflect turning the default ANSI settings on. Figure 20. The Current Connection Properties dialog box. These ANSI options define the query processing environment used by the connection, and reflect many, but not all, of the options required to conform to the SQL-92 standard. Your applications that use either ODBC or OLE DB will also have these options turned on the SQL Server ODBC driver and Microsoft OLE DB Provider for SQL Server automatically set ANSI_DEFAULTS to ON when connecting. 6-18 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items Tools Menu Items The Tools menu contains three groupings, one for the Object Browser and Object Search, one for managing statistics and indexes, and one for setting options and customizing, as shown in Figure 21. Figure 21. Options on the Tools menu. Object Browser The Object Browser is one of the most useful enhancements in SQL Server 2000. It provides a graphical user interface with a hierarchical tree view of your database objects. Launch the Object Browser by choosing Tools Object Browser Show/Hide from the menu or by pressing the F8 key. The Object Browser has two panes: An Objects pane that lists database objects, built-in functions, and system data types. A Templates pane that gives you access to the templates used for creating generic Transact-SQL statements that you can customize. Microsoft SQL Server 2000 Professional Skills Development 6-19
Using the Query Analyzer The Objects Pane Figure 22 shows the Objects pane with the Shark database expanded. Each node in the view can be further expanded to expose the objects further down in the hierarchy. Figure 22. The Objects pane with the Shark database expanded. Use both the left mouse button and the right mouse button to work with the objects. Dragging and dropping with the left mouse button inserts the name of the object in the SQL pane, while right-dragging and dropping gives you a few more options, which you ll explore in the next exercise. 6-20 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items Try It Out! 1. Expand the User Tables node in the Shark database until the table names are displayed. 2. Left-click the tblcategory table and drag it onto the SQL pane in the Query Analyzer. You will see dbo.tblcategory in the SQL pane. Delete the text. 3. Now right-click and drag tblcategory to the SQL pane. When you release the mouse button, you will see the menu items shown in Figure 23. Figure 23. The right-click and drag popup menu. 4. Select the top menu item, Create, and release the mouse. The following script appears in the SQL window: CREATE TABLE [tblcategory] ( [CategoryId] [int] IDENTITY (1, 1) NOT NULL, [Category] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, CONSTRAINT [aaaaatblcategory_pk] PRIMARY KEY NONCLUSTERED ( [CategoryId] ) ON [PRIMARY] ) ON [PRIMARY] GO 5. Delete the script in the SQL window. Microsoft SQL Server 2000 Professional Skills Development 6-21
Using the Query Analyzer 6. Try again and this time select SELECT from the menu. You will then get a query that selects all of the columns from tblcategory: SELECT [CategoryId], [Category] FROM [Shark].[dbo].[tblCategory] 7. Experiment with left- and right-mouse dragging and dropping with the other objects. Right-dragging a function will paste the correct syntax for using that function into the SQL pane when you choose Execute from the drop-down list. Additional functionality is available by simply right-clicking on an object, which brings up the menu shown in Figure 24. Figure 24. The right-click menu in the Object Browser pane. 6-22 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items The Open option opens the table. You can enter and edit data, as shown in Figure 25. Figure 25. Entering data from the Object Browser. The other options allow you to set various properties for the Object Browser, and they are worth exploring so that you know what s available. As you can see, the Object Browser is very convenient for quickly creating queries and scripts without a lot of typing. Microsoft SQL Server 2000 Professional Skills Development 6-23
Using the Query Analyzer The Templates Pane The templates pane gives you access to the templates directory. SQL Server ships with templates you can use to create scripts and queries that perform common tasks. Figure 26 shows the Templates pane with the Create Table node expanded. Figure 26. The Templates pane with the Create Table node expanded. The Templates pane works by left-clicking on a template and then dragging and dropping the template onto the SQL pane or by double-clicking the template to open it in a new window. 6-24 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items Try It Out! To create a table using a template, follow these steps: 1. Expand the Create Table node and left-drag (or double-click) the Create Table Basic Template onto the SQL pane. This displays the following text in the SQL pane: -- ============================================= -- Create table basic template -- ============================================= IF EXISTS(SELECT name FROM sysobjects WHERE name = N'<table_name, sysname, test_table>' AND type = 'U') DROP TABLE <table_name, sysname, test_table> GO CREATE TABLE <table_name, sysname, test_table> ( <column_1, sysname, c1> <datatype_for_column_1,, int> NULL, <column_2, sysname, c2> <datatype_for_column_2,, int> NOT NULL) GO 2. Because the text enclosed in chevrons is not valid Transact-SQL syntax, replace it by choosing Edit Replace Template Parameters from the menu. This loads the Replace Template Parameters dialog box. Microsoft SQL Server 2000 Professional Skills Development 6-25
Using the Query Analyzer 3. Type in valid names and data types, as shown in Figure 27. Click Replace All when finished. Figure 27. The Replace Template Parameters dialog box. 4. All of the parameters and text in chevrons will be replaced and your script will look like the following: -- ============================================= -- Create table basic template -- ============================================= IF EXISTS(SELECT name FROM sysobjects WHERE name = N'tblTest' AND type = 'U') DROP TABLE tbltest GO CREATE TABLE tbltest ( PK int NULL, TestName varchar(50) NOT NULL) GO 6-26 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items Saving Templates You can create and save your own templates. Choose File Save As from the menu, and choose Template SQL Files in the Save Query dialog box. The template folders are located in the following directory: \Program Files\Microsoft SQL Server\80\Tools\Templates\ Choose the appropriate folder, as shown in Figure 28. Your template will show up the next time you open the Object Browser. Figure 28. Saving a script as a template. However, don t expect that saving as a template is going to perform any magic by inserting chevrons and otherwise formatting it like a built-in template. You d have to figure out where the chevrons and marker text go yourself and insert them in your template before saving. Using the Transact-SQL Debugger The Transact-SQL debugger allows you to step through stored procedures, to define watch expressions, and to set breakpoints. You can view and set variable values and perform other debugging tasks much the same way you do in other programming environments. Microsoft SQL Server 2000 Professional Skills Development 6-27
Using the Query Analyzer TIP: The Transact-SQL Debugger can lock certain system resources when stepping through code, and is therefore not recommended for use on a production server. The Transact-SQL Debugger is available from the right-click menu with a stored procedure selected in the Object Browser, or from the Object Search menu by right-clicking on a stored procedure. Try It Out! Here s how to step through the byroyalty stored procedure in the pubs database: 1. Expand the pubs Stored Procedures node in the Object Browser and right-click on the dbo.byroyalty stored procedure. 2. Choose Debug from the menu. This loads the Debug Procedure dialog box as shown in Figure 29. Type in a value for the @percentage parameter, and click Execute. Figure 29. The Debug Procedure dialog box. 6-28 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items 3. This opens a separate window in the Query Analyzer so that you can step through the stored procedure, as shown in Figure 30. All actions are from toolbar buttons, and ToolTips will display help so that you can determine what the icons mean. You can add global functions to the center pane (@@Error has been added here), and choose different step modes. Figure 30. The Transact-SQL Debugger window. 4. After the stored procedure has finished running, try executing it again. Press the F5 key or click the Go toolbar button. Supply a different value for the @percentage variable, as shown in Figure 31 where @percentage is set to 50: Figure 31. Changing the variable value. Microsoft SQL Server 2000 Professional Skills Development 6-29
Using the Query Analyzer 5. The bottom pane shows the new result set and return value from the stored procedure: au_id ----------- 427-17-2319 846-92-7186 899-46-2035 998-72-3567 @RETURN_VALUE = 0 6. Close the debugger by closing the window when you re finished. The Transact-SQL debugger is a welcome addition to the Query Analyzer. Debugging stored procedures was onerous and time consuming in previous versions of SQL Server. Object Search Choose Tools Object Search to locate objects on your SQL Server. The Object Search dialog box allows you to search for a single object or multiple objects by using traditional search methods. You can search for tables, stored procedures, functions, or other SQL Server objects. Try It Out! Follow these steps to locate all tables that have the string order in their names: 1. Choose Tools Object Search New from the menu. This loads the Object Search dialog box. 2. Select User table from the list of object types. 3. Type *order* in the Object name box and choose Find Now. 6-30 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items 4. A list of objects matching the search criteria appears in the lower pane, as shown in Figure 32. Figure 32. Using Object Search to locate all tables with order in the name. Microsoft SQL Server 2000 Professional Skills Development 6-31
Using the Query Analyzer 5. Right-click the Results pane to bring up a context-sensitive menu, as shown in Figure 33. Figure 33. The Results pane has a context-sensitive right-click menu. You can open the selected table or perform other actions as needed. Note that the grayed-out Debug option at the bottom of the menu allows you to launch the Transact-SQL Debugger if a stored procedure is selected. 6-32 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items Extended Properties On several of the right-click menus in the Query Analyzer tools, you ll see Extended Properties. This is a new feature in SQL Server 2000 that will be familiar to Access programmers, and it was added at the request of the Access team. Extended properties can be used to add your own custom annotations to SQL Server objects. For example, a column in a table might have a Caption property specifying the label that should be used to describe that column, or a Format property holding data on how the column should be formatted. Manage Indexes The Tools Manage Indexes menu option gives you a shortcut to your indexes. You can use it to create new indexes or edit existing ones. Figure 34 shows the Manage Indexes dialog box for the tblcustomer table in the Shark database. Figure 34. The Manage Indexes dialog box. Microsoft SQL Server 2000 Professional Skills Development 6-33
Using the Query Analyzer Select the index you are interested in editing, and choose Edit from the menu. This launches the Edit Existing Index dialog box where you can further refine index properties, as shown in Figure 35. Click OK when done. Figure 35. Editing the ZipCode index in tblcustomer. 6-34 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items Manage Statistics SQL Server maintains statistics on the data in your tables and indexes, and uses these statistics in determining the best plan for executing each query. If you have missing or out-of-date statistics, then the best plan may not be generated. Figure 36 shows that the tblorderdetail table in the Shark database does not have any statistics. Figure 36. Missing statistics for the tblorderdetail table. Microsoft SQL Server 2000 Professional Skills Development 6-35
Using the Query Analyzer Click New to load the Create Statistics dialog box, as shown in Figure 37. Check the columns to gather statistics on, and click OK when done. Figure 37. Creating new statistics. Normally you shouldn t need to generate statistics if you ve set your database options to automatically generate statistics. 6-36 Microsoft SQL Server 2000 Professional Skills Development
Tools Menu Items Options and Customize Select Tools Options to set the options for the Query Analyzer. Figure 38 shows the General tab where you can set options such as directories and extensions. Figure 38. Setting Query Analyzer options. The other options are worth exploring so that you can customize the Query Analyzer. Some options are for the Query Analyzer as a whole, and some are specific to a particular connection (such as those found on the Connections tab). Microsoft SQL Server 2000 Professional Skills Development 6-37
Using the Query Analyzer To configure custom keyboard shortcuts, choose Tools Customize from the menu. This loads the Customize dialog box. Type in a stored procedure name or expression as shown in Figure 39. Figure 39. Assigning a keyboard shortcut. When you press the key combination, the results appear automatically in the Results pane. 6-38 Microsoft SQL Server 2000 Professional Skills Development
Window Menu Items Window Menu Items Compared to some of the other menu items, the Window menu items don t do a whole lot. The top grouping allows you to switch panes, move the splitter (that s the bar between the Query pane and the Results pane) and hide the Results pane. The center group of options allows you to arrange the windows, and the bottom set allows you to quickly jump to a particular window. Figure 40 shows the options available in the Window menu. Figure 40. The Window menu options. Microsoft SQL Server 2000 Professional Skills Development 6-39
Using the Query Analyzer Help Menu Items Although there aren t many items on the Help menu, the ones that are there are extremely useful (see Figure 41). Figure 41. The Help menu items. Choose Contents and Index to launch Books Online with the Overview of SQL Query Analyzer topic loaded. This is your gateway to getting help on the Query Analyzer itself. Choose Using Help to launch Books Online with the Using SQL Server Books Online topic loaded. Further clues are to be found here. If you choose Transact-SQL Help to launch Books Online, what you get will depend on where your cursor is located. In a blank query, you ll get the Transact-SQL Overview topic. If you are on a Transact-SQL keyword, then Books Online will open with that topic displayed in the Index pane. 6-40 Microsoft SQL Server 2000 Professional Skills Development
Help Menu Items This is a very useful keyboard shortcut memorizing SHIFT+F1 will save some time if you want to get to Books Online quickly. Highlight the SELECT keyword in the query and press SHIFT+F1. Books Online will open with SELECT activated in the Index tab, as shown in Figure 42. Figure 42. The Index tab in Books Online after highlighting the SELECT keyword and pressing Shift+F1. Microsoft SQL Server 2000 Professional Skills Development 6-41
Using the Query Analyzer Summary The new Query Analyzer in SQL Server 2000 has a rich feature set that allows you to interact with SQL Server objects as well as to create queries and scripts. The Query Analyzer allows you to have multiple connections. You can save both scripts and result sets as text files. The Object Browser provides a hierarchical view of SQL Server objects, functions, templates, and system data types. Templates allow you to quickly create queries and scripts. You can configure indexes and launch the Index Tuning Wizard. The Transact-SQL Debugger allows you to debug stored procedures by stepping through them. You can view and set variables, set breakpoints, and view the Results pane. Object Search lets you search for any object in your SQL Server. You can take further action from the right-click menu. You can create and update statistics from the Query Analyzer. 6-42 Microsoft SQL Server 2000 Professional Skills Development
Help Menu Items Questions 1. How can you launch the Object Browser? 2. What are the two panes displayed in the Object Browser? 3. How can you quickly locate objects in your SQL Server? 4. How can you launch the Transact-SQL Debugger? 5. How can you get help when using the Query Analyzer? Microsoft SQL Server 2000 Professional Skills Development 6-43
Using the Query Analyzer Answers 1. How can you launch the Object Browser? Choose Tools Object Browser Show/Hide from the menu or press the F8 key. 2. What are the two panes displayed in the Object Browser? The Objects pane and the Templates pane 3. How can you quickly locate objects in your SQL Server? Use the Object Search. 4. How can you launch the Transact-SQL Debugger? From the Object Browser, by right-clicking on a stored procedure and choosing Debug, and from the Object Search by right-clicking in the results pane and choosing Debug. 5. How can you get help when using the Query Analyzer? By choosing one of the options from the Help menu, pressing F1, or selecting a Transact-SQL keyword and pressing Shift+F1. 6-44 Microsoft SQL Server 2000 Professional Skills Development
Help Menu Items Lab 6: Using the Query Analyzer Microsoft SQL Server 2000 Professional Skills Development 6-45
Lab 6: Using the Query Analyzer Lab 6 Overview In this lab you ll learn how to use the Object Browser to create a table and a stored procedure. You ll then use the Transact-SQL Debugger to step through the stored procedure code. To complete this lab, you ll need to work through three exercises: Using the Object Browser to Create a Table Using the Object Browser to Create a Stored Procedure Using the Transact-SQL Debugger Each exercise includes an Objective section that describes the purpose of the exercise. You are encouraged to try to complete the exercise from the information given in the Objective section. If you require more information to complete the exercise, the Objective section is followed by detailed step-bystep instructions. 6-46 Microsoft SQL Server 2000 Professional Skills Development
Using the Object Browser to Create a Table Using the Object Browser to Create a Table Objective In this exercise, you ll use the Object Browser to create a new table named tbltestbrowser with two columns. One column will be an identity column named ID, with a data type of int and the second column will be named TestName, with a data type of varchar(50). You ll write script to create the primary key on the ID column. You ll then enter a few rows of sample data in the table. Things to Consider How do you launch the Object Browser from the Query Analyzer? How do you create a new table? How do you create a primary key constraint? How do you enter data in a table from the Object Browser? Step-by-Step Instructions 1. From the Query Analyzer main menu, press the F8 key to load the Object Browser and click the Templates tab. 2. Expand the Create Table node and select the Create Table with IDENTITY Column option. Drag and drop it onto the main query pane. Microsoft SQL Server 2000 Professional Skills Development 6-47
Lab 6: Using the Query Analyzer 3. Choose Edit Replace Template Parameters from the menu. This loads the Replace Template Parameters dialog box. Enter the values shown in Figure 43 for the ID column and the Test column. Click Replace All when finished. Figure 43. Entering the values in the Replace Template Parameters dialog box. 4. You should see the following script in the Query Pane: -- ============================================= -- Create table with IDENTITY column -- ============================================= IF EXISTS (SELECT name FROM sysobjects WHERE name = N'tblTestBrowser' AND type = 'U') DROP TABLE tbltestbrowser GO create table tbltestbrowser ( ID int IDENTITY(100, 1), TestName varchar(50) NOT NULL) GO 6-48 Microsoft SQL Server 2000 Professional Skills Development
Using the Object Browser to Create a Table 5. Add a primary key constraint to the ID column by typing in the following script: ALTER TABLE dbo.tbltestbrowser ADD CONSTRAINT PK_tblTestBrowser PRIMARY KEY CLUSTERED ( ID ) ON PRIMARY GO 6. To verify the syntax of the entire script, choose Query Parse from the menu, or press the CTRL+F5 key. 7. Make sure the Shark database is active in the main window, and choose Query Execute from the menu or press the F5 key. This creates the tbltestbrowser table. 8. Click the Objects tab to view the tbltestbrowser table. Right-click on the Shark database and choose Refresh from the menu. Expand the User Tables node. You should see the tbltestbrowser table in the object list. 9. Right-click on tbltestbrowser and choose Open from the menu. Add a few rows of sample data in the TestName column. Click Close when finished. Microsoft SQL Server 2000 Professional Skills Development 6-49
Lab 6: Using the Query Analyzer Using the Object Browser to Create a Stored Procedure Objective In this exercise, you ll use the Object Browser to create a new stored procedure in the Shark database. The stored procedure will select data from tbltestbrowser and have a single parameter for use in the WHERE clause to limit the rows returned to those that match the ID column. Things to Consider How do you launch the Object Browser from the main Query Analyzer window? How do you create a new stored procedure using the Object Browser? How do you specify a parameter for the stored procedure? Step-by-Step Instructions 1. Expand the Create Procedure node in the Templates tab. Double-click on the Create Procedure Basic Template option. This launches a new window with the script in it. 6-50 Microsoft SQL Server 2000 Professional Skills Development
Using the Object Browser to Create a Stored Procedure 2. Choose Edit Replace Template Parameters from the menu. This loads the Replace Template Parameters dialog box. Enter the values shown in Figure 44 for the name proctestbrowser and @ID parameter. Click Replace All when finished. Figure 44. Name the function and specify @ID as the input parameter. 3. This will leave you with one too many parameters. Edit the script and delete the second @p2 parameter. The stored procedure should select all of the rows from tbltestbrowser with a WHERE clause using the @ID input parameter. The script should look like the following: CREATE PROCEDURE proctestbrowser @ID int = 0 AS SELECT * FROM tbltestbrowser WHERE ID = @ID 4. Parse and then execute the script. To test the script, execute the following statement: EXECUTE proctestbrowser 100 Microsoft SQL Server 2000 Professional Skills Development 6-51
Lab 6: Using the Query Analyzer Using the Transact-SQL Debugger Objective In this exercise, you ll explore the Transact-SQL Debugger, using it to step through the stored procedure you created in the previous exercise. You ll change variable values and view the different result sets generated. Things to Consider How do you launch the Transact-SQL Debugger? How do you step through code? How do you view and modify variable values? Step-by-Step Instructions 1. Refresh the Shark database in the Object Browser so that the stored procedure created in the previous exercise will show up in the Objects tab. 2. Right-click on proctestbrowser and choose Debug from the menu. This launches the Transact-SQL Debugger in a new window. 6-52 Microsoft SQL Server 2000 Professional Skills Development
Using the Transact-SQL Debugger 3. Select a starting value for the @ID variable as shown in Figure 45, and click Execute. Figure 45. Setting a starting value for the @ID variable. Microsoft SQL Server 2000 Professional Skills Development 6-53
Lab 6: Using the Query Analyzer 4. This launches the debugger in a separate window. Click the Toggle breakpoints (F9) button to toggle a breakpoint. Click the Step Into (F11) button to execute the statement. Note the results displayed in the bottom pane, as shown in Figure 46. Figure 46. The stored procedure in the Transact-SQL debugger. 5. To enter break mode a second time, click the Go (F5) button. This time type in a new variable value for @ID. Type the @@error system function name in the Name (Globals) column, as shown in Figure 47. Figure 47. Adding a system function. 6. When finished, close the debugger window. 6-54 Microsoft SQL Server 2000 Professional Skills Development
Using the Transact-SQL Debugger Microsoft SQL Server 2000 Professional Skills Development 6-55