fredagen den 7:e mars 2008

31 SQL Server Tips That Can Save Your Butt

The text is from InformIT and the full article can be read here.

Want to get the most out of SQL Server 2000? We've collected more than two dozen tips and techniques that can make any DBA's life easier.
Want to get the most out of SQL Server 2000? Here are 31 short-and-sweet tips to make your life just a little bit easier.
Tips 1-10
Full Text Search Needs a Single Unique Index
You can set up a full-text index using system-stored procedures (including sp_fulltext_database, sp_fulltext_table, and so on), or through the SQL Enterprise Manager. To create a full-text index on a table using Enterprise Manager, you select Full-Text Indexing from the Tools menu. This loads the Full-Text Wizard. The wizard leads you through the steps for enabling a full-text index on the table.
It is important to note that full-text search needs a single unique index on a table to work. A composite primary key consisting of two or more columns will not work. If you have tables that do not have a single column unique index, you need to add a new, unique column to the table. Identity columns work well for this. If the table has more than one unique index, use the smallest, most narrow available index to get the best performance. For example, if you had a table with a unique GUID column and a unique integer 4 bytes each, instead of the GUID at 16 bytes each.
Handling Special Tags Used Inside XML Templates
XML templates are handy. You don't want to use URL queries when you have many lines of T-SQL code to execute. However, you do need to be smart about handling the special tags used inside these templates. Enclose your sql:query statements and sql:param values between (known as a CDATA section) to avoid having to manually encode any special characters.
This makes things much easier because it instructs the parser to treat comparison characters such as <>, &, ', and ". Convert them to the strings (known as entities) <, >, &, ', and " when you need to use them as element or attribute values.
XML Parsers Are Case Sensitive
One of SQL Server 2000's major enhancements is the inclusion of native XML support, enabling developers to execute queries that return results as XML-formatted data, rather than standard rowsets. One importamt rule to keep in mind before delving into this much-awaited feature is that XML parsers are case sensitive with respect to element and attribute names. When running your XML data through a parser after you get it back from a SQL Server 2000 query, be sure to remember that in the mind of the parser, is not the same as , nor is Myattribute the same as myattribute.
Viewing Locking Activity with SQL Enterprise Manager
Although locking provides isolation for transactions and helps ensure their integrity, it can also have a significant impact on system performance. Keep transactions as short, concise, and non-interfering as possible. One of your goals should be to define transactions to minimize locking performance problems.
As you view and monitor locking behavior, sometimes you need to see output more directly, or you don't like the way the information is presented. Use SQL Server Enterprise Manager to display locking information. To see the output from the Enterprise Manager, expand the server items, expand the Management folder, expand the Current Activity item, and click on either Locks/Process ID or Locks/Object to display the locking information in SQL Server.
To see more information when viewing the lock activity in Enterprise Manager, be sure to go to the EM View menu and choose the Detail option. EM will then display detailed information about the locks, beyond just the process ID or object name. The information displayed includes the lock type, lock mode, lock status, and index involved.
Choosing the Optimal Method to Defragment Data and Indexes
There several methods you can use when you need to defragment your data and indexes. One method available is the DBCC INDEXDEFRAG command. DBCC INDEXDEFRAG eliminates the internal defragmentation in an index, but does not hold locks long term while it runs and doesn't lock the entire table. As a result, it can be run online and will not block concurrently-running queries or updates.
Alternatively, you can rebuild indexes by manually running a series of DROP INDEX and CREATE INDEX commands. However, this can be a tedious process that runs the risk of an index not getting rebuilt if it's missing from the SQL script. Also, if you run out of space while rebuilding an index, the CREATE INDEX command fails leaving you without that index on the table.
A better way of rebuilding all indexes is to use the DBCC DBREINDEX command. Using DBCC DBREINDEX keeps you from having to specify all the indexes to drop and re-create on a table (if you specify just the table name, it automatically rebuilds all indexes). In addition, if DBCC DBREINDEX fails while processing for some reason (out of space, out of locks, and so on), the rebuild is rolled back and the original indexes are left in place.
CAUTION
Caution! Unlike DBCC INDEXDEFRAG, DBCC DBREINDEX applies table-level locks while rebuilding indexes. It should not be run online, as it would block other queries and other updates on the table. This should only be run during off-peak hours or during the normal maintenace window.
Using AWE with SQL Server 2000 to Allocate More Memory
When running the Enterprise Edition of SQL Server 2000 on either the Windows 2000 Advanced Server or Windows 2000 Datacenter Server platforms, you can allocate more than the default maximum of 4GB of memory by enabling the Windows 2000 Address Windowing Extensions (AWE) API. When this option is enabled, a SQL Server instance can then access up to 8GB of physical memory on Advanced Server and up to 64GB on Datacenter Servers.
Although standard 32-bit addressing supports up to only 4GB of physical memory, the AWE API allows the additional memory to be acquired as nonpaged memory. The memory manager can then dynamically map views of the nonpaged memory into the 32-bit address space.
You must be careful when using this extension because nonpaged memory cannot be swapped out. SQL Server allocates the entire chunk requested and does not release it back to the operating system until SQL Server is shut down. Other applications or other instances of SQL Server running on the same machine might not be able to get the memory they need.
Also keep in mind that when using AWE with SQL Server 2000, SQL Server can no longer dynamically allocate RAM. By default, it grabs all available memory, leaving only 128MB available for Windows and other applications. You also need to configure the max server memory option to limit the amount of memory that SQL Server allocates. Be sure to leave enough memory for Windows and any other applications running on the server, usually at least 500MB.
Cascading Referential Integrity: A New Feature
SQL Server 2000 added a new feature that allows you to define cascading actions on your foreign key constraint. When defining the constraints on a table, you can use the ON UPDATE CASCADE or the ON DELETE CASCADE clauses, which cause changes to the primary key of a table to cascade to the related foreign key tables.
To illustrate the usefulness of this, consider a pair of related tables: employee and department. The employee table has a foreign key on the dept column that references the dept column of the department table. If it was created with ON UPDATE CASCADE, any changes to the dept column in the department table would cascade to the employee table. Therefore, if dept 20 has 5,000 employees, and you change the dept number to 200 to comply with a business rule, all 5,000 employee records are automatically updated as well. If ON DELETE CASCADE were specified for the table, then deleting dept 20 would result in the deletion of all 5,000 employees!
This is a powerful and dangerous feature. If you plan to utilize the cascade feature,you should work closely with the application developers to ensure that checks and balances are in place to prevent accidental deletion of data. It is also important to note the potential overhead generated by Cascading Referential Integrity.
Using the inserted and deleted Tables For Testing Purposes
In most trigger situations, you need to know what changes were made as part of the data modification. You can find this information in the inserted and deleted tables. For the AFTER trigger, these tables are actually views of the rows in the transaction log that were modified by the statement. With the new INSTEAD OF trigger, the inserted and deleted tables are actually temporary tables that are created on-the-fly. The tables have identical column structures and names to the tables that were modified.
To be able to see the contents of these tables for testing purposes, create a copy of the table, and then create a trigger on that copy. You can perform data modification statements and view the contents of these tables without the modification actually taking place. Use the following listing to create a copy of the tables and then create a trigger on the copy.--Create a copy of the titles table in the Pubs database
SELECT *
INTO titles_copy
FROM titles
GO
--add an AFTER trigger to this table for testing purposes
CREATE TRIGGER tc_tr ON titles_copy
FOR INSERT, UPDATE, DELETE
AS
PRINT 'Inserted:'
SELECT title_id, type, price FROM inserted
PRINT 'Deleted:'
SELECT title_id, type, price FROM deleted
ROLLBACK TRANSACTION
Clearing the syscacheobjects Table
Because query plans in SQL Server 2000 are re-entrant, it's typical that no more than one copy of an execution plan for a stored procedure is in cache memory. However, sometimes multiple query plans can be created and exist in procedure cache at the same time. One of the more likely causes is when users run the same procedure with different settings for specific session options.
How does SQL Server know what plans are currently in memory and what settings were in effect when they were created? This information is contained in the syscacheobjects table in the master database. syscacheobjects keeps track of all the currently compiled plans in the procedure cache.
A large number of entries can exist in the syscacheobjects table. To clear the procedure cache buffers, and subsequently, the syscacheobjects table, you can issue the DBCC FREEPROCCACHE procedure, which removes all cached plans from memory.
Alternatively, you can use the undocumented command, DBCC FLUSHPROCINDB(dbid), to flush all procedure query plans for the specified database from memory. Needless to say, you shouldn't execute these commands in a production environment because they can impact the performance of the production applications running at the time.
Protect Source Code of Stored Procedures Using the WITH ENCRYPTION Option
To protect the source code of your stored procedures and keep its contents from prying eyes, you can create a procedure using the WITH ENCRYPTION option. When this option is specified, the source code stored in the syscomments table is encrypted. If you use encryption when creating your stored procedures, be aware that while SQL Server can internally decrypt the source code, no mechanisms exist for the user or for any of the end user tools to decrypt the stored procedure text for display or editing.
With this in mind, make sure that you store a copy of the source code for those procedures in a file in case you need to edit or re-create them. Also, if you use the WITH ENCRYPTION option, you can no longer use the Transact-SQL Debugger on the encrypted stored procedure. Don't use the WITH ENCRYPTION option unless you have a good reason to hide the stored procedure code.

