Permissions on new mdf file - sql-server

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

Related

Moving DataBase from Microsoft SQL folder to App_Data folder (appseting.json)

1. "WebApi": "Data Source=.;Initial Catalog=TaskDB; Integrated Security=true"
2. "WebApi": "Server=(localdb)\\mssqllocaldb;AttachDBFilename=%CONTENTROOTPATH%\\App_Data\\TaskDB.mdf;Trusted_Connection=true;MultipleActiveResultSets=true"
I am trying to move my DataBase from main folder of Microsoft SQL to project folder App_Data, but it does not work for some reason. I do not know why maybe my connection string is wrong. So with number 1 is working fine, but it is in main folder of Microsoft SQL, but with number 2 there is something wrong I guess
The files of database are exclusive in hand of SQL Server. You can not move database when it is online. Taking database offline, requires that no one be connected to database.
First take the database offline then try to move the files. You can take the database offline both using SSMS and query. First line of code kill all active sessions then set database multiple user; but it must be offline before anyone can connect to database so all these code must be executed together.
ALTER DATABASE DatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE DatabaseName SET MULTI_USER
GO
USE master
GO
ALTER DATABASE DATABASE_NAME SET OFFLINE
Be aware that when you move file to another location database could not been brought ONLINE if you do not set new filename before taking the database offline.
Use this code for all of files that you want to move them.
ALTER DATABASE TEST
MODIFY FILE (NAME = 'LOGICAL_NAME', FILENAME = 'New_Directort\Filename.mdf')
After you moved the files then bring online the database with this statement.
ALTER DATABASE DATABASE_NAME SET ONLINE
As you can see this action is not a kind, that can be done without plan. Specially with application code. When trying to do it in application code; then all session including application connection will be lost. then you can not continue the progress.

How to get database schema from previously backed up but not known file of SQL-Server in SSMS?

I got an old project of ASP.net Web Form Solution Snapshot where only a file exists under database folder which is related to database, no .mdf files.
I have tried import, restore database, attach all ways to get the Database Schema from SSMS, nothing worked. Got error
While Attaching as .mdf File in SSMS.
Maybe, I had used 2008 sql server and now from sql server 2017, is that a problem or other things?
Is there a possible ways to get database structure from that file?
Thank You.
There confusion in your question (2nd line), do you mean .ldf?, if so, try following:
Create a dummy database with same name
Run following query
It detach existing files of newly created database (Dummy Database) and attach new file that you desired to:
EXEC sp_detach_db #dbname = 'DatabaseName';
EXEC sp_attach_single_file_db #dbname = 'DatabaseName',
#physname =
N'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\Data\NewDBFile.mdf';

recover data from mdf files (ndf being missing)

Our client's server got corrupted and the drives containing NDF and LDF files were gone. The only drive that survived was the one with MDF files.
There were no backups of any sort. They recovered the database, which I know just a gist of, by creating new database (from a old database, I guess) and applied bcp utility to copy data over to the new one. But, they would not release the information how they actually recovered.
So, I was just curious to find how it is possible to recover data from MDF files only, when the NDF files are lost/missing.
You will need to restore your database by using sp_attach_single_file_db system stored procedure. Something like this...
USE [master]
GO
EXECUTE sp_attach_single_file_db #dbname='DB_Name',
#physname=N'C:\Path_To_Your_MDF_FILE\DB_Name.mdf'
GO
Edit
USE [master]
GO
CREATE DATABASE DB_Name
ON (FILENAME = N'C:\Path_To_Your_MDF_FILE\DB_Name.mdf')
FOR ATTACH ;
GO

howt to use .MDF file

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.

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.

Resources