European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

SQL Server Hosting - HostForLIFE :: Rank and Dense_Rank Function in SQL Server

clock September 30, 2024 10:15 by author Peter

I'll go over the Rank and Dense_Rank Functions in SQL Servers with examples in this article. In SQL Server, the RANK and DENSE_RANK procedures were introduced. Once more, these two procedures are utilized to return consecutive numbers beginning at 1 in accordance with the ORDER BY clause's ordering of the rows. Before attempting to comprehend how these functions differ from one another, let's first examine these functions in further detail using a few instances.

Note: If there are two records with identical data, both rows will have the same rank.

RANK Function in SQL Server
The following is the syntax for using the RANK function in SQL Server. As you can see, like the Row_Number function, here also the Partition By clause is optional while the Order By Clause is mandatory.

The PARTITION BY clause is basically used to partition the result set into multiple groups. As it is optional, and if you did not specify the PARTITION BY clause, then the RANK function will treat the entire result set as a single partition or group. The ORDER BY clause is required, and this clause is used to define the sequence in which each row is going to assign its RANK i.e. number. If this is not clear at the moment, then don’t worry. We will try to understand this with some examples.

Examples to understand Rank and Dense_Rank function in SQL Server.

We are going to use the following Employees table to understand the RANK and DENSE_RANK functions.

Please use the following SQL Script to create and populate the Employees table with the required test data.
Create Table Employees
(
    Id INT PRIMARY KEY,
    Name VARCHAR(50),
    Department VARCHAR(10),
    Salary INT,
)
Go

Insert Into Employees Values (1, 'James', 'IT', 80000)
Insert Into Employees Values (2, 'Taylor', 'IT', 80000)
Insert Into Employees Values (3, 'Pamela', 'HR', 50000)
Insert Into Employees Values (4, 'Sara', 'HR', 40000)
Insert Into Employees Values (5, 'David', 'IT', 35000)
Insert Into Employees Values (6, 'Smith', 'HR', 65000)
Insert Into Employees Values (7, 'Ben', 'HR', 65000)
Insert Into Employees Values (8, 'Stokes', 'IT', 45000)
Insert Into Employees Values (9, 'Taylor', 'IT', 70000)
Insert Into Employees Values (10, 'John', 'IT', 68000)
Go

RANK Function without PARTITION
Let us see an example of the RANK function in SQL Server without using the PARTITION BY Clause. When we did not specify the PARTITION BY Clause, then the RANK function will treat the entire result set as a single partition and give consecutive numbering starting from 1 except when there is a tie.

The following is an example of the RANK function without using the PARTITION BY clause. Here we use the Order By Clause on the Salary column. So, it will give the rank based on the Salary column.

SELECT Name, Department, Salary,
RANK() OVER (ORDER BY Salary DESC) AS [Rank]
FROM Employees

Once you execute the above query, you will get the following output. As you can see in the below output, there will be no partition, and hence all the rows are assigned with consecutive sequences starting from 1 except when there is a tie i.e. when the salary is 8000 and 65000, it gives the same rank to both the rows.

The Rank function in SQL Server skips the ranking(s) when there is a tie. As you can see in the above output, Ranks 2 and 6 are skipped as there are 2 rows at rank 1 as well as 2 rows at rank 5. The third row gets rank 3 and the 7th row gets rank 7.


RANK Function with PARTITION BY clause in SQL Server

Let us see an example of the RANK function using the PARTITION BY clause in SQL Server. When you specify the PARTITION BY Clause, then the result set is partitioned based on the column that you specify in the PARTITION BY clause. Please have a look at the following image to understand this better. As you can see we have specified Department in the Partition By clause and Salary in the Order By clause.

As in the Employees table, we have two departments (IT and HR). So, the Partition By Clause will divide all the records into two partitions or two groups. One partition is for IT department employees and another partition is for HR department employees. Then in each partition, the data is sorted based on the Salary column. The RANK function then gives an integer sequence number starting from 1 to each record in each partition except when there is a tie. In the case of a tie, it gives the same rank and then skips the ranking.

Now execute the following code and you will get the output as we discussed in the previous image.
SELECT Name, Department, Salary,
               RANK() OVER (
                               PARTITION BY Department
                               ORDER BY Salary DESC) AS [Rank] FROM Employees

So, in short, The RANK function Returns an increasing unique number for each row starting from 1 and for each partition. When there are duplicates, the same rank is assigned to all the duplicate rows, but the next row after the duplicate rows will have the rank it would have been assigned if there had been no duplicates. So the RANK function skips rankings if there are duplicates.

DENSE_RANK Function in SQL Server

The following is the syntax for using the DENSE_RANK function. As you can see, like the RANK function, here also the Partition By clause is optional while the Order By Clause is mandatory.

The PARTITION BY clause is optional and it is used to partition the result set into multiple groups. If you did not specify the PARTITION BY clause, then the DENSE_RANK function will treat the entire result set as a single partition. The ORDER BY clause is mandatory and it is used to define the sequence in which each row is going to assign with their DENSE_RANK i.e. number. Let us understand how to use the DENSE_RANK function in SQL Server with some examples.
DENSE_RANK Function without PARTITION BY clause in SQL Server

Let us see an example of the DENSE_RANK function without using the PARTITION BY Clause. As we already discussed, if we did not specify the PARTITION BY Clause, then the DENSE_RANK function will treat the entire result set as a single partition and give consecutive numbering starting from 1 except when there is a tie.

The following is an example of the DENSE_RANK function without using the PARTITION BY clause. Like the RANK function, here we also apply for the Order By Clause on the Salary column. So, it will give the rank based on the Salary column.

SELECT Name, Department, Salary,
            DENSE_RANK() OVER (ORDER BY Salary DESC) AS [Rank]
FROM Employees

When you execute the above SQL Query, it will give you the following output. As you can see in the output, there will be no partition, and hence all the rows are assigned with consecutive sequences starting from 1 except when there is a tie i.e. when the salary is 8000 and 65000, it gives the same rank to both the rows.

Unlike the Rank function, the DENSE_RANK function will not skip the ranking(s) when there is a tie. As you can see in the above output, we have two rows with rank 1 and the next immediate row rank is 3 and this is the only difference between RANK and DENSE_RANK function in SQL Server.
DENSE_RANK Function with PARTITION BY clause in SQL Server

Let us see an example of the DENSE_RANK function in SQL Server using the PARTITION BY Clause. Like the RANK function, it will also partition the result set based on the column that you specify in the PARTITION BY Clause. In order to understand this better, please have a look at the following diagram. As you can see we have specified the Department column in the Partition By clause and Salary column in the Order By clause.

As we have two departments i.e. IT and HR, so, the Partition By Clause will divide all the data into two partitions. One partition is going to hold the IT department employees while the other partition is going to hold the HR department employees. Then in each partition, the records are sorted based on the Salary column. The DENSE_RANK function is then applied on each record in each partition and provides sequence numbers starting from 1 except when there is a tie. In the case of a tie, it gives the same rank without skipping the ranking.

Now execute the below SQL Script and you should get the output as we discussed in the previous image.

SELECT Name, Department, Salary,
               DENSE_RANK() OVER (
                               PARTITION BY Department
                               ORDER BY Salary DESC) AS [DenseRank]
FROM Employees

What is the difference between Rank and Dense_Rank functions in SQL Server?
As we already discussed the one and only difference is Rank function skips ranking(s) if there is a tie whereas the Dense_Rank will not skip the ranking.

The Real-time examples of RANK and DENSE_RANK Functions in SQL Server:
If you are attending any interview, then one famous question is being asked in almost all interviews i.e. find the nth highest salary. Both the RANK and DENSE_RANK functions can be used to find nth highest salary. However, when to use which function basically depends on what you want to do when there is a tie. Let us understand this with an example.

Suppose, there are 2 employees with the FIRST highest salary, then there might be 2 business cases as follows.
If your business requirement is not to produce any result for the SECOND highest salary then you have to use the RANK function.
If your business requirement is to return the next Salary after the tied rows as the SECOND highest Salary, then you have to use the DENSE_RANK function.

