Search This Blog

SQL Add a column in a specific position in a tableSQL Add Column Position

SQL Add Column Position is used to add the column at the specific position. The Alter statement copy the structure of existed table and make a modify a table on the basis of specified Query.
Understand with Example
The Tutorial illustrates an example from SQL Add Column Position to the existing table 'Stu_Table'.
Create Table Stu_Table


create table Stu_Table(Stu_Id integer(2), Stu_Name varchar(15))
Insert data into Stu_Table
insert into Stu_Table values(1,'Komal')
insert into Stu_Table values(2,'Ajay')
insert into Stu_Table values(3,'Rakesh')
insert into Stu_Table values(4,'Bhanu')
insert into Stu_Table values(5,'Santosh)
 Stu_Table
Stu_IdStu_Name
1Komal
2Ajay
3Rakesh
4Bhanu
5Santosh
SQL Add Column Syntax
The ALTER Table is used to modify table name 'table_name' and add a column at the specific position. The first column specify the position of the column to be come first in table followed by a after column in a table. The Syntax is given as : 
ALTER TABLE table_name
ADD column_name column-definition [ FIRST | AFTER col_name ]
SQL Add Colum Query
The SQL Add Column Query add a Stu_Name column followed by Stu_Name in the Table Stu_Table.
Alter Table Stu_Table add Stu_Class int(10) AFTER Stu_Name
View data  Stu_Table
Stu_IdStu_NameStu_Class
1KomalNULL
2AjayNULL
3RakeshNULL
4BhanuNULL
5SantoshNULL

How to Move User Databases(2005/2008/2012)

How to Move the System Databases(2005/2008/2012)

Contents

  • Introduction
  • Prerequisites
  • Method 1: Taking the Database Offline Method
  • Method 2: Using the Detach/Attach Method

Introduction

Moving a user database in SQL Server is not only a common DBA task, but a fairly simple and straightforward one as well. Just like any administration task, the goal for the DBA should be to use a method with the least interruption to the server and to the database being relocated. This guide presents two methods that can be employed to change the location of the data files and transaction log files for a user database within the same instance using Transact-SQL as part of a planned relocation or scheduled maintenance operation. Although the sample installation for this guide uses SQL Server 2008 R2, instructions will be provided to handle all versions of SQL Server.

  • Taking the Database Offline Method — (SQL Server 2005 and higher)
  • Using the Detach/Attach Method — (All Versions of SQL Server)

Note that this guide presents how to move user databases and not system databases. The steps necessary to move SQL Server system databases are more involved and will differ from the steps used to move user databases. Click here for step-by-step instructions on how to move SQL Server system databases.How to Move the System Databases(2005/2008/2012)

Prerequisites

The following list of prerequisites should be performed regardless of which method you decide on using to move the data files and log files of the user database.

  1. This cannot be stressed enough. Make a current backup of all databases being considered to move from their current location, especially the master database. Making a mistake or suffering a system failure when attempting to make critical changes of this nature can render your database as unusable. Let me say it again, make a current backup!
  2. You must be authenticated to the SQL Server instance with system administrator (sa) permissions.
  3. The procedures in this guide require you to know the logical name and the physical location of all data files and log files of the database being moved. There are two methods that can be used to obtain the file names and locations depending on which version of SQL Server you are using.
    For SQL Server 2005 and higher, query the system-wide view sys.master_files.
    USE [master]
    Go
    
    SELECT
        DB_NAME(database_id)  AS "Database Name"
      , type_desc             AS "File Type"
      , name                  AS "Logical File Name"
      , physical_name         AS "Physical File"
      , state_desc            AS "State"
    FROM
        sys.master_files
    WHERE
        database_id = DB_ID('<database_name>');
    Go
    For all versions of SQL Server, you can use the sp_helpfile stored procedure.
    
    USE <database_name>
    Go
    
    EXEC sp_helpfile
    Go
  4. You should have exclusive access to the database that you are moving which simply means that all other users have to be logged out of the database.

Method 1: Taking the Database Offline Method

Out of all of the methods that can be used to move a user database, taking the database offline in order to move its physical files is the most simple, flexible, and least intrusive of them all. It does, however, require that are using SQL Server 2005 or higher. The reason why this method is favorable over the detach/attach method is that unlike taking a database offline, detaching a database will loose certain database properties that will need to be re-applied after re-attaching it (for example, cross-database ownership chaining).
The example demonstrated in this section moves one the AdventureWorks sample databases named AdventureWorksDW to a different directory location in the same SQL Server instance using the database offline method. TheAdventureWorksDW database contains one data file, AdventureWorksDW_Data.mdf, and one log file, AdventureWorksDW_Log.LDF, both of which are currently located in theF:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA directory path.

SELECT
    DB_NAME(database_id)  AS "Database Name"
  , type_desc             AS "File Type"
  , name                  AS "Logical File Name"
  , physical_name         AS "Physical File"
  , state_desc            AS "State"
FROM
    sys.master_files
WHERE
    database_id = DB_ID('AdventureWorksDW');
Go

Database Name     File Type  Logical File Name      Physical File                                                         State
----------------- ---------- ---------------------- --------------------------------------------------------------------- ------
AdventureWorksDW  ROWS    AdventureWorksDW_Data  
F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW_Data.mdf  ONLINE
AdventureWorksDW  LOG        AdventureWorksDW_Log   
F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW_Log.LDF   ONLINE

The data file will be relocated to G:\MSSQL\Data while the log file will be moved to L:\MSSQL\Log.


  1. The first step is to take the database offline. Although not mandatory, this operation should be performed while connected to the master database (USE master) and not from the database being moved. Once the command finishes, it will try to set the connection back to the database you were connected to. If you are connected to the database being moved, you will receive a warning message similar to the following because you just took the database offline:
    Failed to restart the current database. The current database is switched to master.
    This is obviously a benign warning since SQL Server will simply switch you to the master database anyway.
    USE [master]
    Go
    
    ALTER DATABASE [AdventureWorksDW] SET OFFLINE;
    Go
  2. Next, physically move the data files and the log files from the current location (F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA) to the new location (G:\MSSQL\Data for data files and L:\MSSQL\Log for log files).
    [VMWINDOWS1] C:\> 
    move F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW_Data.mdf G:\MSSQL\Data\
            1 file(s) moved.
    
    [VMWINDOWS1] C:\> 
    move F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW_Log.LDF L:\MSSQL\Log\
            1 file(s) moved.
  3. Next, update the SQL Server system catalog to modify the physical data file and log file mappings to their logical file name. The new path will be used when the database is restarted or brought back online.
    USE [master]
    Go
    
    ALTER DATABASE [AdventureWorksDW]
        MODIFY FILE (NAME = 'AdventureWorksDW_Data', FILENAME = 'G:\MSSQL\Data\AdventureWorksDW_Data.mdf');
    Go
    
    ALTER DATABASE [AdventureWorksDW]
        MODIFY FILE (NAME = 'AdventureWorksDW_Log', FILENAME = 'L:\MSSQL\Log\AdventureWorksDW_Log.LDF');
    Go
  4. Open the database up for user connections again by bringing it back online.
    USE [master]
    Go
    
    ALTER DATABASE [AdventureWorksDW] SET ONLINE;
    Go
  5. Verify the change in file locations by querying the sys.master_files system-wide view.
    SELECT
        DB_NAME(database_id)  AS "Database Name"
      , type_desc             AS "File Type"
      , name                  AS "Logical File Name"
      , physical_name         AS "Physical File"
      , state_desc            AS "State"
    FROM
        sys.master_files
    WHERE
        database_id = DB_ID('AdventureWorksDW');
    Go
    
    Database Name     File Type  Logical File Name      Physical File                            State
    ----------------- ---------- ---------------------- ---------------------------------------- ------
    AdventureWorksDW  ROWS     AdventureWorksDW_Data  G:\MSSQL\Data\AdventureWorksDW_Data.mdf  ONLINE
    AdventureWorksDW  LOG        AdventureWorksDW_Log   L:\MSSQL\Log\AdventureWorksDW_Log.LDF    ONLINE

 The steps described above explain how to rename the physical database files. While not required, it is also possible to change the logical name of the database file using the ALTER DATABASE command.

USE [master]
Go

ALTER DATABASE [AdventureWorksDW]
    MODIFY FILE (NAME = 'AdventureWorksDW_Data', NEWNAME = 'AdventureWorksDW_Test_Data');
Go

ALTER DATABASE [AdventureWorksDW]
    MODIFY FILE (NAME = 'AdventureWorksDW_Log', NEWNAME = 'AdventureWorksDW_Test_Log');
Go

Method 2: Using the Detach/Attach Method

This method is one of the holdovers from SQL Server 7.0 and 2000 and is commonly used because it works for any Microsoft SQL Server database version (SQL Server 2012, SQL Server 2008, SQL Server 2005, SQL Server 2000, or SQL Server 7.0). The major drawback with this method is that detaching a database in SQL Server loses certain database properties like cross database ownership chaining because these settings are not stored in the database itself, but rather in the meta data contained in the master database. Because of this, you will have to remember to manually re-apply those settings when re-attaching the database. You should also be aware that any users that have that database set as their default database will now be given master as their default database. This could have serious consequences for both applications and users that are expecting their database to be set when they log in.
Another reason why this method is used is that it's the only solution when moving files from one server to another. However, if you are moving files around in the same SQL Server instance and you are running SQL Server 2005 or above, you should consider using the Database Offline method in order to preserve your settings and accomplish the move. Using the Database Offline method merely changes the state value in the sys.databases table in the master database (state=6, state_desc=OFFLINE) while detaching a database actually removes the entry for that database.
Detaching a database is similar to dropping a database as far as SQL Server is concerned. After a database has been detached, no meta data for that database will exist within SQL Server with the only possible exception of recent backup and restore history contained in the msdb database. Although SQL Server does include the DROP DATABASE command, it should not be used to move a database since dropping a database removes the physical files from the operating system. Unless you have a backup, the database is essentially gone.
Finally, note the following restrictions before attempting to detach a database. You cannot detach a database if any of the following conditions exist:

  1. Database is a system database
  2. Database is being mirrored
  3. Database is being published through replication
  4. The database has a snapshot

The following example moves one the AdventureWorks sample databases named AdventureWorksLT to a different directory location in the same SQL Server instance using the Detach/Attach method. The AdventureWorksLTdatabase contains one data file, AdventureWorksLT_Data.mdf, and one log file, AdventureWorksLT_Log.ldf, both of which are currently located in the F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA directory path.


USE [AdventureWorksLT]
Go

EXEC sp_helpfile
Go

name                   fileid filename                                                              }
---------------------- ------ --------------------------------------------------------------------- } <SNIP>
AdventureWorksLT_Data  1      F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\AdventureWorksLT_Data.mdf  } 
AdventureWorksLT_Log   2      F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\AdventureWorksLT_Log.ldf   }

The data file will be relocated to G:\MSSQL\Data while the log file will be moved to L:\MSSQL\Log.



  1. Check for any database properties that may be enabled for the database being detached. For example, I will enable cross database ownership chaining on the AdventureWorksLT database to explain how this process works. Later in this example when the database is re-attached, these properties will need to be manually enabled.
    USE [master]
    Go
    
    ALTER DATABASE [AdventureWorksLT] SET DB_CHAINING ON;
    Go
    Next, verify that cross database ownership chaining is enabled by querying sys.databases. The is_db_chaining_on column should be 1 which indicates that cross database ownership chaining is indeed enabled. A value of 0 would indicate that the property is not enabled.
    SELECT
        DB_NAME(database_id)  AS "Database Name"
      , is_db_chaining_on     AS "Database Chaining Enabled?"
    FROM
        sys.databases
    WHERE
        database_id = DB_ID('AdventureWorksLT');
    Go
    
    Database Name      Database Chaining Enabled?
    ------------------ --------------------------
    AdventureWorksLT   1
  2. Detach the database.
    USE [master]
    Go
    
    EXEC sp_detach_db @dbname = 'AdventureWorksLT', @skipchecks = 'true'
    Go
    The sp_detach_db stored procedure above was executed with two parameters:
    @dbname – is the name of the database you are detaching. Although not required, I included this as a named parameter for the sake of clarity.
    @skipchecks – tells SQL Server whether or not you want to skip or run UPDATE STATISTIC for the database being detached. Valid values are 'true' or 'false'. The default value is NULL which means UPDATE STATISTICS is performed to update information about the data in the tables and indexes in the SQL Server 2005 Database Engine and later versions. To skip UPDATE STATISTICS, specify 'true'. To explicitly run UPDATE STATISTICS, specify 'false'. In most cases, you can set this to 'true' because most often, there is no need to update statistics when detaching a database. Updating statistics can take a significant time to complete (depending on the size of the database) and can be performed at a later time after re-attaching the database. On the other hand, explicitly performing UPDATE STATISTICS is useful for databases that will be moved to read-only media.
  3. Next, move the data files and the log files from the current location (F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA) to the new location (G:\MSSQL\Data for data files and L:\MSSQL\Log for log files).
    [VMWINDOWS1] C:\> 
    move F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\AdventureWorksLT_Data.mdf G:\MSSQL\Data\
            1 file(s) moved.
    
    [VMWINDOWS1] C:\> 
    move F:\MSSQL\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\AdventureWorksLT_Log.ldf L:\MSSQL\Log\
            1 file(s) moved.
  4. Re-attach the database and point to the files in the new location using the CREATE DATABASE command with the FOR ATTACH option.
    USE [master]
    Go
    
    CREATE DATABASE [AdventureWorksLT]
        ON (NAME = 'AdventureWorksLT_Data', FILENAME = 'G:\MSSQL\Data\AdventureWorksLT_Data.mdf'),
           (NAME = 'AdventureWorksLT_Log',  FILENAME = 'L:\MSSQL\Log\AdventureWorksLT_Log.ldf')
    FOR ATTACH
    Go
    If the database that you are moving has multiple data files and/or log files being relocated, specify them in a comma-delimited list to the CREATE DATABASE command as shown above. When re-attaching the database, you only need to specify the primary file to the database (.mdf) and any transaction log files (.ldf) or additional data files (.ndf) that have changed location. The primary file is the first data file created and contains information about the location of all other files for the database. All data files for the database must be available whether or not they are specified in the CREATE DATABASE command.
     SQL Server still includes the sp_attach_db stored procedure to re-attach a database, however, this is deprecated and not recommended in SQL Server 2005 and higher. One of the main reasons it's being deprecated is because you can only specify up to 16 files, unlike the CREATE DATABASE command which allows you to specify up to 32,767 files and 32,767 file groups for each database.
    The following sp_attach_db example performs the same actions as the CREATE DATABASE command above and is only included here for the sake of completeness.

    EXEC sp_attach_db
        @dbname = 'AdventureWorksLT'
      , @filename1 = 'G:\MSSQL\Data\AdventureWorksLT_Data.mdf'
      , @filename2 = 'L:\MSSQL\Log\AdventureWorksLT_Log.ldf'
  5. After re-attaching the database, verify the change in file locations by using the sp_helpfile stored procedure.
    USE [AdventureWorksLT]
    Go
    
    EXEC sp_helpfile
    Go
    
    name                   fileid filename                                  }
    ---------------------- ------ ----------------------------------------- } <SNIP>
    AdventureWorksLT_Data  1      G:\MSSQL\Data\AdventureWorksLT_Data.mdf   }
    AdventureWorksLT_Log   2      L:\MSSQL\Log\AdventureWorksLT_Log.ldf     }
  6. Finally, re-enable any database properties that were set before the database was detached. Remember at the beginning of this section that we enabled the cross database ownership chaining property on theAdventureWorksLT database. Because we detached the database, this setting was lost.
    SELECT
        DB_NAME(database_id)  AS "Database Name"
      , is_db_chaining_on     AS "Database Chaining Enabled?"
    FROM
        sys.databases
    WHERE
        database_id = DB_ID('AdventureWorksLT');
    Go
    
    Database Name      Database Chaining Enabled?
    ------------------ --------------------------
    AdventureWorksLT   0
    Run the following ALTER DATABASE command to re-enable the cross database ownership chaining property for the AdventureWorksLT database and then verify the results.
    USE [master]
    Go
    
    ALTER DATABASE [AdventureWorksLT] SET DB_CHAINING ON;
    Go
    
    SELECT
        DB_NAME(database_id)  AS "Database Name"
      , is_db_chaining_on     AS "Database Chaining Enabled?"
    FROM
        sys.databases
    WHERE
        database_id = DB_ID('AdventureWorksLT');
    Go
    
    Database Name      Database Chaining Enabled?
    ------------------ --------------------------
    AdventureWorksLT   1

How to Move the System Databases(2005/2008/2012)

Click4:How to Move User 
Databases(2005/2008/2012)

Contents
  • Introduction
  • Moving the msdb and model Database
  • Moving the master Database
  • Moving the tempdb Database
  • Moving the Resource Database

Introduction

Moving a user database in SQL Server is a fairly common and straightforward DBA task. This process typically involves detaching the database from the server, moving the physical database and log files to a new location, and then attaching the database back to the server while specifying the new file locations. Moving one of the system databases, on the other hand, involves a bit more work.
This guide presents the steps necessary to move the system databases using Transact-SQL as part of a planned relocation or scheduled maintenance operation. The steps in this guide have been successfully tested with SQL Server 2008 R2 and SQL Server 2012. For more information on how to move user databases SQL Server, see the following articles:

Moving the msdb and model Database

The following example moves the msdb and model databases (data and log files) to a new location as part of a planned relocation. Note that this procedure does not apply to moving the master and Resource databases.
  1. Determine the logical file names of the msdb and model database and their current physical location on the disk.
    USE master
    Go
    
    SELECT
        DB_NAME(database_id)  AS "Database Name"
      , name                  AS "Logical File Name"
      , physical_name         AS "Physical File Location"
      , state_desc            AS "State"
    FROM
        sys.master_files
    WHERE
        database_id IN (DB_ID(N'msdb'), DB_ID(N'model'))
    ORDER BY
        DB_NAME(database_id);
    Go
    
    Database Name  Logical File Name  Physical File Location                                   State
    -------------- ------------------ -------------------------------------------------------- --------
    model          modeldev           F:\MSSQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\model.mdf        ONLINE
    model          modellog           F:\MSSQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\modellog.ldf     ONLINE
    msdb           MSDBData           F:\MSSQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\MSDBData.mdf     ONLINE
    msdb           MSDBLog            F:\MSSQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf      ONLINE
  2. For each file to be moved, run the following statement by providing the logical file name and the new physical location of where the file will be moved to.
    ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name , FILENAME = 'new_path\os_file_name' )
    For example, if the planned relocation for the msdb and model data and log files is F:\MSSQL\Data, run the following:
    USE master
    Go
    
    ALTER DATABASE model
        MODIFY FILE ( NAME = 'modeldev' , FILENAME = 'F:\MSSQL\Data\model.mdf' );
    Go
    
    ALTER DATABASE model
        MODIFY FILE ( NAME = 'modellog' , FILENAME = 'F:\MSSQL\Data\modellog.ldf' );
    Go
    
    ALTER DATABASE msdb
        MODIFY FILE ( NAME = 'MSDBData' , FILENAME = 'F:\MSSQL\Data\MSDBData.mdf' );
    Go
    
    ALTER DATABASE msdb
        MODIFY FILE ( NAME = 'MSDBLog' , FILENAME = 'F:\MSSQL\Data\MSDBLog.ldf' );
    Go
  3. Stop the instance of SQL Server. Remember that if you are using a Command Prompt to open an elevated Command Prompt using the Run as administrator option.
    [SQLPROD1] C:\> net stop SQLSERVERAGENT
    [SQLPROD1] C:\> net stop MSSQLSERVER
  4. Move the physical files to the new location.
    [SQLPROD1] C:\> move F:\MSSQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\model.mdf F:\MSSQL\Data\
            1 file(s) moved.
    
    [SQLPROD1] C:\> move F:\MSSQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\modellog.ldf F:\MSSQL\Data\
            1 file(s) moved.
    
    [SQLPROD1] C:\> move F:\MSSQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\MSDBData.mdf F:\MSSQL\Data\
            1 file(s) moved.
    
    [SQLPROD1] C:\> move F:\MSSQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf F:\MSSQL\Data\
            1 file(s) moved.
  5. Restart the instance of SQL Server.
    [SQLPROD1] C:\> net start MSSQLSERVER
    [SQLPROD1] C:\> net start SQLSERVERAGENT
  6. Verify the file change for the msdb and model databases by running the following query.
    USE master
    Go
    
    SELECT
        DB_NAME(database_id)  AS "Database Name"
      , name                  AS "Logical File Name"
      , physical_name         AS "Physical File Location"
      , state_desc            AS "State"
    FROM
        sys.master_files
    WHERE
        database_id IN (DB_ID(N'msdb'), DB_ID(N'model'))
    ORDER BY
        DB_NAME(database_id);
    Go
    
    Database Name  Logical File Name  Physical File Location        State
    -------------- ------------------ ----------------------------- --------
    model          modeldev          F:\MSSQL\Data\model.mdf       ONLINE
    model          modellog           F:\MSSQL\Data\modellog.ldf    ONLINE
    msdb           MSDBData         F:\MSSQL\Data\MSDBData.mdf    ONLINE
    msdb           MSDBLog           F:\MSSQL\Data\MSDBLog.ldf     ONLINE
