Hướng dẫn học Microsoft SQL Server 2008 part 17 docx

10 340 0
Hướng dẫn học Microsoft SQL Server 2008 part 17 docx

Đang tải... (xem toàn văn)

Thông tin tài liệu

Nielsen c06.tex V4 - 07/21/2009 12:23pm Page 122 Part I Laying the Foundation TABLE 6-1 Useful Query Editor Shortcuts Shortcut Description Ctrl+Shift+R Refresh IntelliSense Ctrl+K+K Add or remove a bookmark Ctrl+K+A Enable all bookmarks Ctrl+K+N Move to the next bookmark Ctrl+K+P Move to the previous bookmark Ctrl+K+L Clear all bookmarks Ctrl+K+C Comment the selection Ctrl+K+U Uncomment the selection Ctrl+K+W Open the Bookmark window Query options When a batch is sent from the Query Editor to SQL Server, several query option settings are included with the batch. The defaults for these settings can be set in Tools ➪ Options ➪ Query Execution ➪ SQL Server. The current query options can be viewed or changed in Query ➪ Query Options, as shown in Figure 6-9. FIGURE 6-9 Advanced and ANSI query options can be viewed and set using the Query Options dialog. This view shows the Advanced Query Options. 122 www.getcoolebook.com Nielsen c06.tex V4 - 07/21/2009 12:23pm Page 123 Using Management Studio 6 Executing SQL batches As a developer’s tool, the Query Editor is designed to execute T-SQL batches, which are collections of multiple T-SQL statements. To submit a batch to SQL Server for processing, use Query ➪ Execute Query, click the Run Query toolbar button, use the F5 key, or press Ctrl+E. (Personally, I’ve always wanted a large button like the Staples ® Easy button plugged into USB and programmed to F5 that I can slam to execute the query.) Because batches tend to be long, and it’s often desirable to execute a single T-SQL command or a portion of the batch for testing or stepping through the code, the SQL Server team provides you with a convenient feature. If no text is highlighted, then the entire batch is executed. If text is highlighted, only that text is executed. You’ll learn more about this in Chapter 21, ‘‘Programming with T-SQL,’’ but technically, when the Query Editor sends the script to SQL Server, it breaks it up into smaller batches separated by the batch separator – go. It’s worth pointing out that the Parse Query menu command and toolbar button checks only the SQL code. It does not check object names (tables, columns, stored procedures, and so on). This actually is a feature, not a bug. By not including object name–checking in the syntax check, SQL Server permits batches that create objects, and then references them. The T-SQL batch will execute within the context of a current database. The current database is displayed, and may be changed, within the database combo box in the toolbar. Results! The results of the query are displayed in the bottom pane, along with the Messages tab, and optionally the Client Statistics or Query Execution Plan tabs. The Results tab format may be either text or grid; you can switch using Ctrl+TorCtrl+D, respectively. The new format will be applied to the next batch execution. Alternately, the results can be displayed in another tab, instead of at the bottom of the query document. In Options, use the Query Results ➪ SQL Server ➪ Results to Grid tab, or the Query context menu Results tab and choose the ‘‘Display results in a separate tab’’ option. Another useful result option is to play the Windows default beep sound file when a query completes. This can only be set in the Query ➪ Option, Query Results ➪ SQL Server tab. SQL Server 2000’s Query Editor had a toolbar button to open or close the results pane. It disappeared with SQL Server 2005, but Ctrl+R still toggles the Query Editor results pane. The command is still in the Customize Toolbar dialog, so you can fix the toolbar if you’d like. It’s called Show Results Pane, and it’s not in the Query category where you’d expect to find it, but hiding in the Window category. Viewing query execution plans One of Query Editor’s most significant features is its ability to graphically view query execution plans (see Figure 6-10). 123 www.getcoolebook.com Nielsen c06.tex V4 - 07/21/2009 12:23pm Page 124 Part I Laying the Foundation FIGURE 6-10 Query Editor’s ability to graphically display the execution plan of a query is perhaps its most useful feature. What makes the query execution plans even more important is that SQL is a descriptive language, so it doesn’t tell the Query Optimizer exactly how to get the data, but only which data to retrieve. While some performance tuning can be applied to the way the query is stated, most of the tuning is accomplished by adjusting the indexes, which greatly affects how the Query Optimizer can compile the query. The query execution plan reveals how SQL Server will optimize the query, take advantage of indexes, pull data from other data sources, and perform joins. Reading the query execution plans and understanding their interaction with the database schema and indexes is both a science and an art. Chapter 63, ‘‘Interpreting Query Execution Plans,’’ includes a full discussion on reading the query execution plan. Query Editor can display either an estimated query execution plan prior to executing the query or the actual plan after the query is run. Both display the exact same plan, the only difference (besides the 124 www.getcoolebook.com Nielsen c06.tex V4 - 07/21/2009 12:23pm Page 125 Using Management Studio 6 wait) is that the actual plan can display both the estimated and actual row counts for each operation, whereas the estimated query execution plan provides only the estimated row count. In addition to the query execution plan, the Query Editor can display the client statistics, which is a quick way to see the server execution times for the batch (although Profiler is a much better tool for detail work.) Enable Include Client Statistics using the Query menu or toolbar to add this tab to the results. Using the Solution Explorer The optional Solution Explorer enables you to organize files and connections within solutions,which contain projects, similar to the Solution Explorer in Visual Studio. You don’t need to use it; File ➪ Open and Save work well without Solution Explorer, but if you work on several database projects, you may find that Solution Explorer helps keep your life organized — or at least your code organized. You can find Solution Explorer in the View menu, and the Solution Explorer icon may be added to the Standard toolbar using the Customize toolbar. To use Solution Explorer for managing query scripts, use the Solution Explorer context menu to create a new project. This will create the nodes and directories for the files. Once the project exists, use it to create new queries. Other than simply organizing your project, Solution Explorer offers two practical benefits. One, if queries are saved within a solution, bookmarks are retained. Two, Solution Explorer can be used with source control. Visual SourceSafe Integration I t’s possible to integrate Solution Explorer with Visual Studio SourceSafe or a third-party version control utility to provide solid document management and version control. When source control is installed and enabled, scripts under the control of Solution Explorer will automatically use the source control. The following commands are added to Solution Explorer’s object context menu: ■ Check Out for Edit ■ Get Latest Version ■ Compare ■ Get ■ View History ■ Undo Checkout Whether you use SourceSafe or integrate Management Studio with source control, I strongly suggest that you use some method of checking your scripts into source control. 125 www.getcoolebook.com Nielsen c06.tex V4 - 07/21/2009 12:23pm Page 126 Part I Laying the Foundation Jump-Starting Code with Templates Management Studio templates are useful because they provide a starting point when programming new types of code and they help make the code consistent. Using templates To use a template, open the Template Explorer, select a template, and double-click. This will open a new query in the Query Editor using code from the template. You can also drag a template from the Template Explorer to an open Query and deposit the template code into the query. The new query will likely include several template parameters. Rather than edit these in text, you can use a dialog box by selecting Query ➪ Specify Values for Template Parameters (Crtl+Shift+M). Sorry, but I didn’t find any way to automatically open this dialog, which has an entry for every parameter and automatically fills in the parameters within the query. If you make an error, the only way to go back is to undo each parameter change (Ctrl+Z). Managing templates The templates are simply stored SQL scripts within a directory structure, which means it’s easy to create your own templates or modify the existing ones. Simply save the . SQL scripts in the following directory: \Documents and Settings\{user}\Application Data\Microsoft\ Microsoft SQL Server\100\Tools\Shell\Templates\ There’s more to saving templates than meets the eye. A common copy is stored here: %ProgramFiles%\Microsoft SQLServer\100\Tools\Binn\ VSShell\Common7\IDE\sqlworkbenchprojectitems When Management Studio launches, it checks the two folders and any template in the common folder that’s not in the local folder is copied to the local user folder. To add parameters to your custom templates, add the parameter name, the type, and the default value inside angle brackets, like this: <parameter name, data type, default value> Thedatatypeisoptional. For developers or organizations desiring consistency in their own development styles or standards, I highly recommend taking advantage of Management Studio’s templates. Summary Management Studio’s Object Explorer and Query Editor are the two primary DBA and developer interfaces for SQL Server. Mastering the navigation of both these tools is vital to your success with SQL Server. 126 www.getcoolebook.com Nielsen c06.tex V4 - 07/21/2009 12:23pm Page 127 Using Management Studio 6 Here are the few chapter takeaways: ■ Management Studio can be visually intimidating — so many windows. I recommend closing any window not needed for the task at hand. Remove the distractions and get the job done. ■ If you upgraded from SQL Server 2005 and haven’t taken the time to explore the new Management Studio, you’re missing some of the best parts of SQL Server 2008. ■ You may not need Registered Servers. It’s only useful if you have a lot of servers. ■ Management Studio offers a scalable experience. The accidental DBA can use the wizards and GUI, while the master DBA can work with raw T-SQL, DMV, and wait states. ■ The T-SQL Debugger is back! ■ As the Query Editor is really the place where T-SQL happens, take the time to master its little features, such as bookmarks, in order to get the most out of SQL Server. ■ IntelliSense takes some getting used to, but when mastered, it’s great. ■ Query Editor can now connect to multiple servers from a single tab — very useful for server farm management. The next chapter rounds out Part I, ‘‘Laying the Foundation,’’ with a new interface for SQL Server that holds a lot of promise for the power DBA: PowerShell. 127 www.getcoolebook.com Nielsen c06.tex V4 - 07/21/2009 12:23pm Page 128 www.getcoolebook.com Nielsen c07.tex V4 - 07/23/2009 9:03pm Page 129 Scripting with PowerShell IN THIS CHAPTER Introduction to PowerShell and PowerShell Scripting Using PowerShell with SMO to automate SQL Server administration Using PowerShell to extract SQL Server data New SQL Server 2008 PowerShell features P owerShell is the new scripting environment for the Microsoft Windows platform. For administrators who don’t have access to the Visual Studio environment, or for the IT professional who prefers scripting to compiled code, PowerShell provides access to most of the .NET Framework and the objects available within it. PowerShell is available as a free download from Microsoft at www.microsoft.com/powershell/. It’s also automatically installed when SQL Server 2008 is installed, unless it’s already present. PowerShell is included with the Windows Server 2008 and later operating systems, but must be installed on Windows 2003, Windows XP (SP2 or later), and Windows Vista. It will not run on operating systems earlier than those mentioned here. PowerShell was introduced in late 2006 to enable administrators to develop scripts for automating processes they did regularly. Prior to the introduction of PowerShell, most administrators used command-line batch files, VBScript, or some third-party proprietary application designed for this function. Batch files had somewhat limited functionality, and significant security problems. It was easy using batch files to ‘‘hijack’’ actual operating system commands by cre- ating a batch file with the same name and placing it in a directory in the PATH environment variable, or in the current directory. Batch files also suffer significant limitations with regard to iterative processes. VBScript was a better solution to the problem of iterative processes and provided interfaces to many of the server products offered, but it lacked consistency and was reliant on the COM object model. The introduction of the .NET Framework rendered the COM object model obsolete (or nearly so). PowerShell addresses these limitations through a strong security foundation that prevents command-line hijacking by only allowing the user (by default) to run digitally signed scripts, and by forcing the user to specify the directory for each command run from the script environment. It also supports the .NET Framework (2.0 and later), so the functionality built in the framework is available in this scripting environment. 129 www.getcoolebook.com Nielsen c07.tex V4 - 07/23/2009 9:03pm Page 130 Part I Laying the Foundation Why Use PowerShell? In today’s business world it’s important to get as much done in as little time as possible. The most suc- cessful people are finding ways to automate every repetitive task for which they’re responsible. Consis- tency is important when automating tasks so that every administrator on the team is equally capable of stepping in to help other team members when necessary. Microsoft has designated PowerShell as part of its common engineering criteria (CEC) for all server prod- ucts. This means that an administrator who’s responsible for Exchange or Active Directory will probably have spent time learning PowerShell, and scripts written to manage SQL Server using PowerShell can be understood by administrators without specific SQL Server knowledge. Companies will be able to run more efficiently with this common scripting language and administrators with skills in PowerShell will be more valuable to their companies. Basic PowerShell PowerShell, like any language, consists of commands, variables, functions, flow control methods, and other features necessary to enable work to be done. Because it is an interpreted language, the scripts don’t have to be compiled into an executable form to be run. Language features A cmdlet (command-let) is a command-line utility built into PowerShell to provide some functionality. These cmdlets use a verb-noun naming convention, so it’s fairly easy to understand what they’re doing. Microsoft has provided about 130 built-in cmdlets with the default installation of PowerShell (1.0), and additional cmdlets are installed depending on various server products that may be running. PowerShell 2.0 is expected in mid-2009, but because it wasn’t ready for release when SQL Server 2008 was shipped, the focus of this chapter is on PowerShell 1.0. (Version 2.0 expands the PowerShell language and introduces an integrated development environment, similar to Visual Studio.) Cmdlets are frequently aliased. In other words, a different command can be entered to run the cmdlet, rather than using its own name. For example, when browsing a directory, the PowerShell cmdlet to view the contents of the current directory is Get-ChildItem. Users of the DOS operating system (or cmd.exe on current windows systems) are familiar with the dir command, and Unix users are familiar with the ls command. All three of these commands do the same thing, and both dir and ls are included with PowerShell as aliases of the Get-ChildItem cmdlet. A feature of Unix shell scripting environments is the capability to ‘‘pipe’’ the results of one command into another command’s input buffer. This is a feature of shell scripting that makes it so powerful — the ability to string multiple commands together to provide information quickly. PowerShell provides this ability, but differs from Unix shell scripting in that the Unix pipe sends text from one command to another, whereas PowerShell pipes objects from one cmdlet to another. Unix scripts must parse the text from one command using commands such as grep, awk,andsed to format the text in a form the next command expects. PowerShell’s objects are understood by the receiving cmdlet and no such parsing is required. 130 www.getcoolebook.com Nielsen c07.tex V4 - 07/23/2009 9:03pm Page 131 Scripting with PowerShell 7 The PowerShell environment can be started in a number of different ways: ■ Select the Start button ➪ Programs ➪ Windows PowerShell 1.0, and then select Windows PowerShell. ■ From the cmd.exe command line, the ‘‘powershell’’ command will launch the environment as well. ■ There’s also the new SQL Server wrapper called sqlps.exe, which is discussed later in the chapter. The examples here are based on the standard powershell.exe environment. Normally, in the Power- Shell environment, the user is informed of this by the prompt ‘‘ PS>’’ at the beginning of the line where the next command is to be entered. Here’s an example of using a series of cmdlets, piping the results of one to the next, and then filtering the results to get useful information. In this set of commands, the get-process command is used to return a set of all processes on the system, pipe the results into a sort on the size of the workingset, or the amount of memory each process is using, in descending order, and then select just the first 10, returning the biggest memory hogs on the system: get-process | sort-object workingset -descending | select-object -first 10 Notice that PowerShell is not case sensitive. In addition, the alias sort could have been used instead of thepropernameof sort-object,andselect could have been used instead of select-object. This set of commands produces results like this: Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName 637 82 163668 157312 1228 232.92 2132 sqlservr 535 80 120208 117256 1225 261.53 1344 sqlservr 562 18 99972 77364 357 457.14 3580 Ssms 598 11 52048 50352 179 57.86 4012 powershell 308 73 61612 45740 1155 156.54 728 sqlservr 602 17 57452 37956 255 298.60 1400 Reporting ServicesService 494 10 26636 33144 155 5.93 3308 SQLPS 713 46 36704 27984 210 241.31 1264 msmdsrv 1011 42 12872 19556 80 144.29 808 svchost 158 4 12248 13272 104 2.22 1204 MsDtsSrvr PowerShell variables are declared by preceding the variable name with the dollar sign ($) character. Variables are really objects of a particular type, and that data type can be created by preceding the variable name with the data type in brackets ([]). For example, a variable called $counter that’s an integer object can be created and set to a value of 7 as follows: PS> $counter = 7 131 www.getcoolebook.com . SMO to automate SQL Server administration Using PowerShell to extract SQL Server data New SQL Server 2008 PowerShell features P owerShell is the new scripting environment for the Microsoft Windows platform upgraded from SQL Server 2005 and haven’t taken the time to explore the new Management Studio, you’re missing some of the best parts of SQL Server 2008. ■ You may not need Registered Servers. It’s. Settings{user}Application Data Microsoft Microsoft SQL Server 100ToolsShellTemplates There’s more to saving templates than meets the eye. A common copy is stored here: %ProgramFiles% Microsoft SQLServer100ToolsBinn VSShellCommon7IDEsqlworkbenchprojectitems When

Ngày đăng: 04/07/2014, 09:20

Tài liệu cùng người dùng

Tài liệu liên quan