Post patching

--Post Patching Steps

--step1: Verify installation from summary.txt file
--step2: Connect to the instance and verify the patch information
       select  serverproperty('productlevel')
       select @@VERSION
--step3: Restart the system
--step4: Check that all dbs has come online
       select  name,state_desc from sys.databases
--step5: Take backup of all system dbs.
       --master, model, msdb, resource
       backup database master to disk='master.bak'
--step6: Verify that all dbs are consistant
       dbcc checkdb(master)
--step7: Allow the appl team/Testing team to check connectivity from appls.
--step8: Make the instance available to the appls by enabling TCP/IP of the instance.
--step9: To check complete information
SELECT
SERVERPROPERTY('ProductLevel') AS ProductLevel,
SERVERPROPERTY('ProductUpdateLevel') AS ProductUpdateLevel,
SERVERPROPERTY('ProductBuildType') AS ProductBuildType,
SERVERPROPERTY('ProductUpdateReference') AS ProductUpdateReference,
SERVERPROPERTY('ProductVersion') AS ProductVersion,
SERVERPROPERTY('ProductMajorVersion') AS ProductMajorVersion,
SERVERPROPERTY('ProductMinorVersion') AS ProductMinorVersion,
SERVERPROPERTY('ProductBuild') AS ProductBuild
GO

How to Reverse Log Shipping Roles in SQL Server

There are times when you may need to reverse the roles of a primary and standby server.  This is common when you need to patch the primary server and still need to allow users access to the data.  When using database mirroring or SQL clustering as your SQL Server high availability option, reserving the roles of the primary and standby servers is quite easy.  With log shipping, however, it is not as straight forward.

You can always bring the standby database online, create a full backup of it, and restore onto the (previously) primary database to initialize it for log shipping.  However, this approach can be cumbersome especially if the database is large. The following steps will allow you to reverse log shipping roles without the need to initialize the (new standby) database.
  • Disable the log shipping backup job on the primary server.
  • On the standby server, run the log shipping copy and restore jobs to restore any remaining transaction log backups.
  • Disable the log shipping copy and restore jobs on the secondary server.
  • On the primary server, create on last transaction log backup using the NORECOVERY option.
  • On the standby server, restore this transaction log backup using the RECOVERY option.
  • On the standby server (which will now be the primary server), right click on the database and select Properties -> Transaction Log Shipping.  Enable the database to become the primary database and configure the backup and secondary server settings.

.NET Unhandled Exception error when running installing SQL Server 2012

Error when launching setup.exe for SQL Server 2012:

"Unhandled exception has occurred in your application.  If you click Continue, the application will ignore this error and attempt to continue.  If you click Quit, the application will close immediately."


This was resolved by deleting the following folder:

C:\Users\%username%\appdata\local\Microsoft_Corporation

Steps to Database Refresh

  • 1. Take the Source Database Backup
  • Run the below script in Destination      server and copy the result script (This will help you to extract all the      permissions on that Database like database permissions and user permissions      and user roles permissions) 
------
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL

 DROP PROCEDURE sp_hexadecimal
 GO
CREATE PROCEDURE sp_hexadecimal
    @binvalue varbinary(256),
    @hexvalue varchar(256) OUTPUT
AS
DECLARE @charvalue varchar(256)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
 DECLARE @tempint int
 DECLARE @firstint int
 DECLARE @secondint int
 SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
 SELECT @firstint = FLOOR(@tempint/16)
 SELECT @secondint = @tempint - (@firstint*16)
 SELECT @charvalue = @charvalue +
   SUBSTRING(@hexstring, @firstint+1, 1) +
   SUBSTRING(@hexstring, @secondint+1, 1)
 SELECT @i = @i + 1
END
SELECT @hexvalue = @charvalue
GO
print 'sp_help_revlogin stored procedure created'
go
/*
**    Create stored procedure 'sp_help_revlogin'
*/
IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
     DROP PROCEDURE sp_help_revlogin