Tips 11-20
Choose the Correct Outlook 2000 Configuration
If you use Outlook 2000, when you set up your initial mail profile you have the option to set it up for Internet Only or for Corporate or Workgroup. Even though you might be setting up Outlook to connect only to an Internet Mail server, choose the Corporate or Workgroup mode. You don't have to add an Exchange Server mail account. However, your mail profile will behave differently.
In Corporate or Workgroup mode, SQL Mail will send e-mail messages immediately when they are generated, whether or not the Outlook client is running. For some reason, when configured for Internet Only mode, the mail messages go into limbo and are not sent unless the Outlook 2000 client is running, is online to the mail server, and is configured to automatically send and receive mail on a schedule (for example, every 2 minutes). You may find similar behavior using the Outlook XP mail client when it is configured with only Internet mail accounts.
Back Up Your Transaction Log Before You Do a Recovery
Any time you think you might have to do a recovery, the first thing you should do is back up the transaction log. If you skip this step and restore the database, you will have unnecessarily lost all the transactions since the last log backup.
There was a bug in SQL 7.0 that prevented the NO_TRUNCATE option from working if the primary data file for the database was damaged. Those of you who found this out the hard way will be happy to know it is fixed in SQL Server 2000.
Good Things Come to Those that Wait
After you run the sp_addumpdevice stored procedure, don't panic when you go looking for the physical files on disk and can't find them. The files aren't created until the first time you actually use the backup device.
Also, the physical pathname to the dump file is not validated until the first time you use the backup device. If a bad pathname is entered when creating the dump device, you receive an error message similar to the following when attempting to back up to it:Server: Msg 3201, Level 16, State 1, Line 1
Cannot open backup device 'mydump'. Device error or device off-line.
See the SQL Server error log for more details.
Constraints Are The Key to Integrity
Constraints are the primary method used to enforce integrity. Constraints can be created in the CREATE TABLE statement or after the table has been created using ALTER TABLE.
Create your tables first, and then use ALTER TABLE to create the constraints. This has the twofold effect of keeping your CREATE TABLE syntax simpler and providing ALTER TABLE scripts that can be rerun or modified as the need arises.
Changing Datatypes Can Affect Your Data
Changing some datatypes can result in changing the data. For example, changing from nchar to char could result in any extended characters being converted.
Similarly, changing precision and scale could result in data truncation. Other modifications (such as changing from char to int) might fail if the data doesn't match the restrictions of the new datatype. When changing datatypes, always validate that the data conforms to the new datatype.
Don't Shrink If You Don't Have To
Unless there is a definite need for the space that would be made available by shrinking a database, you shouldn't shrink the database files if the space will be used again in the future.
For one thing, having free space available in the database files avoids the overhead of having to autogrow the database files when they become full. Also, if a database file is repeatedly shrunk and expanded, the database file itself can become fragmented within the file system, which can degrade IO performance for the file.
Spread It Around
If too many outstanding I/Os are causing bottlenecks in the disk I/O subsystem, you might want to consider spreading the files across more disk drives. Performance Monitor can identify these by monitoring the PhysicalDisk object and Disk Queue Length counter. Consider spreading the files across multiple disk drives if the Disk Queue Length counter is greater than three.
Avoid Direct System Table References
Avoid writing queries that reference the system tables directly. Microsoft tries to provide backward compatibility whenever possible, but it is not guaranteed. What this means is that Microsoft reserves the right to change the names of the system tables at any time.
If you have applications that call these tables, they might not migrate to the next release. The information schema views, on the other hand, will remain consistent.
There's Good Info in the Error Logs
The SQL Server error log is a good place to look to determine the protocols that SQL Server on which listening. You can view the error logs via the Management node in Enterprise Manager, or you can open the error log file using any text editor. The latest error log file is found by default in Program Files\Microsoft SQL Server\Mssql\Log\Errorlog.
Open the error log file with a text editor and search for the word Listening in the error log text to find the relevant messages. The Server Network utility shows you what has been enabled, but there are instances when the server is unable to listen on the enabled protocol at startup.
Choosing the Best Trace Save Operation in SQL Profiler
Two distinct Save operations are available in the SQL Profiler. You can save trace events to a file or table, or you can save a trace definition in a template file. The Save As Trace Table and Save As Trace File options are for saving trace events to a file. The Save As Trace Template option saves the trace definition. Saving a trace template saves you the trouble of having to go through all the properties each time to set up the events, data columns, and filters for your favorite traces.
However, if you are executing a long-running trace, you should save to a file or table, as the trace runs to be sure that you capture the entire trace. Saving to a file allows you to clear the current contents of the trace window and not lose the trace information. Also, if you save the trace to a file or a table, you can open it later and specify whatever grouping you want to reorganize output. This flexibility gives you almost endless possibilities for analyzing the trace data.
If you are saving to a trace file as the trace runs, and the trace is expected to be large, then you can use the Enable File Rollover option, which creates a new event file when the file reaches the size that you specify. This allows you to have smaller, more manageable trace files for your review.

