You are on page 1of 18

1)How to Move TempDB to New Drive in SQL Server

Introduction

This article explains the steps you must follow to move TempDB database
from one drive to another in SQL Server. However, for the changes to come
into effect you must restart SQL Server Service.

Overview of Steps to move TempDB data and log files to new location
are:-

1. Identify the location of TempDB Data and Log Files


2. Change the location of TempDB Data and Log files using ALTER
DATABASE
3. Stop and Restart SQL Server Service
4. Verify the File Change
5. Delete old tempdb.mdf and templog.ldf files

Identify the location of TempDB Data and Log Files

In the New Query window of SQL Server Management Studio, execute the
below mentioned script to identify the location of TempDB data and log file.

Use master
GO

SELECT 
name AS [LogicalName]
,physical_name AS [Location]
,state_desc AS [Status]
FROM sys.master_files
WHERE database_id = DB_ID(N'tempdb');
GO

Once you have identified the location of TempDB files then the next step
will be to create the respective folders on the new drive where you would
like to store the TempDB data and log file. However, you need to make sure
that the new location where the TempDB files are stored is accessible by
SQL Server. i.e., you need to ensure that the Account under which SQL
Server Service is running has read and write permissions on the folder
where the files are stored.

Change the location of TempDB Data and Log files using ALTER
DATABASE

Execute the below ALTER DATABASE command to change the location of


TempDB Data and Log file in SQL Server.

USE master;
GO

ALTER DATABASE tempdb 


MODIFY FILE (NAME = tempdev, FILENAME = 'T:\MSSQL\DATA\
tempdb.mdf');
GO

ALTER DATABASE tempdb 


MODIFY FILE (NAME = templog, FILENAME = 'T:\MSSQL\DATA\
templog.ldf');
GO

Once the above script has executed successfully you will receive a message
to restart SQL Server Service for the changes to come into effect.

The file "tempdev" has been modified in the system catalog. The new
path will be used the next time the database is started.
The file "templog" has been modified in the system catalog. The new
path will be used the next time the database is started.

Stop and Restart SQL Server Service

Stop and restart the instance of SQL Server for the changes to come into
effect.

Verify the File Change

Execute the below TSQL to verify whether TempDB Data and Log files are
residing in the new location.
Use master
GO

SELECT 
name AS [LogicalName]
,physical_name AS [Location]
,state_desc AS [Status]
FROM sys.master_files
WHERE database_id = DB_ID(N'tempdb');
GO

Delete old tempdb.mdf and templog.ldf files

Final step will be to delete the tempdb.mdf & templog.ldf files from the
original location.

Important Note: SQL Server doesn’t support moving TempDB


Database using backup/restore and by using detach database
methods.

Error Message Received when you try Backup and Restore Method

Msg 3147, Level 16, State 3, Line 1 


Backup and restore operations are not allowed on database tempdb. 
Msg 3013, Level 16, State 1, Line 1 
BACKUP DATABASE is terminating abnormally.

Error Message Received when you try Detach Method

Msg 7940, Level 16, State 1, Line 1 


System databases master, model, msdb, and tempdb cannot be detached.

2) HOW TO PUT INSTANCE IN SINGLE USER MODE


What is single-user mode?
There are certain situations when user may have to start a SQL Server
instance in single-user mode. For example, you might need to restore your
master database from a backup in the event of a failure or damage, detach
the database and kill all the connections. Both actions require starting an
instance of SQL Server in single-user maintenance mode.
When a database is started in single-user mode, the following events occur:
 Any current connections to the database are dropped without warning
 Only one user can connect to the database
 The CHECKPOINT process is not started
I’m going to walk you through the process of putting your SQL Server
database into single-user mode. This can be either done via SQL Server
Configuration Manager by setting the startup parameters or through the
Command Prompt.
Method 1: Start SQL Server in single-user mode through SQL Server
Configuration Manager
Run SQL Server Configuration Manager. Choose SQL Server Services from
the left panel and then right-click on desired SQL Server service that needs
to run in single-user mode. Select Properties from the drop-down menu.

In SQL Server 2014 or 2012, click Startup Parameters tab. Type -m in


the Specify a startup parameter box and then click Add.
If you’ve installed SQL Server 2008, 2005 or an earlier version,
click Advanced tab. Append the ;-m to the end of the Startup
Parameters box.
Click Apply to save your changes. Restart your SQL Server instance and it
should then run in single-user mode.
Method 2: Start SQL Server in single-user mode through Command
Prompt
First of all, you need to figure out the name of your SQL Server instance.
Press Windows key + R to bring up the Run box. Type services.msc and
press Enter to open the Services window.
Find your desired SQL Server service in the list, double click it. This will
open the Properties dialog box for that service. Copy the service name
listed there. In my example, the service name is MSSQL$SQLEXPRESS.
Open up a Command Prompt with administrative privileges and run the
following command to stop the SQL Server service.
net stop service_name
The next step is to start the service in single-user mode. This is done by
specifying /m parameter with net startcommand.

How to know if a running SQL Server instance is in single-user mode


When your SQL Server instance is started in single-user mode, it prevents
multiple clients from connecting to the server at the same time. For
example, if you’ve already connected to your DB with the SA account, and
then try to login again through SQL Server Management Studio (SSMS),
you’ll get the following error message:
Login failed for user”. Reason: Server is in single user mode. Only one
administrator can connect at this time. (Microsoft SQL Server, Error: 18461)

To fix this issue, you need to remove -m from the startup parameters and
restart your SQL Server instance, which will bring the database back to
multi-user mode.

3) What are the different database user access modes for the Sql
Server database and their meanings?

Following are the three possible different user access modes in Sql server:

i) SINGLE_USER Database Access Mode

In SINGLE_USER access mode at any given point of time only one user can
access the database. The user can be any user who has access to the
database.

Note: Before setting the database to Single user mode make sure to STOP
the sql server agent or see if any AUTO_UPDATE_STATISTICS_ASYNC
option is set to OFF. Otherwise the Sql Server Agent or the background
thread which updates the stats may utilize the only allowed connection.

ii) RESTRICTED_USER Access Mode

In RESTRICTED_USER access mode only the users who have db_owner or


db_creator permission can access. Users who belong to the sysadmin fixed
server role can also access the database which is in RESTRICTED_USER
access mode.
At any given point of time ZERO or Many user can access the database as
long as they have specified permission as mentioned previously.

iii) MULTI_USER Access Mode

This is the default database user access mode. In this database user access
mode any user who have permission to access the database can access the
database.

2. How to SET database to different user access modes?

For this Demo let us first create a sample demo database with below
statement:

CREATE DATABASE JANARDHAN

GO

i) How to SET database to SINGLE_USER Database Access Mode?

We can use script like below to SET database to SINGLE_USER Database


Access Mode

USE JANARDHAN

GO

ALTER DATABASE JANARDHAN

SET SINGLE_USER WITH ROLLBACK IMMEDIATE

When database is in single user mode and if already one user is connected
to the database, then subsequent database connection request will fail with
an error message like below:

Msg 924, Level 14, State 1, Line 1


Database ‘JANARDHAN’ is already open and can only have one user at a
time.

ii) How to SET database to RESTRICTED_USER Database Access Mode?


We can use script like below to SET database to RESTRICTED_USER
Database Access Mode

USE JANARDHAN

GO

ALTER DATABASE JANARDHAN

SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE

iii) How to SET database to MULTI_USER Database Access Mode?

We can use script like below to SET database to MULTI_USER Database


Access Mode

USE JANARDHAN

GO

ALTER DATABASE JANARDHAN

SET MULTI_USER

GRAPHICALLY

SQL Server 2017:

right-click on the DB > Properties > Options > [Scroll down] State >
RestrictAccess > select Multi_user and click OK

NOTE: “WITH ROLLBACK IMMEDIATE” ALTER Database option causes all


the incomplete transactions to be rolled back and any other connections to
the database to be immediately disconnected.

3. How to check database current user access mode?


Below examples show how we can check the current database user access
mode:

Example 1: We can use the DATABASEPROPERTYEX() function to check


the database user access mode.

SELECT DATABASEPROPERTYEX('DATABASE_NAME','UserAccess')

                      AS 'Current Database Access Mode'

4) How to Recover SA Password on Microsoft SQL Server

