Move SQL Server 2008 R2 database files to a new folder location - sql

Currently i have a list of databases i wish to move on the current server.
DATA:
Current Path: Drive:\MSSQL\DATA\FOLDER
New Path: Drive:\MSSQL\DATA
LOGS:
Current Path: Drive:\MYSSQL\LOGS\FOLDER
New Path: Drive:\MYSSQL\LOGS
Is there a SQL script that can be used to set offline multiple databases, detactch them and attach them to the new location? This is also a production enviroment and are pretty large databases (a backup and restore would take much longer). In total 9 databases need to be moved, is this a simple procedure aslong as the location and user have required permissions? Thank you for any help.

This is a simple procedure, and you don't really need to detach the database to do it either, you can just do something along the lines of:
set db offline
alter the file location in the master db (using alter database)
physically move the files
set db online
The process is described in the following article:
Move User Databases
So long as the user moving the files has the permissions and the service account you're running SQL server as has full control of the new folder it's quite easy, and something I've done many times.
Doing it for multiple databases too is simple once you've worked out the procedure for doing the first one.

You can use this code to change the path. But you have to manually move the files to the new location. The WITH ROLLBACK IMMEDIATE speeds up the offline procedure by disconnecting any current connections.
ALTER DATABASE <db-name> SET OFFLINE WITH ROLLBACK IMMEDIATE;
ALTER DATABASE <db-name> MODIFY FILE ( NAME = <db-name>, FILENAME = <db-path\filename.mdf> );
ALTER DATABASE <db-name> SET ONLINE;
For more info check the relevant MSDN article

Related

Get DBs Location In A Network Server by a query

Is there a query in T-SQL that pulls out the location of all databases within a server in the network (not the local drive).
I had a look at this example SQL Server - get all databases with MDF and LDF File Location
.But, it didn't seem to work, I am guessing this is due to the location of this server which is not local.
The linked answer works but you must have enough permissions to view the results.
From sys.databases:
If the caller of sys.databases is not the owner of the database and the database is not master or tempdb, the minimum permissions required to see the corresponding row are ALTER ANY DATABASE or VIEW ANY DATABASE server-level permission, or CREATE DATABASE permission in the master database. The database to which the caller is connected can always be viewed in sys.databases.
From sys.master_files:
The minimum permissions that are required to see the corresponding row are CREATE DATABASE, ALTER ANY DATABASE, or VIEW ANY DEFINITION.

Copy SQL MDF file

