SQL Server 2012 Always On Step by Step Configuration

Learn Sql Team

SQL Server 2012 always on Step by step configuration –

Prerequisite to configure always on –

1. Domain accounts for SQL Server services should have local admin   access
2. Two IP addess
One is for Cluster
Other one is for always ON listener
Note – These IP address should be in customer facing sub-net
3. UNC share on any non-cluster server and non-domain controller.
Cluster computer account and each node computer account should have  RW access to this share.

if you are not having domain controller access ask your Window Admin team

– Pre-staged cluster computer account in Active Directory. Account can be pre-staged according to the following article: http://technet.microsoft.com/en-us/library/cc731002.aspx#BKMK_steps_precreating

– Pre-staged AlwaysOn listener computer account in Active Directory. Account can be pre-staged according to the following article: http://technet.microsoft.com/en-us/library/cc731002(WS.10).aspx#BKMK_steps_precreating2

Windows cluster installation: 

1) Install Failover Cluster feature using Server Manager on both/all nodes.

2) Open Failover Cluster Manager and create a new cluster:

Cluster1.PNG
3)…

View original post 621 more words

Advertisements

Create Blocking Alert – SQL 2005 , SQL 2008 R2 and SQL 2012

We often need to create blocking alert in our Production server to capture existing blocking on server and keep record for future analysis.

Here are steps which help us to create blocking alerts-

Either you can receive blocking details through e-mail or you can log event id in application log and configure your monitoring tool to capture from application log.

STEP 1 –  Create SP to capture blocking details and generate e-mail\ event id in application log.

Note –  and datediff(minute, last_batch, getdate()) > 15, through which you can define blocking duration to generate e-mail or event, I am using 15 min

USE [db]

go

/****** Object: StoredProcedure [dbo].[usp_checkForLongRunningBlockers_log] Script Date: 5/18/2015 9:22:50 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[usp_checkForLongRunningBlockers_log]

as

declare @@leadblocker_spid smallint

declare @@dbname nvarchar(128)

declare @@login_time datetime

declare @@last_batch datetime

declare @@open_tran smallint

declare @@status nchar(30)

declare @@hostname nchar(128)

declare @@program_name nchar(128)

declare @@cmd nchar(16)

declare @@loginame nchar(128)

declare @@net_address nchar(12)

declare @@net_library nchar(12)

declare @@string varchar(2000)

select

@@leadblocker_spid = sp.spid,

@@dbname = db_name(sp.dbid),

@@login_time = login_time,

@@last_batch = last_batch,

@@open_tran = open_tran,

@@status = sp.status,

@@hostname = hostname,

@@program_name = program_name,

@@cmd = cmd,

@@loginame = loginame,

@@net_address = net_address,

@@net_library = net_library

FROM master.dbo.sysprocesses sp

LEFT JOIN sys.dm_exec_requests er

ON er.session_id = sp.spid

OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) AS qt

WHERE spid IN (SELECT blocked FROM master.dbo.sysprocesses)

AND blocked = 0

and datediff(minute, last_batch, getdate()) > 15

set @@string =

‘Blocking Details -Date: ‘ + convert(varchar(20), getdate(), 9) + ‘

@@leadblocker_spid = ‘ + convert(varchar(5),@@leadblocker_spid) + ‘

@@dbname = ‘ + @@dbname + ‘

@@login_time = ‘ + convert(varchar(20), @@login_time, 9) + ‘

@@last_batch = ‘ + convert(varchar(20), @@last_batch, 9) + ‘

@@open_tran = ‘ + convert(varchar(5), @@open_tran) + ‘

@@status = ‘ + @@status + ‘

@@hostname = ‘ + @@hostname + ‘

@@program_name = ‘ + @@program_name + ‘

@@cmd = ‘ + @@cmd + ‘

@@loginame = ‘ + @@loginame + ‘

@@net_address = ‘ + @@net_address + ‘

@@net_library = ‘ + @@net_library + ”

if @@leadblocker_spid is null

return

else

–exec dbo.sp_SQLSMTPMail_html

— @vcTo = ‘nshukla@xyz.com’,

— @vcBody = @@string,

— @vcSubject = ‘Long Running Blocking’,

— @vcAttachments = null,

— @vcQuery = null,

— @vcFrom = ‘noreply@xyz.com’,

— @vcCC = ”,

— @vcBCC = ”,

— @vcSMTPServer = ‘nav-mail2.xyz.com’, — put local network smtp server name here

— @cSendUsing = ‘2’,

— @vcPort = ’25’,

— @cAuthenticate = ‘0’,

— @vcDSNOptions = ‘0’,

— @vcTimeout = ’30’,

— @vcSenderName = null,

— @vcServerName = null

EXEC xp_logevent 60000, @@string, error

GO

STEP 2 – Create table to capture blocking history –

USE [db]

GO

/****** Object:  Table [dbo].[BLOCKING_HISTORY]    Script Date: 5/18/2015 9:26:40 AM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

SET ANSI_PADDING ON

GO

CREATE TABLE [dbo].[BLOCKING_HISTORY](

[spid] [smallint] NULL,

[kpid] [smallint] NULL,

[blocked] [smallint] NULL,

[waittype] [varbinary](5000) NULL,

[waittime] [bigint] NULL,

[lastwaittype] [nvarchar](500) NULL,

[waitresource] [nvarchar](500) NULL,

[dbid] [smallint] NULL,

[uid] [smallint] NULL,

[cpu] [int] NULL,

[physical_io] [bigint] NULL,

[memusage] [int] NULL,

[login_time] [datetime] NULL,

[last_batch] [datetime] NULL,

[ecid] [smallint] NULL,

[open_tran] [smallint] NULL,

[status] [nvarchar](500) NULL,

[hostname] [nvarchar](500) NULL,

[program_name] [nvarchar](500) NULL,

[hostprocess] [nvarchar](500) NULL,

[cmd] [nvarchar](500) NULL,

[nt_domain] [nvarchar](500) NULL,

[nt_username] [nvarchar](500) NULL,

[net_address] [nvarchar](500) NULL,

[net_library] [nvarchar](500) NULL,

[loginame] [nvarchar](500) NULL,

[context_info] [varbinary](5000) NULL,

[sql_handle] [varbinary](5000) NULL,

[stmt_start] [int] NULL,

[stmt_end] [int] NULL,

[request_id] [int] NULL

) ON [PRIMARY]

GO

SET ANSI_PADDING OFF

GO

STEP 3 – Create SP to INSERT  blocking details in Blocking History table.

USE [db]

GO

/****** Object:  StoredProcedure [dbo].[usp_blockingEntry]    Script Date: 5/18/2015 9:25:52 AM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE Procedure [dbo].[usp_blockingEntry]

as

begin

SET NOCOUNT ON

declare @blockingcount int  =   ( select count(1) from sys.sysprocesses where blocked 0 )

if @blockingcount > 0

INSERT INTO [dbo].[BLOCKING_HISTORY]

(      spid

,      kpid

,      blocked

,      waittype

,      waittime

,      lastwaittype

,      waitresource

,      dbid

,      uid

,      cpu

,      physical_io

,      memusage

,      login_time

,      last_batch

,      ecid

,      open_tran

,      status

–,    sid

,      hostname

,      program_name

,      hostprocess

,      cmd

,      nt_domain

,      nt_username

,      net_address

,      net_library

,      loginame

,      context_info

,      sql_handle

,      stmt_start

,      stmt_end

,      request_id

)

select

spid

,      kpid

,      blocked

,      waittype

,      waittime

,      lastwaittype

,      waitresource

,      dbid

,      uid

,      cpu

,      physical_io

,      memusage

,      login_time

,      last_batch

,      ecid

,      open_tran

,      status

–,    sid

,      hostname

,      program_name

,      hostprocess

,      cmd

,      nt_domain

,      nt_username

,      net_address

,      net_library

,      loginame

,      context_info

,      sql_handle

,      stmt_start

,      stmt_end

,      request_id

from sys.sysprocesses  where blocked 0

end

GO

STEP – 4 – Create SP to get lead blocker –

USE [db]
GO

/****** Object: StoredProcedure [dbo].[usp_leadblocker] Script Date: 5/18/2015 9:44:39 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create procedure [dbo].[usp_leadblocker]
as

select *
from
(
select
‘Blocking’ as State,
hostname as host,
db_name(dbid) as dbname,
SPID,
blocked,
lastwaittype,
dbid,
login_time,
last_batch,
open_tran,
status,
hostname,
program_name,
cmd,
nt_domain,
nt_username

from sys.sysprocesses (nolock)
where
spid in (
select distinct blocked
from sys.sysprocesses (nolock)
where
blocked 0
and blocked spid
)
and blocked = 0
and blocked spid

union all

select
‘Blocked’ as State,
hostname as host,
db_name(dbid) as dbname,
SPID,
blocked,
lastwaittype,
dbid,
login_time,
last_batch,
open_tran,
status,
hostname,
program_name,
cmd,
nt_domain,
nt_username
from sys.sysprocesses (nolock)
where
blocked 0
and blocked spid
) dt
order by 1 desc

GO

STEP 5 – T- SQL to check SPID text.

DECLARE @sqltext VARBINARY(128)

SELECT @sqltext = sql_handle

FROM sys.sysprocesses

WHERE spid = 64

SELECT TEXT

FROM sys.dm_exec_sql_text(@sqltext)

GO

***************************************

DECLARE @sqltext VARBINARY(128)
SELECT @sqltext = sql_handle
FROM sys.sysprocesses
WHERE spid = 64
SELECT TEXT
FROM ::fn_get_sql(@sqltext)
GO

*****************************

DBCC INPUTBUFFER(64)
GO

*************************

SP_WHO2 64

go

How to grant access on SSIS Server

SSIS access permissions are managed via Component Service under DCOM Config

1. Run  –> dcomcnfg.exe or Component Services -> Computers -> My Computer -> DCOM Config -> MSDTSServer

2.Right click on MSDTSServer or MSDTSServer100 ( based on SQL version )

3.Click properties

4.Click on the Security tab

5.Select Customize and add the users/groups to the Launch/Activation and Access tabs accordingly

6.Add the user to the local Distributed COM Users group

7.Restart the SSIS

How to add user in local Distributed COM Users group

  1. Right-click My Computer>Manage>Configuration>Local Users & Groups
  2. Look for the Distributed COM Users group and add the account.

SQL Server 2012 Upgrade from Standard Edition to Enterprise edition

SQL Server 2012 Upgrade from Standard Edition to Enterprise edition

upgrade1

 

Step 1- Identify SQL executable file  , Right click and run as admin

upgrade2

 

Step 2 – click on Maintenance tab on left hand side.

upgrade3

Step 3- Click on Edition Upgrade

upgrade4

Step 4 – Click Okay

upgrade5

Step 5- Click Next

upgrade6

Step 6 – Click next on Production key

upgrade8

Step 7 – Click check on “I accept the License terms” and then click Next

upgrade7

Step 8 – Select Instance you want to upgrade form “Specify the Instance of SQL Server” and click next

upgrade9

 

Step 9 – Click next

upgrade10

Step 10 – Review upgrade and click Upgrade

upgrade11

 

Step 11 – Click Close

upgrade12

Step 11- Open SSMS and check version.

upgrade13

SSRS – How to convert in Day/Hour/Minute format in SSRS report

Scenario – In my SSRS report i have calculate Age field of Tickets like in 1 Day 2 Hours 20 min format and we are getting values in minute .

Solution –

I have created filed called Age(Minutes) in my SP or query

IN SQL –

datediff(minute,date_created, getdate()) as ‘Age (Minute)’

IN SSRS write expression

=  ( Fields!Age__Minute_.Value ) \ 1400 & ” days ” &  ((( Fields!Age__Minute_.Value ) MOD 1400) \ 60 ) & ” Hours ” & ((( Fields!Age__Minute_.Value ) MOD 1400) MOD 60 ) & ” Minutes “

How Get SQL Server Job Name with help of program name

How Get SQL Server Job Name with help of program name

SQLAgent – TSQL JobStep (Job 0x0854F6E4F9E5AE48B164966C0553C8B0 : Step 4)

Step -1 Create Below function

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE FUNCTION [dbo].[GetJobIdFromProgramName] (

@program_name nvarchar(128)

)

RETURNS uniqueidentifier

AS

BEGIN

DECLARE @start_of_job_id int

SET @start_of_job_id = CHARINDEX(‘(Job 0x’, @program_name) + 7

RETURN CASE WHEN @start_of_job_id > 0 THEN CAST(

SUBSTRING(@program_name, @start_of_job_id + 06, 2) + SUBSTRING(@program_name, @start_of_job_id + 04, 2) +

SUBSTRING(@program_name, @start_of_job_id + 02, 2) + SUBSTRING(@program_name, @start_of_job_id + 00, 2) + ‘-‘ +

SUBSTRING(@program_name, @start_of_job_id + 10, 2) + SUBSTRING(@program_name, @start_of_job_id + 08, 2) + ‘-‘ +

SUBSTRING(@program_name, @start_of_job_id + 14, 2) + SUBSTRING(@program_name, @start_of_job_id + 12, 2) + ‘-‘ +

SUBSTRING(@program_name, @start_of_job_id + 16, 4) + ‘-‘ +

SUBSTRING(@program_name, @start_of_job_id + 20,12) AS uniqueidentifier)

ELSE NULL

END

END

Step – 2

Execute below query –

SELECT *

FROM msdb.dbo.sysjobs

WHERE

job_id = dbo.GetJobIdFromProgramName (‘SQLAgent – TSQL JobStep (Job 0x0854F6E4F9E5AE48B164966C0553C8B0 : Step 4) ‘)

How to create Blocking alert and generate e-mail alert.

Being SQL DBA it’s one of Important task to have real time blocking alert on server.

This example demonstrate how to configure blocking alert and capture blocking

Step 1 – Create SP to check blocking log –

This SP will help to identify blocking on server with specific time ( in this example it’s for 2 min )  and log record with event id 60000 in windows application log , you have change your time period in datediff(minute, last_batch, getdate()) > 2 parameter

USE [Test]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[usp_checkForLongRunningBlockers_log]
as

declare @@leadblocker_spid smallint
declare @@dbname nvarchar(128)
declare @@login_time datetime
declare @@last_batch datetime
declare @@open_tran smallint
declare @@status nchar(30)
declare @@hostname nchar(128)
declare @@program_name nchar(128)
declare @@cmd nchar(16)
declare @@loginame nchar(128)
declare @@net_address nchar(12)
declare @@net_library nchar(12)
declare @@string varchar(2000)

select
@@leadblocker_spid = sp.spid,
@@dbname = db_name(sp.dbid),
@@login_time = login_time,
@@last_batch = last_batch,
@@open_tran = open_tran,
@@status = sp.status,
@@hostname = hostname,
@@program_name = program_name,
@@cmd = cmd,
@@loginame = loginame,
@@net_address = net_address,
@@net_library = net_library
FROM master.dbo.sysprocesses sp
LEFT JOIN sys.dm_exec_requests er
ON er.session_id = sp.spid
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) AS qt
WHERE spid IN (SELECT blocked FROM master.dbo.sysprocesses)
AND blocked = 0
and datediff(minute, last_batch, getdate()) > 2

set @@string =

‘Blocking Details -Date: ‘ + convert(varchar(20), getdate(), 9) + ‘
@@leadblocker_spid = ‘ + convert(varchar(5),@@leadblocker_spid) + ‘
@@dbname = ‘ + @@dbname + ‘
@@login_time = ‘ + convert(varchar(20), @@login_time, 9) + ‘
@@last_batch = ‘ + convert(varchar(20), @@last_batch, 9) + ‘
@@open_tran = ‘ + convert(varchar(5), @@open_tran) + ‘
@@status = ‘ + @@status + ‘
@@hostname = ‘ + @@hostname + ‘
@@program_name = ‘ + @@program_name + ‘
@@cmd = ‘ + @@cmd + ‘
@@loginame = ‘ + @@loginame + ‘
@@net_address = ‘ + @@net_address + ‘
@@net_library = ‘ + @@net_library + ”

if @@leadblocker_spid is null
return
else

EXEC xp_logevent 60000, @@string, error

GO

Step 2 – Create SP to capture all blocking details in table for future reference –

USE [Test]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[usp_blockingEntry]
as
begin
SET NOCOUNT ON
declare @blockingcount int = ( select count(1) from sys.sysprocesses where blocked <> 0 )

if @blockingcount > 0

INSERT INTO [dbo].[BLOCKING_HISTORY]
( spid
, kpid
, blocked
, waittype
, waittime
, lastwaittype
, waitresource
, dbid
, uid
, cpu
, physical_io
, memusage
, login_time
, last_batch
, ecid
, open_tran
, status
–, sid
, hostname
, program_name
, hostprocess
, cmd
, nt_domain
, nt_username
, net_address
, net_library
, loginame
, context_info
, sql_handle
, stmt_start
, stmt_end
, request_id
)

select
spid
, kpid
, blocked
, waittype
, waittime
, lastwaittype
, waitresource
, dbid
, uid
, cpu
, physical_io
, memusage
, login_time
, last_batch
, ecid
, open_tran
, status
–, sid
, hostname
, program_name
, hostprocess
, cmd
, nt_domain
, nt_username
, net_address
, net_library
, loginame
, context_info
, sql_handle
, stmt_start
, stmt_end
, request_id
from sys.sysprocesses where blocked <> 0
end

GO

Now if you have monitoring job which capture event log you can ask your monitoring team to configure monitoring with event id 17063 and description 60000 and you all set.

If your requirement is to generate email –

Step 3- You can use below SP. This SP will generate mail if any blocking occurring more than 2 mins ( Remember you need to configure Database mail server and create SP sp_SQLSMTPMail_HTML ( Find below )

USE [Test]

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[usp_checkForLongRunningBlockers_log]
as

declare @@leadblocker_spid smallint
declare @@dbname nvarchar(128)
declare @@login_time datetime
declare @@last_batch datetime
declare @@open_tran smallint
declare @@status nchar(30)
declare @@hostname nchar(128)
declare @@program_name nchar(128)
declare @@cmd nchar(16)
declare @@loginame nchar(128)
declare @@net_address nchar(12)
declare @@net_library nchar(12)
declare @@string varchar(2000)

select
@@leadblocker_spid = sp.spid,
@@dbname = db_name(sp.dbid),
@@login_time = login_time,
@@last_batch = last_batch,
@@open_tran = open_tran,
@@status = sp.status,
@@hostname = hostname,
@@program_name = program_name,
@@cmd = cmd,
@@loginame = loginame,
@@net_address = net_address,
@@net_library = net_library
FROM master.dbo.sysprocesses sp
LEFT JOIN sys.dm_exec_requests er
ON er.session_id = sp.spid
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) AS qt
WHERE spid IN (SELECT blocked FROM master.dbo.sysprocesses)
AND blocked = 0
and datediff(minute, last_batch, getdate()) > 2

set @@string =

‘Blocking Details -Date: ‘ + convert(varchar(20), getdate(), 9) + ‘
@@leadblocker_spid = ‘ + convert(varchar(5),@@leadblocker_spid) + ‘
@@dbname = ‘ + @@dbname + ‘
@@login_time = ‘ + convert(varchar(20), @@login_time, 9) + ‘
@@last_batch = ‘ + convert(varchar(20), @@last_batch, 9) + ‘
@@open_tran = ‘ + convert(varchar(5), @@open_tran) + ‘
@@status = ‘ + @@status + ‘
@@hostname = ‘ + @@hostname + ‘
@@program_name = ‘ + @@program_name + ‘
@@cmd = ‘ + @@cmd + ‘
@@loginame = ‘ + @@loginame + ‘
@@net_address = ‘ + @@net_address + ‘
@@net_library = ‘ + @@net_library + ”

if @@leadblocker_spid is null
return
else
exec dbo.sp_SQLSMTPMail_html
@vcTo = ‘abc@xxx.com’,
@vcBody = @@string,
@vcSubject = ‘Long Running Blocking’,
@vcAttachments = null,
@vcQuery = null,
@vcFrom = ‘noreply@xxxx.com’,
@vcCC = ”,
@vcBCC = ”,
@vcSMTPServer = ‘xxx’, — put local network smtp server name here

@cSendUsing = ‘2’,
@vcPort = ’25’,
@cAuthenticate = ‘0’,
@vcDSNOptions = ‘0’,
@vcTimeout = ’30’,
@vcSenderName = null,
@vcServerName = null

GO

 

Step 4 – Create  SPs – sp_SQLSMTPMail_HTML

USE [master]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[sp_SQLSMTPMail_HTML]
@vcTo varchar(2048) = null,
@vcBody varchar(8000) = ”,
@vcSubject varchar(255) = null,
@vcAttachments varchar(1024) = null,
@vcQuery varchar(8000) = null,
@vcFrom varchar(128) = null,
@vcCC varchar(2048) = ”,
@vcBCC varchar(2048) = ”,
@vcSMTPServer varchar(255) = ‘xxxx’, — put local network smtp server name here
@cSendUsing char(1) = ‘2’,
@vcPort varchar(3) = ’25’,
@cAuthenticate char(1) = ‘0’,
@vcDSNOptions varchar(2) = ‘0’,
@vcTimeout varchar(2) = ’30’,
@vcSenderName varchar(128) = null,
@vcServerName sysname = null,
@text_or_html char(4) = ‘TEXT’

As

/*
Example of usage…
exec sp_configure ‘show advanced options’, 1
reconfigure with override
exec sp_configure ‘Ole Automation Procedures’, 1
reconfigure with override

exec sp_SQLSMTPMail_html
@vcTo = ‘nshukla@xxx.com’,
@vcBody = ‘<html>
<body>

<h4>I am so AWESOME:</h4>
<table border=”1″>
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>

<h4>That he can modify the &#39sp_SQLSMTPMail&#39 stored procedure:</h4>
<table border=”8″>
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>

<h4>To take HTML formatting:</h4>
<table border=”15″>
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>

<text><br><b>So we can send HTML mail on servers without DB_MAIL configured!</b></text>

</body>
</html>’,
@vcSubject = ‘Blocking details’,
@vcAttachments = ”,
@vcQuery = ”,
@vcFrom = ‘NoREPLY@xxxx.com’,
@html = ‘HTML’

*/

/*******************************************************************/
–Name : sp_SQLSMTPMail
–Server : Generic
–Description : SQL smtp e-mail using CDOSYS, OLE Automation and a
— network smtp server; For SQL Servers running on
— windows 2000.

–Note : Be sure to set the default for @vcSMTPServer above to
— the company network smtp server or you will have to
— pass it in each time.

–Comments : Getting the network SMTP configured to work properly
— may require engaging your company network or
— server people who deal with the netowrk SMTP server.
— Some errors that the stored proc returns relate to
— incorrect permissions for the various SQL Servers to
— use the SMTP relay server to bouce out going mail.
— Without proper permissions the SQL server appears as
— a spammer to the local SMTP network server.

–Parameters : See the ‘Syntax’ Print statements below or call the
— sp with ‘?’ as the first input.

–Date : 08/22/2001
–Author : Clinton Herring

–History :
/*******************************************************************/

Set nocount on

— Determine if the user requested syntax.
If @vcTo = ‘?’
Begin
Print ‘Syntax for sp_SQLSMTPMail (based on CDOSYS):’
Print ‘Exec master.dbo.sp_SQLSMTPMail’
Print ‘ @vcTo (varchar(2048)) – Recipient e-mail address list separating each with a ”;” ‘
Print ‘ or a ”,”. Use a ”?” to return the syntax.’
Print ‘ @vcBody (varchar(8000)) – Text body; use embedded char(13) + char(10)’
Print ‘ for carriage returns. The default is nothing’
Print ‘ @vcSubject (varchar(255))) – E-mail subject. The default is a message from’
Print ‘ @@servername.’
Print ‘ @vcAttachments (varchar(1024)) – Attachment list separating each with a ”;”.’
Print ‘ The default is no attachments.’
Print ‘ @vcQuery (varchar(8000)) – In-line query or a query file path; do not ‘
Print ‘ use double quotes within the query.’
Print ‘ @vcFrom (varchar(128)) – Sender list defaulted to @@ServerName.’
Print ‘ @vcCC (varchar(2048)) – CC list separating each with a ”;” or a ”,”’
Print ‘ The default is no CC addresses.’
Print ‘ @vcBCC (varchar(2048)) – Blind CC list separating each with a ”;” or a ”,”’
Print ‘ The default is no BCC addresses.’
Print ‘ @vcSMTPServer (varchar(255)) – Network smtp server defaulted to your companies network’
Print ‘ smtp server. Set this in the stored proc code.’
Print ‘ @cSendUsing (char(1)) – Specifies the smpt server method, local or network. The’
Print ‘ default is network, a value of ”2”.’
Print ‘ @vcPort (varchar(3)) – The smtp server communication port defaulted to ”25”.’
Print ‘ @cAuthenticate (char(1)) – The smtp server authentication method defaulted to ‘
Print ‘ anonymous, a value of ”0”.’
Print ‘ @vcDSNOptions (varchar(2)) – The smtp server delivery status defaulted to none,’
Print ‘ a value of ”0”.’
Print ‘ @vcTimeout (varchar(2)) – The smtp server connection timeout defaulted to 30 seconds.’
Print ‘ @vcSenderName (varchar(128)) – Primary sender name defaulted to @@ServerName.’
Print ‘ @vcServerName (sysname) – SQL Server to which the query is directed defaulted’
Print ‘ to @@ServerName.’
Print ”
Print ”
Print ‘Example:’
Print ‘sp_SQLSMTPMail ”<user@mycompany.com>”, ”This is a test”, @vcSMTPServer = <network smtp relay server>’
Print ”
Print ‘The above example will send an smpt e-mail to <user@mycompany.com> from @@ServerName’
Print ‘with a subject of ”Message from SQL Server <@@ServerName>” and a’
Print ‘text body of ”This is a test” using the network smtp server specified.’
Print ‘See the MSDN online library, Messaging and Collaboration, at ‘
Print ‘http://www.msdn.microsoft.com/library/ for details about CDOSYS.’
Print ‘subheadings: Messaging and Collaboration>Collaboration Data Objects>CDO for Windows 2000>’
Print ‘Reference>Fields>http://schemas.microsoft.com/cdo/configuration/>smtpserver field’
Print ”
Print ‘Be sure to set the default for @vcSMTPServer before compiling this stored procedure.’
Print ”
Return
End