If the msdb database is moved and the instance of SQL Server is configured for Database Mail, complete these additional steps.
  1. Verify that Service Broker is enabled for the msdb database by running the following query.
    USE master
    Go
    
    SELECT  is_broker_enabled
    FROM    sys.databases
    WHERE   database_id = DB_ID(N'msdb');
    Go
    
    is_broker_enabled
    -----------------
    1
    is_broker_enabled will be 1 if Service Broker is enabled for the given database, otherwise it will be 0.
    If the Service Broker is disabled (is_broker_enabled = 0), run the following T-SQL to enable Service Broker for the msdb database:
    USE master
    Go
    
    ALTER DATABASE msdb SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
    Go
     
    The above ALTER DATABASE command requires an exclusive lock on the database. If there are open connections and the WITH ROLLBACK IMMEDIATE termination clause is not specified, the command will wait (hang) indefinitely until those connections are closed. TheWITH ROLLBACK IMMEDIATE tells the SQL Server that if it can't complete the command right away, then the other pending transactions should be rolled back.
  2. Verify that Database Mail is working by sending a test mail.
    USE msdb
    Go
    
    EXEC sp_send_dbmail
        @profile_name = 'iDevelopmentProfile'
      , @recipients = 'dba@idevelopment.info'
      , @subject = 'MSDB Database Moved'
      , @body = 'This is a test message to verify that
    Database Mail is still functioning after moving the
    MSDB system database.'
    Go
    
    Mail queued.
    If the test message fails, you can review the contents of msdb.dbo.sysmail_event_log to troubleshoot the problem.
    SELECT * FROM msdb.dbo.sysmail_event_log;
    Go

Moving the master Database

The following example moves the master database (data and log files) to a new location as part of a planned relocation.

SQL Server 2012

  1. Open SQL Server Configuration Manager.
  2. In the SQL Server Services node, right-click the instance of SQL Server (for example, ) and choose Properties.
  3. Open Startup Parameters dialog.
    In the SQL Server (instance_name) Properties dialog box, click the Startup Parameters tab.
  4. Edit the Startup Parameters values to point to the planned location for the master database data and log files, and click OK. Moving the error log file is optional.
    The parameter value for the data file must follow the -d parameter and the value for the log file must follow the -l parameter. The following example shows the parameter values for the default location of the master data and log files.
    -dC:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\master.mdf
    -eC:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\LOG\ERRORLOG
    -lC:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
    If the planned relocation for the master data and log file is F:\MSSQL\Data, the parameter values would be changed as follows:
    -dF:\MSSQL\Data\master.mdf
    -eC:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\LOG\ERRORLOG
    -lF:\MSSQL\Data\mastlog.ldf
  5. Stop the instance of SQL Server.
    [SQLPROD1] C:\> net stop SQLSERVERAGENT
    [SQLPROD1] C:\> net stop MSSQLSERVER
  6. Move the master.mdf and mastlog.ldf files to the new location.
    [SQLPROD1] C:\> 
    move "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\master.mdf" F:\MSSQL\Data\
            1 file(s) moved.
    
    [SQLPROD1] C:\> 
    move "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mastlog.ldf" F:\MSSQL\Data\
            1 file(s) moved.
  7. Restart the instance of SQL Server.
    [SQLPROD1] C:\> net start MSSQLSERVER
    [SQLPROD1] C:\> net start SQLSERVERAGENT
  8. Verify the file change for the master database by running the following query.
    USE master
    Go
    
    SELECT
        name                  AS "Logical File Name"
      , physical_name         AS "Physical File Location"
      , state_desc            AS "State"
    FROM
        sys.master_files
    WHERE
        database_id = DB_ID(N'master');
    Go
    
    Logical File Name   Physical File Location            State
    ------------------- --------------------------------- --------
    master              F:\MSSQL\Data\master.mdf          ONLINE
    mastlog             F:\MSSQL\Data\mastlog.ldf         ONLINE

