SQL SERVER – Move Data Files

Here is how you can move data files in SQL Server.

1. Retrieve DB LogicalName and current location.

SELECT name, physical_name, state_desc AS OnlineStatus
FROM sys.master_files  
WHERE database_id = DB_ID(N'AdventureWorks2014')  
GO

2. Set Database offline.

ALTER DATABASE AdventureWorks2014 SET OFFLINE;
GO

3. If your database it is taking too slow to become offline, you should kill all session ID’s that are connected to the database (including the sleeping connections). I have a script below to do just that. Just specify the database name for the @DBName variable.

DECLARE @DBName VARCHAR(50) = 'AdventureWorks2014'
DECLARE @sql NVARCHAR (500)
DECLARE @spid INT
DECLARE @numberOfRowsToKill INT
DECLARE @i INT = 0
DECLARE @sessionID INT

SET NOCOUNT ON

SET @sql = 'sp_who'

IF OBJECT_ID('tempdb..#spids') IS NOT NULL
	DROP TABLE #spids

CREATE TABLE #spids
(
	spid INT,
	ecid INT,
	status VARCHAR(30),
	loginname VARCHAR(30),
	HostName VARCHAR(50),
	Blk INT,
	DBName VARCHAR(30),
	Command VARCHAR(MAX),
	RequestID INT
)

INSERT INTO #spids
EXEC (@sql)


SELECT @numberOfRowsToKill = COUNT(*) FROM #spids WHERE DBName = @DBName

IF  @i < @numberOfRowsToKill
	WHILE @i < @numberOfRowsToKill
	BEGIN
		SELECT TOP 1 @sessionID = spid from #spids WHERE DBName = @DBName
		SET @sql =  'kill ' + CAST(@sessionID AS NVARCHAR(10))

		EXEC (@sql)
		PRINT 'SPID ' + CAST(@sessionID AS VARCHAR) + ' has been killed'

		DELETE FROM #spids WHERE spid = @sessionID
		SET @i = @i + 1
	END
ELSE
	PRINT 'There are no more sessions connected to ' + @DBName + ' database.'


Preview(opens in a new tab)

4. Move the physical files using Powershell. Run Powershell as Administrator and run the following command.

Move-Item -Path "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\CreditData.mdf" -Destination "C:\SQL\DATA"

Move-Item -Path "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\CreditLog.ldf" -Destination "C:\SQL\DATA"

5. Modify the file name. Specify the new file path.

ALTER DATABASE AdventureWorks2014 MODIFY FILE (NAME = 'LogicalName'	,FILENAME = 'C:\SQL\DATA\CreditData.mdf')
GO

ALTER DATABASE AdventureWorks2014 MODIFY FILE (NAME = 'LogicalName',FILENAME = 'C:\SQL\DATA\CreditLog.ldf')
GO

6. Set database online.

ALTER DATABASE AdventureWorks2014 SET ONLINE;
GO

7. Verify that the change is okay.

SELECT name, physical_name, state_desc AS OnlineStatus
FROM sys.master_files  
WHERE database_id = DB_ID(N'AdventureWorks2014')  
GO

Cheers!

Knowledge worth sharing...Share on linkedin
Linkedin
Share on facebook
Facebook
Share on google
Google
Share on twitter
Twitter

POWERSHELL – Running scripts is disabled on this system (SOLVED)

I encountered the following error after executing a script in Powershell.

The reason for this error is because the Execution Policy is set to Restricted by default. We have to change it to prevent this error by running the script below.

PS C:\> Set-ExecutionPolicy RemoteSigned

Verify the change.

PS C:\> get-executionpolicy

You can also run the script below to bypass the policy.

c:\> powershell -ExecutionPolicy ByPass -File script.ps1

Cheers!

PowerShell – Send SMTP Email and Add Message Body Sent from Script Using PowerShell

This is the first PowerShell script that I wrote. I was inspired to start using PowerShell after I met with one of our developers. He creates scripts to automate repetitive​​ administrative tasks (e.g. daily system health check). I asked the developer if he learned writing PowerShell from a book or a training class. ​​ He said that he neither read any book nor attend a PowerShell training class. Instead, he told me that he just knows what he wanted to achieve and then he searched the internet on how to achieve it. In other words, he just Googled the codes.

 

I always wanted to learn PowerShell. ​​ As a DBA, I think it would be beneficial to use this powerful tool. I read books about​​ PowerShell and did the exercises but I feel I never progressed and I’m still not able to create anything.​​ 

 

So I tried to do what the developer told me. First, I started to think what I want to achieve and that is to send disk space usage of our Database Servers to my email. ​​ This is so that I won’t have to login to our DB servers everytime.

Below is the PowerShell script.

 

#.SYNOPSIS

# Sends Daily Disk Space Usage Report

#

#EXAMPLE

#.\Send-DiskSpaceUsageReport.ps1

#

 

$smtpServer​​ =​​ "Fsmtp.our.property.com.sg"

$smtpFrom​​ =​​ "NXPOPARVRAPPLE@nhg.local"

$smtpTo​​ =​​ "valenciajec@ncs.com.sg"

$messageSubject​​ =​​ "OPAS TTSH Daily Disk Space Usage Report"

 

[string]$messagebody​​ =​​ ""

 

$logs​​ =​​ Get-Content​​ D:\DBA\DB_Health_Checks_Node1\6.DiskUsage_Node1_/TTSH.txt,​​ \\10.240.xx.xx\d$\DBA\DB_Health_Checks_Node2\2.DiskUsage_Node2_TTSH.txt

 

foreach​​ ($log​​ in​​ $logs​​ )

{

 ​​ ​​ ​​​​ $messagebody​​ =​​ $messagebody​​ +​​ $log​​ +​​ "`r`n"

}

 

$smtp​​ =​​ New-Object​​ Net.Mail.SmtpClient($smtpServer)

$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)​​ 

 

 

This script will add a message body to emails sent from script. I have a SQL Server Agent job that generates the text file that contains the disk space usage report. So basically, the PowerShell script will get the contents of the text​​ file and add it to the message body of the email.

 

 

 

 

The next step is to​​ create a Scheduled Task​​ to run the PowerShell script.

 

  • Open Task Scheduler

 

Open Task Scheduler and Create a new task. Name it and set your security options.  Check "Run with highest​​ privileges" as our scripts need to run as admin. Choose “Run whether user is logged on or not.”

 

 

 

 

 

 

  • Set Triggers

 

 

 

 

  • Create your Action

 

Click on Actions tab and click New.

Action: Start a program

Program /script: PowerShell.exe

 

You don’t need to​​ put a path as it should already be on your system

 

  • Set Argument

 

You first need to set the​​ ExecutionPolicy. There are two options to do that either you set the ExecutionPolicy on the machine or on a per-script basis. I will only set it on a per-script basis but If you want to set the execution policy globally, you can issue this command from within PowerShell.

 

Set-ExecutionPolicy Unrestricted

 

To set the ExecutionPolicy on a​​ per script basis, put the line below on the Add arguments (change the file name to​​ your script’s file name.ps1)

 

 

 ​​ ​​ ​​ ​​ ​​ ​​​​ -ExecutionPolicy Bypass -File D:\DBA\Scripts\PowerShell\Send-DiskSpaceUsageReport.ps1

 

  

  Indicate the path of your script in the Start in(optional)

 

 

 

 

  • Change Settings

 

I encountered the error “Launch request​​ ignored, instance already running (154257)”and the task failed to run. ​​ To resolve this issue, I changed the setting to “Stop the existing instance” ​​ 

 

 

 

  • Save and Test