You are on page 1of 40

SQL Detach Database

Let us see the steps involved to detach the database in SQL. To demonstration this
database detach, we are going to use the existing stored procedure
and Management Studio.

SQL Detach Database Approach 1


From the below screenshot, you can see that the SQL server have the
AdventureWorks2017 database

SQL Server has a sp_detach_db stored procedure to detach the database. The


syntax for detach Database is
EXEC sp_detach_db N'Database Name', 'true';

Let me use the above syntax to detach AdventureWorks 2017 database.

EXEC sp_detach_db N'AdventureWorks2017', 'true';

Query executed.

Messages

-------

Commands completed successfully.

Now you can see the Adventure Works 2017 database removed from our Server
Detach Database Approach 2
You can also use Management Studio to detach the database in SQL Server. To do
so, Right-click on the Databases folder and select the Tasks option and then
select Detach.. from the context menu.
Clicking the Detach.. option will open the following window.

 Database Name: This will display the Name of the database that you want to
detach.
 Drop Connections: Checkmark this option to drop all the existing connections
pointing to this database
 Update Statistics: Checkmark this option to update existing optimization
statistics.
Checkmark the Drop Connections, and Click Ok
The Adventure Works DW 2017 database removed from the Server
The above process will only detach the database from Server, but it will keep the
MDF, and LDF files within the physical location (C Drive).
SQL Restore Database
In this section, we will explain to you the step by step approach for SQL restore
database procedure using the BAK file. For this Restore Database in SQL Server
demonstration, we use the adventure works 2017 .bak file.

SQL Restore Database using BAK File


In this example, we will use the BAK file to Restore the Database. The SQL server
does not have the AdventureWorks2017 database

As you can see, the MDF, and LDF file corresponding to the Adventure Works 2017 is not
there in C Drive
We have an Adventure Works Backup file in our D Drive, and we are going to use this bak
file to restore a database in SQL Server.

Syntax of the restore Database from the backup file


RESTORE DATABASE DatbaseName

FROM DISK = 'D:\Backups\BackupFileName.bak'

WITH MOVE 'LogicalMDFFileName' TO


'location\MDFFileName.mdf',

MOVE 'LogicalLDFFileName' TO 'location\LDFFileName.ldf'

Let me use the above syntax to restore the Adventure Works database.

RESTORE DATABASE AdventureWorks2017

FROM DISK = 'D:\Backups\AdventureWorks2017.bak'

WITH MOVE 'AdventureWorks2017' TO 'C:\Program


Files\Microsoft SQL
Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorks2017.mdf',

MOVE 'AdventureWorks2017_log' TO 'C:\Program


Files\Microsoft SQL
Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorks2017_log.l
df'

The query is executed, and the database is restored successfully.

Now you can see the Adventure Works 2017 database


The above process has automatically added the MDF, and LDF files to the C Drive
If you don’t know the logical file names, then use the Restore File System to retrieve
the Logical Filenames from the database backup.

RESTORE FILELISTONLY

FROM DISK = 'D:\Backups\AdventureWorks2017.bak'


How to Create Database in SQL Server
A database in Sql Server is a storage location where we can store our business
data. The SQL database uses tables to store our information in a normalizes way.
So by creating database in Sql Server, We can easily Select, Update and Delete the
business data.

Let us see how to Create Database in SQL Server, Rename Database in SQL, and
Delete Database in Sql Server with an example of each.

How to Create Database in SQL Server example


Before we start create new database in SQL Server, Let us see the list of available
databases. The list of available databases in Sql Server current instance are.
The syntax for SQL create Database is:

CREATE DATABASE Database_Name

In this example, we create a new database in Sql Server called New_Database. So,
Replace the Database_Name with New_database in SQL Server query window.
-- Code for SQL Create Database

CREATE DATABASE New_Database;

Click on the Execute button to execute the create database command.

The SQL Create Databse Command is executed successfully and you can see the
New_Database in our object explorer. If you didn’t find the newly created database in
Sql Server Object explorer, Please click on the refresh button

Let us see, what will happen, When we execute the same SQL Create Database command
again. It is throwing an error saying: New_database already exists. Choose a different
database name.
How to Check whether SQL Database name exists or
not
In an organization, we may or may not have the privileges to know the available
databases in SQL Server. So, it is always advisable to check whether the database
name already exists or not. This can be done in two ways:

The following statement will only execute SQL Create Database Statement if the
New_database in not available in the system database

-- SQL Create Database Example

IF NOT EXISTS

SELECT name FROM master.dbo.sysdatabases

WHERE name = N'New_Database'

CREATE DATABASE [New_Database]

We just replaced the If Not Exists with If Exists and added select statement to


display the message. Steps involved in the Following statement are:

 If the New_database already exists then the following query will display a message
saying database already exists
 SQL Create database command only execute, if the New_database in not available
in a system database

-- Code to Sql Server Create Database

IF EXISTS

SELECT name FROM master.dbo.sysdatabases


WHERE name = N'New_Database'

BEGIN

SELECT 'Database Name already Exist' AS Message

END

ELSE

BEGIN

CREATE DATABASE [New_Database]

SELECT 'New Database is Created'

END

It will check for the database name New_database in the system database.

SELECT name FROM master.dbo.sysdatabases

WHERE name = N'New_Database'

If the database does not exist, then only following create Databse statement will be
executed

CREATE DATABASE [New_Database]

Otherwise, below command is executed. It’s going to display a message saying that
the database already exists

SELECT 'Database Name already Exist' AS Message