SQL Server 2008 R2

  1. On the Start menu, point to All Programs | Microsoft SQL Server 2008 R2 | Configuration Tools | SQL Server Configuration Manager.
  2. In the SQL Server Services node, right-click the instance of SQL Server (for example, ) and choose Properties.
  3. In the SQL Server (instance_name) Properties dialog box, click the Advanced tab.
  4. Edit the Startup Parameters values to point to the planned location for the master database data and log files, and click OK. Moving the error log file is optional.
    The parameter value for the data file must follow the -d parameter and the value for the log file must follow the -l parameter. The following example shows the parameter values for the default location of the master data and log files.
    -dC:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\master.mdf;
    -eC:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\LOG\ERRORLOG;
    -lC:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
    If the planned relocation for the master data and log file is F:\MSSQL\Data, the parameter values would be changed as follows:
    -dF:\MSSQL\Data\master.mdf;
    -eC:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\LOG\ERRORLOG;
    -lF:\MSSQL\Data\mastlog.ldf
  5. Stop the instance of SQL Server.
    [SQLPROD1] C:\> net stop SQLSERVERAGENT
    [SQLPROD1] C:\> net stop MSSQLSERVER
  6. Move the master.mdf and mastlog.ldf files to the new location.
    [SQLPROD1] C:\> 
    move "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\master.mdf" F:\MSSQL\Data\
            1 file(s) moved.
    
    [SQLPROD1] C:\> 
    move "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\mastlog.ldf" F:\MSSQL\Data\
            1 file(s) moved.
  7. Restart the instance of SQL Server.
    [SQLPROD1] C:\> net start MSSQLSERVER
    [SQLPROD1] C:\> net start SQLSERVERAGENT
  8. Verify the file change for the master database by running the following query.
    USE master
    Go
    
    SELECT
        name                  AS "Logical File Name"
      , physical_name         AS "Physical File Location"
      , state_desc            AS "State"
    FROM
        sys.master_files
    WHERE
        database_id = DB_ID(N'master');
    Go
    
    Logical File Name   Physical File Location            State
    ------------------- --------------------------------- --------
    master              F:\MSSQL\Data\master.mdf          ONLINE
    mastlog             F:\MSSQL\Data\mastlog.ldf         ONLINE

