Manipulating Databases

Other core administration tasks include renaming, dropping, detaching, copying, and moving databases. These tasks are examined in this section.

Renaming a Database

You can rename user databases in SQL Server Management Studio and with the ALTER DATABASE MODIFY NAME statement. With the database in single-user or offline mode, right-click the database name in SQL Server Management Studio and select Rename from the shortcut menu. Then type the database name and press Tab.

To use T-SQL to put the database in single-user mode and change the name, complete the following steps:

  1. Ask all users to disconnect from the database. Make sure that all SQL Server Management Studio connections to the database are closed. If necessary, kill the user processes, as explained in Chapter 5.

  2. Access the Query view in SQL Server Management Studio, and then put the database in single-user mode. The following example puts a database called Customer in single-user mode:

    use master
    
    ALTER DATABASE Customer
    
    SET single_user
    
    GO

    Tip

    Tip

    You execute commands in the Query view by clicking Execute Query or by pressing F5. With SQLCMD, you can execute commands by entering the GO statement.

  3. Rename the database using the ALTER DATABASE statement. In the following example, the Customer database is renamed cust:

    ALTER DATABASE Customer
    
    MODIFY NAME = cust
    
    GO
  4. After you run the SQL commands, set the renamed database back to multiuser mode. The following example sets the cust database to multiuser mode:

    ALTER DATABASE cust
    
    SET multi_user
    
    GO
  5. Be sure that all commands, applications, and processes that use the old database name are pointed to the new database name. If you do not do this, you will have problems using the database.

Dropping and Deleting a Database

In SQL Server 2005, dropping and deleting a database are the same thing. When you drop a database, you remove the database and its associated files from the server. After you drop a database, it is permanently deleted, and you cannot restore it without using a backup. To delete references to a database without removing the database files, use sp_detach_db, as described later in this section.

You cannot drop system databases, and you cannot drop databases that are currently in use by SQL Server or other users. A database can be dropped regardless of its state. However, any replication or database snapshots on a database must be stopped or dropped before the database can be deleted. Furthermore, if the database is configured for log shipping, you should remove log shipping before dropping the database. Also note that a dropped database can be re-created only by restoring a backup. After you drop a database, you should back up the master database.

You can drop a database by completing the following steps:

  1. In SQL Server Management Studio, right-click the database you want to drop, and then select Delete from the shortcut menu to display the Delete Object dialog box.

  2. To delete backup and history information from the msdb database, select Delete Backup And Restore History Information For Databases.

  3. To close existing connections to the database before deleting it, select Close Existing Connections.

    Note

    Note

    You cannot drop a database that is being used by SQL Server or by other users. For example, if you are restoring the database or the database is published for replication, you cannot delete it. You also cannot delete the database if there are any active user sessions.

  4. Click OK. Optionally, back up the master database as explained in Chapter 14. You back up the master database to ensure that the most current system information is stored and that information for the old database will not be restored accidentally with the master database.

You can also delete a database with the DROP DATABASE command. The syntax and usage for this command are shown in Example 7-4.

Example 7-4. DROP DATABASE Syntax and Usage

Syntax

DROP DATABASE { database_name | database_snapshot_name} [,..n]

Usage

use master
ALTER DATABASE Customer
SET single_user
GO
DROP DATABASE "Customer"
GO

Attaching and Detaching Databases

The attach and detach operations are designed primarily to move database files or disable databases without deleting their files. When you detach a database, you remove references to the server in the master database, but you do not delete the related database files. Detached databases are not displayed in SQL Server Management Studio, and they are not accessible to users. If you want to use the database again, you can reattach it. Attaching a database creates a new database that references data stored in existing data and log files.

Before you can detach a database, you must ensure that none of the following conditions are true:

  • A database snapshot exists on the database. You must drop all of the database’s snapshots before you can detach it. Snapshots can be deleted, but they cannot be detached or attached.

  • The database is being mirrored. You must stop database mirroring and end the mirror session.

  • The database is replicated and published. If it is replicated, the database must be unpublished. Before you can detach it, you need to disable publishing by running sp_replicationdboption or sp_removedbreplication.

  • The database is suspect. You must put the database into EMERGENCY mode and then detach it.

Usually, attaching a database places it in the same state that it was in when it was detached. However, SQL Server 2005 disables cross-database ownership chaining and sets the TRUSTWORTHY option to OFF when a database is attached. You can re-enable these features if necessary as discussed in the section titled "Managing Cross-Database Chaining and External Access Options" earlier in this chapter.