Fetch the 2nd Highest Salary using the RANK function
Since, in our Employees table, we have 2 employees with the FIRST highest salary (80000), the Rank() function will not return any data for the SECOND highest Salary. Please execute the SQL script below and see the output.

-- Fetch the 2nd Hight Salary
WITH EmployeeCTE  AS
(
    SELECT Salary, RANK() OVER (ORDER BY Salary DESC) AS Rank_Salry
    FROM Employees
)

SELECT TOP 1 Salary FROM EmployeeCTE WHERE Rank_Salry = 2

Fetch the 2nd Highest Salary using DENSE_RANK Function
As we have 2 Employees with the FIRST highest salary i.e. 80000, the Dense_Rank() function will return the next Salary after the tied rows as the SECOND highest Salary i.e. 70000. Please execute the following SQL Script and see the output.
-- Fetch the 2nd Hight Salary
WITH EmployeeCTE  AS
(
    SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank_Salry
    FROM Employees
)

SELECT TOP 1 Salary FROM EmployeeCTE WHERE DenseRank_Salry = 2



Example to find the Highest Salary Department

You can also use the RANK and DENSE_RANK functions in SQL Server to find the nth highest Salary department-wise. For example, if someone asks you to find the 3rd highest salary of the IT Department, then you can use the DENSE_RANK function as shown below.
WITH EmployeeCTE  AS
(
    SELECT Salary, Department,
           DENSE_RANK() OVER (PARTITION BY Department ORDER BY Salary DESC)
           AS Salary_Rank
    FROM Employees
)

SELECT TOP 1 Salary FROM EmployeeCTE WHERE Salary_Rank = 3
AND Department = 'IT'

To put it briefly, the DENSE_RANK function yields an increasing unique number for each division and row beginning at 1. If there are duplicates, all of the duplicate rows are given the same rank; no levels are skipped. This indicates that the subsequent row in the series will have the next rank after the duplicate rows.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server Hosting - HostForLIFE :: Check the Disk Space Usage of Each Table in the SQL Server Database

clock September 24, 2024 08:36 by author Peter

 

I will show you how to check disk space utilization in SQL Server in this article, with a particular emphasis on how to find the disk space consumed by different tables. Database administrators must keep an eye on disk space use to guarantee optimal database performance and prevent storage-related problems. Through this approach, you will be able to better plan, optimize, and manage your storage resources by knowing how much disk space each table takes up.

How Can I Check How Much Disk Space Each Table Is Using?
A SQL Server database can be checked for disk space use by table using one of two approaches.

Integrated function located in Reports (SQL Server Management Studio)
We will go over "Disk Usage By Table" in this section, but first, let's take a step-by-step look at the built-in function under reports (the report menu has a lot of reports that we may see). I've downloaded the "NorthWind" database in order to provide an example of disk utilization by table.

The total amount of space allotted to each table in the list will be shown in the report. The "Orders" table takes up the most room in the example below, followed by the "OrderDetails" table, the "Employees" table, and so on.

