Administering SQL Server 2000 - Cramsession

Installing and Configuring SQL Server 2000

Installing

Memory: The default, which is generally recommended, is for SQL Server to adjust its memory usage based on the physical memory available in the system.

Clustering

Use clustering for fault-tolerance.
2 or more SQL Servers (nodes) that are a single virtual server.
Active-Active cluster – have 2 different SQL Servers running, one on each node.
Active-Passive cluster – only one of the nodes has SQL Server running, the other does nothing until failover. Better performance, more expensive.
Two Node Clustering - uses Windows 2000 Advanced Server
Three/Four Node Clustering - uses Windows 2000 Datacenter
There is a bit of downtime (few mins) when the failover actually happens.
Must use VIRTUAL_SERVER\Instance-name to connect – SQL Server won’t listen on the actual IP address of the physical server.
Setting up a cluster:

  1. The disks must be in a cluster group (set up in Windows)
  2. Run Setup. Enter a Virtual Server Name rather than a computer name.
  3. Failover Clustering screen – enter an IP address for each network the cluster will be available to.
  4. Cluster Disk Selection screen – select the cluster disk group.
  5. Cluster Management screen – remove any unwanted nodes.
  6. Remote Information screen – enter a log in and password that has admin rights on the remote node.

Collations

Collations determine how character data is stored and sorted.
SQL Server 2000 supports multiple collations in a single installation / instance. Earlier versions did not.
Collations can be applied to databases, columns, variables and parameters.

Services

SQL Server can run up to 16 named instances concurrently.
The default instance has the name of the computer you’re installing on. Further instances are referred to as COMPUTERNAME\INSTANCENAME. The INSTANCENAME can’t exceed 16 characters.
Each instance listens on a unique network address. The connecting application only needs to supply the COMPUTERNAME\INSTANCENAME.
A default instance of SQL Server 2000 listens on the same network addresses as earlier versions of SQL Server; therefore, applications using the client connectivity components of SQL Server version 7.0 or earlier can continue to connect to the default instance with no change.
Named instances listen on alternative network addresses, and client computers using the client connectivity components of SQL Server version 7.0 or earlier must be set up to connect to the alternative addresses.
It’s usually recommended to run with just one instance.
Running multiple instances of SQL Server on a single computer is best:

Services Accounts

Default: Use same log on for both services, automatically start each service.v If you specify the local System account, it does not have network permissions in NT 4, only in Windows 2000. So, you wouldn’t be able to configure replication in NT4.
Autostart – can only be on for SQL Server Agent if it’s on for SQL Server as well.
If services can’t start, it could be that the Administrator has disable the Log on as a service right. To get round this, you could configure the services to run under the local System account.

Upgrading

To upgrade from SQL Server 6.5, you must have a DEFAULT instance of SQL Server 2000. You can only upgrade one 6.5 Server. 6.5 is not removed.
In upgrading SQL Server 7, it is overwritten.
SQL Server 6.5, 7.0 and 2000 can co-exist on the same computer, but only one version at a time can be active.
To upgrade a cluster, you first have to uncluster it using the Cluster Wizard. You must do this before installing SQL Server 2000.

Create a Linked Server

A linked server configuration allows SQL Server to execute commands against OLE DB data sources on different servers. Could link to an Oracle, Access or other SQL Server.
sp_addlinkedserver
Enterprise Manager – Security folder, Linked Servers.
If defining a SQL Server 7.0 database as a linked server in SQL Server 2000, you should replace the client tools and connectivity components on all the client computers with the SQL Server 2000 version.

Email and SQL Server

These are two separate services used by SQL Server to handle mail.
SQL Mail is used by the MSSQLServer service, while SQLAgentMail is used by the SQLServerAgent service.

SQLAgentMail

SQLAgentMail can use a separate domain account and mail profile if required. If you want both to use the same mail profile, then you need to configure both services to use the same domain account.
Email can be sent when:

SQL Mail

SQL Mail uses stored procedures to receive e-mails received in the mailbox that you assign to it (to do this, you need to create a regularly scheduled job that uses the stored procedure xp_processmail), and to send e-mails from a trigger or other stored procedure, using xp_sendmail.
SQL Mail must have a mail profile created for the same domain account that is used to start SQL Server.
In Enterprise Manager, your server has a Support Services folder. If you double click on SQL Mail in this folder, you can configure SQL Mail to use the mail profile that you have set up for the SQL Server domain account.

Configure Network Libraries

A matching pair of SQL Server Net-Libraries must be installed on a client and server computer to support a particular network protocol (for example, client TCP/IP Sockets Net-Library and server TCP/IP Sockets Net-Library). Some Net-Libraries, such as Named Pipes and Multiprotocol, support several network protocols.
Setup installs all of the client and server Net-Libraries.
Defaults:

After the network connections are installed and configured, SQL Server can listen on any combination of the server Net-Libraries simultaneously. To change server Net-Libraries after setup, run SQL Server Network Utility.

The Named Pipes Net-Library, as well as the TCP/IP Sockets Net-Library, supports TCP/IP, so you can disable one of these libraries when using TCP/IP to connect.
Named Instances of SQL Server only support:

The Multiprotocol Net-Library uses Remote Procedure Calls (RPC) and can work over TCP/IP, NWLink or NetBEUI (DEFAULT INSTANCE ONLY!)
SQL Server 2000 supports SSL encryption for all Net-Libraries, but SQL Server 7.0 only supports encryption using RPC so you have to use the Multiprotocol Net-Library if you want encryption in a mixed SQL Server 7.0 / SQL Server 2000 environment.
To enable encryption on the server side, click on the Network Configuration button in the server properties and select the check box entitled Force Protocol Encryption.
To enable encryption on the client side, go into the SQL Server Network Utility and check the Force protocol encryption option.

Creating SQL Server 2000 Databases

Database Performance

Consider:

Raid
Raid levels 0,1 or 5 are the commonest with SQL Server.
Raid 0 - disk striping
Raid 1 - disk mirroring
Raid 5 - striping with parity - improves performance AND provides fault tolerance. Needs at least 3 disks.
Indexes
SQL Server automatically creates indexes for PRIMARY KEY and UNIQUE constraints.
Inserts, updates and deletes take longer with indexes.
A clustered index will improve query performance - you can only have one on a table. Default sort order is ascending. By default, a clustered index is created on a Primary Key.
OLTP vs Decision Support
OLTP dbs should be highly normalized, with short transactions and on-line backup. Indexes should be used with care. Data should be archived regularly. I/O important so use filegroups and RAID. Decision Support dbs are often de-normalized, with summarized data columns to improve query response times. Indexes will be used heavily. Locking - use sp_lock for qualitative information about locking (which processes, which resources) and System Monitor for quantitative information about locking (no. locks per sec).
Pessimistic Concurrency is the default with SQL Server - resources are locked as they are required. Barring deadlocks, pessimistic concurrency assures successful transactions.
"Granularity" of locking - is a row locked? A page? An extent (8 pages)? The whole table? The whole database?! SQL Server automatically determines the granularity appropriate to the task.
SQL Server also determines what mode of locking to use - Shared (for a SELECT statement), Update(prevents deadlocking - only one transaction can get a U lock at a time, which can then be converted to an X lock), Exclusive (for an INSERT, UPDATE or DELETE), Intent, Schema (eg when adding a column or dropping a table) or Bulk Update (when Bulk copying using the TABLOCK hint or table lock on bulk load table option).
Although SQL Server handles locking automatically, you can customize it in your application:
The Lock Monitor Thread in SQL Server detects deadlocks. When a transaction submitted by an application is chosen as the deadlock victim, the transaction is terminated automatically and rolled back, and error message 1205 is returned to the application. All your applications should handle error 1205, for instance by resubmitting the query automatically, so the user is unaware that a deadlock as occurred.
To help minimize deadlocks: If a transaction is BLOCKED rather than deadlocked, it will never time out unless you set the LOCK_TIMEOUT setting. If this limit is exceeded, error message 1222 "Lock request time-out period exceeded" is returned to the application, but the transaction is NOT(!) rolled back or cancelled by SQL Server - so your application needs to handle the error carefully, for instance by resubmitting the particular statement that was blocked, or by rolling back the whole transaction.
To see what the current LOCK_TIMEOUT setting is:
DECLARE @Timeout int
SELECT @Timeout = @@lock_timeout
SELECT @Timeout
GO
A value of -1 means wait indefinitely.
SQL Server's default isolation level is READ COMMITTED.
To set and determine the isolation level:
USE pubs
GO
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
GO
DBCC USEROPTIONS
GO
The SELECT, INSERT, UPDATE and DELETE statements can include locking hints, but you shouldn't normally use these as the SQL Server Query Optimizer usually knows what to do.
Customizing locking for an index:
In cases where access patterns are well understood and consistent, limiting the locking levels available for an index can be beneficial. For example, a database application uses a lookup table that is refreshed weekly in a batch process. The most efficient locking strategy is to turn off page and row locking and allow all concurrent readers to get a shared (S) lock on the table, reducing overhead. During the weekly batch update, the update process can take an exclusive (X) lock, and then update the entire table.
To find out whether certain kinds of locking are disallowed on an index:
USE pubs
SELECT INDEXPROPERTY(OBJECT_ID('authors'), 'UPKCL_auidind', 'IsRowLockDisallowed')
To disallow page locking on an index:
USE Northwind
GO
EXEC sp_indexoption 'Customers.City', 'disallowpagelocks', TRUE