I'm trying to get a copy of an MDF file but coming across the standard "file is in use" message which I believe is the SQL service holding a lock on it. Is it possible to make a copy of the mdf file without having to stop the service or in any way affect users/applications?
If not, is it possible to create a once-off full backup mdf to a different location than the existing one so that it wouldn't be locked by SQL service?
(Variations on this have been asked on this site already, but I don't think this is a duplicate. I am not trying to relocate the database, simply attempting to take a copy of the mdf - without interrupting Live operations - so I can place it on my dev machine at home and play around with the database)
this will let u make a backup :
BACKUP DATABASE MyDatabase TO DISK = 'W:\DBs\MyDatabase.bak' WITH INIT;
and if u want to backup the log file as well then just add this command before the previous one :
ALTER DATABASE MyDatabase SET RECOVERY FULL;
Then if you want to recover the database from the backup file try this command:
USE [master]
ALTER DATABASE MyDatabase
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
-- The previous command will used to close all connections to the database
-- until you recover it
Restore Database MyDatabase From Disk = 'W:\DBs\MyDatabase.bak' WITH REPLACE;
ALTER DATABASE MyDatabase SET MULTI_USER
-- This will reopen the database for users connections

Restore database SQL server query

I want a way to write my own query to restore the database. The database to restore needs to have all the settings to delete the current user and re-map the same user. The reason for that is because when the database is restored, the user will not have the right settings to use the database and will have to re assign the user the privileges.
Check this out:-
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
The reason for that is because when the database is restored, the user will not have the right settings to use the database and will have to re assign the user the privileges.
I guess that:
You are using mixed mode authentication and the user is a SQL Server user (not a Windows user)
You are restoring the database to a different server than the one where the backup was made
Correct?
If yes, you need to consider the following:
The user must exist on the second server as well, it's not created automatically when you restore the database there
It's not enough to just create a new user with the same name on the second server - to SQL Server, this would be a different user!
I guess that the second point is the reason why your user doesn't have "the right settings" after restoring.
Some background:
Internally, all SQL Server users are represented by a SID (something unique and unreadable - similar to a GUID. SQL Server doesn't care about the actual user name internally).
The permissions that each user has on a database are saved inside the database, using the SID and not the username
When you restore the database to a different server, the permissions are restored with the database...but they only work when there's a user with the exact SID on the new server
As I said before: when you just create a new user with the same name, he gets a new SID.
So what probably happened is this:
on the old server, there's a user "Mohammed Tahir" with the SID 123456789
inside the database, there's a permission that says "SID 123456789 is allowed to read from this database"
you restored the database on the new server
you created a user "Mohammed Tahir" on the new server, but he has a different SID (let's say 987654321), so the existing permissions on 123456789 don't work for him!
So what you need is a way to "copy" the user from the old server to the new server, with the exact same SID.
There is a stored procedure from Microsoft named sp_help_revlogin, which does just that.
It generates a script with all the users from the old server. You can then run the script on the new server, and it will create the users with the same SIDs they had on the old server.
Then, you can restore the database from the old server to the new server, and all the permissions already in the database just work.
You can get sp_help_revlogin from this MSDN article:
How to transfer logins and passwords between instances of SQL Server.
Note that there is nothing special about the actual restoring process - it's the users and their SIDs that make the difference.
So you don't need any "special" commands to restore the database, just the standard ones, for example the one from Rahul Tripathi's answer.

Sql Server change data and log path of existing database

I am having a SQL Server 2008 installation with almost 15 databases running on it. Now due to scarcity of space I would like to move the data path to another drive. What is the best practice for this. Please explain in details if including any SQL commands as I'm relatively new to SQL Server administration.
Note - I have already changed the path in SQL server properties from SQL Management Studio 2008, to the new path. But I would also like the existing databases to reside in the new path.
First, detach database:
USE master;
GO
-- Important! We need to drop the existing connections.
ALTER DATABASE DBName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
EXEC sp_detach_db #dbname = N'DBName';
GO
Next step - copy files .mdf and .ldf of this database files to new location
And then attaching the database:
USE master;
EXEC sp_attach_db #dbname = N'dbName',
#filename1 = N'', --path do .mdf
#filename2 = N''; --path to .ldf
GO
If you don't want to attach and detach all databases one-by-one, you can generate SQL script to attach and detach all databases you need (execept system, of course), using curosr that searches in sys.databases dynamic management view. But don't forget to copy the database files.
One way is to detach and attach.
As for commands/steps, see the MSDN article "How to: Move a Database Using Detach and Attach (Transact-SQL)"

Set permissions on newly created databases with rules

I have a situation whereby an application we use has many databases used for storage, and creates new ones on the fly as needed (SQL Server 2008 R2).
ApplicationDatabase
ApplicationDatabase_Storage001
ApplicationDatabase_Storage002
ApplicationDatabase_Storage003
etc...
As needed the application will create a new storage database for itself.
My problem is that I have a sql server account that is used for the ApplicationDatabase, and I want to automatically give it permissions to the storage databases as they are created, but not to any other database that happens to be created in the same sql server instance. I have no control over the creation of the storage databases.
I read In the answer to this question that I can add the account in the model database however this appears to add the permissions for all new databases, when I only want it to apply to the databases mentioned above.
The best solution I could come up with is a SQL server job or external app that runs once a day or so and looks for the existence of each database, applying the permissions on each that it finds, but this does not seem ideal.
You can implement a DDL trigger that will be fired whenever a new database is created. Depending on the properties of the database, like name or storage definition, you can probably run additional scripts on the new database to set up the required security.
http://msdn.microsoft.com/en-us/library/ms186406.aspx
Here's a snippet from the article above:
IF EXISTS (SELECT * FROM sys.server_triggers
WHERE name = 'ddl_trig_database')
DROP TRIGGER ddl_trig_database
ON ALL SERVER;
GO
CREATE TRIGGER ddl_trig_database
ON ALL SERVER
FOR CREATE_DATABASE
AS
PRINT 'Database Created.'
SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
GO
DROP TRIGGER ddl_trig_database
ON ALL SERVER;
GO
Regards
Piotr