Using SQL Stored Procedure/Query
If you want to calculate disk space utilization by tables in an SQL Server database using a stored procedure and customize your report, you can do so with a stored procedure. I’ve created one to calculate disk space utilization by tables. Please see the stored procedure below.
CREATE PROCEDURE USP_GetDiskSpaceUsedByTables
AS
BEGIN
    SELECT
        t.name AS TableName,
        s.name AS SchemaName,
        p.rows,
        SUM(a.total_pages) * 8 AS TotalReservedSpaceKB,
        SUM(a.used_pages) * 8 AS UsedSpaceKB,
        (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
        CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalReservedSpaceMB,
        CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
        CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
    FROM
        sys.tables t
    INNER JOIN
        sys.indexes i ON t.object_id = i.object_id
    INNER JOIN
        sys.partitions p ON i.object_id = p.object_id AND i.index_id = p.index_id
    INNER JOIN
        sys.allocation_units a ON p.partition_id = a.container_id
    LEFT OUTER JOIN
        sys.schemas s ON t.schema_id = s.schema_id
    WHERE
        t.name NOT LIKE 'dt%'
        AND t.is_ms_shipped = 0
        AND i.object_id > 255
    GROUP BY
        t.name, s.name, p.rows
    ORDER BY
        TotalReservedSpaceMB DESC, t.name
END


Let's execute this stored procedure and review the results, which are calculated in the same way as the built-in SQL report functionality.

Why Check Disk Space Utilization by Tables in a SQL Server Database?
Here are the key reasons to check disk space utilization by tables in an SQL Server database.

  • Performance optimization
  • Data management
  • Cost management
  • Compliance and auditing
  • Resource allocation
  • Data Archiving
  • Post index maintenance

Summary
I've covered efficient ways to keep an eye on and control disk space usage in your SQL Server database in this post. I specifically walk through two methods for monitoring disk space usage at the table level. By employing these techniques, you can obtain important knowledge about how much storage is being used by your database, which will enable you to better effectively schedule your tasks. In your database environment, this proactive management may result in better resource allocation and performance.

Happy reading!

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.




SQL Server Hosting - HostForLIFE :: A Solution for the Login Failed SQL Server Error 18456

clock September 19, 2024 07:33 by author Peter

We will talk about a common problem that arises when we try to install SQL Server 2019 Developer Edition in custom mode in this article. SQL Server is typically installed by default and functions perfectly. Occasionally, nevertheless, we may run into some issues when installing the latest version. Upon installing the SQL Server Developer Edition 2019, I encountered a problem that appears to be related to a PolyBase issue.

Issue
When attempting to log in to SQL Server, an error 18456 was encountered.

Reason
Microsoft SQL Server, Error 18456 is the most common error in SQL server login. There are multiple reasons for this error. At least, we can divide them as two types, the error come from

  • SQL Server authentication mode
  • Windows Authentication Mode

SQL Server authentication mode
"Login failed for user'sa'. (Microsoft SQL Server, Error 18456)" refers to a specific user's login using the SQL Server authentication mode in the first two situations of our demo. One possible explanation for this scenario is that the SQL server instance is set up for Windows Authentication mode, but you are attempting to use SQL Server Authentication. This is the result of installing SQL Server Basic Mode, which is limited to operating in Windows Authentication mode and not in SQL Server Authentication mode by default.We must change the Windows Authentication Mode to the Mixed Mode in this situation.

The fix for this, I have discussed in my SQL Server installation article SQL Server Installation: 2022 Developer Edition --- Basic, or you may see [ref1], [ref2].

SQL Server authentication mode
For this, the main reason is due to the ID is not in the login list of the Server. We can get the login list by Click Login, under the security folder of the given database:



This can be obtain by SQL Command:
exec master.dbo.xp_logininfo

In different SQL Server:

We can get only one specific group with given parameter:
exec master.dbo.xp_logininfo 'NT SERVICE\Winmgmt'

Get the group members by the optional second parameter 'members':

Fix
If we have the person's ID, or the group name, then we can add it into the login list:

The name must be a valid user ID or AD group name:

Server role: by default --- public

OK

 Choose the specific data tables, and give the appreciate rights => OK

OK => Done

Summary

This login failed with SQL Server authentication is mainly due to lack of the individual ID or group the ID is belong to. Find out it and add it. The error is fixed.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.




SQL Server Hosting - HostForLIFE :: 20+ SQL Ideas Using Code from MS SQL Server

clock September 11, 2024 10:08 by author Peter

We will go over some key SQL ideas in this blog and provide samples of SQL Server code for each. These ideas include index types as well as standard procedures like writing joins, working with views and triggers, and generating and modifying tables.

Index Clustering
The data rows in the table are sorted and stored by a clustered index according to the key values. There can only be one clustered index per table.

-- Create a clustered index on the 'Id' column of the 'Employee' table
CREATE CLUSTERED INDEX IX_Employee_Id
ON Employee(Id);

Non-Clustered Index
A non-clustered index stores the index structure separately from the actual table data, creating pointers to the rows.
-- Create a non-clustered index on the 'Name' column of the 'Employee' table
CREATE NONCLUSTERED INDEX IX_Employee_Name
ON Employee(Name);

Create Table
Creating a table involves defining the columns and their data types.
-- Create an 'Employee' table
CREATE TABLE Employee (
    Id INT PRIMARY KEY,
    Name NVARCHAR(50),
    DepartmentId INT,
    HireDate DATE
);

Insert Multiple Rows
Insert multiple rows into a table in one query.

-- Insert multiple rows into the 'Employee' table
INSERT INTO Employee (Id, Name, DepartmentId, HireDate)
VALUES
(1, 'Alice', 1, '2021-01-01'),
(2, 'Bob', 2, '2021-02-01'),
(3, 'Charlie', 1, '2021-03-01');

Alter Table
Modify an existing table by adding or modifying columns.
-- Add a new 'Salary' column to the 'Employee' table
ALTER TABLE Employee
ADD Salary DECIMAL(10, 2);

Update Row
Updating the data of a row in a table.

-- Update the salary of the employee with Id 1
UPDATE Employee
SET Salary = 70000
WHERE Id = 1;

Rename Table
Renaming an existing table.
-- Rename 'Employee' table to 'Staff'
EXEC sp_rename 'Employee', 'Staff';

Delete Rows
Delete specific rows from a table based on a condition.
-- Delete an employee with Id 2
DELETE FROM Employee
WHERE Id = 2;


Drop Table
Delete the entire table and all of its data.

-- Drop the 'Employee' table
DROP TABLE Employee;


Truncate Table
Remove all rows from a table without logging each row deletion.
-- Truncate the 'Employee' table
TRUNCATE TABLE Employee;


Cursor
A cursor is used to retrieve rows from a result set one at a time.
DECLARE @EmployeeId INT;
DECLARE employee_cursor CURSOR FOR
SELECT Id FROM Employee;

OPEN employee_cursor;
FETCH NEXT FROM employee_cursor INTO @EmployeeId;

WHILE @@FETCH_STATUS = 0
BEGIN
    -- Do something with each row
    PRINT @EmployeeId;
    FETCH NEXT FROM employee_cursor INTO @EmployeeId;
END;


CLOSE employee_cursor;
DEALLOCATE employee_cursor;

View
A view is a virtual table based on a query.
-- Create a view to show employee names and hire dates
CREATE VIEW EmployeeView AS
SELECT Name, HireDate
FROM Employee
WHERE HireDate > '2021-01-01';

Trigger

A trigger is a special kind of stored procedure that automatically runs when an event occurs in the database.
-- Create a trigger that prints a message after inserting into the Employee table
CREATE TRIGGER trg_AfterInsertEmployee
ON Employee
AFTER INSERT
AS
BEGIN
    PRINT 'New employee inserted!';
END;

WITH CTE (Common Table Expression)
CTEs are used to create a temporary result set that can be referenced in a SELECT, INSERT, UPDATE, or DELETE statement.
WITH EmployeeCTE AS (
    SELECT Name, Salary
    FROM Employee
    WHERE Salary > 60000
)
SELECT *
FROM EmployeeCTE;

Inner Join
An inner join returns rows when there is at least one match in both tables.
-- Inner join between Employee and Department
SELECT e.Name, d.DepartmentName
FROM Employee e
INNER JOIN Department d
ON e.DepartmentId = d.Id;


Left Join
A left join returns all rows from the left table and the matched rows from the right table. Unmatched rows will return NULL for columns from the right table.
-- Left join between Employee and Department
SELECT e.Name, d.DepartmentName
FROM Employee e
LEFT JOIN Department d
ON e.DepartmentId = d.Id;


Right Join
A right join returns all rows from the right table and the matched rows from the left table. Unmatched rows will return NULL for columns from the left table.
-- Right join between Employee and Department
SELECT e.Name, d.DepartmentName
FROM Employee e
RIGHT JOIN Department d
ON e.DepartmentId = d.Id;


Self Join
A self-join is a regular join but joins the table with itself.
-- Self join on Employee table to find employees and their managers
SELECT e1.Name AS Employee, e2.Name AS Manager
FROM Employee e1
LEFT JOIN Employee e2
ON e1.ManagerId = e2.Id;

Cross Join
A cross join returns the Cartesian product of two tables, meaning every row in the left table is combined with every row in the right table.
-- Cross join between Employee and Department
SELECT e.Name, d.DepartmentName
FROM Employee e
CROSS JOIN Department d;

Cross Apply
Cross Apply works like an inner join but is used to join a table with a table-valued function.
-- Cross apply example
SELECT e.Name, sub.TopDepartment
FROM Employee e
CROSS APPLY (
    SELECT TOP 1 d.DepartmentName AS TopDepartment
    FROM Department d
    WHERE d.Id = e.DepartmentId
) sub;

ROW_NUMBER()
The ROW_NUMBER() function assigns a unique sequential integer to rows within a partition of a result set.

-- Assign row numbers to employees based on salary
SELECT
    Name,
    Salary,
    ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNumber
FROM
    Employee;

RANK()
The RANK() function assigns a rank to each row within a partition, with gaps in rank when there are ties.

-- Assign ranks to employees based on salary
SELECT Name,
       Salary,
       RANK() OVER (ORDER BY Salary DESC) AS Rank
FROM Employee;

DENSE_RANK()
The DENSE_RANK() function assigns ranks to rows without gaps between ranks when there are ties.
-- Assign dense ranks to employees based on salary
SELECT
    Name,
    Salary,
    DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank
FROM
    Employee;


This concludes our overview of some essential SQL concepts and SQL Server code examples. These queries and operations form the foundation of working with relational databases, making them crucial for both beginners and advanced users alike.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



SQL Server Hosting - HostForLIFE :: Set Up Email Sending using SQL Server Database Mail

clock September 5, 2024 10:02 by author Peter

How does Database Mail work?
The SQL Server Database Engine may send emails using Database Mail, an enterprise email solution. Your database applications can send users emails by using Database Mail. The messages may include files from any resource on your network in addition to query results.

Step 1: In order to send mail from SQL Server, we must first install Microsoft SQL Server Management Studio (SSMS) on our PC or laptop. Thus, download and install SSMS first if you haven't already on your PC.

Step 2
Now, Open SSMS and connect it to your SQL Server instance.
Expand Management option, there you can find the Database Mail option. As you can see in the following image.

Now, Right click on Database Mail and select the Configure Database Mail option.
This will open a Database Mail Configuration wizard. Select next to continue.
Now choose the first option, Set up Database Mail, by performing the following tasks, and click next.

Now, give your database mail Profile Name and its description as whatever you want. Here, I am giving "Test Profile" as the profile name. In the SMTP account section, select the Add account option to create a new SMTP account as in the following image.

Now, enter the information shown in the following image in the New Database Mail Account box. I'm sending emails from this account using Gmail. Thus, I set the server name to smtp.gmail.com and the port number to 587.

Use the email address and password from which you wish to send emails when logging into SMTP Authentication and Outgoing Mail Server. For security reasons, confirm that the "The server requires a secure connection" check box is checked as well. When you are finished, click OK. To move on to the next screen, click next.


Step 3. The next screen is about making a Database mail profile, either public or private. You can leave this option and move to the next screen. Again, select next to finish the creation process for the Database Mail profile.

Now you are all set up to send e-mail. Now go to Management, right-click on Database Mail, and select Send Test E-mail... option to send test mail as in the following image.


Choose Test Profile as Database Mail Profile from Dropdown and enter To email address, Subject, and Body, and click Send Test E-Mail. Now your e-mail has been sent successfully from SQL Server.

Step 4. If you want to send mail using SQL query, then you can use the system database 'msdb' and its stored procedure 'sp_send_dbmail' as follows.
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Test Profile',
    @recipients = '[email protected]',
    @subject = 'Test Mail',
    @body = 'This is the test mail.',
    @body_format = 'HTML';


To check the status of the e-mail you sent, you can execute the following query in SQL Server.
USE msdb;
GO

SELECT *
FROM sysmail_allitems;


In this query result, you can find all the details about the mail sent from the SQL Server. You can check the sent_status column to check the status of mail.
So, this is all about using the database mail in the SQL Server to send e-mails. I hope you understood my explanation and liked this article. Thank you!

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.




About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in