When you attach a database, all primary and secondary data files must be available. If any data file has a different path than it had when the database was first created or last attached, you must specify the file’s current path.

Detaching a Database

When you detach a database, you can specify if you want to update the statistics before the database is detached. Updating statistics makes the database easier to use with read-only media; otherwise, you really do not need the update. To update statistics, set the skipchecks flag to TRUE.

Because full-text catalogs are associated with databases in SQL Server 2005, you can also control whether they are maintained or dropped during the detach operation. By default, full-text catalogs are maintained as part of the database. To drop catalogs, set the keepfulltextindexfile flag to FALSE.

You detach a database using sp_detach_db, as shown in Example 7-5.

Example 7-5. sp_detach_db Syntax and Usage

Syntax

sp_detach_db [ @dbname= ] "dbname"
    [ , [ @skipchecks= ] "skipchecks" ]
    [ , [ @KeepFulltextIndexFile= ] "KeepFulltextIndexFile" ]

Usage

exec sp_detach_db "sample", "true"

Tip

Tip

You cannot detach system databases, and you can only detach user databases when they are not in use. Furthermore, before detaching a user database, you may want to close all current connections, put the database in single-user mode, and then run the detach operation.

Attaching a Database with Multiple Files

When you reattach a database, use the CREATE DATABASE statement with FOR ATTACH. For this statement to work, all primary and secondary data files must be available. If the database has multiple log files, all the log files must be available. The only exception is for a read-write database with a single log file that is currently unavailable. If the database was shut down with no users or open transactions before it was detached, FOR ATTACH automatically rebuilds the log file and updates the primary data file as appropriate. The log file for a read-only database cannot be rebuilt because the primary data file cannot be updated; you must provide the log files or files in the FOR ATTACH clause.

Any full-text catalogs that are part of the database being attached will be attached with the database. To specify a new path to the full-text catalog, you can specify the catalog file by supplying a directory name without a file name.

When you use the CREATE DATABASE statement with FOR ATTACH, you can specify only the primary file name. This file contains pointers to the original locations of all other database files. If the other files have not changed location, you can specify only the primary file name, and then let the database engine use the primary file to find the rest of the files.

Example 7-6 shows the code required to attach the database using the CREATE DATABASE statement with FOR ATTACH.

Example 7-6. The CREATE DATABASE Statement with FOR ATTACH Syntax and Usage

Syntax

CREATE DATABASE database_name
    ON <filespec> [ ,...n ]
    FOR { ATTACH [ WITH <service_broker_option> ]
        | ATTACH_REBUILD_LOG }
[;]


<filespec> ::=
{
[ PRIMARY ]
(
    [ NAME = logical_file_name , ]
    FILENAME = "os_file_name"
        [ , SIZE = size [ KB | MB | GB | TB ] ]
        [ , MAXSIZE = { max_size [ KB | MB | GB | TB ] | UNLIMITED } ]
        [ , FILEGROWTH = growth_increment  [ KB | MB | % ] ]
) [ ,...n ]
}

Usage

CREATE DATABASE Customer
ON (FILENAME = "c:datacustomer_data.mdf")
FOR ATTACH
GO

Attaching a Database with Only Data Files

You may not need old transaction logs in a new database. If this is the case, you may want only to restore data files and let SQL Server create new log files for you. To do this, use the CREATE DATABASE statement with FOR ATTACH_REBUILD_LOG, as shown in Example 7-7.

Example 7-7. The CREATE DATABASE Statement with FOR ATTACH_REBUILD_LOG Syntax and Usage

Syntax

CREATE DATABASE database_name
    ON <filespec> [ ,...n ]
    FOR ATTACH_REBUILD_LOG }
[;]

<filespec> ::=
{
[ PRIMARY ]
(
    [ NAME = logical_file_name , ]
    FILENAME = "os_file_name"
        [ , SIZE = size [ KB | MB | GB | TB ] ]
       [ , MAXSIZE = { max_size [ KB | MB | GB | TB ] | UNLIMITED } ]
        [ , FILEGROWTH = growth_increment [ KB | MB | % ] ]
) [ ,...n ]
}

Usage

CREATE DATABASE Customer
ON (FILENAME = "c:datacustomer_data.mdf")
FOR ATTACH_REBUILD_LOG
GO
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset