howt to use .MDF file - sql-server

work on SQL Server 2000.i have CustomerDetails_Data.MDF file .from this file i want to take all information on my database .How to do?

You will need to attach the .mdf data file to a database in SQL Server. Then you can simply query the information.
If you just have an .mdf file (and no log file .ldf), follow these steps to create a Database from your lone .mdf file:
Create a new database with the same name and same MDF and LDF files
Stop sql server and rename the existing MDF to a new one and copy the
original MDF to this location and
delete the LDF files.
Start SQL Server
Now your database will be marked suspect 5. Update the sysdatabases to
update to Emergency mode. This will
not use LOG files in start up
Sp_configure "allow updates", 1
go
Reconfigure with override
GO
Update sysdatabases set status = 32768 where name = "BadDbName"
go
Sp_configure "allow updates", 0
go
Reconfigure with override
GO
Restart sql server. now the database will be in emergency mode
Now execute the undocumented DBCC to create a log file
DBCC REBUILD_LOG(dbname,'c:\dbname.ldf') --
Undocumented step to create a new log
file.
(replace the dbname and log file name
based on your requirement)
Execute sp_resetstatus <dbname>
Restart SQL server and see the database is online.

You need to attach the .mdf data file to SQL Server, and SQL server will automatically generate a new LOG file, after that you can pass any query to the database...

What format do you want to extract the information to? You could write sql scripts against it, or use bulk copy.

Related

Permissions on new mdf file

I'm trying to write a program to allow a non-privileged technically naive user to create a new SQL Server database and receive it in the form of a .mdf file. I understand that .mdf files are not really supposed to be treated like database backups, but I need to do it this way to maintain compatibility with existing commercial software that works like this.
I'm using Visual Studio 2013 and SQL Server 2014, though I would like the program to be able to work with versions of SQL Server going back at least to 2008.
What I find is that I can't copy the .mdf file created by
CREATE DATABASE XXXXX on
(NAME=<name>,FILENAME=<filename>')
because it ends up belonging (I think) to MSSQL$SQLEXPRESS. The reason I say 'I think' is that when I go to the file properties and accept Administrator privileges to view the owner, it tells me 'Unable to display current owner.' I can transfer ownership of the file, but only using Administrator privileges.
So it seems that I cannot copy the .MDF file without Administrator privileges, which seems fairly ridiculous given that I was able to create the file without those privileges. I've tried creating the file in a folder located under my user's App_Data folder and with full access for everyone to subfolders and files, but that didn't help.
Can anyone suggest me what I can do (programatically) to make this file available to a non-privileged user?
Many thanks for your help.
Try following script before trying to copy mdf file:
USE [master]
GO
EXEC master.dbo.sp_detach_db #dbname = N'DatabaseName';
GO
It will detach Database from SQL Server and you can treat it's files as regular files within a system.
After copying you'd have to re-attach the database by "sp_attach_db".
Be aware that during that period database won't be visible by SQL Server.
USE [master]
GO
EXEC master.dbo.sp_attach_db #dbname = N'DatabaseName'
, #filename1 = 'C:\Data\Datfile.mdf';
, #filename2 = 'C:\Data\Logfile.ldf';
GO
First get location of data files into a variable, so that you can easly move from there after you detach.
select a.filename from sys.sysfiles a inner join sys.master_files b on a.fileid=b.file_id
where b.database_id=db_id('DB_NAME')
Verify if there is any open session with the database.
select spid from sysprocesses where dbid=db_id('DB_NAME')
Kill All the sessions using [kill spid]
Then Detach your database
USE [master]
GO
EXEC master.dbo.sp_detach_db 'DB_NAME';
Now you can move the database from the source holded in the variable to desired destination.
Now if you want to attach the database on other server.
If you moved both .ldf and .mdf to same directory
USE [master]
GO
EXEC master.dbo.sp_attach_db #dbname = 'DB_NAME', #filename1 = 'C:\Data\Datfile.mdf';
If you moved .ldf and .mdf to seperate directory.
Use the script suggested by Mr. Slava Murygin here to attach database.
Thanks

Using SQL Server Management Studio Express to Backup DB

I am wanting to backup a SQl Server 2005 db at a remote site (ie. to ultimately have a backup file of the db here locally on my machine).
Can this be done using SQL Server Management Studio Express ? I have this installed and running.. but cannot seem to find a way of backing up using it.
If this isn't possible, how do I create a backup of my remote db some other way ?
Thank you,
Bazza
It should be possible, right click on the database, select Tasks->Backup.
The other good option is the bcp command line utility. If your backup needs to be done regularly it's a better option since you can use it in a bacth file or script and create a scehduler task for it.
I'm not sure, however if you have remote access to the system concerned you should be able to run a SQLCMD and issue the backup from the command line.
1) create a script called say backup.sql
USE [master]
GO
BACKUP DATABASE [somedatabase]
TO DISK = N'C:\somedatabase.bak'
WITH NOFORMAT,
INIT,
NAME = N'Full Database Backup of somedatabase',
SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
2) issue:
sqlcmd -U username -P password -i backup.sql
Then copy the file over.
Unfortunately, I can't answer your specific question regarding SSMS Express - I've not used the tool extensively. However, I do know that you can open a New Query window and issue a BACKUP DATABASE command. An example of this would be:
backup database <dbname,,> to disk='c:\mydbbackup.bak';
You could then use standard methods (such as FTP) to get the file copied locally. Hope that helps!
This works in SSMS 2008 Express:
Right-click the database name in object explorer > Tasks > Backup…
Select "Full" (should already be default), enter a name, and at the bottom click "Add" and create the file to which you want to back up.
Run the backup.
Copy the file to your local machine.
Connected to the local machine, select the "Databases" node in Object Explorer > Restore Database…
Now name the new database, select "from device" and choose the backup file from which to create the new database, and go.
Done.

