1. Trang chủ
  2. » Công Nghệ Thông Tin

Hướng dẫn học Microsoft SQL Server 2008 part 128 pps

10 131 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 1,48 MB

Nội dung

Nielsen c53.tex V4 - 07/21/2009 3:44pm Page 1232 www.getcoolebook.com Nielsen c54.tex V4 - 07/21/2009 3:48pm Page 1233 Schema Audit Triggers IN THIS CHAPTER Tracking schema changes I n some shops, the path to production can be complicated. For a recent contract, the client had 20 servers dedicated to the project, which included a dev environment, a QA testing environment, an integration testing environment, a performance testing environment, and a production environment. Because the project scaled out using four servers, each environment had four identical servers. Adding my development notebook to the mix pushed us to 21 machines. At least once, as I was deploying change scripts, I missed a server — and of course I wouldn’t catch it in my testing. If I was lucky, another DBA would catch it before it broke something for one of the app programmers. No doubt you’ve been there too. While the schema audit trigger presented in this chapter couldn’t have prevented my error, it would have made it much easier to diagnose and correct. This chapter builds on its sister chapter, Chapter 27, ‘‘Creating DDL Triggers.’’ That chapter demonstrates how to create a DDL trigger, while this chapter applies the technology for a specific purpose. DDL triggers are easy enough to code, but it’s not a common task, so I’ve tried to automate the process for you with SchemaAudit, an open- source schema auditing script available for download from my website, www.sqlserverbible.com,orfromCodePlex.com.TheSchemaAudit script creates a SchemaAudit table and installs the DDL trigger to track all schema changes. You can (and should) download the most recent version of the SchemaAudit script from www.sqlserverbible.com. It’s quite likely this script will be updated over time. 1233 www.getcoolebook.com Nielsen c54.tex V4 - 07/21/2009 3:48pm Page 1234 Part VIII Monitoring and Auditing SchemaAudit Table Just as with the Audit table in the previous chapter, any audit system needs a repository. The following table is designed to track schema changes: CREATE TABLE dbo.SchemaAudit ( AuditDate DATETIME NOT NULL, UserName sysname NOT NULL, [Event] sysname NOT NULL, [Schema] sysname NULL, [Object] VARCHAR(50) NULL, [TSQL] NVARCHAR(MAX) NOT NULL, [XMLEventData] XML NOT NULL); The SchemaAudit script creates this table. SchemaAudit Trigger The following DDL trigger captures information about any database changes in the user database and records the changes to an audit table. The key is the EventData() XML function, which contains information generic to any DDL command. The SchemaAudit script creates this trigger: CREATE TRIGGER [SchemaAuditDDLTrigger] ON DATABASE FOR DDL_DATABASE_LEVEL_EVENTS AS BEGIN www.SQLServerBible.com Paul Nielsen SET NoCount ON DECLARE @EventData XML, @Schema SYSNAME, @Object SYSNAME, @EventType SYSNAME, @SQL VARCHAR(MAX) SET @EventData = EventData() SET @Schema = @EventData.value (’data(/EVENT_INSTANCE/SchemaName)[1]’, ‘VARCHAR(50)’) SET @Object = @EventData.value (’data(/EVENT_INSTANCE/ObjectName)[1]’, ‘VARCHAR(50)’) SET @EventType = @EventData.value (’data(/EVENT_INSTANCE/EventType)[1]’, ‘VARCHAR(50)’) INSERT SchemaAudit (AuditDate, UserName, [Event], [Schema], 1234 www.getcoolebook.com Nielsen c54.tex V4 - 07/21/2009 3:48pm Page 1235 Schema Audit Triggers 54 Object, TSQL, [XMLEventData]) SELECT GETDATE(), @EventData.value(’data(/EVENT_INSTANCE/UserName)[1]’, ‘SYSNAME’), @EventType, @Schema, @Object, @EventData.value(’data(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]’, ‘VARCHAR(max)’), @EventData END With the trigger in place, it’s time to make several schema changes: CREATE TABLE Test ( PK INT NOT NULL Primary Key, Col1 VARCHAR(1) ); GO ALTER TABLE Test DROP Column Col1 ALTER TABLE Test ADD Col1 CHAR(1) DROP TABLE Test Use the following to view the Schema Audit log and see the full history of the database schema changes: SELECT AuditDate, User, [Event], [Schema] + ‘.’ + [Object] as Object, TSQL FROM SchemaAudit; Result: AuditDate User Event Object TSQL 2009-03-29 18:36:00 dbo CREATE_TABLE dbo.Test CREATE TABLE Test (PK INT NOT NULL Primary Key, Col1 VARCHAR(1); 2009-03-29 18:36:00 dbo ALTER_TABLE dbo.Test ALTER TABLE Test DROP Column Col1 2009-03-29 18:36:00 dbo ALTER_TABLE dbo.Test ALTER TABLE Test DROP Column Col1 2009-03-29 18:36:00 dbo ALTER_TABLE dbo.Test ALTER TABLE Test ADD Col1 CHAR(1) 2009-03-29 18:37:00 dbo DROP_TABLE dbo.Test DROP TABLE Test 1235 www.getcoolebook.com Nielsen c54.tex V4 - 07/21/2009 3:48pm Page 1236 Part VIII Monitoring and Auditing Summary Although this chapter is short, auditing schema changes is a critical task for any database, whether it’s a dev database, test environment, or production. I strongly recommend adding schema auditing to every database, and the SchemaAudit script automates the process. The next chapter in this part covering monitoring and auditing discusses tracing and profiling, the ability to see into SQL Server and its traffic. 1236 www.getcoolebook.com Nielsen c55.tex V4 - 07/21/2009 3:50pm Page 1237 Performance Monitor IN THIS CHAPTER Observing server performance Saving counter logs W hen I tuned the search feature in Nordic (my T-SQL based O/R DBMS) I pushed the database up to five million objects by running several instances of Query Editor, each running a loop to generate random names using the distribution of names from the 1990 U.S. Census. To be as efficient as possible, I played with the number of Query Editor instances and found that, on my machine, about ten instances with a .025-second pause produced the highest number of transactions per second. The tool I used to watch the transactions per second, and the number of objects in the database, was PerfMon. Performance Monitor, or ‘‘PerfMon,’’ has been around for quite a while. Anyone working with Windows as an IT platform is familiar with PerfMon. These are the first tools used for high-level diagnostics and health of any server. SQL Server extends PerfMon by adding dozens of SQL Server–specific counters. While PerfMon alone doesn’t provide enough detail to fully diagnose SQL Server, it does a great job of illustrating the overall server performance issues and high- lighting SQL Server themes. PerfMon i s more than just a pretty face. PerfMon’s counter logs can write data to a binary perflog ( *.blg) file or to a comma-delimited file (universal across Windows versions). Either type of file can be integrated into SQL Server Profiler. All in all, anyone working with SQL Server needs to be proficient with PerfMon. 1237 www.getcoolebook.com Nielsen c55.tex V4 - 07/21/2009 3:50pm Page 1238 Part VIII Monitoring and Auditing Using Performance Monitor Performance Monitor (PerfMon) includes two snap-ins: System Monitor and Performance Logs and Alerts. Some servers have it installed in the Administrative Tools menu. It’s also found at Control Panel ➪ Administrative Tools ➪ Performance, and it can be launched from SQL Server Profiler’s Tools ➪ Performance Monitor menu command. System monitor System Monitor, or ‘‘sysmon,’’ is familiar to anyone with experience with Windows server administration. System Monitor graphically displays multiple counters, aggregate but detailed data from the server inter- nals. It looks a bit like a heart EKG monitor for Windows and SQL Server, as shown in Figure 55-1. FIGURE 55-1 System Monitor is useful for watching the overall activity within SQL Server. 1238 www.getcoolebook.com Nielsen c55.tex V4 - 07/21/2009 3:50pm Page 1239 Performance Monitor 55 The performance counters are added to System Monitor one counter at a time using the plus-symbol button in the toolbar. A performance counter can watch the local server or a remote server, so it isn’t necessary to run System Monitor at the SQL Server machine. The counters can be watched as a timed line graph, a histogram bar graph, or a real-time report. Counters are organized by object and, sometimes, instance. For example, in Figure 55-1, the SQL Server: Databases object exposes many counters, including the Transactions/sec counter. This counter can be watched for All Instances (all databases), or as selected instances (the PerfTest database). The SQL Server Database Engine isn’t the only server to expose counters to System Mon- itor. Analysis Services, Reporting Services, .NET, ASP, BizTalk, and other servers all add counters to System Monitor. Typically, a new counter will display a s a line at the top or bottom of the graph because the scale needs adjustment. Using the System Monitor Properties dialog, available from the context menu, you can adjust the scale of the graph, the scale of each counter, and the presentation of each counter. Although there are hundreds of possible System Monitor counters, Table 55-1 describes the counters commonly used when investigating a SQL Server installation. The ‘‘best counter’’ list seems to change with e very performance conference presentation. These are the counters I had success with, but by no means am I saying there aren’t other counters worth watching. So, read the blogs, experiment, and keep track of the ones you find meaningful. Additionally, the SQL Server: Wait Statistics counters are useful windows into potential SQL Server bot- tlenecks; and there are a number of interesting memory counters in SQL Server: Resource Pool Stats. A complete list of SQL Server counters and their current values can be queried from the sys.dm_os_performance_counters dynamic management view. This is cool, because you can get the counter data from within Transact-SQL code. You can create custom counters using T-SQL to pass data from your database code to System Monitor. This can be useful to show the number of transactions processed by a performance test or the number of rows inserted by a data generator. There are ten possible user c ounters. The following trivial example increments one of the counters: DECLARE @Counter Int SET @Counter = 0 While @Counter < 100 BEGIN SET @Counter = @Counter + 1 EXEC sp_user_counter1 @Counter WAITFOR Delay ‘00:00:02’ END 1239 www.getcoolebook.com Nielsen c55.tex V4 - 07/21/2009 3:50pm Page 1240 Part VIII Monitoring and Auditing TABLE 55-1 Key Performance-Monitor Counters Object Counter Description Usefulness SQLServer: Buffer Manager Buffer-cache hit ratio Percentage of reads found already cached in memory SQL Server typically does an excellent job of pre-fetching the data into memory. If the ratio is below 95 percent, more memory will likely improve performance. Processor Percentage of processor time Total percentage of processor activity If CPUs are regularly more than 60 percent active, additional CPU cores or a faster server will increase performance. SQLServer: SQL Statistics Batch requests per second SQL batch activity A good indicator of user activity Physical Disk Average disk-queue length Number of both reads and writes waiting on the disk; an indication of disk throughput; affected by the number of disk spindles on multi-disk RAID configurations. According to Microsoft, the disk-queue length should be less than the number of disk spindles plus two. (Check the scale when applying.) Disk throughput is a key hardware performance factor. Carefully splitting the database across multiple disk subsystems will probably improve performance. SQLServer: SQL Statistics Failed auto-params per second Number of queries for which SQL Server could not cache the query execution plan in memory; an indication of poorly written queries. (Check the scale when applying.) Locating and correcting the queries will improve performance. SQLServer: Locks Average wait time (in milliseconds), lock waits, and lock timeouts per second A cause of serious performance problems; lock waits, the length of the wait, and the number of lock timeouts are all good indicators of the level of locking contention within a database. If locking issues are detected, the indexing structure and transaction code should be examined. SQLServer: User Connections User connections Number of current connections Indicates potential database activity SQLServer: Databases Transactions per second Number of current transactions within a database A good indicator of database activity 1240 www.getcoolebook.com Nielsen c55.tex V4 - 07/21/2009 3:50pm Page 1241 Performance Monitor 55 Best Practice U se System Monitor to get an overall picture of the health of the server and to get an idea of the types of issues that might be occurring within SQL Server. Then, armed with this information, move to SQL Server Profiler to target the specific problem. The configuration of System Monitor, including every counter, can be saved to a configuration file using File ➪ Save As, and later restored using File ➪ Open. Using this technique, you can export a System Monitor configuration to other servers. There is one catch: the counter must be monitoring the local server to move from server to server. However, if the counters monitor a remote server, then the configuration will monitor that remote server regardless of where the System Monitor configuration file is opened. Because DBAs are seldom physically at the SQL Server being monitored, this is a problem. If this bothers you as much as it bothers me, e-mail me; one of these days I’m going to write a custom system monitor to fix this and other problems. Counter Logs Performance Monitor also includes the Performanc e Logs and Alerts plug-in, which includes counter logs, Trace Alerts, and Alerts. This section focuses on counter logs. Counter logs use the same server counters as System Monitor, but instead of graphically displaying the data in real time, the counter logs write the counter data to a log file. This means the data can be analyzed after the fact or even replayed within SQL Server Profiler (more o n this cool feature in the next chapter). Counter log configurations are listed under the counter logs node in Performance Monitor. To see the resulting log files you have to look in the output directory. To create a new counter log, use the counter log’s context menu and choose N ew Log Settings. After naming the log, the SQL Server Trace Property dialog (shown in Figure 55-2) is used to define the log. Adding an object adds every counter for the object, while adding counters provides a more granular capability to select counters similarly to System Monitor. Counter Logs can be scheduled to run in the Counter Log Property dialog, or manually started and stopped using the log’s context menu or the start and stop toolbar buttons. If the Counter Log file was defined as a text file (comma-delimited or tab-delimited), you can open it using Excel. Each column is a counter value, and each row is a sample interval. 1241 www.getcoolebook.com . and health of any server. SQL Server extends PerfMon by adding dozens of SQL Server specific counters. While PerfMon alone doesn’t provide enough detail to fully diagnose SQL Server, it does a. meaningful. Additionally, the SQL Server: Wait Statistics counters are useful windows into potential SQL Server bot- tlenecks; and there are a number of interesting memory counters in SQL Server: Resource. integrated into SQL Server Profiler. All in all, anyone working with SQL Server needs to be proficient with PerfMon. 1237 www.getcoolebook.com Nielsen c55.tex V4 - 07/21/2009 3:50pm Page 1238 Part VIII

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

TỪ KHÓA LIÊN QUAN