— Declare variables
Declare @iMessageObjId int
Declare @iHr int
Declare @iRtn int
Declare @iFileExists tinyint
Declare @vcCmd varchar(255)
Declare @vcQueryOutPath varchar(50)
Declare @dtDatetime datetime
Declare @vcErrMssg varchar(255)
Declare @vcAttachment varchar(1024)
Declare @iPos int
Declare @vcErrSource varchar(255)
Declare @vcErrDescription varchar(255)
Declare @html varchar(255)

— Set local variables.
Set @dtDatetime = getdate()
Set @iHr = 0

— Check for minimum parameters.
If @vcTo is null
Begin
Set @vcErrMssg = ‘You must supply at least 1 recipient.’
Goto ErrMssg
End

— CDOSYS uses commas to separate recipients. Allow users to use
— either a comma or a semi-colon by replacing semi-colons in the
— To, CCs and BCCs.
Select @vcTo = Replace(@vcTo, ‘;’, ‘,’)
Select @vcCC = Replace(@vcCC, ‘;’, ‘,’)
Select @vcBCC = Replace(@vcBCC, ‘;’, ‘,’)

— Set the default SQL Server to the local SQL Server if one
— is not provided to accommodate instances in SQL 2000.
If @vcServerName is null
Set @vcServerName = @@servername