Moving the tempdb Database

The following example moves the tempdb data and log files to a new location as part of a planned relocation.
Because tempdb is re-created each time the instance of SQL Server is started, you do not have to physically move the data and log files. The files are created in the new location when the service is restarted in step 3 (see below). Until the service is restarted, tempdb continues to use the data and log files in the existing location.
  1. Determine the logical file names of the tempdb database and their current physical location on the disk.
    USE master
    Go
    
    SELECT
        name                  AS "Logical File Name"
      , physical_name         AS "Physical File Location"
    FROM
        sys.master_files
    WHERE
        database_id = DB_ID(N'tempdb');
    Go
    
    Logical File Name   Physical File Location
    ------------------- ---------------------------------
    tempdev            T:\MSSQL\TempDB\Data\tempdb.mdf
    templog             T:\MSSQL\TempDB\Log\templog.ldf
  2. Change the location of each file in the system catalog by using the ALTER DATABASE command. The new path will be used the next time the database is started.
    USE master
    Go
    
    ALTER DATABASE tempdb 
        MODIFY FILE (NAME = 'tempdev', FILENAME = 'F:\MSSQL\Data\tempdb.mdf');
    Go
    
    ALTER DATABASE tempdb 
        MODIFY FILE (NAME = 'templog', FILENAME = 'L:\MSSQL\Log\templog.ldf');
    Go
  3. Stop and restart the instance of SQL Server.
    [SQLPROD1] C:\> net stop SQLSERVERAGENT
    [SQLPROD1] C:\> net stop MSSQLSERVER
    
    [SQLPROD1] C:\> net start MSSQLSERVER
    [SQLPROD1] C:\> net start SQLSERVERAGENT
  4. Verify the new physical location(s).
    USE master
    Go
    
    SELECT
        name                  AS "Logical File Name"
      , physical_name         AS "Physical File Location"
    FROM
        sys.master_files
    WHERE
        database_id = DB_ID(N'tempdb');
    Go
    
    Logical File Name   Physical File Location
    ------------------- ---------------------------------
    tempdev             F:\MSSQL\Data\tempdb.mdf
    templog             L:\MSSQL\Log\templog.ldf
  5. Delete the old tempdb.mdf and templog.ldf files from the original location.
    [SQLPROD1] C:\> del T:\MSSQL\TempDB\Data\tempdb.mdf
    [SQLPROD1] C:\> del T:\MSSQL\TempDB\Log\templog.ldf

Moving the Resource Database

A new system database was introduced in SQL Server 2005 called the Resource Database. The Resource database is a read-only database that contains all the system objects that are included with SQL Server. SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user meta data.
The Resource database makes upgrading to a new version of SQL Server an easier and faster procedure. In earlier versions of SQL Server, upgrading required dropping and creating system objects. Because the Resource database file contains all system objects, an upgrade is now accomplished simply by copying the single Resource database file to the local server.
The physical file names of the Resource database are mssqlsystemresource.mdf and mssqlsystemresource.ldf. The location of these files are dependent on which version of SQL Server you are running (as explained in this section). Each instance of SQL Server has one and only one associated mssqlsystemresource.mdf file, and instances do not share this file.
In SQL Server 2008 and higher, the Resource database resides under the following directory and cannot be changed:

SQL Server 2008
<drive>:\Program Files\Microsoft SQL Server\MSSQL10.<instance_name>\MSSQL\Binn\

SQL Server 2008 R2
<drive>:\Program Files\Microsoft SQL Server\MSSQL10_50.<instance_name>\MSSQL\Binn\

SQL Server 2012
<drive>:\Program Files\Microsoft SQL Server\MSSQL11.<instance_name>\MSSQL\Binn\

For example, in SQL Server 2012, the Resource database is located under the directory:

C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn

  mssqlsystemresource.mdf  mssqlsystemresource.ldf

 
Although it was possible to move the Resource database in SQL Server 2005, things changed in SQL Server 2008 and higher where the location of the Resource database can no longer be relocated from its default directory. In SQL Server 2005, the Resource database depended on the location of the master database. The Resource data and log files had to reside together and had to be in the same location as the master data file (master.mdf). Therefore, in SQL Server 2005, if you moved the master database, you had to also move the Resource database to the same location as the master data file. In SQL Server 2008 and higher, the location of the Resource database cannot be moved from its default location.

