<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abdellateef Ibrahim on Medium]]></title>
        <description><![CDATA[Stories by Abdellateef Ibrahim on Medium]]></description>
        <link>https://medium.com/@eng.abedibrahim?source=rss-43c31eefa5fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6VcralV2P4I1_uNnG90k_A.jpeg</url>
            <title>Stories by Abdellateef Ibrahim on Medium</title>
            <link>https://medium.com/@eng.abedibrahim?source=rss-43c31eefa5fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 09:30:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eng.abedibrahim/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Detecting Failed Logins Against SQL Server]]></title>
            <link>https://medium.com/@eng.abedibrahim/detecting-failed-logins-against-sql-server-9ff9822e397f?source=rss-43c31eefa5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ff9822e397f</guid>
            <category><![CDATA[dba]]></category>
            <category><![CDATA[extended-event]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Abdellateef Ibrahim]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 20:06:10 GMT</pubDate>
            <atom:updated>2026-11-06T20:06:10.189Z</atom:updated>
            <content:encoded><![CDATA[<p>Many of us who have worked with SQL Server have experienced a failed login attempt at least once. This can happen when connecting to a SQL Server instance using incorrect credentials, whether due to an incorrect SQL Server username, password, or both.</p><p>When you enter invalid credentials, SQL Server returns an error message similar to the following:</p><p>“Login failed for user ‘…’.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*zC-Zhh1b0-qko6YFaVc4fg.png" /></figure><p>However, this is just a login failure message that you are aware of because it originates from your own connection to SQL Server.</p><p>In a real-world environment, where multiple applications and users may be connected to the same SQL Server instance, some connection attempts may fail due to incorrect credentials without your knowledge. For example, you might update the SQL login password in all application configuration files but accidentally miss one of them. As a result, that application will continue attempting to connect using the old password.</p><p>When SQL Server receives multiple failed login attempts, the impact depends mainly on the number of attempts, how frequently they occur, and whether they originate from a single source or multiple sources.</p><p>In general, repeated failed login attempts can have several impacts on different aspects of the SQL Server environment, as explained below:</p><ol><li><strong>CPU and memory impact: </strong>Each SQL Server login attempt requires the server to process the connection request and validate the supplied credentials. The impact depends on the number of failed login attempts within a given timeframe. A small number of failed login attempts generally has a negligible impact on server resources. However, when dealing with thousands of repeated failed login attempts, the cumulative processing overhead can become noticeable, potentially affecting CPU utilization and overall server performance..</li><li><strong>SQL Server error log can grow</strong> : Failed login attempts are typically recorded in the SQL Server Error Log. If the server receives a large number of failed login attempts, the Error Log can grow significantly in size. This can make troubleshooting more difficult by generating excessive log entries and making it harder to identify important errors. Additionally, frequent logging can introduce extra disk I/O overhead..</li><li>Network/connection overhead : As mentioned earlier, each login attempt requires SQL Server to process a connection request and perform authentication. A large number of repeated attempts can consume resources associated with connection handling. If the attempts are sufficiently frequent and aggressive, they can lead to a connection-flooding or resource-exhaustion situation, potentially affecting SQL Server availability and performance, even if none of the login attempts succeeds.</li><li><strong>Application problems</strong> : if the application is keep attempting to login to SQL Server with wrong credentials , it might enter an infinite loop of failed attempts and this will affect the application itself .</li><li><strong>SQL login can become disabled </strong>: SQL Server allows password policies to be applied to SQL logins through Windows password policy enforcement. When enabled, repeated failed login attempts can trigger the account lockout policy, depending on the Windows password policy configuration. This means that a SQL login can become locked out after a specified number of consecutive failed login attempts, potentially preventing legitimate applications or users from connecting until the account is unlocked.</li></ol><p>To identify which process or application is attempting to connect to SQL Server using incorrect credentials, we can use a built-in SQL Server feature called Extended Events (XEvents).</p><p>Extended Events allows us to capture failed login attempts and collect useful information about each attempt, helping us identify the source of the connection, the application name, the login name, and other relevant details.</p><h3>Creating the Extended Events Session :</h3><p>1. From <strong>SSMS </strong>&gt; <strong>Management </strong>&gt; <strong>Extended Events</strong> &gt; Right click on <strong>Sessions </strong>and click on<strong> New Session</strong> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*AHBP8r-D9fPrxWLw06DQGw.png" /></figure><p>2. Specify the name you want in the required field , ex : FailedLogins :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*BjyLJnXVLuHCjSa9sezTBQ.png" /></figure><p>3. Click on the Events tab, then search for error_reported in the Event Library. Select the Admin channel event.</p><p>This event captures errors and messages reported by the SQL Server Database Engine, allowing us to monitor and investigate errors, including failed login attempts.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*9vG3UPPMUIh6UbIM7czlVQ.png" /></figure><p>4. Add it to the Selected Events in the right pane:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*rXiGhj-pxJY-ED0LAaUN9w.png" /></figure><p>5. After that click on Configure to add the details related to failed login , from Filter ( Predicate ) pane , we need to add 3 filters :</p><ul><li>severity = 14 indicates a security-related error or permission issue</li><li>error_number = 18456 , error raised from SQL when login failed occured and it can occur for several reasons:<br>- Incorrect SQL login password.<br>- Login does not exist.<br>- Login is disabled.<br>- SQL Server is configured for Windows Authentication only, but SQL Authentication is attempted.<br>- The login cannot access the requested database.<br>- Authentication or login configuration problems.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*YswmpQgjxkrYf1adVNp3kQ.png" /></figure><p>6. After that we need to know which process or application is triggering this error , this by going to the left pane Global Fields ( Actions ) , we will choose the output fields that can be useful for our investigation :</p><ul><li>client_app_name</li><li>client_connection_id</li><li>client_hostname</li><li>client_pid</li><li>database_name</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*X5tll2Kji4BSie9WU8ibmQ.png" /></figure><p>By completing these steps, you have added the event that will capture SQL Server errors, including failed login attempts.</p><p>Before clicking OK, you can also generate the T-SQL script for this Extended Event session by clicking the Script button in the upper-left corner and selecting your preferred output type.</p><p>This allows you to save the script for future use or deploy the same Extended Event session on another SQL Server instance. :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*EqEH50qhksiUjxkJFNAlVg.png" /></figure><p>Its script will be :</p><pre>CREATE EVENT SESSION [FailedLogins] ON SERVER <br>ADD EVENT sqlserver.error_reported(<br>    ACTION(sqlserver.client_app_name,sqlserver.client_connection_id,sqlserver.client_hostname,sqlserver.client_pid,sqlserver.database_name)<br>    WHERE (([severity]=(14)) AND ([error_number]=(18456))))<br>GO</pre><p>After creating this event , it will be listed under Sessions :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*IGjv72YWjjUzDJQslLUtGw.png" /></figure><p>Right click on it and click on Start Session to enable capturing the login failed events .</p><h3>Simulating Failed Login Action</h3><p>To view any failed login and its details , right click on the same session and choose “ Watch Live Data “ , new tab will be opened to show the details for any captured session :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*pHUFgyFYFhk3pqoyXRWoLg.png" /></figure><p>For the purpose of demonstration , I will generate a failed login from Powershell script which tries to connect to SQL Server with wrong username and password :</p><pre>$Server = &quot;Node1\DEMOSQL&quot;<br>$Database = &quot;master&quot;<br>$Username = &quot;TestLogin&quot;<br>$Password = &quot;WrongPassword123&quot;<br><br>$ConnectionString = &quot;Server=$Server;Database=master;User ID=$Username;Password=$Password;Application Name=PowerShell Login Test;Connection Timeout=5;&quot;<br><br>$Connection = New-Object System.Data.SqlClient.SqlConnection<br>$Connection.ConnectionString = $ConnectionString<br><br>try {<br>    $Connection.Open()<br>    Write-Host &quot;Connection successful!&quot; -ForegroundColor Green<br>}<br>catch {<br>    Write-Host &quot;Connection failed!&quot; -ForegroundColor Red<br>    Write-Host $_.Exception.Message<br>}<br>finally {<br>    $Connection.Close()<br>}</pre><p>After executing the script in Powershell , error appeared in Powershell state that connection failed and the SQL error generated which is related to failed login:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*8Ggta2-wCkweGJ3LoGbogQ.png" /></figure><p>Once go back to Watch Live Data in SSMS , you will see the event captured and the most important output to focus on are the highlighted below :</p><ul><li>client_app_name : The name of the application that initiated the SQL Server connection</li><li>client_hostname : The hostname of the machine that initiated the connection</li><li>client_pid : The process ID (PID) of the client application that initiated the connection .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*1N8XBxuqVtn7y4PwwD2dJQ.png" /></figure><p>Since I performed the test from the same server where SQL Server is installed, I can simply locate the corresponding Process ID (PID) in Windows Task Manager to identify the process responsible for the failed login attempt.</p><p>However, if the connection originates from a remote server or application, the captured event can also provide the Hostname and Process ID, helping us identify the remote source of the connection and investigate which application or process is generating the failed login attempts</p><h3>Monitor Failed Logins Silently</h3><p>In some situations, you may need to monitor SQL Server for failed login attempts without continuously watching the live event data. Instead, you may want to capture these events and store them in a file so you can review them later for investigation, analysis, and reporting.</p><p>This can be achieved using the same Extended Events session by adding an event target that writes the captured events to a file.</p><p>To do this, go back to the Extended Events session we created earlier. First, stop the session by right-clicking it and selecting Stop Session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*996XdeHYFGDeNz6Ah9FP2A.png" /></figure><p>Next, right-click the same Extended Events session, select Properties, and navigate to Data Storage.</p><p>Under Targets, select event_file and specify the destination path where you want SQL Server to store the captured events.</p><p>You can also configure additional settings to control the file storage, such as:<br>- Maximum File Size: Defines the maximum size of each event file. In this example, I set it to 1 GB per file.<br>- Maximum Number of Files: Defines how many event files can be generated. In this example, I set it to 5 files.<br>- Enable Rollover: Allows SQL Server to reuse the available file space by removing the oldest event data when the configured file limit is reached. This means older events will eventually be overwritten as new events are captured.<br>Once you have configured the required settings, click OK to save the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*KyjrlU9tE4y9SS_BiGyUpg.png" /></figure><p>Then go to the session and start it :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*zz_pRCO3gDB6XTVahbsjaA.png" /></figure><p>You will see a file automatically created in the target path :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*Tn-9OabneYgZCiCVHpWgUQ.png" /></figure><p>Any failed login will be captured and logged in the session’s file , and once the file size reach 1 GB , new file will be opened till we reach 5 files , and once the 5th file reach 1 GB , the process will be rolled over and start logging the events from the first file.</p><p>The below is the session’s SQL script after adding target file to save the events to it , you need to adjust the target path only based on your need :</p><pre>CREATE EVENT SESSION [FailedLogins] ON SERVER <br>ADD EVENT sqlserver.error_reported(<br>    ACTION(sqlserver.client_app_name,sqlserver.client_connection_id,sqlserver.client_hostname,sqlserver.client_pid,sqlserver.database_name)<br>    WHERE ([severity]=(14) AND [error_number]=(18456)))<br>ADD TARGET package0.event_file(SET filename=N&#39;E:\Failed Logins Against SQL Server\FailedLogins.xel&#39;)<br>WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF)<br>GO</pre><h4>Reading from .xel file and view the results in tabular mode :</h4><p>The captured Extended Events data is stored in an .xel file (Extended Events Log file), using an XML-based format.</p><p>To make this data easier to read and analyze, we can use the following T-SQL query to read the .xel file and extract the failed login information into separate columns, making it easier to investigate and identify the source of the failed login attempts.</p><pre>SELECT<br>    XEvent.value(&#39;(event/@timestamp)[1]&#39;, &#39;datetime2&#39;) AS EventTime,<br><br>    XEvent.value(&#39;(event/data[@name=&quot;error_number&quot;]/value)[1]&#39;, &#39;int&#39;) AS ErrorNumber,<br><br>    XEvent.value(&#39;(event/data[@name=&quot;severity&quot;]/value)[1]&#39;, &#39;int&#39;) AS Severity,<br><br>    XEvent.value(&#39;(event/data[@name=&quot;state&quot;]/value)[1]&#39;, &#39;int&#39;) AS State,<br><br>    XEvent.value(&#39;(event/data[@name=&quot;message&quot;]/value)[1]&#39;, &#39;nvarchar(max)&#39;) AS ErrorMessage,<br><br>    XEvent.value(&#39;(event/action[@name=&quot;client_app_name&quot;]/value)[1]&#39;, &#39;nvarchar(256)&#39;) AS ClientAppName,<br><br>    XEvent.value(&#39;(event/action[@name=&quot;client_hostname&quot;]/value)[1]&#39;, &#39;nvarchar(256)&#39;) AS ClientHostname,<br><br>    XEvent.value(&#39;(event/action[@name=&quot;client_pid&quot;]/value)[1]&#39;, &#39;int&#39;) AS ClientPID,<br><br>    XEvent.value(&#39;(event/action[@name=&quot;client_connection_id&quot;]/value)[1]&#39;, &#39;nvarchar(100)&#39;) AS ClientConnectionID<br><br>FROM<br>(<br>    SELECT CAST(event_data AS XML) AS XEvent<br>    FROM sys.fn_xe_file_target_read_file<br>    (<br>        &#39;E:\Failed Logins Against SQL Server\FailedLogins*xel&#39;,<br>        NULL,<br>        NULL,<br>        NULL<br>    )<br>) AS EventData<br><br>ORDER BY EventTime DESC;</pre><p>Lets break the query and explain its parts :</p><p>The SELECT section :</p><ul><li>Each XEvent.value() extracts a specific value from the XML event data</li></ul><p>The FROM (SELECT CAST(event_data AS XML) AS XEvent</p><ul><li>event_data contains the captured Extended Events information.</li><li>CAST(event_data AS XML) converts the event data into XML format.</li><li>XEvent is the alias given to the XML data</li></ul><p>The FROM sys.fn_xe_file_target_read_file<br>(<br> ‘E:\Failed Logins Against SQL Server\FailedLogins*xel’,<br> NULL,<br> NULL,<br> NULL<br>)</p><ul><li>This function <strong><em>sys.fn_xe_file_target_read_file</em></strong> reads the Extended Events file</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9mCltaPsT32QqBple_yKg.png" /></figure><p>So , we may raise question of what is next ? I collected the failed logins , what can I do as DBA ?</p><p>After capturing failed login events using Extended Events, the DBA should:</p><p>1. Identify the failed login: Determine which SQL login is generating authentication failures.</p><p>2. Investigate the failure reason: Use the error state to understand why authentication failed.</p><p>3. Identify the source: Determine which machine, application, and process initiated the connection.</p><p>4. Check login configuration: Verify whether the login exists, is disabled, or has incorrect credentials.</p><p>5. Investigate repeated failures: Identify unusual patterns or potential brute-force attempts.</p><p>6. Coordinate with application teams: Correct outdated passwords, connection strings, or application configurations.</p><p>7. Apply security measures: Restrict suspicious sources and review login permissions when necessary.</p><p>8. Automate monitoring: Use SQL Agent Jobs to process XE files and detect repeated failures.</p><p>9. Configure alerts: Use Database Mail to notify the DBA when predefined failure thresholds are exceeded.</p><p>10. Maintain historical records: Store captured events in a SQL table for auditing, reporting, and future investigations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ff9822e397f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Server Always on Availability Group Series : Enable Always on for 3 Multi-Subnets Nodes]]></title>
            <link>https://medium.com/@eng.abedibrahim/sql-server-always-on-availability-group-series-enable-always-on-for-3-multi-subnets-nodes-c8684c0383d5?source=rss-43c31eefa5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8684c0383d5</guid>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[hadr]]></category>
            <category><![CDATA[sql-ag]]></category>
            <category><![CDATA[high-availability]]></category>
            <dc:creator><![CDATA[Abdellateef Ibrahim]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 13:22:37 GMT</pubDate>
            <atom:updated>2026-09-23T13:24:36.877Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most important thing that any IT or Database Administrator aiming to achieve today is to ensure that the application is always available when it comes to storing the application data into Database , alongside with keeping the application is always accessible and browsable with minimal to zero downtime.</p><p>Achieving the high availability requires aligning the application with Microsoft SQL Server requirements and choose the right technology which covers the need for this and based on how your application is built and what the business actually requires , not just enabling all features blindly since this may cost additional time , effort and money.</p><p>In terms of what technologies are available to achieve high availability ,we have Microsoft SQL Server Always-On Availability Groups (AG). Basically this technology provides access to user databases by synchronizing them across multiple SQL Server instances running on separate servers. Always-On Availability Groups (AG) supported in both Enterprise and Standard Editions, though Standard edition provides a limited features known as <strong>Basic Availability Groups </strong>, below is comparison between both editions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*_Vp32wX7P8aHz_HdE280qw.png" /></figure><p><strong>Demo Lab :</strong></p><p>We have three servers hosting SQL Server 2025 Enterprise edition , two servers acting as production servers ( Node1 , Node2 ) and 1 as DR server ( Node3 ) , DR server resides in different subnet to simulate a real live environment setup, subnets 192.168.10.x and 192.168.20.x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*_yqN9xlgMhx9Ac2fCgY6-g.png" /></figure><p>So we will begin enable Always on AG feature by navigating to one of the the servers and we will choose Node1 . So from Node1 &gt; SQL Server Configuration Manager &gt; Select the SQL Server Services &gt; SQL Server ( Node1 ) &gt; Right click and select Properties</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZ2ZrL4McRoxj2CoigRZGA.png" /></figure><p>Navigate to Always on Availability Group pane and enable the feature highlighted in Red .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*5zxW8veToBmZTyRGhBYTeg.png" /></figure><p>But if you may notice , there is part above the checkbox above which is related to Windows Server Failover Cluster ( WSFC ) , what is WSFC ? and why it is required to have it configured in the servers ( all nodes ) ? basically the WSFC will act as orchestration engine for managing the underlying servers , quorums and automatic failovers. While SQL Server handles Database level data replication and transaction logging , there are more details and full description on the WSFC available in this article ( <a href="https://medium.com/@eng.abedibrahim/sql-server-always-on-availability-group-series-window-server-failover-cluster-wsfc-in-details-68cd5b6ab72e?sharedUserId=eng.abedibrahim">Windows Server Failover Cluster </a>).</p><p>Moving forward and once click on Apply, small box appear to restart the SQL Service to apply the changes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*xmvzQw9trUKglm-UikB7Jw.png" /></figure><p>So we restart the SQL Server Engine Service from the following button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*EnbTZQmjqxCDZ-APDriGRQ.png" /></figure><p>As a result , we have enabled this feature in Node1 , you need to do the same in all other nodes which are targeted to be added in the Always on , this is required. On this level we just enabled the feature of Always on AG, we did not configure it yet .</p><p>But before moving next to the configuration of AG, below settings should be enabled to make sure we can configure the feature and all nodes can be added:</p><ol><li>Port 5022 enabled and rule ( Bidirectional ) in firewall for all nodes : this port mainly for exchanging the traffic from SQL Server to SQL Server communication and data replication . The need for enabling the port bidirectionally , since each SQL Server can be primary or secondary.</li><li>Port 1433 in configuration manager and enabled in the firewall as incoming rule in each node : this is client to SQL Server port , once trying to add nodes to AG from SSMS ( as will show this later in this story ) , SSMS is considered as client and therefore 1433 should be enabled. However the port here may be different depend on what custom port you are using instead of 1433</li><li>SQL Server Browser Service in running mode : in case you are using SQL Server named instances , any client or application will need to know what port the SQL engine it is listening , as it may be not the default one 1433</li><li>Service account to be used as login for SQL Server Service ( Recommended ) : A dedicated domain service account lets SQL Server communicate securely across network servers for Always On features while strictly limiting its permissions on the local machine for safety.</li></ol><p>Now and once done the above , we navigate to SQL Server Management Studio SSMS &gt; Always on Availability Group , to create a new availability group which will allow us to configure this feature .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*d5EjJlTsEgsZHnGwJl-6hA.png" /></figure><p>From the wizard , first we provide a name for the AG ( Availability Group ) , we will give it name DemoAG, and we will choose Cluster Type to be Windows Server Failover Cluster , as we mentioned above this WSFC is an orchestration engine for managing the server and failover processes..etc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*eDeUIx5jHxkIMKJsPw3qRA.png" /></figure><p>Moving next to select the required database to be participated in the always on feature , below it saying a Full Backup is required , so we take full backup for the database and then refresh the page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*py3R40w0r6C5UGcoXbUIvA.png" /></figure><p>After backing up the database and refreshing the page , the database is ready to be selected , keep in mind that the other requirement that make the DB eligible to be selected in AG that the database recovery mode must be in Full Recovery mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*lbfs0LVjcQcJyvhnmHyykg.png" /></figure><p>Moving next to add the needed replicas or nodes , in this page you will see Node1 added automatically and its Role is Primary . Now the setup of this AG will be Node1 and Node2 will be in Synchronous Mode with Automatic Failover since they are assigned to the same subnet. Meanwhile we will add Node3 to act as DR node with Manual Failover and Asynchronous Mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ASHMLnNK3RFHFCQxrm3ew.png" /></figure><p>But what is Synchronous Mode and Asynchronous Mode ? These modes control how the primary node handles the transaction log commit in all secondaries before confirming a commit on your application :</p><ul><li>Synchronous Mode ( in our AG between Node1 and Node2 considering Node1 is the primary) : The primary node writes transaction log locally and send them to secondaries , in the same time the primary holds off the commit message to be send to the application till the secondaries confirm that the same logs has been written and hardened in their transaction log files. This guarantees both nodes are 100% in sync at all times, making automatic failover possible without losing data</li><li>Asynchronous Mode ( in our AG between Node1 and Node3 considering Node1 is the primary): The primary nodes writes transaction log locally and send them to the secondary , and then directly confirm a commit to the application without waiting the secondary’s acknowledge that the log is hardened. By design , DR ( Node3 ) reside in different datacenter that may be allocate in far away distance from the primary , so to prevent network latency between Primary and DR and to avoid any database performance issue on Primary , Asynchronous Mode is chosen.</li></ul><p>Going back to our AG configuration and by click on Add Replica button, a small box appears to connect to the target replica , we will add Node2 and the same to do for Node3 ( DR Node ) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VN4INfrzaiXMbXpCokxnBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7YB3Poq0lYvggeDExqJqVw.png" /></figure><p>Moving next to select the Seeding method , we have the following options , each options has its own description underneath it , we will choose Automatic Seeding to automatically stream the database files across the network to all secondaries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvJQDsyeO7G4jsgpKPb26w.png" /></figure><p>Next page is for Validation , it should shows all steps succeeded , the last one is for configuring Listener which we will configure it later in this story</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzJmdofzi2z1BRJhb9dRfg.png" /></figure><p>Next page is summary page for all configurations done previously , click on Finish to allow the SQL Server to apply these configurations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGEpDYz1yd1ioDqrtul3NQ.png" /></figure><p>Once done , all steps below should be done successfully</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpic3DI4j8HcioIVJMhiLw.png" /></figure><p>To make sure everything is ok , you can refresh the Always on Availability Group in SSMS and expand it to see the changes , replicas were added , DB is included , and underneath the Databases section , you will notice a ( Synchronized ) beside the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*kdNhHylcXtR173jEACeQtw.png" /></figure><p>Navigating to SSMS in Node2 and Node3 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*yMhdhhg7b92Kwq5P6ad1zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*42JpsV-XaAUFpJkmnmWOmw.png" /></figure><p>Database is propagated into the other 2 servers due to the option of Automatic Seeding , in this lab we have a small size DB , so it is synced in short period of time , the time of seeding will depend on the size of the database , if the database is in syncing process in Node2 and Node3 , you will see ( Restoring ) status beside the database and once finish it will be changed to Synchronized .</p><p>And as long as we configured this feature in Node1 , it will become the primary node by default , Node2 and Node3 will be considered as secondaries.</p><p><strong>Configure AG Listener</strong></p><p>Now that the AG is ready and the databases are synchronized across all secondary replicas, we can connect our application to the Availability Group. But how does the application know which node is currently the primary whether it is Node1, Node2, or Node3?</p><p>If we configure the application’s connection string to point directly to a specific node’s instance name or IP address, it will only work as long as that node remains the primary. If a failover occurs, that node will no longer hold the primary role, and application connections will fail.</p><p>This is where the Listener takes over. The Listener is a Virtual Network Name (VNN) with its own IP/s that the application connects to. It automatically routes application traffic to whichever node is currently acting as the primary. Regardless of which node takes on the primary role, the Listener ensures the application is always guided to the correct node</p><p>Now , we will create the Listener on our AG created . Navigate to SSMS &gt; Expand Always on High Availability &gt; Expand the created AG &gt; Right click on Availability Group Listener &gt; Add Listener</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*NZfO1JEpqUoHksxngAvdNA.png" /></figure><p>A configuration window will appear to set the Listener Name , Port and IP , we will assign a Static IP for the Listener</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*_mx9BXtwKTLltShhPdMX_Q.png" /></figure><ul><li>Listener Name : DemoLSTNR</li><li>Port : 1433</li><li>IP/s : since we have multiple subnets configured 192.168.10.x and 192.168.20.x , we need to add 2 IPs for this listener , why ? An AG Listener requires a dedicated IP address for every subnet hosting a replica because a single IP address cannot exist or bind natively across two separate network subnets . So we will give IPs 192.168.10.8 and 192.168.20.8 as Listener IPs</li></ul><p>By click on Add button , we will add the first IP 192.168.10.8</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*PE-Qh8xdnFajjpd1O63UQQ.png" /></figure><p>And click on Ok , the IP will be added :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*pxBQAMH265AGATs4epRSIA.png" /></figure><p>Once added the first IP and then try to add the second IP , the other subnet will be assigned automatically waiting for you to enter the second IP :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*rl9bP-e4xxjTA-trqtRJWA.png" /></figure><p>Click on Ok to add the second IP :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*INBsUGFJb3TxSyDY1mIrAA.png" /></figure><p>Now click on OK in the very end of this configuration window to apply the configurations , and you will see a new object created underneath the Availabilty Group Listeners</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*iUM3Bp69aZaXOhQoq5bjQA.png" /></figure><p>Now to verify this Listener hostname , we can ping it to find out what its IP . As long as the primary role assigned to subnet 10.x , once ping the Listener it should resolve to 192.168.10.8</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*3J3MjvLBV4T5yd5IeAfufw.png" /></figure><p>And from WSFC manager , once navigate to Roles , we will see the created AG listed there along with its listener IPs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdUkXz4RbViY8eE44PfR1A.png" /></figure><p>By design , one listener IP will be online for the active subnet , while the other IP will be offline , and this is called <strong>Subnet Bounding </strong>as the Listener’s Virtual Network Name (VNN) needs an IP address that is valid within each network location. The 192.168.10.8 IP handles client traffic when the primary is in Subnet 192.168.10.x , and the 192.168.20.8 IP handles traffic when the primary fails over to Subnet 192.168.20.x</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8684c0383d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Server Always on Availability Group Series : Window Server Failover Cluster WSFC in Details]]></title>
            <link>https://medium.com/@eng.abedibrahim/sql-server-always-on-availability-group-series-window-server-failover-cluster-wsfc-in-details-68cd5b6ab72e?source=rss-43c31eefa5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/68cd5b6ab72e</guid>
            <category><![CDATA[windows-server]]></category>
            <category><![CDATA[wsfc]]></category>
            <category><![CDATA[windows-server-2022]]></category>
            <category><![CDATA[failover-cluster]]></category>
            <dc:creator><![CDATA[Abdellateef Ibrahim]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 13:18:35 GMT</pubDate>
            <atom:updated>2026-09-23T13:18:35.499Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are working as a System Administrator, Database Administrator, Infrastructure Engineer, or in any role that interacts with the Windows Server systems, you have definitely heard about high-availability setups with near-zero downtime.</p><p>You know the headache that comes that IT teams facing everyday such as sudden disk failure, an urgent OS update patch need to be installed ,an application process freezing completely, or even a total data center outage caused by a severed fiber optic link . In all of these situations ensuring that server resources, storage, virtual IP addresses, and database instances remain continuously accessible by automatically shifting them to a healthy node the moment something failed , and that&#39;s what Windows Server Failover Cluster WSFC is do.</p><p>WSFC is core operating system feature that design to handle the above scenarios before it comes to business disaster . Rather than relying on manual intervention during an emergency . WSFC act as coordinator across the servers by solving the major challenges which are :</p><ul><li>Automating Hardware &amp; Service Failovers</li><li>Near Zero Downtime Maintenance</li><li>Bridging Datacenters for DR failovers</li><li>Preventing Data Corruption.</li></ul><h3>WSFC Deployment :</h3><p>We will have a common setup we will consider it in SQL Server AG Series articles , which is three servers hosting SQL Server 2025 Enterprise edition , two servers acting as production servers ( Node1 , Node2 ) and 1 as DR server ( Node3 ) , DR server resides in different subnet to simulate a real live environment setup, subnets 192.168.10.x and 192.168.20.x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*_yqN9xlgMhx9Ac2fCgY6-g.png" /></figure><p>Make sure that all 3 nodes are joined to a domain .</p><p>First , I will demonstrate the cluster on 2 nodes in main site , then add DR site in different subnet</p><p>In both nodes 192.168.10.11 and 192.168.10.12 , I will enable feature ( Failover Clustering )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*1ye7GNtutKJRd3KCYt3yVA.png" /></figure><p>Then open the WSFC &gt; Validate Cluster and add both nodes by entering the Node full hostname in the field and click on Add</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*_jvak_z6f2s3MWHmbcma7A.png" /></figure><p>After click on next and start validating , the process finished and I did not receive any error considered as stopper for creating the cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*f5YctRGK8Hi68oVeOgSgeA.png" /></figure><p>I reviewed the report and found the following :</p><p>Warning is related to install windows updates</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*f7b5A70jFtTuUgSkhDrf3w.png" /></figure><p>Lets move now to create the cluster as there is option to create the cluster after finish reviewing the report , and re-add both Node1 and Node2. We will choose a name for the cluster which is CLSTRLAB-A</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*mbPpIXgjidMnYKHRq10Jrw.png" /></figure><p>After naming the cluster : CLSTRLAB-A and gave IP 192.168.10.9, cluster was created . I parallel , you will find new record added in DC in Active Directory Users and Computers &gt; Computers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*tb83bWZ4jVPoWEMfO3bt3Q.png" /></figure><p><strong>Adding Node3 DR site to the cluster</strong></p><p>By applying the same done on Node1 or Node2 , enabling the Failover clustering feature in Node3 server is required.</p><p>Navigate to Node1 or Node2 , and from WSFC &gt; Nodes &gt; Add node</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*9Yyo5XgAmlbNE_Al6rNLMA.png" /></figure><p>When entered the server name for Node3 and clicked on Add, we received below message stating that the operation is taking longer than expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*LxfoKbZ2uZMLOzm1U1g3qg.png" /></figure><p>And after that received the below error :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*hYVE4VhNmiM0evojUyou8w.png" /></figure><p>To troubleshoot , check the below :</p><ul><li>Ping cluster name ( CLSTRLAB-A ) from Node3 , make sure it is reachable and provide a TTL results</li><li>Failover Cluster feature enabled from roles and features before adding Node3 to the cluster</li><li>Cluster service should be enabled but not started in Services</li><li>Check Remote Registry service in Node3</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*1GJix1NA8pra8XwzMGE7sA.png" /></figure><p>Now after checked and solved the above points , I was able to add node3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*PZlu0n9xsuHg5Jn5XpkN_w.png" /></figure><p>Click on Next and Finish to add the Node3 to the cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*UVVV3bK2s87BS8Rl0PMmNg.png" /></figure><p>After adding node3 to the cluster, you should see 2 networks now, each network covers each subnet that the nodes are assigned to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*cX7u6pDfkvWWr27_Zsdvgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*tq66lMO8WQeNdUcv9VO-Mw.png" /></figure><p>And for the best practice setup , in a multi-subnet Windows Server Failover Cluster (WSFC), you must assign an IP address for each subnet because IP addresses are bound to their specific Layer 3 routing boundaries . So you need to add and IP for the cluster to point to DR site , as we have 192.168.10.9 only which work on main site .</p><p>Now right click on the cluster name below and select properties</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*E4CkHqRKonimSVUuMKYQ9g.png" /></figure><p>You will find one IP which point to subnet 192.168.10.x :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*WKtyYw4pW9t0AdmaxtE9gQ.png" /></figure><p>Click on add and assign IP for DR site which is 192.168.20.9</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*ihxRuR8GAwYPvk-X8JwBqw.png" /></figure><p>To be like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*KhfnpUNq-PgHvcLEGFujlA.png" /></figure><p>And once to review the resource IP in the Cluster Core Resource part , you will find 2 IPs , one is online and the other for DR is offline. This is normal and expected since the Cluster Core Resource CLSTRLAB-A is pyhsically located in network subnet 192.168.10.x so the IP assigned and brought online is 192.168.10.9</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*5K2c_cC8t2RXXLtHZmuS1A.png" /></figure><p>If you initiate a failover of CLSTRLAB-A to a node in the DR site 192.168.20.x, the IP resource statuses will automatically swap to bring 192.168.20.9 online and leaving 192.168.10.9 in offline state.</p><p>What will happen if we did not add the DR IP for the WSFC ?When a failover occurs to the DR node, WSFC will attempt to bring the single Prod IP address online on the DR node. Because the DR node does not have a local network interface matching the Prod IP’s subnet, the IP Address resource will fail to start.</p><p>Now , WSFC is created , and all nodes were joined , WSFC nodes begin communicating with each other over port 3343 . Primary will send a periodic keep alive messages to all secondaries , all secondaries will do the same with the primary. Also , a keep alive messages are being exchanged between the same secondaries since if the Primary node dies, the secondaries must already know each other’s health status so they can immediately hold an election</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68cd5b6ab72e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring SQL Server Agent Jobs & Sending Email Notifications]]></title>
            <link>https://medium.com/@eng.abedibrahim/monitoring-sql-server-agent-jobs-sending-email-notifications-eb3488e6782a?source=rss-43c31eefa5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb3488e6782a</guid>
            <category><![CDATA[sql-server-agent]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[monitor-sql]]></category>
            <dc:creator><![CDATA[Abdellateef Ibrahim]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 19:44:43 GMT</pubDate>
            <atom:updated>2026-08-25T19:44:43.862Z</atom:updated>
            <content:encoded><![CDATA[<p>Apart from SQL Server monitoring, you can monitor SQL Server Agent jobs and trigger notifications to specific recipients on certain conditions such as when the job failed or not.</p><p>If you want to get more familiar with SQL Agent Jobs , please refer to this article <a href="https://medium.com/@eng.abedibrahim/sql-server-agent-jobs-2c7d0690c3e3"><strong>SQL Server Agent</strong></a><strong>.</strong></p><p>We will consider that you have created the SQL Agent Job/s , and you need to monitor them especially to ensure you get notified immediately if a job fails.</p><p>To achieve this in our demo lab, you need to define a recipient who will receive email notifications. Please note that while there are third-party applications that can handle this, I am demonstrating how to rely solely on native SQL Server features without using any external or open-source tools.</p><p>To define a recipient, you must create an object called an Operator in SQL Server Agent. An Operator is a predefined contact (or a group of contacts) that SQL Server Agent can notify when specific events occur.</p><p>Before you can create Operators, you first need to enable notifications in SQL Server Agent. You can do this by right-clicking SQL Server Agent, selecting Properties, and navigating to the Alert System page. Check the box to enable the mail profile, and then select the profile you created when configuring Database Mail.</p><p><em>Take into consideration that Database Mail </em><strong><em>must</em></strong><em> be configured as prerequisite and you can refer to my other article </em><a href="https://medium.com/@eng.abedibrahim/database-mail-in-sql-server-2022-4d9a1908c17c"><strong><em>Database Mail</em></strong></a><strong><em> </em></strong><em>to achieve this.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/0*Cz5JbjgDG5AjN2Vs.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*pkiJfpVC1YO7Y5r0.png" /></figure><p>After enabling the mail profile and clicking OK, please restart the SQL Server Agent service to apply the changes.</p><p>Once the service has restarted, you can create a new Operator. To do this, expand SQL Server Agent in the Object Explorer, right-click Operators, and select New Operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/0*wfz2vwoPRkePGE41.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*kamsmte-0IkOrtex.png" /><figcaption>General page contains the following options :</figcaption></figure><p><strong>Name</strong> : Operator name</p><p><strong>Email</strong> : Operator email address</p><p><strong>Pager Email Name</strong> : this is legacy option was intended for pagers ( beepers ) which were popular years ago , pager provider can provide you an email address such as 1234567@pagerprovider.com .</p><p>SQL Server agent will send email to this address and the pager service would convert it into pager message. Almost <strong>no one</strong> use this option.</p><p><strong>Pager on duty schedule</strong> : this option applies on Pager Email name only and since we will not use it , we will leave it blank.</p><p>After click on OK , operator will be created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/0*WvOzhEuUnKOBUHLh.png" /></figure><p>You can now use this Operator in a SQL Agent Job to send a notification if the job fails.</p><p>To configure this, open the job properties and navigate to the Notifications page. Check the box for email, select the Operator you just created from the drop-down list, and choose one of the three available conditions: When the job succeeds, When the job fails, or when the job completes. In most practical scenarios, you will only need to monitor for failures, so you should select When the job fails.</p><p>Finally, click OK to save your changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/0*LdZsq71_7SgICDpq.png" /></figure><p>The job has its own schedule that will run based on it, but we will run it manually by right click on the job and click Start Job at Step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*ngbkpRRstfuwyDW1.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/0*kAGomXDVR0DqUQiT.png" /></figure><p>Whenever a job fails or succeeds, a record is inserted into the sysmail_mailitems table within the msdb database. This table contains all the details of the email transaction, including the recipient, CC, BCC, subject, sent status (success or failure), timestamp, and more. You can easily query this table whenever you need to review a history of all triggered emails.</p><pre>SELECT TOP 1 sent_status,subject,body,send_request_user,*<br>  FROM [msdb].[dbo].[sysmail_mailitems]<br>  order by mailitem_id desc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*V3hSHmjbUMkrYEE4.png" /></figure><p>Since you configured the job to notify us upon failure, DatabaseMail.exe will initiate the email sending process whenever a failure occurs. The email will be routed through the configured SMTP server to the recipient (the Operator we defined earlier).</p><p>The recipient will receive an email formatted as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*IUDvswWikz0nYPvE.png" /></figure><p>Note that this email template is generated by SQL Server at runtime rather than being stored in a table. As a result, you cannot modify the default layout for SQL Server Agent job notifications. Additionally, the native notification system does not allow you to CC other recipients on these automated alerts.</p><h3>Customize the notification email</h3><p>If the default email template meets your needs, the standard notification setup is sufficient. However, if you require a custom layout or additional details, you will need to modify the notification process. Below are a few approaches you can use to send custom emails:</p><p><strong>Send Email in Job Step (TRY/CATCH)</strong></p><p>You can use TRY…CATCH blocks to validate whether a script executes successfully. The TRY block contains the main script. If an error occurs during execution, the logic within the CATCH block is triggered. Inside this CATCH block, you can capture details like the error message, error number, line number, and severity, and then send them via email to the intended recipient(s).</p><p>To send the email, you will use msdb.dbo.sp_send_dbmail, which is a built-in stored procedure in Microsoft SQL Server. This procedure allows you to send email messages directly from the SQL Server Database Engine and accepts several parameters, such as:</p><ul><li>@profile_name : Database Mail profile you will use to send the notification, the same one once you configured Database Mail in the first time :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*Z0RP94BWqemU2rNH.png" /></figure><ul><li>@recipients: The (To) list of primary recipient/s</li><li>@copy_recipients: CC recipient/s</li><li>@subject: Email subject</li></ul><p>Example of ( TRY / CATCH ) script which contain sending email notification :</p><pre>Begin Try<br>/*Your block of script inserted here */--Ex: <br>Select 1 / 0<br>End Try<br>Begin Catch<br>    Declare @Body nvarchar(500)<br>    SET @Body =<br>        &#39;The script execution failed.&#39; + CHAR(13) + CHAR(10) +<br>        &#39;Error Number: &#39; + CAST(ERROR_NUMBER() AS VARCHAR(10)) + CHAR(13) + CHAR(10) +<br>        &#39;Error Message: &#39; + ERROR_MESSAGE() + CHAR(13) + CHAR(10) +<br>        &#39;Error Line: &#39; + CAST(ERROR_LINE() AS VARCHAR(10)) + CHAR(13) + CHAR(10) +<br>        &#39;Severity: &#39; + CAST(ERROR_SEVERITY() AS VARCHAR(10));<br>    EXEC msdb.dbo.sp_send_dbmail<br>        @profile_name = &#39;AlertsProfile&#39;,<br>        @recipients = &#39;recipient@gmail.com&#39;, -- you can add more than one recipient separated by comma<br>        --@copy_recipients = &#39;recipient1@example.com;recipient2@example.com&#39;, -- OPTIONAL : if you want to add CCs<br>        @subject = &#39;Script X Failed&#39;,<br>        @body = @Body<br>End Catch</pre><p>Once the above script being executed and if there was error captured , email notification will be triggered , example of email received from the above script</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*FIKzMK3DA1xfCaTz.png" /></figure><p><strong>Job Step Failure Action</strong></p><p>Another approach is to add your email notification script as a separate, subsequent step. You can then configure your main step to proceed directly to this email step if a failure occurs.</p><p>To configure this, open the properties of your main step, navigate to the Advanced page, and set the On failure action to Go to the next step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*kC8Kies8hX1MnOih.png" /></figure><p>And the next step will be the email notification script to send:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/0*QBBriFiPuNSHlgCG.png" /></figure><p>Example of script for sending email:</p><pre> EXEC msdb.dbo.sp_send_dbmail<br>        @profile_name = &#39;AlertsProfile&#39;,<br>        @recipients = &#39;recipient@gmail.com&#39;, -- you can add more than one recipient separated by comma<br>        --@copy_recipients = &#39;recipient1@example.com;recipient2@example.com&#39;, -- OPTIONAL : if you want to add CCs<br>        @subject = &#39;Job X failed&#39;,<br>        @body = &#39;Job X failed , please check ...&#39;</pre><p><strong>Query MSDB Job History</strong></p><p>In this approach, you can create a job to run every x minutes depending on the jobs schedules configured , this job will monitor the SQL Agent Jobs in the last X minutes and send email listing the failed ones .</p><p>The below query retrieves SQL Server Agent jobs that failed within the last 30 minutes, including the job name, execution time, duration, failed step, and error message.</p><p>It uses the SQL Server Agent system tables in the msdb database:</p><ul><li>sysjobs : contains SQL Agent job details, such as the job name and job_id.</li><li>sysjobhistory : contains the execution history, status, duration, and messages for jobs and their individual steps.</li></ul><p>The CROSS APPLY uses a correlated subquery to find the most recent failed step for each failed job. Top (1) with Order By instance_id Desc ensures that the latest failed step and its error message are returned.</p><pre>WITH JobHistoryWithDateTime AS<br>(<br>    SELECT<br>        h.instance_id,<br>        h.job_id,<br>        j.name,<br>        h.message,<br>        h.run_status,<br>        h.server,<br>        h.run_duration,<br>        CAST(<br>            STUFF(STUFF(CAST(run_date AS CHAR(8)),5,0,&#39;-&#39;),8,0,&#39;-&#39;)<br>            + &#39; &#39; +<br>            STUFF(STUFF(RIGHT(&#39;000000&#39; + CAST(run_time AS VARCHAR(6)),6),3,0,&#39;:&#39;),6,0,&#39;:&#39;)<br>            AS DATETIME<br>        ) AS RunDateTime<br>    FROM msdb.dbo.sysjobhistory h<br>    INNER JOIN msdb.dbo.sysjobs j<br>        ON h.job_id = j.job_id<br>    WHERE h.step_id = 0<br>)<br>SELECT<br>    JR.job_id,<br>    JR.name AS JobName,<br>    JR.server,<br>    JR.RunDateTime, <br>    (<br>        (JR.run_duration / 10000) * 3600 +<br>        ((JR.run_duration % 10000) / 100) * 60 +<br>        (JR.run_duration % 100)<br>    ) AS DurationInSeconds,<br>    HS.step_id,<br>    HS.step_name,<br>    HS.message AS ErrorMessage<br>FROM JobHistoryWithDateTime JR<br>CROSS APPLY<br>(<br>    SELECT TOP (1)<br>        H.step_id,<br>        H.step_name,<br>        H.message<br>    FROM msdb.dbo.sysjobhistory H<br>    WHERE H.job_id = JR.job_id<br>      AND H.instance_id &lt; JR.instance_id<br>      AND H.step_id &gt; 0<br>      AND H.run_status = 0<br>    ORDER BY H.instance_id DESC<br>) HS<br>WHERE JR.run_status = 0<br>  AND JR.RunDateTime &gt;= DATEADD(MINUTE, -30, GETDATE())<br>ORDER BY JR.RunDateTime DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*p7c5wyEBrjUXcT_r.png" /></figure><p>Will send this query output by email through sp_send_dbmail , by designing an email with HTML and style it with CSS , the script is a bit long however we will go through it part by part .</p><p><strong>Part 1</strong> : We will check first if there is any job(s) failed during the last x minutes by using the below script that contains a CTE and temporary table with joins , this query get the failed job(s) , then we will count the records in that temporary table .</p><p>If no job failed , the script will stop on this stage without any need to proceed further with HTML email creation</p><pre>IF OBJECT_ID(&#39;tempdb..#JobsHistory&#39;) IS NOT NULL <br>BEGIN<br>DROP TABLE #JobsHistory<br>END<br><br>;WITH JobHistoryWithDateTime AS<br>(<br>    SELECT<br>        h.instance_id,<br>        h.job_id,<br>        j.name,<br>        h.message,<br>        h.run_status,<br>        h.server,<br>        h.run_duration,<br>        CAST(<br>            STUFF(STUFF(CAST(run_date AS CHAR(8)),5,0,&#39;-&#39;),8,0,&#39;-&#39;)<br>            + &#39; &#39; +<br>            STUFF(STUFF(RIGHT(&#39;000000&#39; + CAST(run_time AS VARCHAR(6)),6),3,0,&#39;:&#39;),6,0,&#39;:&#39;)<br>            AS DATETIME<br>        ) AS RunDateTime<br>    FROM msdb.dbo.sysjobhistory h<br>    INNER JOIN msdb.dbo.sysjobs j<br>        ON h.job_id = j.job_id<br>    WHERE h.step_id = 0<br>)<br>SELECT<br>    JR.job_id,<br>    JR.name AS JobName,<br>    JR.server,<br>    JR.RunDateTime, <br>    (<br>        (JR.run_duration / 10000) * 3600 +<br>        ((JR.run_duration % 10000) / 100) * 60 +<br>        (JR.run_duration % 100)<br>    ) AS DurationInSeconds,<br>    HS.step_id,<br>    HS.step_name,<br>    HS.message AS ErrorMessage<br>INTO #JobsHistory<br>FROM JobHistoryWithDateTime JR<br>CROSS APPLY<br>(<br>    SELECT TOP (1)<br>        H.step_id,<br>        H.step_name,<br>        H.message<br>    FROM msdb.dbo.sysjobhistory H<br>    WHERE H.job_id = JR.job_id<br>      AND H.instance_id &lt; JR.instance_id<br>      AND H.step_id &gt; 0<br>      AND H.run_status = 0<br>    ORDER BY H.instance_id DESC<br>) HS<br>WHERE JR.run_status = 0<br>  AND JR.RunDateTime &gt;= DATEADD(MINUTE, -30, GETDATE())<br>ORDER BY JR.RunDateTime DESC;<br><br>Declare @RecCount TINYINT = (SELECT COUNT(*) FROM #JobsHistory)<br>IF @RecCount = 0<br>Return</pre><p><strong>Part 2</strong> : If there is any job(s) failed , script will continue to HTML email creation process .</p><p>The core strategy here is to use T-SQL variables to dynamically construct the email body; you can draft your entire HTML layout within a single variable, which I have named @Body.</p><pre>DECLARE @Body NVARCHAR(MAX);</pre><p><strong>Part 3 : </strong>Within this variable, HTML tags and CSS styling define the structure and appearance of the email. HTML uses opening and closing tags, such as &lt;html&gt; and &lt;/html&gt;, to encapsulate all the content. Inside the root &lt;html&gt; tag are several sub-tags, including &lt;head&gt;, which serves multiple purposes in a web page. In our setup, we use the &lt;head&gt; section to embed the email’s styling using a &lt;style&gt; tag.</p><p>Within this styling section, you can see that each HTML element (such as table, body, or th) or CSS class (such as .greeting or .text) has its own properties enclosed in curly braces {}. These CSS properties — including font size, font color, and background color — will take effect on the tags inside the &lt;body&gt; section, formatting the email body once it is sent.</p><p>Inside the &lt;body&gt; tag, the actual email text is structured. It starts with greeting paragraphs, followed by a table containing table headers (&lt;th&gt;) and table data (&lt;td&gt;).</p><pre>SET @Body = N&#39;<br>&lt;html&gt;<br>&lt;head&gt;<br>&lt;style&gt;<br><br>body<br>{<br>    font-family: Calibri, Arial, sans-serif;<br>    font-size:14px;<br>    color:#000000;<br>    margin:20px;<br>}<br>.header<br>{<br>    background-color:#2F75B5;<br>    color:#FFFFFF;<br>    font-size:22px;<br>    font-weight:bold;<br>    padding:12px;<br>    border-radius:4px;<br>}<br>.greeting<br>{<br>    color:#2F75B5;<br>    font-size:16px;<br>    font-weight:bold;<br>    margin-top:20px;<br>    margin-bottom:10px;<br>}<br>.text<br>{<br>    color:#000000;<br>    line-height:1.5;<br>    margin-bottom:15px;<br>}<br>table<br>{<br>    width:100%;<br>    border-collapse:collapse;<br>    font-family:Calibri, Arial, sans-serif;<br>    font-size:13px;<br>}<br>th<br>{<br>    background-color:#2F75B5;<br>    color:white;<br>    border:1px solid #D9D9D9;<br>    padding:8px;<br>    text-align:left;<br>}<br>td<br>{<br>    border:1px solid #D9D9D9;<br>    padding:7px;<br>}<br>tr:nth-child(even)<br>{<br>    background-color:#F7F9FC;<br>}<br>.footer<br>{<br>    margin-top:20px;<br>    background-color:#F2F2F2;<br>    border-left:5px solid #2F75B5;<br>    padding:12px;<br>    font-size:12px;<br>    color:#555555;<br>    line-height:1.5;<br>}<br>.warning<br>{<br>    color:#C00000;<br>    font-weight:bold;<br>}<br><br>&lt;/style&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br><br>&lt;p class=&quot;greeting&quot;&gt;Dear DBA Team,&lt;/p&gt;<br><br>&lt;p class=&quot;text&quot;&gt;<br>This is an &lt;b&gt;automated notification&lt;/b&gt; generated by SQL Server through &lt;b&gt;sp_send_dbmail&lt;/b&gt;.<br>&lt;/p&gt;<br><br>&lt;p class=&quot;text&quot;&gt;<br>Below are the failed SQL Jobs in the last &lt;b&gt;30 minutes&lt;/b&gt; from &lt;b&gt;msdb.dbo.sysjobhistory&lt;/b&gt; and &lt;b&gt;msdb.dbo.sysjobs&lt;/b&gt; .<br>&lt;/p&gt;<br><br>&lt;table&gt;<br><br>&lt;tr&gt;<br>    &lt;th&gt;Job ID&lt;/th&gt;<br>    &lt;th&gt;Job Name&lt;/th&gt;<br>    &lt;th&gt;Server&lt;/th&gt;<br>    &lt;th&gt;Run Date &amp; Time&lt;/th&gt;<br>    &lt;th&gt;Duration In Seconds&lt;/th&gt;<br>    &lt;th&gt;Step ID&lt;/th&gt;<br>    &lt;th&gt;Step Name&lt;/th&gt;<br>    &lt;th&gt;Error Message&lt;/th&gt;<br>&lt;/tr&gt;&#39;;</pre><p><strong>Part 4</strong> : Up to this point, no dynamic data has been included in our email. To embed the query output directly into our HTML table, we will use the script block below.</p><p>This script is essentially a standard SQL SELECT statement with an added FOR XML PATH(‘tr’), TYPE clause. This clause instructs SQL Server to format the query results as XML data. By passing ‘tr’ as an argument, we tell SQL Server to wrap every single row returned by the query in &lt;tr&gt;&lt;/tr&gt; tags. Additionally, assigning empty strings (‘’) as column aliases ensures that the column values aren’t wrapped in individual element tags, acting as a clean text separator.</p><p>This block needs to be appended to our existing script via concatenation, like so: @Body = @Body + … .</p><pre>SET @Body = @Body +<br>CAST<br>(<br>(<br>    SELECT <br>        td = job_id,&#39;&#39;,<br>        td = JobName,&#39;&#39;,<br>        td = server,&#39;&#39;,<br>        td = RunDateTime,&#39;&#39;,<br>        td = DurationInSeconds,&#39;&#39;,<br>        td = step_id ,&#39;&#39;,<br>        td = step_name ,&#39;&#39;,<br>        td = ErrorMessage ,&#39;&#39;<br>    FROM #JobsHistory<br>    ORDER BY RunDateTime DESC<br>    FOR XML PATH(&#39;tr&#39;), TYPE<br>) AS NVARCHAR(MAX)<br>);</pre><p><strong>Part 5</strong> : After that we can include the footer of the email in &lt;div&gt;&lt;/div&gt; tag or in paragraph &lt;p&gt;&lt;/p&gt; , and append it with the previous @Body variable content.</p><pre>SET @Body = @Body + N&#39;<br><br>&lt;/table&gt;<br><br>&lt;div class=&quot;footer&quot;&gt;<br><br>&lt;span class=&quot;warning&quot;&gt;Automated Notification&lt;/span&gt;<br>&lt;br&gt;&lt;br&gt;<br><br>Please review the information above,and take the appropriate action in accordance with your operational<br>procedures.<br><br>&lt;br&gt;&lt;br&gt;<br><br>&lt;b&gt;Please do not reply to this email.&lt;/b&gt;<br><br>&lt;/div&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;&#39;;</pre><p><strong>Part 6</strong> : Send email through sp_send_dbmail , and passing the @Body variable in sp_send_dbmail parameter which contains all HTML and CSS design along with the SQL script used.</p><pre>EXEC msdb.dbo.sp_send_dbmail<br>      @profile_name                 = &#39;AlertsProfile&#39;,<br>      @recipients                   = &#39;recipient@gmail.com&#39;,<br>      @subject                      = &#39;SQL Agent Jobs Notification&#39;,<br>      @body                         = @Body,<br>      @body_format                  = &#39;HTML&#39;,<br>      @importance                   = &#39;High&#39;, <br>      @execute_query_database       = &#39;msdb&#39;</pre><p>Once executed the SP , I received the following email :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*WRFd_5oAOMYnxb-D.png" /></figure><p>These scripts above can be useful in case there are SQL jobs related to Database backups , and you need to detect the failed backups as early as possible and take the action required accordingly.</p><p>Or use this script to monitor any job that unexpectedly took time longer than usual .</p><p>Regardless of the purpose, you should adjust the script to meet your specific needs.</p><p>You can schedule the above script to be executed every x minutes within SQL job , but make sure that this script / job is running successfully since it will monitor the other jobs , you do not want to miss any failed job(s) because of your monitoring job itself is failed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb3488e6782a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Server Agent Jobs]]></title>
            <link>https://medium.com/h7w/sql-server-agent-jobs-2c7d0690c3e3?source=rss-43c31eefa5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c7d0690c3e3</guid>
            <category><![CDATA[microsoft-sql-server]]></category>
            <category><![CDATA[sql-agent]]></category>
            <category><![CDATA[database-administration]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Abdellateef Ibrahim]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 17:16:50 GMT</pubDate>
            <atom:updated>2026-10-24T01:40:50.075Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL Server Agent is a built-in SQL service used to automate and schedule tasks such as :</p><ul><li>Run SQL scripts at scheduled times in SQL Server Job</li><li>Back up databases</li><li>Rebuild or reorganize indexes</li><li>Update statistics</li><li>Execute SSIS (SQL Server Integration Services) packages</li><li>Run PowerShell scripts or Command Prompt commands</li><li>Send alerts or email notifications</li><li>Monitor SQL Server events and performance</li></ul><p>For example, suppose you need to run SQL scripts to process records in a specific database on a daily basis at midnight and you do not want to depend on an external process or application to do this job . You can create a SQL job containing these scripts and schedule it to run once at midnight, or at any specific interval (seconds, minutes, or hours). Once configured, this job will automatically execute on schedule without my intervention.</p><p>We will focus in this article on how to create SQL Server Job</p><p>It is important to note that the SQL Server Agent service is available in all SQL Server editions except the Express edition.</p><p>Before proceeding, please make sure the service is running by checking the SQL Server Agent status in the Windows Services console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*IWSbaNdNOw6vwfIR.png" /></figure><h3>How to create a SQL job</h3><p>If you want to start automating SQL script or Backup Database or perform some tasks on scheduled time , you can start from SQL Server Agent , there will be object called Jobs underneath it , right click on Jobs and choose New Job</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/0*sDXN_5SLYzcRQwpc.png" /></figure><p>There are several pages in the job configuration window below. The first page is <strong>General</strong>, which contains the following settings:</p><ul><li><strong>Name</strong>: You can choose a name that clearly represents the task or tasks you intend to execute.</li><li><strong>Owner</strong>: By default, this is set to the user currently logged into the SQL engine. The owner is the account that has full control over the job.</li><li><strong>Category</strong>: This is used to group jobs using organizational tags. Your selection here is strictly for organization and has no effect on the actual execution process.</li><li><strong>Enabled</strong>: This checkbox is used to enable or disable the job.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*mimZL5EDv1mMJKgf.png" /></figure><p>Next is the Steps page, where you can define one or more SQL scripts (e.g., INSERT, DELETE, UPDATE, EXEC SP) or scripts related to rebuild indexes , update statistics , DBCC commands . Depending on the task you are automating, your job may consist of one or multiple steps.</p><p>For example, you might create a first step that inserts records into Table X and updates them based on a specific condition, followed by a second step that deletes records from Table Y based on a different condition.</p><p>To configure this on the Steps page, begin by clicking New:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*IGomJH7BSFeZWMm_.png" /></figure><p>A new window for the step settings will open. Here, you can provide a meaningful name for the step, such as “Insert Step,” and make sure the correct database context is selected. Finally, in the <strong>Command</strong> field, place the SQL script that you want to execute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*nHxyHT_tMMGKuUeF.png" /></figure><p>After click on Ok, the step will be saved, you can repeat the step for table y as a second step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*5yYDZuaVXNF3nFOI.png" /></figure><p>Next is the Schedules page, which is where you define when the SQL job will run. The schedule depends on the nature of your task. Some tasks need to be executed periodically, such as database backups or index rebuilds. Other tasks may only need to run once a day or week, while some depend on a specific day and time (for example, every Friday at 5:00 AM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*8yZ41ltI9G6bJivs.png" /></figure><p>Here is a detailed explanation of the options available under Schedule type:</p><ul><li><strong>Start automatically when SQL Server Agent starts:</strong> When you select this option, the other scheduling fields (such as the specific date, time, or frequency) will be disabled. The job will simply run whenever the SQL Server Agent service is started.</li><li><strong>Start whenever the CPUs become idle</strong>: This allows the job to execute once CPU usage falls below a specific threshold. You can define this threshold by right-clicking SQL Server Agent, selecting Properties, navigating to the Advanced page, and setting the Idle CPU condition. Note that you must enable this condition in the Agent properties before you can use this schedule type.</li><li><strong>Recurring</strong>: The job will run repeatedly based on a regular frequency. The configuration options for recurring schedules are explained in detail below.</li><li><strong>One time</strong>: The job will run exactly once. You will need to specify the exact date and time for its execution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*yiEOlP-0odecgkMJ.png" /></figure><p>Once you select Recurring, you will have a wide range of options to configure depending on the nature of your task. You can set the overall frequency to run daily, weekly, or monthly, and choose the specific days it should execute. Additionally, you can configure the daily frequency to run just once a day, or repeatedly every specified number of hours, minutes, or seconds.</p><p>Finally, you can set a duration for the schedule. For example, if you only want the job to run for the next month, you can specify an exact End date for the schedule to stop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*H8RjyB0xcXH1dqaI.png" /></figure><p>After set the schedule you want, you can click on Ok and it will be listed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*VGh067lU8mYfvrGc.png" /></figure><p>As a result, you can now say the job was created and you can monitor its history by right click on the job itself and choose view history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*oQf73RCVc1xyKk6n.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*ur5M8N7OIeCVbVwV.png" /></figure><p>There will be other articles on SQL Server Agent and how to monitor the jobs status if completed , succeeded or failed . Also , articles related to triggering SQL Server Alerts from SQL Agent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c7d0690c3e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/h7w/sql-server-agent-jobs-2c7d0690c3e3">SQL Server Agent Jobs</a> was originally published in <a href="https://medium.com/h7w">T3CH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Mail in SQL Server 2022]]></title>
            <link>https://medium.com/h7w/database-mail-in-sql-server-2022-4d9a1908c17c?source=rss-43c31eefa5fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d9a1908c17c</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[dba]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[mssql-server]]></category>
            <category><![CDATA[mssql]]></category>
            <dc:creator><![CDATA[Abdellateef Ibrahim]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 11:33:07 GMT</pubDate>
            <atom:updated>2026-10-12T01:44:38.212Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have worked with Microsoft SQL Server and used the SQL Server Management Studio ( SSMS ), you may have noticed there is a service available, which is Database Mail. This service was introduced first in Microsoft SQL Server 2005, though it was deployed since a long time, many DBAs are not utilizing this feature because of depending on 3rd party applications, which can offer you the same functionalities along with other capabilities such as monitoring or visualization tools.</p><p>If you are planning to start automating sending emails from the same SQL Server without depending on any external application, we can use Database Mail. Database Mail can be used in the following ways:</p><ul><li>Sending emails after the SQL jobs / Queries fail or success in SQL Server Agent .</li><li>When configuring alerts, we can include some recipients to receive email notifications, ex : high CPU usage detected.</li><li>Query results and reporting : we can send periodic results from an executed queries which cover various insights either on SQL Instance or on SQL Databases, attachments can be added .</li><li>Application Notification : in some applications, there is notification module for email, this service can be helpful when it comes to sending email notifications regarding some actions / reports to the end users .</li></ul><h3>Enabling Database Mail</h3><p>To get started, first open SSMS and then connect to your instance. In the Object Explorer, choose Management &gt; Database Mail as shown here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*kkl-HKCyRGmtAXJe.png" /></figure><p>Right Click on <strong>Database Mail</strong> and click on <strong>Configure Database Mail.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*zUjNyJJNaRHDa2ll.png" /></figure><p>Choose the first option below to create new SMTP account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*klM70EhJqfJnwtva.png" /></figure><p>Once click on Next, you will get the below message box since you are configuring the DB mail for the first time, click on Yes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*9MJX95lT2lgsmGyW.png" /></figure><p>In the below image, we need to define a mail profile and within this profile we can define one or multiple SMTP accounts . Click Add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*qeUTOIaB68yUYQXV.png" /></figure><p>We gave a name for this profile: AlertsProfile. We need to connect to an SMTP server. I will use my own Gmail account for our demonstration, but a in real world environment, do not use any personal account as there should be a dedicated SMTP server with dedicated account that serves this purpose</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*GRyTkNaucnWUKjUo.png" /></figure><p>Enter your Email Address and Display Name, which is the name will appear in the recipient mail box once receive the email. The Reply Email can be the same as your email, and the SMTP for Google which is smtp.gmail.com</p><p>Once click on OK, and you have created the first SMTP account, you can add another account if you have for the purpose of failover. If the first SMTP server is down or unreachable, SQL Server will switch to the second SMTP server.</p><p>We will keep it as one account in our demonstration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*YayvpiNFCk5NvSAF.png" /></figure><p>Once click on Next, you have the option to select this profile as public to be used by all users in SQL, or private with restriction to specific users or roles, we will use it public one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*hw_siMUUbBIRzwWR.png" /></figure><p>Moving Next, we will get the system parameters below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*20pVTJ-S-7R8JsOD.png" /></figure><p>The above values are the default ones, here is brief explanation on each one of them :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zX4vVt7p3OtSMdzEZt5SgA.png" /></figure><p>After click on Next and Finish, the process of configuring DB mail is done</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*nVKQlaxgCR259qn6.png" /></figure><p>Now, let us perform sending test email by apply the following steps :</p><p>Right click on Database Mail from Object Explorer and click on “Send Test E-mail”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*gW38JsZlk56QkcXN.png" /></figure><p>Fill in the fields with the required information and click on the Send Test Email button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*TePqVDSn_5RM6Wca.png" /></figure><p>You will get the below box</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*pWxC20v_YnyldPCN.png" /></figure><p>There is number 1 appeared. This is the mailitem_id column for the transaction in msdb.dbo.sysmail_allitems DMV.</p><p>That’s it; Database Mail is working.</p><p>We will deep dive into DB Mail DMVs and how to troubleshoot the issues in different article, and also we will cover the usage for DB mail in more practical ways.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d9a1908c17c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/h7w/database-mail-in-sql-server-2022-4d9a1908c17c">Database Mail in SQL Server 2022</a> was originally published in <a href="https://medium.com/h7w">T3CH</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>