Tuesday, June 25, 2013

SQL Server 2012 AlwaysOn Availability Groups setup scripts - Part 3

4. Setup 2 nodes alwayson availability group 
    a) Enable alwayson on both 2 nodes
enable-sqlalwayson -Path "SQLSERVER:\SQL\SQL2012-01\DEFAULT"
enable-sqlalwayson -Path "SQLSERVER:\SQL\SQL2012-02\DEFAULT"

    b) Restore database "MYHA" to secondary server "SQL2012-02"
Backup-SqlDatabase -Database "MYHA" -ServerInstance "SQL2012-01" -BackupAction Database -CompressionOption On -backupfile "\\WIN-JIASUMAU0DF\Backup\MYHA_FULL.bak"

Restore-SqlDatabase -Database MYHA -ServerInstance sql2012-02 -BackupFile "\\WIN-JIASUMAU0DF\Backup\MYHA_FULL.bak" -NoRecovery

Backup-SqlDatabase -Database "MYHA" -ServerInstance "SQL2012-01" -BackupAction log -CompressionOption On -backupfile "\\WIN-JIASUMAU0DF\Backup\MYHA_log.trn"

Restore-SqlDatabase -RestoreAction Log -Database MYHA -ServerInstance sql2012-02 -backupfile "\\WIN-JIASUMAU0DF\Backup\MYHA_log.trn" -NoRecovery

    c)Create endpoint for alwayson availability group on both 2 nodes
$endpoint=New-SqlHADREndpoint -Port 5022 -Owner sa -Encryption Supported -EncryptionAlgorithm Aes -Name AlwaysonEndpoint -Path "SQLSERVER:\SQL\SQL2012-01\DEFAULT"
Set-SqlHADREndpoint -InputObject $endpoint -State Started

$endpoint=New-SqlHADREndpoint -Port 5022 -Owner sa -Encryption Supported -EncryptionAlgorithm Aes -Name AlwaysonEndpoint -Path "SQLSERVER:\SQL\SQL2012-02\DEFAULT"
Set-SqlHADREndpoint -InputObject $endpoint -State Started

     d) Create login for sql server service account and grant connection permission on alwayson endpoint
use [master]
GRANT CONNECT ON ENDPOINT::[AlwaysonEndpoint] TO [MSFT\sqlsvc]


      e)  Create alwayson availability group "MYAG"
$primaryServer = Get-Item "SQLSERVER:\SQL\SQL2012-01"
$secondaryServer = Get-Item "SQLSERVER:\SQL\SQL2012-02"

$primaryReplica = New-SqlAvailabilityReplica `
-Name "SQL2012-01" `
-EndpointUrl "TCP://SQL2012-01:5022" `
-FailoverMode "Manual" `
-AvailabilityMode "SynchronousCommit" `
-AsTemplate `
-Version 11

# Create the initial secondary replica
$secondaryReplica = New-SqlAvailabilityReplica `
-Name "SQL2012-02" `
-EndpointUrl "TCP://SQL2012-02:5022" `
-FailoverMode "Manual" `
-AvailabilityMode "SynchronousCommit" `
-AsTemplate `
-Version 11

New-SqlAvailabilityGroup -Name MyAG -AvailabilityReplica ($primaryReplica, $secondaryReplica) -Database "MYHA" -Path "SQLSERVER:\SQL\SQL2012-01\DEFAULT"

Join-SqlAvailabilityGroup -Name MyAG -Path "SQLSERVER:\SQL\SQL2012-02\DEFAULT\AvailabilityGroups"

Add-SqlAvailabilityDatabase -Database MYHA -Path "SQLSERVER:\SQL\SQL2012-02\DEFAULT\AvailabilityGroups\MyAG"

New-SqlAvailabilityGroupListener -Name SQL2012HA -StaticIp '' -Path "SQLSERVER:\SQL\SQL2012-01\DEFAULT\AvailabilityGroups\MyAG"

    f) Config cluster quorum
Import-Module FailoverClusters
Set-ClusterQuorum -Cluster SQLCluster -NodeAndFileShareMajority \\WIN-JIASUMAU0DF\fsw

SQL Server 2012 AlwaysOn Availability Groups setup scripts - Part 2

3. Install SQL Instance
   a) Configure the firewall setting on both 2 nodes.
echo Default Instance
netsh advfirewall firewall add rule name="SQLServer" dir=in action=allow protocol=TCP localport=1433 profile=DOMAIN

echo Dedicated Admin Connection
netsh advfirewall firewall add rule name="SQL DAC" dir=in action=allow protocol=TCP localport=1434 profile=DOMAIN

echo SQL Browser Service 
netsh advfirewall firewall add rule name="SQL Browser" dir=in action=allow protocol=UDP localport=1434 profile=DOMAIN

echo Mirroring EndPoint for Alwayson Availability Group
netsh advfirewall firewall add rule name="Mirroring EndPoint" dir=in action=allow protocol=TCP localport=5022 profile=DOMAIN

    b) Install .Net 3.5 Framework on all sql nodes
Install-WindowsFeature -Name NET-Framework-Features -source D:\sources\sxs

    c) Install SQL Server instance
.\setup.exe /ConfigurationFile="Z:\ConfigurationFile.ini"
get-service | where name -like "*sql*"

for "Configurationfile.ini", you can use the template below

;SQL Server 2012 Configuration File

; Specifies a Setup work flow, like INSTALL, UNINSTALL, or UPGRADE. This is a required parameter. 



; Detailed help for command line argument ENU has not been defined yet. 


; Setup will not display any user interface. 


; Setup will display progress only, without any user interaction. 


; Specify whether SQL Server Setup should discover and include product updates. The valid values are True and False or 1 and 0. By default SQL Server Setup will include updates that are found. 


; Specifies features to install, uninstall, or upgrade. The list of top-level features include SQL, AS, RS, IS, MDS, and Tools. The SQL feature will install the Database Engine, Replication, Full-Text, and Data Quality Services (DQS) server. The Tools feature will install Management Tools, Books online components, SQL Server Data Tools, and other shared components. 


; Specify the location where SQL Server Setup will obtain product updates. The valid values are "MU" to search Microsoft Update, a valid folder path, a relative path such as .\MyUpdates or a UNC share. By default SQL Server Setup will search Microsoft Update or a Windows Update service through the Window Server Update Services. 


; Displays the command line parameters usage 


; Specifies that the detailed Setup log should be piped to the console. 


; Specifies that Setup should install into WOW64. This command line argument is not supported on an IA64 or a 32-bit system. 


; Specify the root installation directory for shared components.  This directory remains unchanged after shared components are already installed. 

INSTALLSHAREDDIR="C:\Program Files\Microsoft SQL Server"

; Specify the root installation directory for the WOW64 shared components.  This directory remains unchanged after WOW64 shared components are already installed. 

INSTALLSHAREDWOWDIR="C:\Program Files (x86)\Microsoft SQL Server"

; Specify a default or named instance. MSSQLSERVER is the default instance for non-Express editions and SQLExpress for Express editions. This parameter is required when installing the SQL Server Database Engine (SQL), Analysis Services (AS), or Reporting Services (RS). 


; Specify the Instance ID for the SQL Server features you have specified. SQL Server directory structure, registry structure, and service names will incorporate the instance ID of the SQL Server instance. 


; Specify that SQL Server feature usage data can be collected and sent to Microsoft. Specify 1 or True to enable and 0 or False to disable this feature. 


; RSInputSettings_RSInstallMode_Description 


; Specify if errors can be reported to Microsoft to improve future SQL Server releases. Specify 1 or True to enable and 0 or False to disable this feature. 


; Specify the installation directory. 

INSTANCEDIR="C:\Program Files\Microsoft SQL Server"

; Agent account name 


; Auto-start service after installation.  


; Startup type for Integration Services. 


; Account for Integration Services: Domain\User or system account. 

ISSVCACCOUNT="NT Service\MsDtsServer110"

; CM brick TCP communication port 


; How matrix will use private networks 


; How inter brick communication will be protected 


; TCP port used by the CM brick 


; Startup type for the SQL Server service. 


; Level to enable FILESTREAM feature at (0, 1, 2 or 3). 


; Set to "1" to enable RANU for SQL Server Express. 


; Specifies a Windows collation or an SQL collation to use for the Database Engine. 


; Account for SQL Server service: Domain\User or system account. 

; Windows account(s) to provision as SQL Server system administrators. 

SQLSYSADMINACCOUNTS="XXXX\operations" "XXXX\administrator"

; The default is Windows Authentication. Use "SQL" for Mixed Mode Authentication. 


; Specify 0 to disable or 1 to enable the TCP/IP protocol. 


; Specify 0 to disable or 1 to enable the Named Pipes protocol. 


; Startup type for Browser Service. 


; Specifies which account the report server NT service should execute under.  When omitted or when the value is empty string, the default built-in account for the current operating system.
; The username part of RSSVCACCOUNT is a maximum of 20 characters long and
; The domain part of RSSVCACCOUNT is a maximum of 254 characters long. 


; Specifies how the startup mode of the report server NT service.  When 
; Manual - Service startup is manual mode (default).
; Automatic - Service startup is automatic mode.
; Disabled - Service is disabled 


; Add description of input argument FTSVCACCOUNT 


    d)Enable SQL Server network protocol
$m=New-Object("Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer") "."
$m.ServerInstances.ServerProtocols | select DisplayName, IsEnabled
$m.ServerInstances.ServerProtocols | foreach {$_.IsEnabled=$True;$_.Alter()}

Restart-Service MSSQLSERVER -Force

SQL Server 2012 AlwaysOn Availability Groups setup scripts - Part 1

Here are some scripts which can be used for setting up 2 nodes AlwaysOn Availability Groups, you can make your own automation script based on them.

Environment :
Name IP Address OS Description
SQL2012-01 Win2012 Primary
SQL2012-02 Win2012 Secondary
SQL2012HA N/A AG Listener
SQLClUSTER N/A Cluster Name

1. Configure Powershell enviroment
    a) Configure execution policy on all servers

        set-executepolicy unrestricted

        based on your company security policy, you can use other parameter instead of "unrestricted". here is just a sample
     b)Configure Powershell remote command on all servers
        Enable-PSRemoting -Force  
        Set-Item wsman:\localhost\client\auth\CredSSP -value true -force   
        Enable-WSManCredSSP -force -role server   
        set-item wsman:localhost\client\trustedhosts -value *    -force 
        set-item wsman:\localhost\listener\listener*\port -value 5985    -force 
        restart-Service winrm   
        winrm get winrm/config   
        winrm enumerate winrm/config/listener   

         If you want to centralize the installation process, and want to run the code from remote server, ps remote call and winrm need to be enabled and configured correctly. winrm is for powershell remote command call, for instance "invoke-command -computer".

2. Setup Cluster
Before sql server installation, we create a new cluster with 2 nodes(SQL2012-01, SQL2012-02)

Import-Module FailoverClusters

$ClusterNode1=Read-Host "Enter Cluster Node 1 Name"
$ClusterNode2=Read-Host "Enter Cluster Node 2 Name"

$CMD={Set-Service -Name ClusSvc -StartupType Automatic}

$useraccount=$env:USERDOMAIN+"\" + $env:USERNAME 
$cred= Get-Credential -UserName $useraccount -Message "Please enter the user name"

Invoke-Command -ComputerName $ClusterNode1 -ScriptBlock $CMD -Credential $cred
Invoke-Command -ComputerName $ClusterNode2 -ScriptBlock $CMD -Credential $cred

Write-Host "Testing Node $ClusterNode1"
Test-Cluster -Node @($ClusterNode1) -Ignore network,inventory,storage

Write-Host "Testing Node $ClusterNode2"
Test-Cluster -Node @($ClusterNode2) -Ignore network,inventory,storage

Write-Host "Clear old info on Node $ClusterNode1"
Clear-ClusterNode $ClusterNode1 -Force

Write-Host "Clear old info on Node $ClusterNode2"
Clear-ClusterNode $ClusterNode2 -Force

$ClusterFqdn=Read-Host "Enter New Cluster Name(Please specify the name without domain information)"
$ClusterIP=Read-Host "Enter New Cluster IP"

Write-Host "Creating Cluster $ClusterFqdn...."
New-Cluster -Name $ClusterFqdn -Node @($ClusterNode1,$ClusterNode2) -NoStorage -StaticAddress @($ClusterIP)
Here cluster node 1 is "SQL2012-01", cluster node 2 is "SQL2012-02", cluster name is "SQLCluster", cluster ip is ""

if cluster service hasn't been installed on all sql nodes, you can run the command below to install the service first.
Import-Module ServerManager
Add-WindowsFeature Failover-Clustering

Friday, June 21, 2013

Huge collection of Free Microsoft eBooks

I must share it, there are many useful resource




Thank you , Eric

Thursday, June 20, 2013

use Table Variables in transaction

when using table variable, please note table variable doesn't support transaction rollback. here is the words from BOL

Because table variables have limited scope and are not part of the persistent database, they are not affected by transaction rollbacks.

let's do a testing:
DECLARE @MyTableVar table(
    EmpID int NOT NULL,
    OldVacationHours int,
    NewVacationHours int,
    ModifiedDate datetime);

begin tran
insert into @MyTableVar


select * from @MyTableVar

well, we still get the result returned even if we rollback the transaction. the only place this feature might be useful is for log. we can log what happen during transaction rollback by table variable.

another thing might cause big issue is:
table variable don't have statistics, so don't anticipate it can get good enough execution plan if you insert a lot of data into table variable.