— Set a default “subject” if one is not provided.
If @vcSubject is null
Set @vcSubject = ‘Message from SQL Server ‘ + @vcServerName

— Set a default “from” if one is not provided.
If @vcFrom is null
Set @vcFrom = ‘SQL-‘ + Replace(@vcServerName,’\’,’_’)

— Set a default “sender name” if one is not provided.
If @vcSenderName is null
Set @vcSenderName = ‘SQL-‘ + Replace(@vcServerName,’\’,’_’) + ‘@xxxx.com’

— Create the SMTP message object.
EXEC @iHr = sp_OACreate ‘CDO.Message’, @iMessageObjId OUT
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error creating object CDO.Message.’
Goto ErrMssg
End

— Set SMTP message object parameters.
— To
EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘To’, @vcTo
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message parameter “To”.’
Goto ErrMssg
End

— Subject
EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘Subject’, @vcSubject
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message parameter “Subject”.’
Goto ErrMssg
End

— From
EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘From’, @vcFrom
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message parameter “From”.’
Goto ErrMssg
End

— CC
EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘CC’, @vcCC
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message parameter “CC”.’
Goto ErrMssg
End

— BCC
EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘BCC’, @vcBCC
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message parameter “BCC”.’
Goto ErrMssg
End

— DSNOptions
EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘DSNOptions’, @vcDSNOptions
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message parameter “DSNOptions”.’
Goto ErrMssg
End

