19 May 2022

Resource Governor


Resource Governor  is a feature that you can use to manage SQL Server workload and system resource consumption. Resource Governor enables you to specify limits on the amount of CPU, physical I/O, and memory that incoming application requests can use.

/*step1 Enable SQL Server Resource Governor

ALTER RESOURCE GOVERNOR RECONFIGURE;  
GO

/*step2 Create resource pool and set limits.

CREATE RESOURCE POOL PoolAdmin WITH (MAX_CPU_PERCENT = 50);

/*step3 Create Resource Governor Workload Group in that pool  

CREATE WORKLOAD GROUP [GroupAdmin] 
CREATE WORKLOAD GROUP [Quries] 
GO

/*step4 Direct relevant connections or hosts to those workload groups by using classifier function

USE [master]
GO
CREATE FUNCTION [dbo].[RG_Classifier]() 
RETURNS SYSNAME
WITH SCHEMABINDING
AS
BEGIN
    DECLARE @grp_name sysname
    IF (SUSER_NAME()  = 'sa')
        SET @grp_name = 'GroupAdmin'

    IF (HOST_NAME()  =  'hostclient')
        SET @grp_name = 'Quries'
    ELSE
          SET @grp_name = 'default'

    RETURN @grp_name 
END;
GO

/*step5 Testing i.e. run the quries from host and check result
USE master;  
SELECT * FROM sys.resource_governor_configuratin; 
SELECT * FROM sys.resource_governor_resource_pools;  
SELECT * FROM sys.resource_governor_workload_groups;  
SELECT  object_schema_name(classifier_function_id) AS [schema_name],  
      object_name(classifier_function_id) AS [function_name]  
FROM sys.dm_resource_governor_configuration;  
--Find out what sessions are in each group by using the following query.
SELECT s.group_id, CAST(g.name as nvarchar(20)), s.session_id, s.login_time, 
    CAST(s.host_name as nvarchar(20)), CAST(s.program_name AS nvarchar(20))  
FROM sys.dm_exec_sessions AS s  
INNER JOIN sys.dm_resource_governor_workload_groups AS g  
    ON g.group_id = s.group_id  
ORDER BY g.name;  
GO  
GO  

source
https://docs.microsoft.com/en-us/sql/relational-databases/resource-governor/create-and-test-a-classifier-user-defined-function?view=sql-server-ver15

15 December 2020

Transparent Data Encryption

PRIMARY REPLICA

STEP 1

USE MASTER 
BACKUP DATABASE DEMO TO DISK = 'E:\BACKUP\DEMO.Bak' 
GO 
BACKUP LOG DEMO TO DISK = 'E:\BACKUP\DEMO.trn' 

STEP 2

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'TESTDBPASSWORD' 

--SELECT name KeyName,  symmetric_key_id KeyID,  key_length KeyLength, 

--algorithm_desc KeyAlgorithm,create_date FROM sys.symmetric_keys;

STEP 3

CREATE CERTIFICATE TDECert WITH SUBJECT = 'My TDE Certificate for all user database'

--SELECT name CertName,   certificate_id CertID,   pvt_key_encryption_type_desc EncryptType, 

--issuer_name Issuer,start_date,expiry_date FROM sys.certificates 

STEP 4

USE [DEMO]

GO  

CREATE DATABASE ENCRYPTION KEY  

WITH ALGORITHM = AES_128  

ENCRYPTION BY SERVER CERTIFICATE TDECert 

GO 

SELECT DB_NAME(database_id) DbName,   /*CASE CONVERT(int,[encryption_state]) 

    WHEN 0 THEN 'no encryption'     WHEN 1 THEN 'Unencrypted' 

WHEN 2 THEN 'Encryption in progress' WHEN 3 THEN 'Encrypted' 

WHEN 4 THEN 'Key change in progress' WHEN 5 THEN 'Decryption in progress' 

WHEN 6 THEN 'Protection change in progress'     ELSE encryption_state 

END as [EncryptState]*/ encryption_state EncryptState,   key_algorithm KeyAlgorithm,   key_length KeyLength, 

