Monday, July 6, 2020

How to Configure Database Mail and Enable it on SQL Server



How to Configure Database Mail and Enable it on the SQL Server Agent

A. Prerequisite Checks and Steps

SMTP Server Info: you’re going to need the fully qualified name, port information, and authentication information for your smtp server. Get this from your sysadmin so you don’t stall out along the way.
SQL Agent Operator: you may want to create an operator before you set this all up. You’ll use it here in your final test. (Don’t worry, that’s fast.)
Setting Checks: There are a couple things we like to look at before trying to configure Database Mail that can throw a real monkey in your wrench.
  1. Make sure Service Broker is still enabled in msdb (it is by default)
  2. Make sure SQL is configured to use the Database Mail XPs (it is NOT by default)
Here’s code to check those things:
Here’s an example of the results that come back:
Picture4
1 & 1

What if Someone Turned Off Service Broker in msdb?

If for some reason Service Broker isn’t enabled, you may have larger issues than this to worry about:
  • Are you using an Edition of SQL Server that supports Database Mail?
  • Was msdb ever restored from backup?
You need to ask these questions before enabling it.

How to Enable Database Mail Extended Procedures – TSQL Option

Reconfiguring your server to use the Database Mail XPs is straightforward. You can do this using TSQL, or you can walk through the wizard below. (It will prompt you if you need to make this change.)

B. Configuring Database Mail Using the Wizard

In Object Explorer, expand Management and right click Database Mail:
Picture5
To Boldly Get Bolded So You Know Exactly Where to Click
Click ‘Next’, then click the first option to set up Database Mail.

Step 1: Create a Profile

Name your profile, then click ‘Add’ to add an account:
Picture6
The more descriptive the better, since you may want multiple profiles for different purposes.

STEP 2: Create An Account

When adding an account, specify:
  • Email address: Most people use SQLSERVER01@yourdomain.com
  • Display name: Most people use the SQL Server’s name here, like SQLSERVER01
  • Reply email: Most people use DONOTREPLY@yourdomain.com
  • Server name: this is the smtp server you’re using. Don’t use gmail for production servers, the screenshot is just an example. Seriously.
  • Port and your authentication options. This varies by email service.
Picture7
Ask your sysadmin for the details of your Exchange server.
Remember to use a smpt server or service you trust; these emails will be vital to monitoring your server’s health.

C. Send a Test Email

Right click on “Database Mail” in Object Explorer. Select “Send a Test Email.” Fill out the helpful little form and make sure it works.
If it doesn’t work, there’s a problem in your setup. Right click “Database Mail” again and select “View Database Mail Log” to go hunting and find out where the issue is.

D. Enable Database Mail on the SQL Server Agent

You’re almost there, we promise. At this point your SQL Server can send mail, but the SQL Server Agent can’t yet. You need to tell it how you want it to use Database Mail for it to have powers to alert you about problems.
Right click on the SQL Server Agent and select properties, like this:
SQL Server Agent Properties

Now Click on the Alert System Tab

This is where you tell the SQL Server Agent what database mail profile to use. Enable the mail profile, then select your mail profile. You may also want to set up your failsafe operator right now. Then click OK.
SQL Agent Alert System

Restart the SQL Server Agent Service to Make That Take Effect

The SQL Server Agent is a little slow to learn: it won’t be able to use database mail until you restart the Agent service. Important reminders:
  • Note that we aren’t talking about the whole SQL Server itself: only the Agent service
  • Check if any jobs are running before restarting the SQL Server Agent Service. It will kill the jobs, and won’t automatically restart them, so you may want to wait until a quiet time when jobs aren’t running to do this step.

E. Test Your Work

You’ve come a long way. Here’s how to revel in your success:
  1. Create a SQL Server agent job named ‘Test’
  2. Give it a single step named ‘Hi’ which executes: print ‘I love my hometown’
  3. Set the step to notify an operator on completion of the job
  4. Run the job
  5. Get the email
  6. Delete the job
  7. Party like it’s 2020

Below query can be used to the check the email status in msdb database.

USE msdb

SELECT * FROM sysmail_allitems
SELECT * FROM sysmail_event_log

DELETE FROM sysmail_allitems

EXECUTE msdb.dbo.sp_send_dbmail
@profile_name = 'MonitorDBActivity',
@recipients = 'nXXXXXXXn@gmail.com',
@subject = 'SQL alert Test email',
@body = 'this is sent from sql server via sp_send_dbmail'
GO

Friday, July 3, 2020

How to find slow performing SQL Server query


Approach to find slow performing SQL Server query

1. Check with Activity monitor in SSMS
2. sp_who2
3. For looking SPID, which is creating problem.

SELECT * 
FROM sys.dm_exec_sessions es
CROSS APPLY sys.dm_exec_input_buffer(es.session_id, NULL) ib
WHERE es.session_id > 50

4. With the help of below query to find out wait statistics, for slow running queries.

WITH Waits AS 
 ( 
 SELECT  
   wait_type,  
   wait_time_ms / 1000. AS wait_time_s, 
   100. * wait_time_ms / SUM(wait_time_ms) OVER() AS pct, 
   ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn 
 FROM sys.dm_os_wait_stats 
 WHERE wait_type  
   NOT IN 
     ('CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'RESOURCE_QUEUE', 
   'SLEEP_TASK', 'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 
   'CLR_AUTO_EVENT', 'CLR_MANUAL_EVENT') 
   ) -- filter out additional irrelevant waits 
    
SELECT W1.wait_type, 
 CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s, 
 CAST(W1.pct AS DECIMAL(12, 2)) AS pct, 
 CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS running_pct 
FROM Waits AS W1 
 INNER JOIN Waits AS W2 ON W2.rn <= W1.rn 
GROUP BY W1.rn,  
 W1.wait_type,  
 W1.wait_time_s,  
 W1.pct 
HAVING SUM(W2.pct) - W1.pct < 95; -- percentage threshold;

Make use of below Query to check the queries running multiple time and taking huge execution time.

SELECT TOP 10 
t.TEXT AS [QueryName],
s.execution_count AS [ExecutionCount],
s.max_elapsed_time AS [MaxElapsedTime],
ISNULL(s.total_elapsed_time / 1000 / NULLIF(s.execution_count,0),0) AS [AvgElapsedTime],
s.creation_time AS [LogCreatedOn],
ISNULL(s.execution_count / 1000 / NULLIF(DATEDIFF(s, s.creation_time, GETDATE()),0),0) AS [AvgExecutionCount],
query_plan
FROM sys.dm_exec_query_stats s
CROSS APPLY sys.dm_exec_query_plan(s.plan_handle) u
CROSS APPLY sys.dm_exec_sql_text(s.plan_handle) t

ORDER BY MaxElapsedTime DESC



Drop All Auto Created Statistics

The way the statistics work is that when SQL Server runs any query and it needs the statistics for them, it will automatically create them if the required statistics do not exist.

When your database about to go live, do this practice to check all user created statistics by load testing on TEST/STAGE environment, So drop all the auto-created statistics, so when the system goes live, it can build from the scratch all the necessary statistics based on the query patterns.

SELECT DISTINCT 'DROP STATISTICS '
+ QUOTENAME(SCHEMA_NAME(ob.Schema_id)) + '.'
+ QUOTENAME(OBJECT_NAME(s.object_id)) + '.' +
QUOTENAME(s.name) DropStatisticsStatement
FROM sys.stats s
INNER JOIN sys.Objects ob ON ob.Object_id = s.object_id
WHERE SCHEMA_NAME(ob.Schema_id) <> 'sys'
AND Auto_Created = 1


The above script will generate the drop script which you can run for your server and drop all the auto created statistics. Remember, if you are not sure if this step will help you or not, you should reach out to any SQL Server Performance Tuning Expert before you execute the drop statistics query

You can download Database Performance Analyser from below link to find and tune heavy workload i.e. tables and queries 

https://bit.ly/dpa-blog-918

If you found the Slow running query, you can also go through for below checks.

  • ·    Check for Execution Plan (Read execution plan right to left and top to bottom)
  • ·    Check for Spooling
    • Lazy Spooling - Duplicates of agreegation happens/ it's good in case of recursive CTE call
    • Egar Spooling - is Good
  • ·    Check for Hashmatch - Unsorted data (check for missing index)
  • ·   Check for KeyLookup - Missing data (to remove keylookup use covering index with include keyword)
  • ·    Check for Bad views - (Check for those joined tables, which are already including in the view and made extra join with that view)
  • ·    Check for Multiple subqueries - (In any select statement in multiple subqueries used then use CROSS APPLY instead)
  • Check for implicit conversion (remove or change the implicit conversion in where cause of data comparison)

Wednesday, June 24, 2020

SQL Server Database Health checkup tips

  ----// To monitor pressure observing task by workload (CPU/Memory/IO) 

 SELECT 
 AVG(current_tasks_count) AS [avg_current_tasks_count],
 AVG(runnable_tasks_count) AS [avg_runnable_tasks_count],
 AVG(work_queue_count) AS [avg_work_queue_count],
 AVG(pending_disk_io_count) AS [avg_pending_disk_io_count]
 FROM sys.dm_os_schedulers
 WHERE scheduler_id < 255

 ----// To monitor TempDB space usage

 USE [tempdb]
 GO

 SELECT GETDATE() AS [Run Time], SUM(user_object_reserved_page_count) * 8 AS [user_obj_kb]  ,
 SUM(internal_object_reserved_page_count) * 8 AS [internal_obj_kb],
 SUM(version_store_reserved_page_count) * 8 AS [version_store_kb],
 SUM(unallocated_extent_page_count) * 8 AS [freespace_kb],
 SUM(mixed_extent_page_count) * 8 AS [mixedextent_kb]
 FROM sys.dm_db_file_space_usage

 USE [tempdb]
 GO

 SELECT name AS [logical_name], size/128.0 AS [Total size in MB],
 size/128.0 -CAST(FILEPROPERTY(name, 'SpaceUsed') AS INT)/128.0 AS [Available space in MB]
 FROM sys.database_files


-- To check the workload RUN this query to check internal_obj_kb and tempDB size
 USE [AdventureWorks2017]
 GO

 WHILE (1=1)
 BEGIN
DBCC DROPCLEANBUFFERS
SELECT TOP (100000)
a.*
FROM master..spt_values a, master..spt_values b, master..spt_values c
ORDER BY a.number DESC, b.number DESC, c.number DESC
 END

GO

--To check version_store_kb values

----// Enable READ COMMITED SNAPSHOT Isolation level ON database PWI_TEMPDBFULL 
USE [master]
GO
ALTER DATABASE [AdventureWorks2017] SET READ_COMMITTED_SNAPSHOT ON WITH NO_WAIT
GO

----Open a new query window and execute below query

USE [AdventureWorks2017]
GO
CREATE TABLE OpenTran (NAME VARCHAR(50));
GO
INSERT INTO OpenTran VALUES('PWI')
GO


USE [AdventureWorks2017]
GO
SELECT * FROM OpenTran

BEGIN TRANSACTION
UPDATE [OpenTran] SET [NAME] = 'Test'


SELECT * FROM sys.dm_tran_version_store  ----// This DMV s used to check the current transaction detail

ROLLBACK TRANSACTION

GO

----// T-SQL Script to Check SQL Server Job History

SELECT jobs.name AS [Job_Name], 
msdb.dbo.agent_datetime(run_date, run_time) AS [Run DateTime], 
history.run_duration AS [Duration in Second]
FROM msdb.dbo.sysjobs jobs
INNER JOIN msdb.dbo.sysjobhistory history ON jobs.job_id = history.job_id
WHERE jobs.enabled = 1
GO

----// T-SQL Script to Check SQL Server Agent's properties from SSMS

EXEC msdb.dbo.sp_get_sqlagent_properties

----// T-SQL Script to Check Service account for SQL Server

SELECT servicename, service_account
FROM sys.dm_server_services
GO

----// Check the space occupied by the Data file and Log file on the drive by any database.

SELECT DB_NAME(database_id) AS DBName,Name AS Logical_Name, Physical_Name,(size*8)/1024 SizeMB
FROM sys.master_files

WHERE DB_NAME(database_id) = 'Test_CLR'
GO

----// Check how much space will it contain on the drive with the help of the command RESTORE FILELISTONLY.
1
2
RESTORE FILELISTONLY
FROM DISK = N'E:\My Work\DBA\DB Backup\Test_Data.bak';
Once you run the command it will display the details of the MDF, LDF or any other file contained in the backup. Pay attention to the column Size. This column actually contains the size of the file in bytes once the backup is restored on the database.
In our example, if you notice there are two different files MDF and LDF. The respective sizes in the bytes are as following:
  • MDF: 53477376
  • LDF: 3538944
Now you can convert the same using the following formula:
  • 1 byte = 8 bits
  • 1 kilobyte (K / Kb) = 2^10 bytes = 1,024 bytes
  • 1 megabyte (M / MB) = 2^20 bytes = 1,048,576 bytes
  • 1 gigabyte (G / GB) = 2^30 bytes = 1,073,741,824 bytes
  • 1 terabyte (T / TB) = 2^40 bytes = 1,099,511,627,776 bytes
  • 1 petabyte (P / PB) = 2^50 bytes = 1,125,899,906,842,624 bytes
  • 1 exabyte (E / EB) = 2^60 bytes = 1,152,921,504,606,846,976 bytes
Or just use Google Calculator (which I do most of the time), which also displays the formula divide the digital storage value by 1e+9.
  • MDF: 53477376 = 51 MB
  • LDF: 3538944= 3 MB

We need around 512 MB of free space if we want to restore my backup. now you can see, how to forecast the Size of Restore has a very simple solution.