— Sender
EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘Sender’, @vcSenderName
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message parameter “Sender”.’
Goto ErrMssg
End

— Is there a query to run?
If @vcQuery is not null and @vcQuery <> ”
Begin
— We have a query result to include; temporarily send the output to the
— drive with the most free space. Use xp_fixeddrives to determine this.
— If a temp table exists with the following name drop it.
If (Select object_id(‘tempdb.dbo.#fixeddrives’)) > 0
Exec (‘Drop table #fixeddrives’)

— Create a temp table to work with xp_fixeddrives.
Create table #fixeddrives(
Drive char(1) null,
FreeSpace varchar(15) null)

— Get the fixeddrive info.
Insert into #fixeddrives Exec master.dbo.xp_fixeddrives

— Get the drive letter of the drive with the most free space
— Note: The OSQL output file name must be unique for each call within the same session.
— Apparently OSQL does not release its lock on the first file created until the session ends.
— Hence this alleviates a problem with queries from multiple calls in a cursor or other loop.
Select @vcQueryOutPath = Drive + ‘:\TempQueryOut’ +
ltrim(str(datepart(hh,getdate()))) +
ltrim(str(datepart(mi,getdate()))) +
ltrim(str(datepart(ss,getdate()))) +
ltrim(str(datepart(ms,getdate()))) + ‘.txt’
from #fixeddrives
where FreeSpace = (select max(FreeSpace) from #fixeddrives )

— Check for a pattern of ‘\\*\’ or ‘?:\’.
— If found assume the query is a file path.
If Left(@vcQuery, 35) like ‘\\%\%’ or Left(@vcQuery, 5) like ‘_:\%’
Begin
Select @vcCmd = ‘osql /S’ + @vcServerName + ‘ /E /i’ +
convert(varchar(1024),@vcQuery) +
‘ /o’ + @vcQueryOutPath + ‘ -n -w5000 ‘
End
Else
Begin
Select @vcCmd = ‘osql /S’ + @vcServerName + ‘ /E /Q”‘ + @vcQuery +
‘” /o’ + @vcQueryOutPath + ‘ -n -w5000 ‘
End

— Execute the query
Exec master.dbo.xp_cmdshell @vcCmd, no_output

— Add the query results as an attachment if the file was successfully created.
— Check to see if the file exists. Use xp_fileexist to determine this.
— If a temp table exists with the following name drop it.
If (Select object_id(‘tempdb.dbo.#fileexists’)) > 0
Exec (‘Drop table #fileexists’)

— Create a temp table to work with xp_fileexist.
Create table #fileexists(
FileExists tinyint null,
FileIsDirectory tinyint null,
ParentDirectoryExists tinyint null)

— Execute xp_fileexist
Insert into #fileexists exec master.dbo.xp_fileexist @vcQueryOutPath

— Now see if we need to add the file as an attachment
If (select FileExists from #fileexists) = 1
Begin
— Set a variable for later use to delete the file.
Select @iFileExists = 1

— Add the file path to the attachment variable.
If @vcAttachments is null
Select @vcAttachments = @vcQueryOutPath
Else
Select @vcAttachments = @vcAttachments + ‘; ‘ + @vcQueryOutPath
End
End

— Check for multiple attachments separated by a semi-colon ‘;’.
If @vcAttachments is not null
Begin
If right(@vcAttachments,1) <> ‘;’
Select @vcAttachments = @vcAttachments + ‘; ‘
Select @iPos = CharIndex(‘;’, @vcAttachments, 1)
While @iPos > 0
Begin
Select @vcAttachment = ltrim(rtrim(substring(@vcAttachments, 1, @iPos -1)))
Select @vcAttachments = substring(@vcAttachments, @iPos + 1, Len(@vcAttachments)-@iPos)
EXEC @iHr = sp_OAMethod @iMessageObjId, ‘AddAttachment’, @iRtn Out, @vcAttachment
IF @iHr <> 0
Begin
EXEC sp_OAGetErrorInfo @iMessageObjId, @vcErrSource Out, @vcErrDescription Out
Select @vcBody = @vcBody + char(13) + char(10) + char(13) + char(10) +
char(13) + char(10) + ‘Error adding attachment: ‘ +
char(13) + char(10) + @vcErrSource + char(13) + char(10) +
@vcAttachment
End
Select @iPos = CharIndex(‘;’, @vcAttachments, 1)
End
End

— TextBody
IF @html = ‘TEXT’
BEGIN
EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘TextBody’, @vcBody
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message parameter “TextBody”.’
Goto ErrMssg
End
END
ELSE
BEGIN
EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘HTMLBody’, @vcBody
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message parameter “TextBody”.’
Goto ErrMssg
End
END
— Other Message parameters for reference
–EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘MimeFormatted’, False
–EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘AutoGenerateTextBody’, False
–EXEC @iHr = sp_OASetProperty @iMessageObjId, ‘MDNRequested’, True

— Set SMTP Message configuration property values.
— Network SMTP Server location
EXEC @iHr = sp_OASetProperty @iMessageObjId,
‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/smtpserver&#8221;).Value’,
@vcSMTPServer
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message configuraton field “smtpserver”.’
Goto ErrMssg
End

— Sendusing
EXEC @iHr = sp_OASetProperty @iMessageObjId,
‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/sendusing&#8221;).Value’,
@cSendUsing
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message configuraton field “sendusing”.’
Goto ErrMssg
End

— SMTPConnectionTimeout
EXEC @iHr = sp_OASetProperty @iMessageObjId,
‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/SMTPConnectionTimeout&#8221;).Value’,
@vcTimeout
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message configuraton field “SMTPConnectionTimeout”.’
Goto ErrMssg
End

— SMTPServerPort
EXEC @iHr = sp_OASetProperty @iMessageObjId,
‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/SMTPServerPort&#8221;).Value’,
@vcPort
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message configuraton field “SMTPServerPort”.’
Goto ErrMssg
End

— SMTPAuthenticate
EXEC @iHr = sp_OASetProperty @iMessageObjId,
‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/SMTPAuthenticate&#8221;).Value’,
@cAuthenticate
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error setting Message configuraton field “SMTPAuthenticate”.’
Goto ErrMssg
End

— Other Message Configuration fields for reference
–EXEC @iHr = sp_OASetProperty @iMessageObjId,
–‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/SMTPUseSSL&#8221;).Value’,True

–EXEC @iHr = sp_OASetProperty @iMessageObjId,
–‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/LanguageCode&#8221;).Value’,’en’

–EXEC @iHr = sp_OASetProperty @iMessageObjId,
–‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/SendEmailAddress&#8221;).Value’, ‘Test User’

–EXEC @iHr = sp_OASetProperty @iMessageObjId,
–‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/SendUserName&#8221;).Value’,null

–EXEC @iHr = sp_OASetProperty @iMessageObjId,
–‘Configuration.Fields(“http://schemas.microsoft.com/cdo/configuration/SendPassword&#8221;).Value’,null

— Update the Message object fields and configuration fields.
EXEC @iHr = sp_OAMethod @iMessageObjId, ‘Configuration.Fields.Update’
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error updating Message configuration fields.’
Goto ErrMssg
End

EXEC @iHr = sp_OAMethod @iMessageObjId, ‘Fields.Update’
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error updating Message parameters.’
Goto ErrMssg
End

— Send the message.
EXEC @iHr = sp_OAMethod @iMessageObjId, ‘Send’
IF @iHr <> 0
Begin
Set @vcErrMssg = ‘Error Sending e-mail.’
Goto ErrMssg
End
Else
Print ‘Mail sent.’

Cleanup:
— Destroy the object and return.
EXEC @iHr = sp_OADestroy @iMessageObjId
–EXEC @iHr = sp_OAStop

— Delete the query output file if one exists.
If @iFileExists = 1
Begin
Select @vcCmd = ‘del ‘ + @vcQueryOutPath
Exec master.dbo.xp_cmdshell @vcCmd, no_output
End
Return

ErrMssg:
Begin
Print @vcErrMssg
If @iHr <> 0
Begin
EXEC sp_OAGetErrorInfo @iMessageObjId, @vcErrSource Out, @vcErrDescription Out
Print @vcErrSource
Print @vcErrDescription
End

— Determine whether to exist or go to Cleanup.
If @vcErrMssg = ‘Error creating object CDO.Message.’
Return
Else
Goto Cleanup
End

GO

SQL Server 2012 Always On Step by Step Configuration

SQL Server 2012 always on Step by step configuration –

Prerequisite to configure always on –

1. Domain accounts for SQL Server services should have local admin   access
2. Two IP addess
One is for Cluster
Other one is for always ON listener
Note – These IP address should be in customer facing sub-net
3. UNC share on any non-cluster server and non-domain controller.
Cluster computer account and each node computer account should have  R\W access to this share.

if you are not having domain controller access ask your Window Admin team

– Pre-staged cluster computer account in Active Directory. Account can be pre-staged according to the following article: http://technet.microsoft.com/en-us/library/cc731002.aspx#BKMK_steps_precreating

– Pre-staged AlwaysOn listener computer account in Active Directory. Account can be pre-staged according to the following article: http://technet.microsoft.com/en-us/library/cc731002(WS.10).aspx#BKMK_steps_precreating2

Windows cluster installation: 

1) Install Failover Cluster feature using Server Manager on both/all nodes.

2) Open Failover Cluster Manager and create a new cluster:

Cluster1.PNG
3) In “Select Servers” step add all your cluster nodes. Click Next.

4) Pass the validation, all test. Warnings regarding storage are OK – you’re setting up AlwaysOn, so you don’t have shared storage.

5) Specify cluster name and IP address on the next screen. If cluster account was pre-staged make sure to specify correct name (same as the pre-staged computer account name). Make sure to use IP, that was provided by customer and is 100% not in use.

6) Finish cluster installation.

7) Configure quorum or the newly created cluster:

How to configure Quorun –

a. Right Click on Cluster Name –> More action –>Configure Cluster Quorum setting

b) On the “Select Quorum Configuration Option” window select “Select the quorum witness”. Click “Next”.

c) On the “Select Quorum Witnes” window select “Configure a file share witness”. Click “Next”.

d) Specify a file share path, provided by the customer. Click “Next”

e) Click “Next”, then “Finish”

Installing SQL Server:

1) Install SQL Server as a stand-alone instance.

2) Following components are required and recommended for basing SQL Server installation:

SQLInstallation1.PNG

3) Complete the installation.

4) Make sure to add SQL Server service account to sysadmins at each instance. This is required.

Enabling AlwaysOn on instance level:

1) Open SQL Server configuration manager.

2) Select SQL Server Services in the left-side menu.

3) Right click SQL Server service and select “Properties”:

SQLConfiguration1.PNG
4) Go to “AlwaysOn High Availablity Tab” and check “Enable AlwaysOn Availability Groups”:

5) Click “OK”. Make sure to restart SQL Server service.

6) Repeat 1-5 on each node.

Configuring AlwaysOn high availability group (single interface option)

Please skip to the next part if you want to use separate NICs for mirroring traffic and user connections.

1) Open SQL Server Management studio and connect to the first node.