Tips 21-31
SQL Server 2000 Allows You to Schedule when a Trace Stops
Basic properties of a trace are defined in the General tab of the Trace Properties window. While these are straight-forward, there is a new feature. The General Properties screen contains a new option, Enable Trace Stop Time. This is a scheduling-oriented feature that allows you to specify a date and time at which you want to stop tracing. This is handy if you want to start a trace in the evening before you go home. You can set the stop time so that the trace will run for a few hours but won't affect any nightly processing that might occur later in the evening.
Save Trace Definitions as a Template File
SQL Server 2000's trace templates contain predefined trace settings that address some common auditing needs. These are not actual traces; they simply provide a foundation for you when creating your own traces.
When using these templates, it is important to note that the Trace Name is a relatively unimportant trace property for future traces. When you create a new trace, you can specify a name for the trace; however, this trace name will not be used again. You will not be selecting the trace to run based on the Trace Name that you entered originally. Trace Name is useful only if you are running multiple traces simultaneously and need to distinguish between them more easily. The Trace Name is used as the window title.
If you have a trace definition that you like, you can save it as a template file. If you want to run the trace again in the future, you can create a new trace and select the template file that you saved. This saves you the trouble of having to go through all the properties each time you set up the events, data columns, and filters for your favorite traces.
Create Your Own Custom Shortcuts in Query Analyzer
Query Analyzer provides up to 12 keyboard shortcuts for quickly executing stored procedures in Query Analyzer. SQL Server provides three predefined shortcuts:
Alt+F1—sp_help
Ctrl+1—sp_who
Ctrl+2—sp_lock
You can view or modify these shortcuts, or even add your own by selecting the Customize option from the Tools menu. On the Custom tab, you can enter the name of the stored procedure in the Stored Procedure column next to the desired keyboard shortcut you want to use to execute that stored procedure. You might want to add your frequently executed procedures to the Custom menu to save you the trouble of having to type them every time you want to run them.
Here's a bonus tip: if you have a word, data value, or comma-separated list of values highlighted when you invoke a keyboard shortcut, Query Analyzer passes the highlighted value(s) as parameters to the associated stored procedure.
Use a Batch File to Save Time when Executing Command-Line Utilities
SQL Server command-line utilities provide administrators with a set of powerful tools for tasks such as automating routine maintenance procedures and verifying client connectivity. A batch file, typically a text file with the .bat extension, can be a real timesaver when executing the command-line utilities. You can create the batch file in the same directory as your executable file and specify the appropriate parameters.
One helpful technique: A PAUSE command at the end of the batch file allows you to view the results in the command prompt window before the window disappears.
Connecting with ISQL Utility Using Named Instances
According to the Books Online documentation, the ISQL utility (which is based on Db-Library) does not support named instances. Contrary to the documentation,you can connect with ISQLusing named instance, but you might encounter problems.
If you do experience problems, one workaround is to set up an alias for the named instance using the Client Network utility. After this alias has been created, then the alias name can be used with the \S parameter in ISQL. Another alternative is to use OSQL, which does support named instances and all other SQL Server 2000 features.
Windows 2000 Clients Can Use PathPing to Troubleshoot TCP/IP Connectivity Problems
One way to verify that a client's ODBC connectivity is properly configured is to use the obdcping utility. However, there is another option for Windows 2000 clients. A new utility named PathPing is also available for troubleshooting TCP/IP connectivity problems. Given a target server name, this utility displays the computer name and IP address for each router as it moves toward its destination. If successfully connected to the destination server, the utility echoes reply packets (messages) to the client machine to indicate that TCP/IP connectivity exists.
For Windows 9.x and NT clients, the Ping utility, which has less functionality, is available instead.
Using the rebuildm Utility to Rebuild System Databases Requires Caution
The rebuildm lets you rebuild system databases, including the master, msdb, and model databases that are shipped with SQL Server 2000. The rebuildm utility is typically used if the following situations exist:
A current backup of the master database is unavailable. If the backup were available, the server would need to be started in single user mode first.
Microsoft SQL Server 2000 cannot start because the master database is severely damaged.
However, rebuildm needs to be used with extreme caution because it essentially copies the original versions of these databases over the copies that you have in your database. After rebuildm has been run, all of the information that you had in these databases prior to running rebuildm (including user database information, scheduled tasks, and default database settings) will be gone.
Alternative Methods for Starting and Stopping Services
Usually, SQL Server can be stopped and started easily from the EM console by right-clicking a server, which displays a pop-up window. The available options are to stop the server, which stops the SQL Server service and any dependent services, to pause the server, in which case the server remains running but no new connections are allowed, and to start the server in the case that the server has been stopped. If the server has been paused, then a Continue option appears in the pop-up menu to resume SQL server in a normal connection state.
However, occasionally, Enterprise Manager and the taskbar Service Manager get confused as to what state the server is in and won't allow services to be stopped or started. In this case, go to the Services applet in the Control Panel, or use the net stop/net start commands to stop and restart the appropriate services.
Change Server-Level Settings Cautiously
Changing server-level settings affects all databases on the server and can adversely affect performance. When changing configuration options, consider the effect the change might have and carefully document your changes so they can be undone if required.
Free Text Searches: CONTAINSsbm vs. FREETEXTsbm
While the SQL engine does support basic text searches against specific columns, you may find this method too slow and inflexible. The Microsoft Full Text Search Services provides full text searching capabilities, which is useful for searching large text fields, such as movie reviews, book descriptions, or case notes. You can specify tables or entire databases that you want to index. When you use full text indexing to perform a search for text, your query will use either the CONTAINSsbm or FREETEXTsbm function.
On the flip side, CONTAINS is a better performing function and returns more exact results. FREETEXT returns looser results based on the meaning of the search phrase you enter. It does this by finding alternate word forms in your queries. For example, FREE TEXT (*,'work independently') would match 'work independently",'Independent work preferred', and 'Independence in my work'.
Run SQL Profiler to Trap SQL-EM Commands
SQL Enterprise Manager interacts with SQL Server using standard Transact-SQL commands. For example, when you create a new database through the SQL-EM interface, behind the scenes it generates a CREATE DATABASE SQL command. Whatever you can do through SQL-EM, you can do with the Query Analyzer or even the command line ISQL or OSQL programs.
If you're curious how EM is accomplishing something, you can run SQL Profiler to trap the commands that SQL-EM is sending to the server. You can use this technique to discover some interesting internals information. You can also use this tactic to capture SQL scripts, and then repeat tasks using the script instead of a few dozen interface clicks.

0 kommentarer: