SQL Server – Exetended Events example : failed logins

-- create the extended event session and start it
CREATE EVENT SESSION FailedLogins
ON SERVER
 ADD EVENT sqlserver.error_reported
 (
   ACTION 
   (
     sqlserver.client_app_name,
     sqlserver.client_hostname,
     sqlserver.nt_username
    )
    WHERE severity = 14
      AND state > 1
  )
  ADD TARGET package0.asynchronous_file_target
  (
    SET FILENAME = N'D:\Program Files\Microsoft SQL Server\MSSQL12.MSSQL\MSSQL\Log\xEventSessions\FailedLogins.xel',
    METADATAFILE = N'D:\Program Files\Microsoft SQL Server\MSSQL12.MSSQL\MSSQL\Log\xEventSessions\FailedLogins.xem'
  );
GO

ALTER EVENT SESSION FailedLogins ON SERVER
  STATE = START;
GO
-- Query the files
WITH event_data AS 
(
  SELECT data = CONVERT(XML, event_data)
    FROM sys.fn_xe_file_target_read_file(
   'D:\Program Files\Microsoft SQL Server\MSSQL12.MSSQL\MSSQL\Log\xEventSessions\FailedLogins*.xel', 
   'D:\Program Files\Microsoft SQL Server\MSSQL12.MSSQL\MSSQL\Log\xEventSessions\FailedLogins*.xem', 
   NULL, NULL
 )
),
tabular AS
(
  SELECT 
    [host] = data.value('(event/action[@name="client_hostname"]/value)[1]','nvarchar(4000)'),
    [app] = data.value('(event/action[@name="client_app_name"]/value)[1]','nvarchar(4000)'),
    [error] = data.value('(event/data[@name="error_number"]/value)[1]','int'),
    [state] = data.value('(event/data[@name="state"]/value)[1]','tinyint'),
    [message] = data.value('(event/data[@name="message"]/value)[1]','nvarchar(250)')
  FROM event_data
)
SELECT [host],[app],[state],[message],[date/time]
  FROM tabular
  WHERE error = 18456 
  ORDER BY [date/time] DESC;

SQL Server – Add Powershell dbatools module

Add Powershell dbatools module

Execute an elevated powershell session (Execute as administrator) and run the command:

Import-Module dbatools

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

Loading personal and system profiles took 756ms.
PS C:\WINDOWS\system32> Install-Module dbatools

NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
 'C:\Users\hell\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want
 PowerShellGet to install and import the NuGet provider now?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y

Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the
modules from 'PSGallery'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): Y
PS C:\WINDOWS\system32>

Security Aspects

This article Security Aspects by Chrissy Lemaire explains security-related issues (for the dbatools module and PowerShell in general).

SQL Server – Query Plans, Plan handles, DBCC FREEPROCCACHE

select
[Average Duration (msec]=total_elapsed_time/execution_count/1000, 
creation_time,last_execution_time, 
execution_count from sys.dm_exec_query_stats
where plan_handle in 
(
SELECT plan_handle
FROM sys.dm_exec_cached_plans 
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)
where text like '%<sql text>%'
)
SELECT UseCounts, Cacheobjtype, Objtype, TEXT, query_plan, plan_handle
FROM sys.dm_exec_cached_plans 
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)
where text like '%<sql text>%'
order by text

DBCC FREEPROCCACHE(<plan_handle>)

SQL Server – Display Statistics for a Database

SELECT DISTINCT
OBJECT_NAME(s.[object_id]) AS TableName,
c.name AS ColumnName,
s.name AS StatName,
s.auto_created,
s.user_created,
s.no_recompute,
s.[object_id],
s.stats_id,
sc.stats_column_id,
sc.column_id,
STATS_DATE(s.[object_id], s.stats_id) AS LastUpdated
FROM sys.stats s JOIN sys.stats_columns sc 
              ON sc.[object_id] = s.[object_id] AND sc.stats_id = s.stats_id
JOIN sys.columns c ON c.[object_id] = sc.[object_id] AND c.column_id = sc.column_id
JOIN sys.partitions par ON par.[object_id] = s.[object_id]
JOIN sys.objects obj ON par.[object_id] = obj.[object_id]
WHERE OBJECTPROPERTY(s.OBJECT_ID,'IsUserTable') = 1
AND (s.auto_created = 1 OR s.user_created = 1)
order by LastUpdated desc; 

sp_msforeachtable 'sp_autostats ''?'''

SQL Server – Memory and CPU Consumption

-- total buffer usage by database for current instance
WITH DB_CPU_Stats
AS
(SELECT DatabaseID, DB_Name(DatabaseID) AS [DatabaseName], SUM(total_worker_time) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID] 
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS F_DB
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [row_num],
       DatabaseName, [CPU_Time_Ms], 
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPUPercent]
FROM DB_CPU_Stats
WHERE DatabaseID > 4 -- system databases
AND DatabaseID <> 32767 -- ResourceDB
ORDER BY row_num OPTION (RECOMPILE);

-- Memory utilization by database
SELECT DB_NAME(database_id) AS [Database Name],
COUNT(*) * 8/1024.0 AS [Cached Size (MB)]
FROM sys.dm_os_buffer_descriptors
WHERE database_id > 4 -- system databases
AND database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id)
ORDER BY [Cached Size (MB)] DESC OPTION (RECOMPILE);

SQL Server – kill with statusonly

When a SQL Server process is killed (kill spid), the non-commited work (transactions) will take a certain amount of time to roll back.

Use kill spid with statusonly to determine how much time a killed process will take to rollback

SQL Server – Deadlock History with Extended Events

Using SSMS to Display Deadlock History with Extended Events

To use Extended Events to display deadlock history, the following method can be used.
In the Object Explorer, Open Management folder

Extended Events to display deadlock history

Extended Events to display deadlock history

Open Extended Events/Sessions/system_health

Right-click on package0.eventfile and select “View Target Data”. This will display a list of events.

To apply a filter, for example “deadlock”, select Filters toolbar button (may be hidden in a drop-down list)

Set the filter(s)

The results are displayed.

SQL Server – Truncate transaction log

The transaction log is truncated when a transaction log backup is executed (recovery mode Full).

In an emergency situation, if the log becomes full and it is not possible to backup the log normally, it can be pseudo-backed-up to a fictitious location.

Use at your own risk and only do this if you know what you’re doing.

This will prevent the possibilty of point-in-time recovery, so a full backup should be done after this operation

BACKUP LOG <db name> TO DISK='NUL:'