Click4:How to Move User Databases(2005/2008/2012)

List of all users database roles for all databasesList all users of all databases with all roles


drop procedure [dbo].[List_DBRoles]
go
Create procedure [dbo].[List_DBRoles]
@database nvarchar(128)=null, 
@user varchar(20)=null, 
@dbo char(1)=null, 
@access char(1)=null, 
@security char(1)=null, 
@ddl char(1)=null, 
@datareader char(1)=null, 
@datawriter char(1)=null, 
@denyread char(1)=null, 
@denywrite char(1)=null 

as 
declare @dbname nvarchar(1000) 
declare @mSql1 varchar(8000) 
CREATE TABLE #DBROLES 
( DBName sysname not null, 
UserName sysname not null, 
db_owner varchar(3) not null, 
db_accessadmin varchar(3) not null, 
db_securityadmin varchar(3) not null, 
db_ddladmin varchar(3) not null, 
db_datareader varchar(3) not null, 
db_datawriter varchar(3) not null, 
db_denydatareader varchar(3) not null, 
db_denydatawriter varchar(3) not null, 
Cur_Date datetime not null default getdate() 

DECLARE DBName_Cursor CURSOR FOR 
select name 
from master.dbo.sysdatabases 
where name not in ('mssecurity','tempdb') 
Order by name 
OPEN DBName_Cursor 
FETCH NEXT FROM DBName_Cursor INTO @dbname 
WHILE @@FETCH_STATUS = 0 
BEGIN 
Print @dbname 
Set @mSQL1 = ' Insert into #DBROLES ( DBName, UserName, db_owner, db_accessadmin, 
db_securityadmin, db_ddladmin, db_datareader, db_datawriter, 
db_denydatareader, db_denydatawriter ) 
SELECT '+''''+@dbName +''''+ ' as DBName ,UserName, '+char(13)+ ' 
Max(CASE RoleName WHEN ''db_owner'' THEN ''Yes'' ELSE ''No'' END) AS db_owner, 
Max(CASE RoleName WHEN ''db_accessadmin '' THEN ''Yes'' ELSE ''No'' END) AS db_accessadmin , 
Max(CASE RoleName WHEN ''db_securityadmin'' THEN ''Yes'' ELSE ''No'' END) AS db_securityadmin, 
Max(CASE RoleName WHEN ''db_ddladmin'' THEN ''Yes'' ELSE ''No'' END) AS db_ddladmin, 
Max(CASE RoleName WHEN ''db_datareader'' THEN ''Yes'' ELSE ''No'' END) AS db_datareader, 
Max(CASE RoleName WHEN ''db_datawriter'' THEN ''Yes'' ELSE ''No'' END) AS db_datawriter, 
Max(CASE RoleName WHEN ''db_denydatareader'' THEN ''Yes'' ELSE ''No'' END) AS db_denydatareader, 
Max(CASE RoleName WHEN ''db_denydatawriter'' THEN ''Yes'' ELSE ''No'' END) AS db_denydatawriter 
from ( 
select b.name as USERName, c.name as RoleName 
from ' + @dbName+'.dbo.sysmembers a '+char(13)+ 
' join '+ @dbName+'.dbo.sysusers b '+char(13)+ 
' on a.memberuid = b.uid join '+@dbName +'.dbo.sysusers c 
on a.groupuid = c.uid )s 
Group by USERName 
order by UserName' 
--Print @mSql1 
Execute (@mSql1) 
FETCH NEXT FROM DBName_Cursor INTO @dbname 
END 
CLOSE DBName_Cursor 
DEALLOCATE DBName_Cursor 

Select @@SERVERNAME as [Servername], * from #DBRoles 
where ((@database is null) OR (DBName LIKE '%'+@database+'%')) AND 
((@user is null) OR (UserName LIKE '%'+@user+'%')) AND 
((@dbo is null) OR (db_owner = 'Yes')) AND 
((@access is null) OR (db_accessadmin = 'Yes')) AND 
((@security is null) OR (db_securityadmin = 'Yes')) AND 
((@ddl is null) OR (db_ddladmin = 'Yes')) AND 
((@datareader is null) OR (db_datareader = 'Yes')) AND 
((@datawriter is null) OR (db_datawriter = 'Yes')) AND 
((@denyread is null) OR (db_denydatareader = 'Yes')) AND 
((@denywrite is null) OR (db_denydatawriter = 'Yes')) 
 


Output:
EXEC [dbo].[List_DBRoles]