encryptor_type EncryptType,percent_complete FROM sys.dm_database_encryption_keys; 

STEP 5

   USE DEMO

   ALTER DATABASE [DEMO] SET ENCRYPTION ON

STEP 6

USE MASTER  

GO  

BACKUP CERTIFICATE TDECert   

TO FILE = 'E:\BACKUP\TDECert_File.cer'  

WITH PRIVATE KEY (FILE = 'E:\BACKUP\TDECert_Key.pvk' ,  

ENCRYPTION BY PASSWORD = 'TESTDBPASSWORD' )  

GO

BACKUP DATABASE DEMO TO DISK = 'E:\BACKUP\DEMOTDE.Bak' 

GO 

BACKUP LOG DEMO TO DISK = 'E:\BACKUP\DEMOTDE.trn' 

GO 

==============Secondary replica,

USE MASTER  

GO  

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'TESTDBPASSWORD' 

GO  

CREATE CERTIFICATE TDECert  

FROM FILE = 'E:\BACKUP\TDECert_File.cer'   

WITH PRIVATE KEY (FILE = 'E:\BACKUP\TDECert_Key.pvk',   

DECRYPTION BY PASSWORD =  'TESTDBPASSWORD'

GO

ALTER DATABASE [DEMO] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE [DEMO] FROM  DISK = N'E:\BACKUP\DEMOTDE.Bak' 

WITH  FILE = 1,  MOVE N'DEMO' TO N'C:\Program Files\Microsoft SQL Server\MSSQL13.SECOND\MSSQL\DATA\DEMO.mdf', 

MOVE N'DEMO_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL13.SECOND\MSSQL\DATA\DEMO_log.ldf',  NOUNLOAD,  REPLACE,  STATS = 5


ALTER DATABASE [DEMO] SET MULTI_USER

GO

=============ROLLBACK

USE DEMO

ALTER DATABASE [DEMO] SET ENCRYPTION ON

DROP DATABASE ENCRYPTION KEY

USE MASTER

DROP CERTIFICATE TDECertificate

DROP MASTER KEY


16 March 2020

sqlauthority



Stored Procedure – Clean Cache and Clean Buffer

DBCC FREEPROCCACHE (ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE)
DBCC DROPCLEANBUFFERS
sys.dm_os_buffer_descriptors returns cached pages for all user and system databases


DBCC Commands can be ran to free memory:
  • DBCC FREESYSTEMCACHE
  • DBCC FREESESSIONCACHE
  • DBCC FREEPROCCACHE

DBCC FREESYSTEMCACHE:
Releases all unused cache entries from all caches.
DBCC FREESESSIONCACHE
Flushes the distributed query connection cache used by distributed queries against an instance of Microsoft SQL Server.

USE database_name
CHECKPOINT;
DBCC shrinkfile (logfilename1)

USE AdventureWorks
GO
BACKUP LOG AdventureWorks TO DISK='d:\adtlog.bak'
GO
-- Get Logical file name of the log file
sp_helpfile
GO
DBCC SHRINKFILE(AdventureWorks_Log,TRUNCATEONLY)
GO
ALTER DATABASE AdventureWorks
MODIFY 
FILE
(NAME AdventureWorks_Log,SIZE 1GB)
GO
DBCC LOGINFO
GO

DBCC CHECKIDENT can reseed (reset) the identity value of the table. For example, YourTable has 25 rows with 25 as last identity. If we want next record to have identity as 35 we need to run following T SQL script in Query Analyzer.
DBCC CHECKIDENT (yourtablereseed34)
Call your Stored Procedure prefixed with dbo.SPName – fully qualified name.
When SP are called prefixed with dbo. or database.dbo. it will prevent SQL Server from placing a COMPILE lock on the procedure. While SP executes it determines if all objects referenced in the code have the same owners as the objects in the current cached procedure plan.

PATINDEX is CHARINDEX + WildCard Search. Use either of them depending your need.\\\

·         Set a reasonable size of your database and transaction log (25% of database size).
·         Leave the Autogrow feature ON for the data files and for the log files with reasonable size of autogrow increment.
·         Don’t set the autoshrink feature run the task during off-peak hours.
·         Place the log files on other physical disk arrays than those with the data files to improve I/O Performance.
ALTER DATABASE [mydb] SET OFFLINE WITH ROLLBACK AFTER 30 SECONDS
OR
ALTER DATABASE [mydb] SET OFFLINE WITH ROLLBACK IMMEDIATE

RAID (redundant array of independent disks) levels 0, 1, and 5 are typically implemented with SQL Server.


  • Use SORT_IN_TEMPDB option when the table is created if tempdb is on different disks. This will increase the performance to create the Index.
  • Rebuild Index frequently using ALTER INDEX and De-fragment Index to keep performance optimal for Indexes.

ALTER DATABASE AdventureWorks
SET SINGLE_USER WITH
ROLLBACK 
IMMEDIATE
RESTORE DATABASE AdventureWorks
FROM DISK = 'C\:BackupAdventureworks.bak'
WITH MOVE 'AdventureWorks_Data' TO 'C:\Data\datafile.mdf',
MOVE 'AdventureWorks_Log' TO 'C:\Data\logfile.ldf',
REPLACE

USE pubs
GO
SELECT a.au_id
FROM authors a
JOIN titleauthor b ON a.au_id b.au_id
OPTION (MERGE JOIN)
GO


DBAs are creating all the tables with no Clustered Index.
USE AdventureWorks ----Replace AdventureWorks with your DBName
GO
SELECT DISTINCT [TABLE] OBJECT_NAME(OBJECT_ID)
FROM SYS.INDEXES
WHERE INDEX_ID 0
AND OBJECTPROPERTY(OBJECT_ID,'IsUserTable'1
ORDER BY [TABLE] GO

sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
sp_configure 'fill factor', 90
GO
RECONFIGURE
GO

EXEC sys.sp_configure 'show advanced options', '1'
RECONFIGURE WITH OVERRIDE
GO
EXEC sys.sp_configure 'fill factor (%)', '90'
GO
RECONFIGURE WITH OVERRIDE
GO
EXEC sys.sp_configure 'show advanced options', '0'
RECONFIGURE WITH OVERRIDE
GO

Disable Nesting/Recursing Triggers
Following script will stop executing all the nested triggers.
sp_CONFIGURE 'nested_triggers',0
GO
RECONFIGURE
GO
There is also alternate way to stop Trigger Recursion

ALTER DATABASE 
databasename
SET RECURSIVE_TRIGGERS ON OFF
Restrict Trigger Nesting to certain level
Put following script in trigger code. This will stop the trigger recursion after certain levels. In following case it will stop after 5 recursion.
IF ((
SELECT TRIGGER_NESTLEVEL()) > )
RETURN

USE AdventureWorks
GO
----Diable Index
ALTER INDEX [IX_StoreContact_ContactTypeID] ON Sales.StoreContact DISABLE
GO
----Enable Index
ALTER INDEX [IX_StoreContact_ContactTypeID] ON Sales.StoreContact REBUILD
GO

SQL SERVER 2005 Syntax
SET DEADLOCK_PRIORITY { LOW | NORMAL | HIGH | <numeric-priority> | @deadlock_var | @deadlock_intvar }
<numeric-priority> ::= { -10 | -9 | -8 | … | 0 | … | 8 | 9 | 10 }
Example:
The following example sets the deadlock priority to NORMAL.
SET DEADLOCK_PRIORITY NORMAL;
GO


Best Practices and Recommendations for TempDB in SQL Server.
Analyze the existing workload and adjust the space for projected concurrent activities in SQL TempDB.
SQL Server does not cache the temp table if it is created as part of dynamic SQL.
Perform index maintenance and update statistics on TempDB as well, even thought objects in TempDB are not permanent.
Set Auto Grow to ON for TempDB.
Instant file initialization improves the performance of auto grow operations in TempDB.
Create TempDB database on other disk drive than other database. This will improve performance for database as different disk controller will improve the performance for disk input/output.

SQL SERVER 2000:
DBCC SHOWCONTIG was used to find index fragmentation. In SQL SERVER 2005 it is deprecated and replaced by query to sys.DM_DB_INDEX_PHYSICAL_STATS.
SQL SERVER 2005:
SELECT query to sys.DM_DB_INDEX_PHYSICAL_STATS displays all the Index Fragmentation related information.

To return the Index Information for only Sales.SalesOrderDetail Table:
USE AdventureWorks;
SELECT INDEX_IDAVG_FRAGMENTATION_IN_PERCENT
FROM sys.dm_db_index_physical_stats
(DB_ID(),OBJECT_ID(N'Sales.SalesOrderDetail'), NULL, NULL, 'DETAILED')
To return all the information for all the Indexes in Database:
SELECT *
FROM sys.dm_db_index_physical_stats (NULL, NULL, NULL, NULL, NULL);

SQL SERVER 2000:
The DBCC INDEXDEFRAG and DBCC DBREINDEX statements are used to reduce table fragmentation.
To Rebuild only one Index:
USE AdventureWorks
GO
ALTER INDEX PK_ProductPhoto_ProductPhotoID
ON Production.ProductPhoto
REORGANIZE
GO

TO Rebuild all the Indexes on Table with Specifying options:
USE AdventureWorks
GO
ALTER INDEX ALL ON Production.Product
REBUILD 
WITH (FILLFACTOR = 90SORT_IN_TEMPDB = ON,
STATISTICS_NORECOMPUTE = ON)
GO

T-SQL to rebuild all the indexes on table.
USE AdventureWorks;
GO
ALTER INDEX ALL ON Production.Product REBUILD
GO

-- Change database Parameterization to Forced
ALTER DATABASE AdventureWorks
SET PARAMETERIZATION FORCED
GO
-- Change database Parameterization to Simple
ALTER DATABASE AdventureWorks
SET PARAMETERIZATION Simple
GO

Find Unused Indexes of Current Database


USE AdventureWorks
GO
DECLARE @dbid INT
SELECT 
@dbid DB_ID(DB_NAME())
SELECT OBJECTNAME OBJECT_NAME(I.OBJECT_ID),
INDEXNAME I.NAME,
I.INDEX_ID
FROM SYS.INDEXES I
JOIN SYS.OBJECTS O
ON I.OBJECT_ID O.OBJECT_ID
WHERE OBJECTPROPERTY(O.OBJECT_ID,'IsUserTable'1
AND I.INDEX_ID NOT IN (
SELECT S.INDEX_ID
FROM SYS.DM_DB_INDEX_USAGE_STATS S
WHERE S.OBJECT_ID I.OBJECT_ID
AND I.INDEX_ID S.INDEX_ID
AND DATABASE_ID @dbid)
ORDER BY OBJECTNAME,
I.INDEX_ID,
INDEXNAME ASC
GO

Display Fragmentation Information of Data and Indexes of Database Table



SELECT 
OBJECT_NAME(i.OBJECT_IDAS TableName,
i.name AS IndexName,
indexstats.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'DETAILED'indexstats
INNER JOIN sys.indexes i ON i.OBJECT_ID indexstats.OBJECT_ID
AND i.index_id indexstats.index_id
WHERE indexstats.avg_fragmentation_in_percent 20

Resource Governor

Resource Governor  is a feature that you can use to manage SQL Server workload and system resource consumption. Resource Governor enables y...