If you ever lost SA password, you may have thought your only option is to
reinstall SQL Server and re-attach all of the user databases. However, SQL
server provides a much better disaster recovery method which preserves
objects and data in the master database. Simply start SQL Server in single
user mode and you can recover SA password easily with the OSQL
command. Here are the detailed steps:
Part 1: Start SQL Server in Single User Mode
1. Open SQL Server Configuration Manager.
2. Find the SQL Server instance you need to recover the SA password.
3. Stop the SQL Server instance.
4. Right-click on the instance and select Properties.
5. Click on the Advanced tab, and add -m; to the beginning of Startup
parameter.
6. Click OK and start the instance.
Part 2: Recover SQL Server SA Password
1. Open an elevated command prompt and enter the command:
osql -S myServer\instanceName -E
Replace myServer\instanceName with the name of the computer and
the instance of SQL Server that you want to connect to.
2. At the next prompts, enter the following commands:
1> alter login sa enable
2> go
1> sp_password NULL,'new_password','sa'
2> go
1> quit
3. Stop the SQL Server instance.
4. Remove the -m option from the Start parameters field, and then start
the SQL Server service.
5) Options to Reset Forgotten SQL Server 2017 Password

Forgot the SA password for your SQL Server 2012 instance? If you have
tried to access the database too many times with wrong passwords, the SA
account may be locked out. In this tutorial we’ll show you two options to
take control of your SQL Server 2012 by either adding a sysadmin account
or resetting the SA password.
Option 1: Reset SQL Server 2012 Password in Single-user Mode
1. Launch the SQL Server Configuration Manager utility. Look for your SQL
Server 2012 instance and stop the service.

2. Open a Command Prompt with admin privileges, run the following


command to start SQL Server 2012 in single-user mode:
net start MSSQL$SQLEXPRESS /m"SQLCMD"
Be sure to change MSSQL$SQLEXPRESS to the service name of your SQL
Server instance. Each instance has its own SQL Server service. The service
name could be found within the Windows Services panel (services.msc).
3. Use the sqlcmd command to connect to your SQL Server 2012 database
locally. If your SQL Server is installed on a remote computer, make sure
you substitute the . (dot) with the host name of that server.
sqlcmd -E -S .
4. Type the following SQL statement to create a new account and granting it
any server-level permission.
CREATE LOGIN tom WITH PASSWORD = 'P@ssw0rd'
GO
ALTER SERVER ROLE sysadmin ADD MEMBER tom
GO
5. Type exit to quit sqlcmd. Restart your SQL Server 2012 service to get out
of the single-user mode. You can then connect to the database using the
new login you just created.
Option 2: Offline Reset SQL Server 2012 Password
SQL Server creates the user’s password hash, which is stored in the master
database (sysxlogins). With SQL Server Password Changer you can unlock /
reset SQL Server 2012 passwords for the SA and other user accounts.
Here’s how:
1. First of all, you need to stop your SQL Server 2012 instance from within
the SQL Server Configuration Manager utility.
2. Download and install the SQL Server Password Changer program.
3. Start the SQL Server Password Changer program. Click on Open
File button to browse for the master.mdf file. Usually the master.mdf file
is located at C:\Program Files\Microsoft SQL Server\
MSSQL11.SQLEXPRESS\MSSQL\DATA.
4. Once you have clicked on the Open button, the program will display a list
of user accounts for your SQL Server instance. Select the SA account and
click on Change Password button.

5. In the pop-up window, type a new password and click OK. The new
password can be as short or simple as you want, no need to meet the
password complexity requirements.
6. After resetting the SA password, start your SQL Server instance and you
can then login to the SA account successfully.
6) WHAT IS SQL BROWSER SERVICE

To connect directly to a SQL server instance running on a specific port, you


would use the following format:

SERVERNAME\INSTANCENAME,PORTNUMBER

eg:

SQLSVR3\DEVELOPMENT,15032

This will bypass the SQL Browser service query, and connect directly to the
SQL server called “SQLSVR3″ with an instance name of “DEVELOPMENT”
which is running on TCP port 15032.

7)How to Add Datafile.ndf in Production database ?


Or

I have 2TB database in production which has 1 MDF file ,2NDF files i
am Planning to add one more datafile with out any down time in
production ? Can I add file directly to DB right click and add file ?

Ans:

Right click on database ->properties->files->add file(this is your ndf


file)

