Whatsql
FOR MS SQL DBA KNOWLEDGE
19 May 2022
Resource Governor
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
ALTER
DATABASE
SCOPED
CONFIGURATION CLEAR PROCEDURE_CACHE)
- DBCC FREESYSTEMCACHE
- DBCC FREESESSIONCACHE
- DBCC FREEPROCCACHE
Flushes the distributed query connection cache used by distributed queries against an instance of Microsoft SQL Server.
DBCC shrinkfile (logfilename, 1)
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
(
yourtable
,
reseed
,
34
)
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.
OR
ALTER DATABASE [mydb] SET OFFLINE WITH ROLLBACK IMMEDIATE
- 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
GO
SELECT a.au_id
FROM authors a
JOIN titleauthor b ON a.au_id = b.au_id
OPTION (MERGE JOIN)
GO
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
Following script will stop executing all the nested triggers.
sp_CONFIGURE 'nested_triggers',0
GO
RECONFIGURE
GO
ALTER DATABASE databasename
SET RECURSIVE_TRIGGERS ON | OFF
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()) > 5 )
RETURN
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
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
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.
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.
SELECT query to sys.DM_DB_INDEX_PHYSICAL_STATS displays all the Index Fragmentation related information.
USE
AdventureWorks
;
SELECT
INDEX_ID
,
AVG_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);
The DBCC INDEXDEFRAG and DBCC DBREINDEX statements are used to reduce table fragmentation.
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 =
90
,
SORT_IN_TEMPDB
= ON
,
STATISTICS_NORECOMPUTE
= ON
)
GO
USE
AdventureWorks
;
GO
ALTER INDEX
ALL
ON
Production.Product REBUILD
GO
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
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_ID) AS 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...