Database Capacity

Microsoft's tool for "scaling out" doing this is the federated server. With federated servers, you split a table horizontally across as many database servers as necessary. That is, one server contains the first hundred thousand rows of the table, the next contains the next hundred thousand, and so on. SQL Server 2000 sports updateable distributed partitioned views, which is a fancy way to say that a single view can treat this collection of federated tables as a single table. With federated servers, there's no practical limit to the amount of data you can store and update in a single table. Scaling out has the added bonus of being less expensive than scaling up for equivalent power.

Affinity Mask

You can use the affinity mask option to improve the performance of computers with more than 4 processors, that handle a lot of processes. This way, you can limit SQL Server to using the CPUs that are not being used heavily by the NICs (the highest numbered CPUs. Eg 00111111 (dec 63) makes SQL Server stick to the first 6 CPUs.

Attaching and Detaching Databases

To detach:
sp_detach_db @dbname='myDB', @skipchecks= 'true'
If you set skipchecks to true, then UPDATE STATISTICS is not run. This is useful if you're moving the database to read-only media. Only members of sysadmin can run this.
To attach:
sp_attach_db @dbname='myDB', @filename1='physical file name' filename2 etc.
Only members of sysadmin and dbcreator can run this.
If the db only has one data file and one transaction log file, you can attach it without the transaction log, as long as the db was closed cleanly, and SQL Server will create a new transaction log automatically when the data file is attached. Useful for emailing a db.
If you are detaching and attaching a db from a server configured for replication, you need to run sp_removedbreplication to remove replication. This can be done either before detaching or after attaching.

Files and Filegroups

Data and log information are never mixed on the same file, and individual files are used only by one database.

The locations of all the files are recorded in both the master database and the primary file for the database. Most of the time the database engine uses the file location information from the master database. For some operations, however, the database engine uses the file location information from the primary file to initialize the file location entries in the master database:
Files have a logical name and a physical name.
Files can be on FAT or NTFS but not compressed.
Pages within each file are numbered sequentially starting at 0.
You can specify a growth increment and a maximum size for each file. If there are muliple files in a filegroup, they won't autogrow until all the files are full.
Log files are never in a filegroup.
Each db has a PRIMARY filegroup containing the primary data file and any other files not assigned to a user filegroup.
You can specify one default filegroup (ALTER DATABASE mydb; MODIFY FILEGROUP myFG DEFAULT). Unless you do, the PRIMARY filegroup is the default. Changing the default filegroup prevents user objects that are not specifically created on a user-defined filegroup from competing with the system objects and tables for data space on PRIMARY.
Filegroups do not have to be specified, and if they aren't, SQL Server manages with just the PRIMARY filegroup. Filegroups are useful for spreading I/O across multiple drives. (Similar performance advantage as implementing one file on a RAID stripe set).
How to create a database with a primary data file, a user-defined filegroup, and a log file:
USE master
GO
-- Create the database with the default data
-- filegroup and the log file. Specify the
-- growth increment and the max size for the
-- primary data file.
CREATE DATABASE MyDB
ON PRIMARY
( NAME='MyDB_Primary',
FILE NAME=
'c:\Program Files\Microsoft SQL Server\MSSQL\data\MyDB_Prm.mdf',
SIZE=4,
MAXSIZE=10,
FILEGROWTH=1),
FILEGROUP MyDB_FG1
( NAME = 'MyDB_FG1_Dat1',
FILE NAME =
'c:\Program Files\Microsoft SQL Server\MSSQL\data\MyDB_FG1_1.ndf',
SIZE = 1MB,
MAXSIZE=10,
FILEGROWTH=1),
( NAME = 'MyDB_FG1_Dat2',
FILE NAME =
'c:\Program Files\Microsoft SQL Server\MSSQL\data\MyDB_FG1_2.ndf',
SIZE = 1MB,
MAXSIZE=10,
FILEGROWTH=1)
LOG ON
( NAME='MyDB_log',
FILE NAME =
'c:\Program Files\Microsoft SQL Server\MSSQL\data\MyDB.ldf',
SIZE=1,
MAXSIZE=10,
FILEGROWTH=1)
GO
ALTER DATABASE MyDB
MODIFY FILEGROUP MyDB_FG1 DEFAULT
GO
-- Create a table in the user-defined filegroup.
USE MyDB
CREATE TABLE MyTable
( cola int PRIMARY KEY,
colb char(8) )
ON MyDB_FG1
GO

Size and Place Transaction Log

Best write performance is obtained by putting the transaction log on a separate physical disk. But if you have to have the transaction log on a disk with either a data file or OS & SQL Server files, choose to have it with a data file as this will probably have less I/O than the O/S files etc.
To stop a transaction log from getting full (error 9002), back it up using the default options as this truncates the log after backing up. Or, set the db to use the Simple Recovery model - this truncates the transaction log after every checkpoint.
If best READ performance is the objective, and you only have two physical disks to play with, then it may be more beneficial to have two datafiles on separate disks, one of which contains the transaction log as well. But this will impact WRITE performance.

Constraints

CHECK constraints enforce data integrity when applied to one or multiple columns of a table.
E.g. to ensure that no date in the past is entered in the 'dateintable' column:
ALTER TABLE mytable ADD CONSTRAINT myconstraint (dateintable < GETDATE()).
Rules are similar to Check Constraints but are for backward compatibility only. While CHECK constraint are specified as part of the CREATE TABLE (or ALTER TABLE) statement, rules must be created as separate objects and then bound to the column.

Triggers

Triggers are a kind of stored procedure.
INSTEAD OF triggers run instead of the triggering action. They can be defined on the UPDATE, INSERT or DELETE of a table or view. These triggers are useful for updating base tables from a view.
AFTER triggers (this is the default) run after the triggering action has finished. They can be defined on the UPDATE, INSERT or DELETE of a table only.
FOR triggers are the same as AFTER triggers and are for backward compatibility only.

Stored Procedures

On first run, SQL Server compiles the Stored Procedure into an execution plan, stored on the server. This makes subsequent runs quicker and reduces network traffic.
If you make large changes to a db, like adding lots of data, adding or recreating indexes, or recalculating statistics, then an execution plan may become outdated and the stored procedures may run slowly. You should recompile them.

Table Size

Rows can never span pages. How many rows on a page? Divide the size of a page (8K) by the estimated size of an average row. Thence you can work out the needed size of the table - but remember that any indexes will require additional space.

Managing, Monitoring and Troubleshooting SQL Server 2000 Databases

Restoring

After restoring a full backup, you only need to restore the LATEST differential backup, not every single one since the full backup. You DO need to restore every single transaction log since the last differential backup, though.

Power Outages

When SQL Server writes data, the data first goes to the write cache on a disk controller and then to the disk. SQL Server considers data on the write cache to be written, but it will be lost if there is a power outage, making the db inconsistent. You can disable the write cache to prevent this, but this makes I/O slower. So, you could implement a battery-backed write cache.

Database Failure

When a db failure occurs, the first thing you should do, if possible, is back up the current transaction log. Use NO_TRUNCATE to prevent the inactive portion of the log from being truncated. With SQL Server 7.0, this was not possible if the Primary data file was lost, because the information about file locations was stored only in the primary data file. SQL Server 2000, though, stores file location information both in the primary data file and in the master db (the latter is where the information is mainly used).
If restoring master, you should start SQL Server in single-user mode (Sqlservr.exe -m)

DRA and Full-Text Catalogs

Full-Text searching is installed by default with Standard and Enterprise edition installations.
Full-Text involves two features: the ability to issue queries against character data, and the creation and maintenance of the underlying Full-Text Indexes facilitating these queries.
Unlike regular indexes, full-text indexes are stored in the file system. Only one full-text index is allowed per table, and the full-text indexes for the database are stored together in one or more full-text catalogs.
Full-text indexes are NOT backed up or restored with the database. You should back them up separately, for instance using NT Backup.
If you restore your database to a new machine, it knows about the full-text catalogs it used to have, but they are no longer there in the file system!
In Enterprise Manager, Full-Text Catalogs window, right-click on each (non-existent) catalog and select Rebuild All Catalogs. The catalogs will contain no data after you have done this - you need to perform a full population of each catalog before you will be able to use them.

Log Shipping

With log shipping, copies of a transaction log are fed from a source database to a destination database on a constant basis. This lets you keep the destination database as a warm standby, ready to replace the source database at any time. It also provides an easy way to separate OLAP analysis applications from OLTP data entry applications; let the data entry proceed at your primary server, then use log shipping to update a secondary server where you can run time-consuming analyses. The Database Maintenance Plan Wizard has been enhanced to include log shipping setup. A separate server within your organization can be designated as the Monitor Server to keep track of all log shipping operations.

DBCC

DataBase Console Commands that check the physical and logical consistency of a database, and often can fix any problems that are detected.
Important examples include:
DBCC SHOWCONTIG - displays information about fragmentation of the table's data and indexes. If table fragmentation is OK, then Scan Density will be high and Logical Scan Fragmentation will be low. If this is reversed, then you should rebuild the table's clustered index to improve performance.
DBCC DBREINDEX - Rebuilds the clustered index without having to drop the index first. This also means that any non-clustered indexes are rebuilt, because they use the clustered index keys as pointers to the data. This DBCC command has the same effect as using the CREATE INDEX statement with the DROP_EXISTING option.
DBCC SHRINKFILE (myfile, desiredsize) - Reclaim free space. This CAN be run while users are using the db. Also, you can enable the autoshrink option, but you don't know when SQL Server will run the shrink operation, and it may interfere with your backups.
DBCC CHECKDB (myDB, REPAIR_ALLOW_DATA_LOSS - to repair consistency and allocation errors with possible loss of data.
DBCC CHECKCATALOG - checks system tables. Does no repairs.
DBCC CHECKALLOC - corrects allocation errors only. Can be run against a db.
DBCC CHECKTABLE(myTable, REPAIR_ALLOW_DATA_LOSS) - as it's run against a table, can only fix consistency errors, not allocation errors. With REPAIR_REBUILD, rebuilds including rebuilding indexes etc, but no data loss.
DBCC DBREPAIR - This DROPS a db!! ONLY for backward compatibility so don't use it!
DBCC CHECKIDENT ('myTable', NORESEED | RESEED, [new reseed value] - Checks and if necessary corrects the current identity value for the table.
DBCC FREEPROCCACHE - clears the procedure cache. Freeing the procedure cache would cause, for example, an ad-hoc SQL statement to be recompiled rather than reused from the cache.

SQL Profiler

You can capture data about SQL Server and save to a trace (.trc) file. You can also save a template (.tdf) and run that trace any time.
A trace can only monitor one instance of SQL Server.
Multiple traces can be run simultaneously.
Important uses:

To troubleshoot deadlocks:
Create a trace that captures events relating to TSQL and Stored Procedure event classes (RPC:Starting and SQL:BatchStarting) and Locks event classes (Lock:Deadlock and Lock:Deadlock Chain). Include all data columns in the trace and group by Event Class. If you want to monitor only one database at a time, specify a value for the Database ID event criteria.
To view the connections involved in a deadlock, do one of the following:
You need 10MB of free space to run SQL Profiler.
You may have excessive deadlocking if your application is operating in implicit transactions mode, which starts a new transaction right away after finishing one - often unnecessarily. If this is the case, then change your application to use autocommit mode. This will reduce transaction times.

Extracting and Transforming Data with SQL Server 2000

Copying Databases

The easiest way to copy whole databases is to use the DTS Import/Export Wizard - it can copy all the db objects like constraints etc etc. You can specify a source and destination, or else specify a new destination db to be created. You can run the package, save it or save and schedule it.

SQL Server 2000, IIS Virtual Directories and XML

Users can access a db, perform queries and update data through a Web Browser.
To set up:

  1. Configure a Virtual Directory using IIS Virtual Directory Management for SQL Server.
  2. In the new Virtual Directory's properties, specify a path to the virtual directory to access the SQL Server db.
  3. Enable the Use Windows Integrated Authentication option on the Security sheet.
Users which have been granted the right to log in to SQL Server can then:
  1. Log locally on to their laptops
  2. Type the URL associated with the Virtual Directory into their web browser
  3. An Enter Network Password dialog box will appear, and the user will enter their user name, password and domain
Other options:
1. You could enable Use Basic Authentication (Clear Text) to SQL Server Account BUT passwords would be sent unencrypted, plus you would have to set up duplicate SQL Server logins for each user.
2. You could enable Anonymous access, but anyone would be able to use the db.
Note: You can only have ONE authentication scheme for a virtual directory.
SQL Server 2000 can also work directly with XML documents. The new system stored procedure sp_xml_preparedocument can read any well-formed XML document into memory and parse its contents. From there, the OPENXML keyword can be used in a SELECT statement to make any set of nodes from the document available as an updateable recordset.
If you Allow template queries on the virtual directory, rather than Allow URL queries, then users can only run the specific queries in the XML templates, instead of running any queries that they want to.

Bulk Insert

When you want to use a DTS package to import data and you want to do it quickly, you can create a Bulk Insert task. This is the fastest because it doesn't allow transforming of the data. You CAN specify columns, their order and column names. Format files are useful when the data file contains more or less columns than the destination table, or the columns are ordered differently.

Bulk Copy

Bulk copy operations can be fully logged or minimally logged.
bcp can be run against a table, view or query. When you run bcp to export data from a query, you must use the queryout parameter to specify the direction of data flow.
bcp CAN'T copy db objects like indexes or constraints.
If you issued a query in bcp that returned multiple result sets, only the first would be exported.
You could also run a SELECT INTO query, specifying a temporary table, and then run bcp against the resulting table. But it would need to be a global temporary table (##mytable), not a local temporary table(#mytable) because if you create a local temporary table in Query Analyzer, the table is only available to Query Analyzer and not to bcp.
The TABLOCK hint will make it load faster.
If you know there is no duplicate data, you can load multiple files simultaneously from multiple client computers. This is especially useful if your server has multiple processors.

Heterogeneous Data Sources

For those maintaining data in heterogeneous sources, the new OPENROWSET function in T-SQL will come as a distinct improvement over the old OPENQUERY. OPENROWSET allows you to specify OLE DB connection information directly in an ad-hoc query. On a practical level, this means that you can use a rowset from any OLE DB provider in place of a native SQL Server base table.
If you are running a DTS package using an OLE DB provider on a CLIENT computer, then the provider needs to be installed on that computer.

DTS Packages

DTS packages can be saved to:

Packages saved in SQL Server or Meta Data Services can be scheduled using the Schedule Package command or the DTS Run utility.
But for a structured storage file, you need to create a batch file that will execute the dtsrun comand. This batch file can then be scheduled using the Windows Task Scheduler.
If you need to save the package to a network drive, then use the structured storage file or vb file, as packages in SQL Server are saved to the sysdtspackages table in the msdb database. Passwords can't be specified for VB file or Meta Data Services packages.
Scheduling options:
  1. Start automatically when SQL Server Agent starts
  2. Start whenever the CPU(s) become idle
  3. One time
  4. Recurring
You can specify what is meant by the CPU being idle by selecting the properties of the SQL Server Agent in Enterprise Manager and clicking on the Advanced tab. Select The computer is idle when:, then enter a value between 10% and 100% in the Average CPU usage falls below box, and a value between 20 seconds and 86400 seconds in the And remains below this level for: box.
DTS packages and connections
To take the connection outside of the package, specify it as Microsoft Data Link and give a name of a .udl file. A developer who needs to customise the connection can then create his own .udl file and put it in the right place. If you want this to be possible, though, you need to enable Always read properties from UDL file in the connection properties - otherwise, the connection details will be cached in the package after the first execution.
DTS Packages and Alerts
If you want to be notified if a DTS package fails, you should configure it to write an event to the application log on completion, and configure an alert.
In the DTS properties, enable the Write completion status to event log option on the Logging tab. Then define an alert that will fire when a specific error is logged, define yourself as an operator, and specify what message should be sent.
Another method, more flexible but more work, is to include an Execute SQL task in the package that will execute when an error occurs. This would include RAISERROR WITH LOG.
Backup DTS packages
If a db backup is scheduled to run but a shrink operation is in progress, the backup cannot run. The dts package may time out and not run at all!
Misc uses of packages
You can easily export data to a text file with a package. You can include transformations to the data eg changing the format of the dates.

Converting Data Types

Using CAST:
CAST ( expression AS data_type )
Using CONVERT:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
SET DATEFORMAT is used only in the interpretation of character strings as they’re converted to dates. The display is NOT affected!
E.G.
SET DATEFORMAT mdy
GO
DECLARE @datevar datetime
SET @datevar = '12/31/98'
SELECT @datevar
GO

Returns:
1998-12-31 00:00:00.000
You can change the data type of a column quickly in Enterprise Manager. If it is a foreign key that you are changing, or a column referenced by foreign keys in other tables, then you will get the Data Type Change Required dialog. If you choose Yes, then the schema change will be populated to all the other related tables - this is true for length changes as well as data type changes.
Note: ON UPDATE CASCASE is only for update statements, NOT schema changes.

Replication

Assigning a domain user to the MSSQLServer service lets SQL Server communicate with other computers on the network. After you assign this, the domain user is automatically granted the Log on as a service right.
SQL Server 2000 replication lets you copy, distribute and modify data across your enterprise.
You can configure a single publication with vertical or horizontal partitions.
Snapshot Replication
Schema, data and db objects are sent to the Subscribers in a replication scheme. A snapshot image is put in a snapshot folder, by default created on the Distributor. You can reduce load on the Distributor by setting the snapshot folder to sit on a network share, and by configuring pull subscriptions rather than push subscriptions.
Merge Replication
Setting the @keep_partition_changes parameter using the sp_addmergepublication stored procedure can reduce the amount of time required by the Merge Agent to determine whether certain rows that were recently changed should be send to subscribers.
Transactional Replication
Where dbs have to be exactly the same all the time - e.g. where inventory levels must be consistent - use Transactional Replication and configure replication to occur continuously. Either push or pull can be used, and the changes will be applied to the subscribers in the same order that they occurred at the publisher.
If the changes can also come from the Subscribers, you need to have immediate-updating subscribers. The servers must be connected with a high-speed, reliable link. 2-phase commit ensures that changes at the subscribers will be applied immediately to the publisher.

Updating Foreign Keys

If you need to change the data in a Foreign Key column, then do an ALTER TABLE on the table you’re updating, and specify an ON UPDATE clause with the CASCADE option on the column you’re updating.

Managing and Monitoring SQL Server 2000 Security

Removing a User

USE myDB
EXEC sp_revokedbaccess User
EXEC sp_droplogin Login

SQLServer Agent and Security

If the SQLServerAgent service is assigned to a user account that is a member of the Administrators group on the SQL Server computer, then users who aren’t members of sysadmin will be able to create jobs that include CmdExec and ActiveScript steps!

Application Roles

Use an application role to accommodate complex security requirements or to enable users to only access data via an application and not directly.
Application roles have no members.
Application roles bypass all existing permissions for a connection.
The application must provide a password, by hard coding or in another way, for instance using an encrypted key in the registry.
To create:
EXEC sp_addapprole ‘approlename’, ‘password’
To change the password:
EXEC sp_approlepassword, ‘approlename’, ‘newpassword’
To use the application role from an application:
EXEC sp_setapprole ‘approlename’, ‘password’

Fixed DB Roles

db_accessadmin - can add & remove db user accounts but not fully manage the db.

Views

Data can be updated through a view if it only has one base table. If the WITH CHECK OPTION is specified in the definition of the view, then rows can’t be modified in a way that would cause them to disappear from the view.
If there are multiple base tables, you can use an INSTEAD OF trigger to update the base tables.

Permissions

When a user logs on to a database, what they can do is determined by the permissions of their log in an those of the roles (or groups) that their log ins belong to.
Object permissions allow the user to work with data and execute procedures.
Statement permissions allow the user to create a db or an object in a db.
GRANT ALL TO user_id gives the user permission to execute any statement.
GRANT CREATE DATABASE TO user_id does what it says!
Implied permissions are granted when a user is added to a role.
DROP TABLE is only allowed for members of the db_owners, sysadmin and ddl_admin fixed db roles, and can’t be explicitly granted to other users in the database.

Security Auditing

SQL Server auditing can be enabled or modified by members of sysadmin.
There are several categories of events that can be audited using SQL Profiler, such as:

It is possible to audit the following aspects of SQL Server through SQL Profiler:
Auditing can have a significant performance impact. If all audit counters are turned on for all objects, the performance impact could be high. It is necessary to evaluate how many events need to be audited compared to the resulting performance impact. Audit trail analysis can be costly, so it is recommended that audit activity be run on a server separate from the production server.
Note If SQL Server is started with the -f flag, auditing will not run.
The max size of the audit log is 200 MB. After this the file is closed and a new one started. If there’s no more disk space available for auditing, SQL Server stops.

Managing, Monitoring and Troubleshooting SQL Server 2000

Torn Pages

A torn page is when an I/O fails to complete successfully. For this to be detected by the recovery process, Torn Page Detection db option must be on. If torn pages are found, the db is marked as suspect and you will need to restore it from a backup.
If you didn’t have Torn Page Detection on, you could run DBCC CHECKDB PHYSICAL_ONLY to check physical consistency.
You can turn off the suspect flag using sp_resetstatus but this doesn’t repair anything!

Alerts and operators in SQL Server Agent

SQL Server events are written to the Windows application log.
SQL Server agent monitors the application log for SQL Server events, and looks for ones that you’ve defined to:

If the windows application log gets full and is not configured to overwrite itself, no more SQL Server alerts will fire.
You can set SQL Server to forward all event messages (or filtered by severity) to another SQL Server. Do this in the Management folder in Enterprise Manager, by selecting the Advanced Tab on the SQL Server Agent properties.

System Monitor - Important things to track

Queries

If you disable the query govenor cost limit option, then SQL Server will let any query execute, no matter how long it will take.

Jobs

Multi-server jobs - if you manage multiple instances of SQL Server on different computers. First, configure a master server and one or more target servers. The target servers connect to the master server at regular intervals, download the jobs, disconnect, execute the jobs then send the execution results back to the master.
If you use Enterprise Manager to create and maintain the multi-server jobs, then you don’t need to notify the targets of any changes.
If you use the sp_update_jobstep stored procedure, then you need to run sp_post_msx_operation stored procedure in the msdb database. This updates the sysdownloadlist system table, which contains job information for the target servers. They will then download the full job definition again
. sp_msx_enlist enlists a new target server.
sp_msx_defect defects the current server so it’s no longer a target server.

Cassie Simons (MCSE, MCSD, MCDBA) is the author of
"How to Pass Your MCSE/MCSD Quickly and Easily".
Visit www.ExamsAreEasy.com today and subscribe to a unique
free "Bootcamp" ezine giving you important
tips and secrets to help you to certification success!