Script: SELECT name, physical_name FROM sys.database_files;

8)If Model db corrupted, what is the status of Sql


Server Instance
If ur master and model DB is corrupted Your sql server instance will not start.

In the startup process, once SQL has opened and recovered the master database it needs to
bring the other system databases online, starting with TempDB. However, SQL Server cannot
simply locate and open the TempDB files and run crash recovery, as it does for the other system
databases. TempDB is not like the other databases in the instance in that it's not intended to be a
permanent store of data. As such, logging works differently for TempDB; for this database, SQL
Server cannot roll transactions forward, which is part of a normal crash recovery. Therefore,
instead of simply recovering TempDB on startup, SQL Server must return it to a known state, and
the model database provides that known state. What happens is that SQL Server:

1.Locates and opens the existing tempDB data and log files
2.Sets their file sizes to those specfied for tempDB in the system catalogs
3.Recreates or 'clears' (the terms are used interchangeably in the documentation and error logs)
tempDB using model, copying over allocation pages, bitmaps, etc.
If the TempDB files don't exist SQL will create them based off the model database files (much as
it would when a user database is created) and size them according to the file sizes specified for
TempDB in the system catalog

9) can we put master database ldf and mdf file on different location

Master mdf and ldf can be at different folders. Resource db cannot be moved. 

You can put .mdf, .ndf and .ldf files where ever you want. I am giving you the steps to move
system databases here.
 
1 ) To Move system databases model,msdb and tempdb logically, run the below query in Query
Analyzer.
ALTER DATABASE model  MODIFY FILE (NAME = 'modeldev', FILENAME = '<NewPath>\
model.mdf')
ALTER DATABASE model  MODIFY FILE (NAME = 'modellog', FILENAME = '<NewPath>\
modellog.ldf')
ALTER DATABASE msdb   MODIFY FILE (NAME = 'MSDBData', FILENAME = '<NewPath>\
MSDBData.mdf')
ALTER DATABASE msdb   MODIFY FILE (NAME = 'MSDBLog',  FILENAME = '<NewPath>\
MSDBLog.ldf')
ALTER DATABASE tempdb MODIFY FILE (NAME = 'tempdev',  FILENAME = '<NewPath>\
tempdb.mdf')
ALTER DATABASE tempdb MODIFY FILE (NAME = 'templog',  FILENAME = '<NewPath>\
templog.ldf')
 
2 )  Change the master database data and log file paths. Go to the SQL Server configuration
Manager -> SQL Server Services -> select "SQL Server(MSSQLSERVER)" service -> properties ->
Advanced -> "Startup parameters" and change the value for data and log file locations.
 
-d is the parameter for data file path and
-l is the parameter for log file path.
 
Generally the value of "Startup parameters" looks like mentioned in below string.
 
-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
 
we need to change the above parameter to <New Path>
 
-d<New Path>\master.mdf;-eC:\Program Files\Microsoft SQL Server\
MSSQL10_50.MSSQLSERVER\MSSQL\Log\ERRORLOG;-l<New Path>\mastlog.ldf
 
3 ) Stop SQL Server services.
 
4 ) Move system databases master,model,msdb and tempdb physically to New location
 
5 ) Start SQL Server service with /f and trace flag 3608 from command prompt.
net start MSSQLSERVER /f /T3608
 
6 ) move resource database logically to New path from command rompt
sqlcmd -E -S<SQL Server Name> -Q"ALTER DATABASE mssqlsystemresource MODIFY FILE (NAME
= 'data', FILENAME = '<NewPath>\mssqlsystemresource.mdf')"
sqlcmd -E -S<SQL Server Name> -Q"ALTER DATABASE mssqlsystemresource MODIFY FILE (NAME
= 'log',  FILENAME = '<NewPath>\mssqlsystemresource.ldf')"
 
7 ) Move resource database files to corresponding new locaton.
 
8 ) Run the below command from command prompt.
sqlcmd -E -S<SQL Server Name> -Q"ALTER DATABASE mssqlsystemresource SET READ_ONLY"
 
9 ) Stop the SQL Server from command prompt.
net stop MSSQLSERVER
 
10 ) Start the SQL Server from Configuration manager.
 
11 ) you can move the user databases by detach / attach to any location.  

You might also like