GO
--USE [ADMIN]
GO
/****** Object:  StoredProcedure [dbo].[sp_help_revlogin]    Script
  ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[sp_help_revlogin] @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @type varchar (1)
DECLARE @hasaccess int
DECLARE @denylogin int
DECLARE @is_disabled int
DECLARE @PWD_varbinary  varbinary (256)
DECLARE @PWD_string  varchar (514)
DECLARE @SID_varbinary varbinary (85)
DECLARE @SID_string varchar (514)
DECLARE @tmpstr  varchar (1024)
DECLARE @is_policy_checked varchar (3)
DECLARE @is_expiration_checked varchar (3)
DECLARE @defaultdb sysname
IF (@login_name IS NULL)
 DECLARE login_curs CURSOR FOR
     SELECT p.sid, p.name, p.type, p.is_disabled,
 p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
     ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND
 p.name <> 'sa'
ELSE
 DECLARE login_curs CURSOR FOR
     SELECT p.sid, p.name, p.type, p.is_disabled,
 p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
     ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND
 p.name = @login_name
OPEN login_curs
FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type,
 @is_disabled, @defaultdb, @hasaccess, @denylogin
IF (@@fetch_status = -1)
BEGIN
 PRINT 'No login(s) found.'
 CLOSE login_curs
 DEALLOCATE login_curs
 RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on '
 + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
 IF (@@fetch_status <> -2)
 BEGIN
   PRINT ''
   SET @tmpstr = '-- Login: ' + @name
   PRINT @tmpstr
   IF (@type IN ( 'G', 'U'))
   BEGIN -- NT authenticated account/group
     SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM
 WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']'
   END
   ELSE BEGIN -- SQL Server authentication
       -- obtain password and sid
           SET @PWD_varbinary = CAST( LOGINPROPERTY( @name,
 'PasswordHash' ) AS varbinary (256) )
       EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT
       EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT
       -- obtain password policy state
       SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN
 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name =
 @name
       SELECT @is_expiration_checked = CASE is_expiration_checked
 WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins
 WHERE name = @name
           SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + '
 WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ',
 DEFAULT_DATABASE = [' + @defaultdb + ']'
       IF ( @is_policy_checked IS NOT NULL )
       BEGIN
         SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked
       END
       IF ( @is_expiration_checked IS NOT NULL )
       BEGIN
         SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' +
 @is_expiration_checked
       END
   END
   IF (@denylogin = 1)
   BEGIN -- login is denied access
     SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name )
   END
   ELSE IF (@hasaccess = 0)
   BEGIN -- login exists but does not have access
     SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name )
   END
   IF (@is_disabled = 1)
   BEGIN -- login is disabled
     SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE'
   END
   PRINT @tmpstr
 END
 FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type,
 @is_disabled, @defaultdb, @hasaccess, @denylogin
  END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
go
print 'logins-----------------------------------------------'
exec sp_help_revlogin
print '--ServerRoles'
set nocount on
declare @srvroles varchar(255)
declare @vnum varchar(255)
create table #srvroles
( srvrolename varchar(255))
create table #rolemember
(rolename varchar(255),
rolemember varchar(255),
rolememberid varbinary(255))
--create table #version(vnum varchar(255))
--insert into #version
--select @@version
--select @vnum = vnum from #version
--if substring(@vnum,1,30) ='Microsoft SQL Server  7.00 - 7'
--begin
--    insert into #srvroles values ('sysadmin')
--    insert into #srvroles values ('securityadmin')
--    insert into #srvroles values ('serveradmin')
--    insert into #srvroles values ('setupadmin')
--    insert into #srvroles values ('processadmin')
--    insert into #srvroles values ('diskadmin')
--    insert into #srvroles values ('dbcreator')
--end
--else
--if substring(@vnum,1,30) ='Microsoft SQL Server  2000 - 8'
--begin
     insert into #srvroles values ('sysadmin')
     insert into #srvroles values ('securityadmin')
     insert into #srvroles values ('serveradmin')
     insert into #srvroles values ('setupadmin')
     insert into #srvroles values ('processadmin')
     insert into #srvroles values ('diskadmin')
     insert into #srvroles values ('dbcreator')
     insert into #srvroles values ('bulkadmin')
--end
declare srvroles cursor for
select srvrolename from #srvroles
open srvroles
fetch next from srvroles into @srvroles
while @@fetch_status = 0
begin
     insert into #rolemember(rolename,rolemember,rolememberid)
     exec sp_helpsrvrolemember @srvroles
     fetch next from srvroles into @srvroles
end
select 'exec master..sp_addsrvrolemember '+''''+rolemember+''''+',
 '+rolename from #rolemember
where rolemember not in ('sa')
drop table #srvroles
drop table #rolemember
--drop table #version
close srvroles
deallocate srvroles
set nocount off
GO
--Role Memberships'
SELECT --rm.role_principal_id,
'EXEC sp_addrolemember @rolename ='
+ SPACE(1) + QUOTENAME(USER_NAME(rm.role_principal_id), '''')
+ ', @membername =' + SPACE(1) +
 QUOTENAME(USER_NAME(rm.member_principal_id), '''') AS '--Role
 Memberships'
FROM sys.database_role_members AS rm
ORDER BY rm.role_principal_id
--Object Level Permissions'
SELECT
CASE WHEN perm.state != 'W' THEN perm.state_desc ELSE 'GRANT' END + SPACE(1) +
perm.permission_name + SPACE(1) + 'ON '+
 QUOTENAME(Schema_NAME(obj.schema_id)) + '.'
+ QUOTENAME(obj.name) collate Latin1_General_CI_AS_KS_WS
+ CASE WHEN cl.column_id IS NULL THEN SPACE(0) ELSE '(' +
 QUOTENAME(cl.name) + ')' END
+ SPACE(1) + 'TO' + SPACE(1) + QUOTENAME(usr.name)
+ CASE WHEN perm.state <> 'W' THEN SPACE(0) ELSE SPACE(1) + 'WITH
 GRANT OPTION' END AS '--Object Level Permissions'
FROM sys.database_permissions AS perm
INNER JOIN
sys.objects AS obj
ON perm.major_id = obj.[object_id]
INNER JOIN
sys.database_principals AS usr
ON perm.grantee_principal_id = usr.principal_id
LEFT JOIN
sys.columns AS cl
ON cl.column_id = perm.minor_id AND cl.[object_id] = perm.major_id
ORDER BY usr.name
--Database Level Permissions'
SELECT CASE WHEN perm.state <> 'W' THEN perm.state_desc ELSE 'GRANT' END
+ SPACE(1) + perm.permission_name + SPACE(1)
+ SPACE(1) + 'TO' + SPACE(1) + QUOTENAME(usr.name) COLLATE database_default
+ CASE WHEN perm.state <> 'W' THEN SPACE(0) ELSE SPACE(1) + 'WITH
 GRANT OPTION' END AS '--Database Level Permissions'
FROM sys.database_permissions AS perm
INNER JOIN
sys.database_principals AS usr
ON perm.grantee_principal_id = usr.principal_id
WHERE
--usr.name = @OldUser
--AND
perm.major_id = 0
ORDER BY perm.permission_name ASC, perm.state_desc ASC
DROP PROCEDURE sp_hexadecimal
DROP PROCEDURE sp_help_revlogin
  • Restore database in destination database     
  • Fix Orphan users:
a) SP_CHANGE_USERS_LOGIN REPORT – TO Find the orphan users
b) Script to map the orphaned users in one step

create table #login(loginname varchar(25),usersid varbinary(500))
insert into #login exec sp_change_users_login'report'
Declare GetResultSet cursor FAST_FORWARD For
Select distinct loginname from #login
Declare @login  as Varchar(50)
declare @sEXEC as nvarchar (800)
declare @blkid as nvarchar (50)
declare @sEXEC1 as nvarchar (50)
declare @sEXEC2 as nvarchar (50)
Open GetResultSet
Fetch from GetResultSet into @login 
While @@Fetch_Status=0
Begin
SET @sEXEC = 'sp_change_users_login '+''''+'update_one'+''''+','+''''+@login+''''+','+''''+@login+''''
print 'Trying to map the login .....'+ @login
EXEC sp_executesql @sEXEC
Fetch Next From GetResultSet into @login
End
Close GetResultSet
DeAllocate GetResultSet
drop table #login
  • Run the result script in Destination      server from  above Step
  • Verify the Database permissions and user permissions

SQL Queries taking longer than normal to complete in SQL Server

Cause:

When a database is frequently updated via INSERT, UPDATE, or DELETE statements we can expect it to become fragmented over the time.

If database indexes are fragmented, the SQL Server query optimizer may chose a non-optimal execution plan when using an index to resolve a query.

This will affect the overall query performance and you may notice a query behaving slower than normal.

Resolution:

*Warning: Irreparable database damage can occur. This procedure should only be performed by users familiar with SQL Server Management Studio. Databases should be backed up prior to performing this procedure.*

The following is a simple query that will list every index on every table in your database, ordered by percentage of index fragmentation.

SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID()
ORDER BY indexstats.avg_fragmentation_in_percent desc

This query can be modified to focus on specific tables by append the table name to the 'where' clause: WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
In order to reduce fragmentation we will have to reorganize or rebuild the indexes. Choosing between reorganizing or rebuilding depends on the query results.

For heavily fragmented indexes a rebuild process is needed, otherwise index reorganization should be sufficient.