How to Create Database in SQL Server
Management Studio
In order to create new database in SQL server, first, open the SQL Server
Management Studio. Right click on the Databases folder and select New database..
option from the context menu
Once you select New database.. option, following window will be opened. Here we left
Owner as default and database name as New_database as shown below. Click OK to create
new database in Sql Server
Let us see what will happen When we SQL create database with an existing name. As you
can observe that it is throwing an error
How to Delete Database in SQL Server
To Delete database in SQL server, we can simply use the following syntax

The syntax for SQL Delete database or Drop Database in SQL server is:

DROP DATABASE [Database Name]

In this example we are going to delete New_Database. So, within the query window,
Please write the following SQL Drop Database query
DROP DATABASE [New_Database]

Let us see, What will happen when we execute the same SQL Drop Database  
command once again:

From the above screenshot, you can observe that it is throwing an error saying:
New_database doesn’t exist.

The better approach is to check whether the SQL database name exists or not.
Because sometimes, your colleges or your team leader may delete the database
which you are trying to delete.

IF EXISTS

SELECT name FROM master.dbo.sysdatabases

WHERE name = N'New_Database'

DROP DATABASE [New_Database]

Output

Messages

-------
Command(s) completed successfully.

The following statement will check for the database name New_database in the
system database.

SELECT name FROM master.dbo.sysdatabases

WHERE name = N'New_Database'

If the database exists, then only following SQL drop database statement will be
executed

DROP DATABASE [New_Database]

How to Rename Database in SQL Server


To rename database in SQL server, we can simply use the system stored procedure
sp_renamedb

The syntax to rename database in Sql Server is:

SP_RENAMEDB [Old Database Name],[New Database Name]

In this example we rename New_Database with New_Db. So, within the query
window, Please write the following query

SP_RENAMEDB [New_Database],[New_Db]

Output

Messages
-------

The database name 'New_Db' has been set.


SQL Server Rename Database along with Files
This section shows you how to Rename Database in Sql Server along with Files
(MDF, and LDF). For this SQL Server Rename Database demonstration, we created
a database OldNameDB.

Below SQL Server query will show you the Logical File names, and the Physical
location of the database

USE master
GO

SELECT name, physical_name, type_desc, state_desc, size

FROM sys.master_files

WHERE database_id = DB_ID(N'NewNameDB')

GO

SQL Server Rename Database


Generally, we use a sp_renamedb stored procedure to rename the Database.
However, this will only change the name that appears over here.

EXEC sp_renamedb 'NewNameDB', 'OldNameDB'

Output

Messages

--------

The database name 'NewNameDB' has been set.


You can see the new name under the SQL Server Object Explorer

Let me execute the below database query

USE master
GO

SELECT name, physical_name, type_desc, state_desc, size

FROM sys.master_files

WHERE database_id = DB_ID(N'NewNameDB')

GO

You can see from the Output sp_renamedb hasn’t changed the Logical database
Name or the Files that represent the Database.

Let me rename Database to OldNameDB, and perform the following operations in a


specified manner.

Rename Database along with Files


In SQL Server Rename database along with files involves in modifying the MDF and
LDF file names. It will modify the Logical names of the Database.

-- Set the database to Single User

ALTER DATABASE OldNameDB


SET SINGLE_USER WITH ROLLBACK IMMEDIATE

ALTER DATABASE OldNameDB

MODIFY FILE (NAME = N'OldNameDB', NEWNAME = N'NewNameDB')

GO

ALTER DATABASE OldNameDB

MODIFY FILE (NAME = N'OldNameDB_log', NEWNAME =


N'NewNameDB_log')

GO

It will detach the OldNameDB Database. After detaching the database, you can
modify the File names in the physical location

USE master
GO

EXEC sp_detach_db @dbname = N'OldNameDB'

GO

Output

Messages

--------

Commands completed successfully.

Navigate yourself to the location of the database

we renamed the MDF, and LDF names


it will create a new Database in SQL Server called NewNameDB using the File names that
we changed before

-- SQL Server Rename Database along with Files Example

USE master

GO

CREATE DATABASE NewNameDB ON

(FILENAME = N'C:\Program Files\Microsoft SQL


Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\NewNameDB.mdf'),

(FILENAME = N'C:\Program Files\Microsoft SQL


Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\NewNameDB_log.ldf')

FOR ATTACH
GO

Output

Messages

--------

Commands completed successfully.

Now you can see the database with a new name


Let me see the Logical File name and the files

USE master

GO
SELECT name, physical_name, type_desc, state_desc, size

FROM sys.master_files

WHERE database_id = DB_ID(N'NewNameDB')

GO

I think, I forgot to set the database to Multi-user

ALTER DATABASE NewNameDB SET MULTI_USER

GO

Output

Messages

--------

Commands completed successfully.


Get Database Names from SQL Server
In this article, we will show how to write a SQL Query to Get Database Names from
SQL Server with an example. The list of databases in SQL Server that are available
in our current instance.

Get Database Names Example 1


Here, we will show you how to Get database names in Sql Server

-- Query to get SQL Server Database Names

USE master
GO

SELECT name FROM sys.databases

You can also use sysdatabases to get the list of databases in SQL Server.

-- Query to get SQL Server Database Names

USE master

GO

SELECT name FROM sysdatabases


Or, use sp_databases stored procedure to get a list of databases in Sql Server.

-- Query to get SQL Server Database Names

USE master

GO

EXEC sp_databases
Get Database Names Example 2
In this example, we will restrict the result. I mean, we will get Database names in a
Server without system databases. If you know the database id, use the following
query to display the list of databases except for system databases

-- Query to get SQL Server Database Names

USE master

GO

SELECT database_id, name FROM sys.databases

WHERE database_id > 4


Or, try NOT IN operator

-- Query to get SQL Database Names

USE master

GO

SELECT database_id, name FROM sys.databases

WHERE name NOT IN ('master', 'model', 'msdb', 'tempdb')

You might also like