Import .bak file to a database in SQL server

I have a file with .bak extension.
How can I import this date to a database in SQL Server?
On SQL Server Management Studio
Right click Databases on left pane (Object Explorer)
Click Restore Database...
Choose Device, click ..., and add your .bak file
Click OK, then OK again
Done.
This will show you a list of database files contained in DB.bak:
RESTORE FILELISTONLY
FROM DISK = 'D:\3.0 Databases\DB.bak'
You will need the logical names from that list for the MOVE operation in the second step:
RESTORE DATABASE YourDB
FROM DISK = 'D:\3.0 Databases\DB.bak'
and you have to move appropriate mdf,ndf & ldf files using
With Move 'primarydatafilename' To 'D:\DB\data.mdf',
Move 'secondarydatafile' To 'D:\DB\data1.ndf',
Move 'logfilename' To 'D:\DB\log.ldf'
You can simply restore these database backup files using native SQL Server methods, or you can use ApexSQL Restore tool to quickly virtually attach the files and access them as fully restored databases.
Disclaimer: I work as a Product Support Engineer at ApexSQL
Instead of choosing Restore Database..., select Restore Files and Filegroups...
Then enter a database name, select your .bak file path as the source, check the restore checkbox, and click Ok. If the .bak file is valid, it will work.
(The SQL Server restore option names are not intuitive for what should a very simple task.)
On Microsoft SQL Server Management Studio 2019:
On Restore Database window:
Choose Device
Choose Add and pick target file
OK to confirm
OK to confirm restore
Connect to a server you want to store your DB
Right-click Database
Click Restore
Choose the Device radio button under the source section
Click Add.
Navigate to the path where your .bak file is stored, select it and click OK
Enter the destination of your DB
Enter the name by which you want to store your DB
Click OK
Done
Although it is much easier to restore database using SSMS as stated in many answers.
You can also restore Database using .bak with SQL server query, for example
RESTORE DATABASE AdventureWorks2012 FROM DISK = 'D:\AdventureWorks2012.BAK'
GO
In above Query you need to keep in mind about .mdf/.ldf file location.
You might get error
System.Data.SqlClient.SqlError: Directory lookup for the file "C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\AdventureWorks.MDF" failed with the operating system error 3(The system cannot find the path specified.). (Microsoft.SqlServer.SmoExtended)
So you need to run Query as below
RESTORE FILELISTONLY
FROM DISK = 'D:\AdventureWorks2012.BAK'
Once you will run above Query you will get location of mdf/ldf use it Restore database using query
USE MASTER
GO
RESTORE DATABASE DBASE
FROM DISK = 'D:\AdventureWorks2012.BAK'
WITH
MOVE 'DBASE' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE.MDF',
MOVE 'DBASE_LOG' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE_1.LDF',
NOUNLOAD, REPLACE, NOUNLOAD, STATS = 5
GO
Source:Restore database from .bak file in SQL server (With & without scripts)
Simply use
sp_restoredb 'Your Database Name' ,'Location From you want to restore'
Example: sp_restoredb 'omDB','D:\abc.bak'
You can use node package, if you often need to restore databases in development process.
Install:
npm install -g sql-bak-restore
Usage:
sql-bak-restore <bakPath> <dbName> <oldDbName> <owner>
Arguments:
bakpath, relative or absolute path to file
dbName, to which database to restore (!! database with this name will be deleted if exists !!)
oldDbName, database name (if you don't know, specify something and run, you will see available databases after run.)
owner, userName to make and give him db_owner privileges (password "1")
!! sqlcmd command line utility should be in your PATH variable.
https://github.com/vladimirbuskin/sql-bak-restore/

How to recover database from MDF in SQL Server 2005?

I have an MDF file and no LDF files for a database created in MS SQL Server 2005. When I try to attach the MDF file to a different SQL Server, I get the following error message.
The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure.
I would like to accomplish any one of the following options:
Attach the database without data loss (unlikely but would save me some time).
Attach the database with data loss (whatever transactions were open are lost).
Recover the schema only (no data) from the MDF file.
What SQL commands can I try to get my database going again?
I found the following document on Experts Exchange.
patrikt:
You will have data loss but it can be done.
1. Detach database and move your mdf to save location.
2. Create new databse of same name, same files, same file location and same file size.
3. Stop SQL server.
4. Swap mdf file of just created DB to your save one.
5. Start SQL. DB will go suspect.
6. ALTER DATABASE yourdb SET EMERGENCY
7. ALTER DATABASE yourdb SET SINGLE_USER
8. DBCC CHECKDB (yourdb, REPAIR_ALLOW_DATA_LOSS)
9. ALTER DATABASE yourdb SET MULTI_USER
10. ALTER DATABASE yourdb SET ONLINE
Here are details that cover parts 2) and 3) in case re-creating log doesn’t work which can happen if MDF file is corrupted.
You can recover data and structure only by reading MDF file with some third party tool that can de-code what’s written as binary data but even with such tools you can’t always do the job completely.
In such cases you can try ApexSQL Recover. From what I know this is the only tool that can do this kind of job but it’s quite expensive.
Much better idea is to try to recover these from any old backups if you have any.
FROM a post at SQL Server Forums Attaching MDF without LDF:
If you want to attach a MDF without LDF you can follow the steps below
It is tested and working fine
Create a new database with the same name and same MDF and LDF files
Stop sql server and rename the existing MDF to a new one and copy the original MDF to this location and delete the LDF files.
Start SQL Server
Now your database will be marked suspect 5. Update the sysdatabases to update to Emergency mode. This will not use LOG files in start up
Sp_configure "allow updates", 1
go
Reconfigure with override
GO
Update sysdatabases set status = 32768 where name = "BadDbName"
go
Sp_configure "allow updates", 0
go
Reconfigure with override
GO
Restart sql server. now the database will be in emergency mode
Now execute the undocumented DBCC to create a log file
DBCC REBUILD_LOG(dbname,'c:\dbname.ldf') -- Undocumented step to
create a new log file.
(replace the dbname and log file name based on ur requirement)
Execute sp_resetstatus
Restart SQL server and see the database is online.
UPDATE: DBCC REBUILD_LOG does not existing SQL2005 and above. This should work:
USE [master]
GO
CREATE DATABASE [Test] ON
(FILENAME = N'C:\MSSQL\Data\Test.mdf')
FOR ATTACH_REBUILD_LOG
GO
have you tried to ignore the ldf and just attach the mdf:
sp_attach_single_file_db [ #dbname = ] 'dbname' , [ #physname = ] 'physical_name'
i don't know exactly what will happen to your open transactions (probably just lost), but it might get your data back online.
-don
See here : Rebuild master and restore system databases from complete disk failure which has a very nice explanation
Just had this problem myself, but none of the above answers worked for me.
But instead, I found this which worked a treat and so I thought I'd share this for everyone else:
http://www.kodyaz.com/articles/sql-server-attach-database-mdf-file.aspx
Found a another way that works completely:
Create new database with same name to default database location.
Stop SQL server.
Copy old mdf file to overwrite newly created mdf file and delete new ldf file
Start SQL Server, database will be in emergency mode
Detach the emergency mode database
Copy original ldf file to default database location (where new LDF file as created and deleted under step 3 above.
Attach the database MDF file.
I got a working database after trying all of the above that failed for me.
I hope it is easy to do so,
Open SQL Server
Click New Query
Execute the following query
sp_attach_single_file_db #dbname='dbname',#physname='C:\Database\dbname.MDF'
Where dbname is you want to show in Object Explorer, where #physname is the local filepath location of your mdf file.
Hope it will help someone, i done by above, got both structure and also data.
Tested in Sql Server 2000 and 2008. In Sql Server 2000 it is not working, but works perfectly in 2008.

How do I attach a MSSQL 2000 database with only an MDF file

I have an old server with a defunct evaluation version of SQL 2000 on it (from 2006), and two databases which were sitting on it.
For some unknown reason, the LDF log files are missing. Presumed deleted.
I have the mdf files (and in one case an ndf file too) for the databases which used to exist on that server, and I am trying to get them up and running on another SQL 2000 box I have sitting around.
sp_attach_db complains that the logfile is missing, and will not attach the database. Attempts to fool it by using a logfile from a database with the same name failed miserably. sp_attach_single_file_db will not work either. The mdf files have obviously not been cleanly detached.
How do I get the databases attached and readable?
I found this answer, which worked with my SQL 2000 machines:
How to attach a database with a non-cleanly detached MDF file.
Step 1: Make a new database with same name, and which uses the same files as the old one on the new server.
Step 2: Stop SQL server, and move your mdf files (and any ndf files you have) over the top of the new ones you just created. Delete any log files.
Step 3: Start SQL and run this to put the DB in emergency mode.
sp_configure 'allow updates', 1
go
reconfigure with override
GO
update sysdatabases set status = 32768 where name = 'TestDB'
go
sp_configure 'allow updates', 0
go
reconfigure with override
GO
Step 4: Restart SQL server and observe that the DB is successfully in emergency mode.
Step 5: Run this undocumented dbcc option to rebuild the log file (in the correct place)
DBCC REBUILD_LOG(TestDB,'D:\SQL_Log\TestDB_Log.LDF')
Step 6: You might need to reset the status. Even if you don't, it won't do any harm to do so.
exec sp_resetstatus TestDB
Step 7: Stop and start SQL to see your newly restored database.
In Enterprise Manager, right-click the server and choose Attach Database. Select the MDF file and click Ok. It will then ask you if you want to create a new log file or not. Say Yes.

Resources