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
CREATE LOGIN [MSFT\sqlsvc] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
GO
use [master]
GO
GRANT CONNECT ON ENDPOINT::[AlwaysonEndpoint] TO [MSFT\sqlsvc]

GO

      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 '192.168.1.41/255.255.255.0' -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

#ConfigurationFile.ini#
;SQL Server 2012 Configuration File
[OPTIONS]

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

ACTION="Install"

IACCEPTSQLSERVERLICENSETERMS="True"

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

ENU="True"

; Setup will not display any user interface. 

QUIET="True"

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

QUIETSIMPLE="False"

; 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. 

UpdateEnabled="False"

; 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. 

FEATURES=SQLENGINE,REPLICATION,FULLTEXT,RS,BIDS,CONN,IS,SSMS,ADV_SSMS

; 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. 

UpdateSource="MU"

; Displays the command line parameters usage 

HELP="False"

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

INDICATEPROGRESS="False"

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

X86="False"

; 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). 

INSTANCENAME="MSSQLSERVER"

; 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. 

INSTANCEID="MSSQLSERVER"

; 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. 

SQMREPORTING="False"

; RSInputSettings_RSInstallMode_Description 

RSINSTALLMODE="FilesOnlyMode"

; 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. 

ERRORREPORTING="False"

; Specify the installation directory. 

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

; Agent account name 

AGTSVCACCOUNT="XXXX\SQLSVC"
AGTSVCPASSWORD="XXXXXX"

; Auto-start service after installation.  

AGTSVCSTARTUPTYPE="Automatic"

; Startup type for Integration Services. 

ISSVCSTARTUPTYPE="Manual"

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

ISSVCACCOUNT="NT Service\MsDtsServer110"

; CM brick TCP communication port 

COMMFABRICPORT="0"

; How matrix will use private networks 

COMMFABRICNETWORKLEVEL="0"

; How inter brick communication will be protected 

COMMFABRICENCRYPTION="0"

; TCP port used by the CM brick 

MATRIXCMBRICKCOMMPORT="0"

; Startup type for the SQL Server service. 

SQLSVCSTARTUPTYPE="Automatic"

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

FILESTREAMLEVEL="0"

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

ENABLERANU="False"

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

SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS"

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

SQLSVCACCOUNT="XXX\SQLSVC"
SQLSVCPASSWORD="XXXXXX"
; 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. 

SECURITYMODE="SQL"
SAPWD="XXXXXX"

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

TCPENABLED="0"

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

NPENABLED="0"

; Startup type for Browser Service. 

BROWSERSVCSTARTUPTYPE="Disabled"

; 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. 

RSSVCACCOUNT="XXXX\SQLSVC"
RSSVCPASSWORD="XXXXXX"

; 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 

RSSVCSTARTUPTYPE="Manual"

; Add description of input argument FTSVCACCOUNT 

FTSVCACCOUNT="NT Service\MSSQLFDLauncher"


    d)Enable SQL Server network protocol
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement")
$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 192.168.1.21 Win2012 Primary
SQL2012-02 192.168.1.31 Win2012 Secondary
SQL2012HA 192.168.1.41 N/A AG Listener
SQLClUSTER 192.168.1.50 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
       #winrmsetup.ps1
        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   
        #winrmsetup.ps1

         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)

#Create-WinCluster.ps1
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)
#Create-WinCluster.ps1
Here cluster node 1 is "SQL2012-01", cluster node 2 is "SQL2012-02", cluster name is "SQLCluster", cluster ip is "192.168.1.50"

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

http://blogs.msdn.com/b/mssmallbiz/archive/2013/06/18/huge-collection-of-free-microsoft-ebooks-for-you-including-office-office-365-sharepoint-sql-server-system-center-visual-studio-web-development-windows-windows-azure-and-windows-server.aspx?Redirected=true

http://blogs.msdn.com/b/mssmallbiz/archive/2012/07/27/large-collection-of-free-microsoft-ebooks-for-you-including-sharepoint-visual-studio-windows-phone-windows-8-office-365-office-2010-sql-server-2012-azure-and-more.aspx

http://blogs.msdn.com/b/mssmallbiz/archive/2012/07/30/another-large-collection-of-free-microsoft-ebooks-and-resource-kits-for-you-including-sharepoint-2013-office-2013-office-365-duet-2-0-azure-cloud-windows-phone-lync-dynamics-crm-and-more.aspx

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
values(1,2,3,getdate())

rollback

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.