Friday, 15 April 2016

Add more tempdb files

USE [master];
GO
ALTER DATABASE [tempdb] ADD FILE (NAME = N'tempdev2', FILENAME = N'T:\MSSQL\DATA\tempdev2.ndf' , SIZE = 8GB , FILEGROWTH = 0);
ALTER DATABASE [tempdb] ADD FILE (NAME = N'tempdev3', FILENAME = N'T:\MSSQL\DATA\tempdev3.ndf' , SIZE = 8GB , FILEGROWTH = 0);
ALTER DATABASE [tempdb] ADD FILE (NAME = N'tempdev4', FILENAME = N'T:\MSSQL\DATA\tempdev4.ndf' , SIZE = 8GB , FILEGROWTH = 0);
GO

TSQL backup all databases script

DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
-- specify database backup directory
SET @path = 'C:\db\backup\'
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb') -- exclude these databases
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @fileName = @path + @name + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName
FETCH NEXT FROM db_cursor INTO @name
END
DEALLOCATE db_cursor

Friday, 1 April 2016

TSQL How to Manually Failover a SQL Server Database Mirroring Session

USE master;
ALTER DATABASE [Database_Name] SET PARTNER FAILOVER
The mirror database becomes the principal and the principal database becomes the mirror, clients are disconnected from the former principal database and active transactions are rolled back:
“Nonqualified transactions are being rolled back. Estimated rollback completion: 100%.”
If you try to manually failover SQL Server database mirroring session when the database is NOT in the SYNCHRONIZED state, you will get an error message:
Msg 1422, Level 16, State 2, Line 2
The mirror server instance is not caught up to the recent changes to database “Database_Name”. Unable to fail over.

Set Up SQL Server Mirroring T-SQL Script


The first thing you need to do when setting up Database Mirroring is perform a full backup followed by a transaction log backup on the principal server.  You then must restore these to the mirror server using the WITH NORECOVERY option of the RESTORE command.  

/*Create endpoints on both servers*/

CREATE ENDPOINT EndPointName
STATE=STARTED AS TCP(LISTENER_PORT = PortNumber, LISTENER_IP = ALL)
FOR DATA_MIRRORING(ROLE = PARTNER, AUTHENTICATION = WINDOWS NEGOTIATE, ENCRYPTION = REQUIRED ALGORITHM RC4)

/*Set partner and setup job on mirror server*/

ALTER DATABASE DatabaseName SET PARTNER = N'TCP://PrincipalServer:PortNumber'
EXEC sys.sp_dbmmonitoraddmonitoring -- default is 1 minute

/*Set partner, set asynchronous mode, and setup job on principal server*/

ALTER DATABASE DatabaseName SET PARTNER = N'TCP://MirrorServer:PortNumber'
ALTER DATABASE DatabaseName SET SAFETY OFF
EXEC sys.sp_dbmmonitoraddmonitoring -- default is 1 minute

/*FAILOVER */

ALTER DATABASE <database_name> SET PARTNER FAILOVER
ALTER DATABASE <database_name> SET PARTNER FORCE_SERVICE_ALLOW_DATA_LOSS