Attach .mdf file located on desktop? - sql-server

In SQL Server 2008 I can attach databases located only in its predefined folder (C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA). On may occasions, especially when I read a book, I need to attach test database from desktop rather then copy each database every time I need it, but SQL Server does not allow me to access desktop.
Any workaround to solve this issue?

It's probably a matter of granting the account running the SQL service appropriate permissions to your desktop folder (C:\Documents and Settings\YourLogin\Desktop). But, rather than use a location like Desktop that is specific to your login and possibly inaccessible to the account running the SQL service, why not use a common holding location for these files? Something like C:\AdHocDBs or whatever you want to call it.

When a database file (data or log) is first created, it is (of course) located in a specific drive and folder. When a backup is created, this information is stored as part of the backup. A database RESTORE command will assume that the database is to be restored in the exact same location, unless instructed otherwise. To do this, in the RESTORE command under the "with" option, you must include the "move" option. It looks something like this:
RESTORE ...
with
move '<logcalFileName>' to 'physicalFileName'
,move '<logcalLogFileName>' to 'physicalLogFileName'
One move must be included for each file to be so moved, so you usually end up with at least two of these clauses. The tricky part is that you must know the database files' logical names. These can be found via sp_helpFile on an attached database, and
RESTORE FILELISTONLY
from disk = '<backupFile>'
On an existing backup.
(I'm sure all this can be done somehow with the SSMS backup/restore GUIs. I switched over to TSQL-based scripts years ago, to provide quick and flexible access to all the features wrapped in the backup and restore commands.)

Related

Temporarily attach/connect to SQL Server LocalDB file

I am trying to programmatically create and connect to an application specific LocalDB database. I would like to do this by specifying the file name of a .MDF file only, ideally without specifying an instance name or a name for the database that gets registered anywhere.
The database is to be accessed from some unit tests so it will only be used for a brief time before being deleted. My current approach creates the .MDF file correctly but also registers the name with the default instance which I would like to avoid given the temporary and 'non-singleton' nature of the database instances.
Is it possible to do what I am trying to do, or have I misunderstood how LocalDB works?
LocalDB automatic instance with specific data file
Server=(localdb)\v11.0;Integrated Security=true;
AttachDbFileName=C:\MyFolder\MyData.mdf;
Update
This can be used with the Deployment area in your .testsettings file. You just need to check 'Enable deployment' and add both the .mdf and .ldf files to 'Additional files and directories to deploy'.
You can then simply use the connection string above, and the test runner will take care of moving your data files to an appropriate temp folder for you.
Chrisb's answer got me on the right lines to solve this, but I noticed that the database remained attached to the default instance in LocalDB even after the connection had been closed. I read that this might eventually be purged after a few minutes but in my case this was too long as the file was located in a temporary directory used by MSTest and had to be closed in time for the cleanup at the end of the test run.
The solution was to use a connection string similar to https://stackoverflow.com/a/26712648 and a detach process similar to https://stackoverflow.com/a/6646319 immediately after I had finished using the connection.
Creating the MDF file in the first place could be accomplished by connecting to the automatic LocalDB instance, executing CREATE DATABASE and then using the same detach method. By using the file name for the database name, which is allowed in LocalDB due to the much longer names permitted, I ensured beyond reasonable doubt that the database name will not clash with anything else on the computer even during the short period it stays attached.

SQL Server Restore Error - Access is Denied

I created a database on my local machine and then did a backup called tables.bak of table DataLabTables.
I moved that backup to a remote machine without that table and tried to do a restore but get the following error:
System.Data.SqlClient.SqlError: The operating system returned the
error '5(Access is denied.)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'c:\Program
Files\Microsoft SQL Server\MSSQL.1\MSSQL\DataLabTables.mdf'.
How do I fix my rights, if that is the problem?
I have just had this issue with SQL Server 2012.
It turns out all I had to do was tick the box marked 'Relocate all files to folder' on the 'Files' section:
(Click to see image full size)
This of course assumes you have the correct version of SQL Server installed.
From the error message, it says there's an error when validating the target (c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DataLabTables.mdf) of your restore operation.
That sounds like:
a) that file already exists (because you've already restored it previously) and is in use by SQL Server
or
b) that directory doesn't exist at all
In your question, you mentioned you created a backup for that table - that's not how SQL Server backups work. Those backups are always the whole database (or at least one or several filegroups from that database).
My hunch is: you've already restored that database previously, and now, upon a second restore, you didn't check the checkbox "Overwrite existing database" in your restore wizard - thus the existing file cannot be overwritten and the restore fails.
The user that's running the restore on your remote server obviously doesn't have access to that directory on the remote server.
C:\program files\.... is a protected directory - normal (non-admin) users don't have access to this directory (and its subdirectories).
Easiest solution: try putting your BAK file somewhere else (e.g. C:\temp) and restore it from there
I was having the same problem. It turned out that my SQL Server and SQL Server Agent services logon as were running under the Network Services account which didn't have write access to perform the restore of the back up.
I changed both of these services to logon on as Local System Account and this fixed the problem.
Recently I faced this issue with SQL 2008 R2 and the below solution worked for me:
1) Create a new database with the same name as the one you are trying to restore
2) While restoring, use the same name you used above and in the options, click the overwrite option
You might give the above a shot if the other solutions don't work.
The backup creator had MSSql version 10 installed, so when he took the backup it also stores the original file path (to be able to restore it in same location), but I had version 11, so it could not find the destination directory.
So I changed the output file directory to C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\, and it was able to restore the database successfully.
Source
I had a similar problem. I tried to restore a 2005 .bak file, and i received exactly the same error. I selected the overwrite option as well to no avail.
my solution was to grant the SQL user access to the directory in question, by going to the folder and editing the access rights through the property screen.
lost a couple of hours to this problem too. got it going though:
"access denied" in my case really did mean "access denied". mssqlstudio's user account on my windows device did NOT have full control of the folder specified in the error message. i gave it full control. access was no longer denied and the restore succeeded.
why was the folder locked up for studio ? who knows ? i got enough questions to deal with as it is without trying to answer more.
I had this issue, I logged in as administrator and it fixed the issue.
Another scenario could be the existence of multiple database paths. First, make note of the path where new databases are currently being stored. So if you create a new empty database and then do Tasks/Restore, make sure that the path the restore is trying to use is the same directory that the empty database was created in. Even if the restore path is legal, you will still get the access denied error if it is not the current path you are working with. Very easy to spot when the path is not legal, much harder to spot when the path is legal, but not the current path.
Sorry because I cannot comment...
I had the same problem. In my case the problem was related to trying to restore in an old sql server folder (that existed on the server). This is due to old sql server backup (i.e. SQL Server 2012 Backup) restored in a new sql server (SQL Server 2014). The real issue is not too different from #marc_s answer. Anyway, I changed only the target folder to the new SQL Server DATA folder.
This may not be the best solution, but I was trying to do the restore at SQL Server 2005, but I changed to SQL Server 2008 and it worked.
Got problem like this. Error caused by enabled compression on SQL Server folders.
Frnds... I had the same issue while restroring database and tried every solution but could nt get resolved. Then i tried to re install SQL 2005 and the problem solved. Actully last time i forgot to check on customize option while instlling SQL.. It comes two times while installing and i checkd it for ones only..
In my case - I had to double check the Backup path of the database from where I was restoring. I had previously restored it from a different path when I did it the first time. I fixed the Backup path to use the backup path I used the first time and it worked!
I ended up making new folders for Data and Logs and it worked properly, must have been a folder/file permission issue.
This also happens if the paths are correct, but the service account is not the owner of the data files (yet it still has enough rights for read/write access). This can occur if the permissions for the files were reset to match the permissions of the folder (of course, while the service was stopped).
The easiest solution in this case is to detach each database and attach it again (because when attaching the owner is changed to be the service account).
Try this:
In the Restore DB wizard window, go to Files tab, Uncheck "Relocate All files to folder" check box then change the restore destination from C: to some other drive. Then proceed with the regular restore process. It will get restored successfully.
I had the same problem but I used sql server 2008 r2, you must check in options and verify the paths where sql going to save the files .mdf and .ldf you must select the path of your sql server installation. I solved my problem with this, I hope it helps you.
Then try moving it to a sub folder under the C:, but verify that the user has full rights on the folder your use.

Create a SQL Server database on a remote machine mdf file path issue

I'm trying to create a MS Sql Server database on a database instance running on a remote machine. When I'm doing so I need to be able to specify the path to the database (.mdf) file. If I try to create a database in a folder which doesn't exist, SQL Server will just fail (wouldn't it be nice if it created the folder structure automatically).
Is there any way that I can create the folder path on the target machine in SQL before I try to create the database, or at least to determine what the default folder is for new databases in which I could safely create the new database file?
If you have appropriate permissions, and xp_cmdshell is enabled, you can:
EXEC xp_cmdshell 'md "<path>"';
--...repeat for each node in the path
If cmdshell is disabled, again assuming appropriate permissions, you can enable it temporarily using sp_configure:
Ancient article removed
Don't forget to set it back!
Otherwise why can't you let the engine place the database files in their default location? If you are using a drive other than C:, you'll also need to verify that the drive you specify even exists, and shouldn't you check with the user that it is okay for you to put these files elsewhere? If you choose some arbitrary location they might not know to check there for active SQL Server files.
You can check the default path by using xp_regread (undocumented, unsupported)... these are in the registry as keys DefaultDataDir and DefaultLogDir for the default instance under:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer
If it's not the default instance, check this article:
http://foxtricks.blogspot.com/2009/06/how-to-determine-default-database-path.html
Are you doing this just so that you can name your MDF/LDF files the way you want to, instead of dbname-data, dbname-log? If so, why? Have you written scripts that depend on the physical name of the file? Really curious as to the motivation behind this.

