How to add a database in SQL Server Management Studio? - sql

I have been sent a database called StudentsDB.mdf and I want to enter it into my SQL Server Management Studio databases . How to do that ?
I want to know if I copy a .mdf file from the directory where are all my databases which is C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA
and sent it to another person will he be able to import this database in his SQL Server Management Studio and see the database?

Try this one
Step 1
Right-click “Databases” and click the “Attach” option to open the Attach Databases dialog box.
Step 2
Click the “Add” button to open the Locate Database Files dialog box.
Step 3
Type in the full name of the .MDF file, including the full device and directory path, as the following example illustrates:
c:\StudentsDB.mdf
Click the "OK" button. SQL Server Management Studio loads the database from the .MDF file.
OR
Step 1
Click “New Query” in the Management Studio’s main toolbar.
Step 2
Type a Create Database statement using the following Transact-SQL code:
CREATE DATABASE MyDatabase ON
(FILENAME = 'c:\StudentsDB.mdf'),
(FILENAME = ' c:\StudentsDB.ldf') FOR ATTACH;
Step 3
Click the “Execute” button in the Transact-SQL toolbar. SQL Server Management Studio restores the database.
OR
CREATE DATABASE StudentDB ON
(FILENAME = N'C:\StudentsDB.mdf')
FOR ATTACH_REBUILD_LOG
GO

Execute the following command from SSMS.
USE master;
GO
EXEC sp_attach_single_file_db #dbname = N'StudentsDB'
,#physname = N'D:\<path to mdf file>\StudentsDB.mdf'
GO
Now if you refresh the database list in SSMS it should show a database StudentsDB in the list.

I want to know if I copy a *.mdf file ... and [send] it to another person, will he be able to import this database?
You can do this, but there are a few considerations. The first is that you need to take the database offline, or use another command to ensure there are no pending transactions waiting to be written or locks or latches waiting to be closed.
The second consideration is that, once the database is imported, you may need to recreate (by hand or by script) a few items that aren't stored within the mdf file itself. This includes users and permissions, links to other databases, and other services that are provided by at the Server level rather than the Database level.

Related

How to create a copy of database tables into another computer

I am using Microsoft SQL Server 2012. I have some table in the test database. How to create a copy of the tables into another computer ?
Here is what I did to make a copy of all the tables along with the data present in my database of "computer A" into the database of "computer B".
Microsoft SQL Server Management Studio > Connect.
Right Click on The database which has the tables > Tasks > Generate Scripts.
Select either full database Specific table > Next
Advanced > Scroll down to "Types of Data to Script" and select "Schema and Data". > OK
Select location to save Script
Next > Next > Finish.
Now copy This Script File into "computer B"
Double click will open it into Microsoft SQL Server Management Studio
Click "Execute" button from top toolbar.
Done, Just Refresh the database and all your tables with the data are now copied.
For some objects, Do tasks, copy database objects, in ssms
If you want to copy whole database,
Do backup database, then do restore on target machine
You can copy the relevant .mdf files from SQL server Installation folder(C:\Program Files \Microsoft SQL Server\MSSQL.10\MSSQL\Data) to other
computer's SQL server Installation folder
Then you can attach those mdf files using SQL Server Management Studio
1) In object explorer, right click on "Databases" and click on attach
2) Click on "Add button"
3) Then select copied mdf files from the SQL server Installation folder
4) Then click OK

Backup/Restore from different database causing Restore failed exclusive access could not be obtained

I have a database A. I have taken a backup of database A called A.bak. I created a new database B. Now, I right click and Restore B from A.bak. In the Restore Dialog, I checked overwrite existing database and change the LogicalFileName from C:\Program Files\Microsoft SQL Server\MSSQL11.SQLSERVER2012\MSSQL\DATA\A.mdf to C:\Program Files\Microsoft SQL Server\MSSQL11.SQLSERVER2012\MSSQL\DATA\B.mdf and did the same with ldf file. But I am getting
Exclusive access could not be obtained because the database is in use.
Also tried,
ALTER DATABASE [B] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
Also sp_who2, there was no existing connection of [B]
A cause for the attempt to get exclusive access comes from the options page of the restore dialog in SQL Server 2012 Management Studio. It will turn on tail-log and leave in restoring state options for the SOURCE database. So, it will try to gain exclusive access to the source database (in this case A) in order to perform this action. If you turn off the tail log option, you will find that the operation works much more smoothly.
The answer was very simple,
Run this command to grab the LogicalNames,
RESTORE FILELISTONLY FROM DISK = 'C:\Users\MyUSer\Desktop\A.bak'
Then Just put the in LogicalName in below,
RESTORE DATABASE B
FROM DISK = 'C:\Users\MyUSer\Desktop\A.bak'
WITH
MOVE 'LogicalName' TO 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLSERVER2012\MSSQL\Data\B.mdf',
MOVE 'LogicalName_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLSERVER2012\MSSQL\Data\B.ldf'
GO
Note you might need to change the path. Helpful links,
How to restore to a different database in sql server?
http://technet.microsoft.com/en-us/library/ms186390.aspx
B. ’Restore Database’ Dialog will be displayed on the General page
1. The name of the restoring database appears in the To database list box. To create a new database, enter its name in the list box.
Select ‘From device’
Click button to display ‘Specify Backup’ Dialog
Click ‘Add’ to browse the .bak file from the directory and click OK

How to copy SQL Server 2008 R2 database from one machine to another

I have a database in SQL Server 2008 R2, and I want to copy this database onto another machine.
How do I make a copy?
And how do I restore it?
Thanks
You can't copy Database to another machine.
Yes you can take back up to same machine and copy it to another machine and do restore.
To take backup follow procedure:
Right Click on the database you want to take backup.
Choose Task -> Back Up.
In Destination, Choose Add.
In File Name click on ... button and choose destination folder where you want to backup with backupname.bak . Click Ok, Ok and Ok. and wait until backup process is completed. Click Ok.
Now copy that backup file into pendrive or any media and paste it to another machine and Open SQL Server 2008 R2
To restore backup follow procedure:
Right Click on the Databases.
Choose Restore Database.
Write database name which you want to restore in To Database field
Select From device radio button in Source for restore. Click on ...
Click on Add button, Select database backup file you have pasted. Click Ok, Ok.
Check the checkbox of Restore in Select the beckup sets to restore.
Go on Options Check Overwrite the existing database & Preserve the replication settings (this fields needed to check only when you try to restore database which is already resided on that another device)
Click Ok. wait until restore complete and click ok.
Tell me if you face any problem.
By Code
To Backup:
USE DATABASE_NAME;
GO
BACKUP DATABASE DATABASE_NAME
TO DISK = 'D:\DATABASE_NAME.Bak'
WITH FORMAT, MEDIANAME = 'D_SQLServerBackups',
NAME = 'Full Backup of DATABASE_NAME';
GO
(If you want to put backup in any folder, the folder must be exist before you take the backup.)
To Restore:
Step 1: Retrive the Logical file name of the database from backup.
RESTORE FILELISTONLY
FROM DISK = 'D:BackUpYourBaackUpFile.bak'
GO
Step 2: Use the values in the LogicalName Column in following Step.
----Make Database to single user Mode
ALTER DATABASE YourDB
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
----Restore Database
RESTORE DATABASE YourDB
FROM DISK = 'D:BackUpYourBaackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:DataYourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'D:DataYourLDFFile.ldf'
/If there is no error in statement before database will be in multiuser
mode.
If error occurs please execute following command it will convert
database in multi user./
ALTER DATABASE YourDB SET MULTI_USER
GO
There are probably more ways to do this but I usually right-click the database and choose "Tasks → Back up..." with Backup type "Full". After that you can copy the created file to your target machine, connect to its SQL Server in SQL Server Management Studio, right-click the "Databases" folder and choose "Restore Database". Select "Device" and choose the file, then restore.
Another approach would be to script the database in SQL Server Management Studio (right-click the database, then "Tasks → Generate scripts..."). During this process there'll be a step called "Set Scripting Options", where you'll have to click the "Advanced" button and carefully go through the options. You'll definitely want to choose "Data and schema" for the option "Types of data to script". I sometimes prefer this method if I really just want the data structures and the data itself to be transferred.
Update: Sorry, I forgot to mention how to restore the database for the scripting option. I always generate the scripts by selecting "Save to new query window" during the "Set Scripting Options" step. After the script is generated, just leave it there for a moment.
On the target server create a new database with the same name as the one you generated the scripts for. Or you can create a script for that on the source server, too (right-click the database, choose "Script Database as → CREATE TO... → Clipboard") and execute this script by right-clicking the server node in the SSMS Object Explorer, selecting "New query", pasting the script into the query window and executing it. This second option is the better choice if you really need a complete copy of the database and not just the data itself.
Once you've gone down one of these two roads you should have created a new database. Right-click this database in Object Explorer and select "New Query", then copy and paste the script containing the database structure and data into the new query window and execute the query. This should do the trick.
Copying a database using a full database backup will not copy the transactions in the online transaction log.
If this is important, use the following steps to take the database offline, copy the MDF and LDF files, and attach them:
Select the database in SQL Server Management Studio , right-click the database and select Properties. Copy the location of the MDF and LDF files
2.Click OK
3.Right-click the database again, select Tasks, Take offline
4.In Windows Explorer, copy the MDF and LDF files using the location found in step #1
5.Paste them to another location
6.In SQL Server Management Studio right-click the SQL Server instance and select Attach
7.In the next dialog, click Add, find the copied files, select them and click OK
8.Change the default name offered in the Attach AS field. Specify the new name you want for your database here.
9.Click OK
To bring back online the original database, right-click it and select Tasks, Bring online
if you are copying it to a SQL 2008 R2 then all u have to do is
open SQL server management studio
choose your database
right click, go to Tasks --> BackUp
in the database backup window, click add and then give your backup path and file name
click ok
copy the backup file to any drive in the machine to which you want to restore then,
Open SQL server management studio
create a new database
right click on the newly created database, go to Tasks --> Restore --> Database
on the restore window select from device option
add the backup file path
click ok
In addition for copy or move database to another server in same network level you can use SQL Server Copy Database Wizard
for use this method you should
Right click on database
Select task and
Select copy database
Fill source database server login data
Fill destination database server login data
Select transfer method
Select databases to transfer(except system databases)
Extra description about this method
Justin's answer above was almost correct, it is simply right click on database in SSMS and select "Tasks" > "Export Data". This wizard allows you to duplicate the entire database to another location.

Creating new database from a backup of another Database on the same server?

I am trying to create a new database from an old backup of database on the same server.
When using SQL server management studio and trying to restore to the new DB from the backup I get this error
System.Data.SqlClient.SqlError: The backup set holds a backup of a database
other than the existing 'test' database. (Microsoft.SqlServer.Smo)
after googling around I found this piece of code
RESTORE DATABASE myDB
FROM DISK = 'C:\myDB.bak'
WITH MOVE 'myDB_Data' TO 'C:\DATA\myDB.mdf',
MOVE 'myDB_Log' TO 'C:\DATA\myDB_log.mdf'
GO
I was wondering will the move statements mess with the database that the backup came from on that server?
Thanks, all help appreciated.
What I should to do:
Click on 'Restore Database ...' float menu that appears right clicking the "Databases" node on SQL Server Management Studio.
Fill wizard with the database to restore and the new name.
Important If database still exists change the "Restore As" file names in the "Files" tab to avoid "files already in use, cannot overwrite" error message.
What I do
IDk why I prefer to do this:
I create a blank target database with my favorite params.
Then, in "SQL Server Management Studio" restore wizard, I look for the option to overwrite target database. It is in the 'Options' tab and is called 'Overwrite the existing database (WITH REPLACE)'. Check it.
Remember to select target files in 'Files' page.
You can change 'tabs' at left side of the wizard (General, Files, Options)
It's even possible to restore without creating a blank database at all.
In Sql Server Management Studio, right click on Databases and select Restore Database...
In the Restore Database dialog, select the Source Database or Device as normal.
Once the source database is selected, SSMS will populate the destination database name based on the original name of the database.
It's then possible to change the name of the database and enter a new destination database name.
With this approach, you don't even need to go to the Options tab and click the "Overwrite the existing database" option.
Also, the database files will be named consistently with your new database name and you still have the option to change file names if you want.
Checking the Options Over Write Database worked for me :)
Think of it like an archive.
MyDB.Bak contains MyDB.mdf and MyDB.ldf.
Restore with Move to say HerDB basically grabs MyDB.mdf (and ldf) from the back up, and copies them as HerDB.mdf and ldf.
So if you already had a MyDb on the server instance you are restoring to it wouldn't be touched.
The script in the question is just missing the replace statement so the restore script will be
RESTORE DATABASE myDB
FROM DISK = 'C:\myDB.bak' ,
WITH MOVE 'myDB_Data' TO 'C:\DATA\myDB.mdf',
,
MOVE 'myDB_Log' TO 'C:\DATA\myDB_log.mdf' , NOUNLOAD, REPLACE, STATS = 5

Sql Server 2005 Restore Failing

Running sql server 2005 I have database A. I am trying to restore from a backup of A to database B. I want to retain the database A and create a new testing database B from a previous set of data.
I tried to create B and restore from the .bak AND restore database to B from management studio.
The error is...
TITLE: Microsoft SQL Server Management
Studio
Restore failed for Server
'195448-APP2'.
(Microsoft.SqlServer.Smo)
For help, click:
http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.1399.00&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476
------------------------------ ADDITIONAL INFORMATION:
System.Data.SqlClient.SqlError: The
backup set holds a backup of a
database other than the existing 'B'
database. (Microsoft.SqlServer.Smo)
For help, click:
http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.1399.00&LinkId=20476
------------------------------ BUTTONS:
OK
I found this snippet which I am hesitant to use and want to ask if it would solve my problem of changing the location of the mdf and ldf during the process of restoring the database or does it replace database A's items altogether.
ALTER DATABASE AdventureWorks
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
RESTORE DATABASE AdventureWorks
FROM DISK = 'C\:BackupAdventureworks.bak'
WITH MOVE 'AdventureWorks_Data' TO 'C:\Data\datafile.mdf',
MOVE 'AdventureWorks_Log' TO 'C:\Data\logfile.ldf',
REPLACE
[http://blog.sqlauthority.com/2007/04/30/sql-server-fix-error-msg-3159-level-16-state-1-line-1-msg-3013-level-16-state-1-line-1/][1]
and for me I would make it...
RESTORE DATABASE B
FROM DISK = 'C:\backupofA.bak'
WITH
MOVE 'B' TO 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\B.mdf',
MOVE 'B_log' to 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\B_log.ldf',
REPLACE
What I don't know is if it will affect database A at all. I am hoping the replace refers files associated with B.
or if it should be
RESTORE DATABASE B
FROM DISK = 'C:\backupofA.bak'
WITH
MOVE 'A' TO 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\B.mdf',
MOVE 'A_log' to 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\B_log.ldf',
REPLACE
If anyone could help me with the error and/or confirm this fix I would be very grateful as it is not my database I'm playing with.
Thanks.
You could simply use the Copy Database Wizard.
If you wanna do it like pros and use T-SQL the RESTORE .. MOVE ... REPLACE will do what you expected: move the two files at the locations you intend and replace database B with content from the backup. A will be unaffected.
I would use the wizard if I were you: In Sql Server Management Studio right click on "Databases" and select "Restore Database...". This dialog / wizard will do exactly what you are asking - simply select the source .bak file(s) / Database that you want to restore from, enter the name of the database you want to restore to and hit "Ok".
Some notes - if you enter the name of a database that doesnt yet exist (it sounds like this is what you want to do), it will create that database for you. If you enter the name of an existing database it will attempt to restore to that database. If you attempt to restore to an existing database from a backup made of a different database it will fail, however you can force the Sql Server to overwrite the existing database by going to "Options" and checking the "Overwrite the existing database" checkbox.
Also, if you are restoring a backup of an existing database to create a new second copy of that database you may find that the wizard fails as its attempting to create a database using the same database file paths as the ones currently in use by the source database. To fix this you need to click on "Options" and change all of the "Restore As" file paths to files that dont yet exist.
You can also get this wizard to generate an SQL script instead of actually performing the actual restore (click on the "script" button at the top), which is handy if you want learn how to do this sort of thing in raw SQL instead.
It is possible to restore a database from sql server 7, sql server 2000 to sql server 2005.
It can be achieved by using restore and with replace command
use master
restore database mydatabase from disk ='c:\mybackup.bak' with replace
It is easy to take a backup in sql server using this script without any external tools.
Check out Restore with Example.
drop database b first. then do the restore.