2) Open AlwaysOn High Availablity -> Availablity groups and select “New Availability Group” (make sure to use 2012 Management Studio):

3) In the new window enter availability group name (it may be any name you wish), click “Add” and specify secondary replica name:

alwayson_3

4) You can use default settings or customize them.

5) Click “OK”.

6) Go to SQL Server Management Studio, expand AlwaysOn High Availablity, expand your Availability Group, expand “Availability Replicas”, right click your second server and select “Join Availablity Group” (if it exists).
7) In new Window connect to it and click “Next” and “Finish”.

Configuring AlwaysOn availability group listener

1) Go to SQL Server Management Studio, expand AlwaysOn High Availablity, expand your Availability Group, created earlier, right click “Availabilty Group Listeners” and select “Add Listener”:

2) Specify Listener DNS Name (if AlwaysOn listener computer account was pre-staged, this should match the name of the computer), enter 1433 into “Port”, for “Network mode” select Static IP and click “Add” to add an IP address:
alwayson_1

3) In the “Add windows” select the correct subnet and enter an IP address provided by customer:

always_2

4) Click “OK” and “OK”.

Adding/Removing databases to/from AlwaysOn availability group.

1) To add a database to availability group you select “Add database” in “Availability databases” and follow the Wizard.

– You can use fully automated addition. In this case you will need network share, accessible from both servers and with RW rights for SQL Server service account.

SQL Server will perform backup and restore of the database automatically.

– You can use “Join only” addition. In this case you will need to perform full backup and t-log backup and restore (as when configuring Mirroring, WITH NORECOVERY) and then use the Wizard.

2)  To remove a database from availability group just right click the database and select “Remove database from availablity group…”:

Please note that before deleting database, that is part of AlwaysOn HA, you must delete it from Availability group.