SQL Server 2008 database copy - file permissions

For SQL Server 2008 Developer Edition on Vista 64 bit:
I tried copying a database using a Vista admin account using the attach/detach method and it failed due to a file permission error so I gave the user that sql services are running as write and modify to the directory. The copy didn't work. I then gave it full control. The copy worked.
Does that make sense?
If I revoke full control from the user, will that cause problems?
The weird thing is that in an existing working database with files in a different directory, there are no special permissions on the directory and files for the database, so why does a copy require full control?
When you detach a DB, the MDF/LDF files may be set with more restricted perms than you expect, like exclusive to the principal that did the detach - maybe the SQL Server service account or the domain account of the user that performed the detach. I have in the past had to manually add back permissions on the files' Properties > Security tab for other users, or else the files act as if they are locked. See also http://www.onupdatecascade.com/2009/07/sql-server-locks-mdf-and-ldf-files-upon.html
also: http://msdn.microsoft.com/en-us/library/ms189128.aspx
( thanks GrumpyOldDBA )
If the server and/or data you are working on does not require those restrictive permissions to be set, you can set a startup flag in SQL Server that will override this function. I understand what Microsoft is going for with this - they assume if you detach a DB they don't want just anyone to walk away with the file; however, I think keeping a good hacker from doing that is easier said than done, and encrypting the DB is the best method for safeguarding data.
Anyway, there is a "Trace Flag 1802" which is oddly named, since it's nothing to do with tracing. You'll want to add it to your SQL startup in SQL Configuration Manager if you want to keep this behavior.
https://support.microsoft.com/en-us/kb/922804
I myself had the same issue and found the answer in StackExchange:
https://dba.stackexchange.com/a/77683/11001

Is there any way to undelete a SQL server database and stored procedures?

Is there any way to undelete a SQL server database and stored procedures?
Edit:
No I don't have a backup. That is the reason I need help
Restore from backup.
You do have a backup, right?
Edit:
I'm assuming you probably did a right-click, "Delete" from SQL Management Studio? If so, that actually does a "drop" of the database, which literally removes the files from the hard drive. If this is the case, you'll have to restore from your latest backup (if you have one).
If you just did a "detach", then the MDF and LDF files are still on the hard drive, and you can simply attach them.
How exactly have you deleted it.
If you haven't made any changes to you disks file system since then (and not defraged) then its possible the file will still be sitting on the disk as windows doesn't delete the file completely, just the File Handle.
Have a look at something like this and you may be able to recover the .mdf/.ldf files from your HD.
http://www.undelete.com/file-recovery.aspx
If not, you'll have to restore from your last back.
And if you don't have a backup... you're screwed.
If you accidently deleted the database in SQL Server Management Studio by right clicking and hitting delete in a hurry and you have no backup then there might still be a chance of getting back the database:
Don't do any save / delete file operations on the disk where the database file was stored, browsing should be ok.
Find the location where the .mdf file used to be. In my case it was "c:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS2012\MSSQL\DATA". If you have multiple databases you can right click on an existing one, select properties and files. Find the location entry in the listbox under path (select and ctrl+c to copy it)
Download a portable undelete program e.g. Recuva to a USB drive/stick (unzip) and run it from the USB drive/stick.
Set the copied path as the "search location" in your undelete program (ctrl+v), recover "YOURDATABASE.mdf" and "YOURDATABASE_log.ldf" to the USB drive.
Copy the files from USB drive/stick to the original location.
In SQL Server Management Studio right click on "Databases" select "Attach.." click Add, select "YOURDATABASE.mdf".
Get some coffee and think about backups :-)
Did you drop the database or detach it ? If you've detached it then just reattach it again from the mdf and ldf files.

Resources