How to Send Emails from SQL Server (T-SQL)

SQL Server provides the ability to send emails via its Database Mail solution.

The actual act of sending mail is done with the sp_send_dbmail stored procedure. But before you start sending emails from SQL Server, you need to enable and configure Database Mail.

You can do this with the SSMS GUI, or with T-SQL.

This article demonstrates how to do it with T-SQL. It assumes that Database Mail has never been enabled on your system, and therefore it goes through the steps involved in enabling it.

If you prefer to use the SSMS GUI, see How to Setup Database Mail in SQL Server (SSMS).

Read more

Delete Database Mail Messages from the msdb Database in SQL Server (T-SQL)

When you use Database Mail to send emails from SQL Server, email messages and their attachments are stored in the msdb database. You should periodically delete these messages to prevent the database from growing to large.

To delete these messages with T-SQL, use the sysmail_delete_mailitems_sp stored procedure.

You can delete mail messages based on their send request date (i.e. before a certain date) or based on their status. You can also delete all mail messages by using the current date as the request date.

Read more

How to Use GOTO in SQL Server

In SQL Server, you can use GOTO to alter the flow of execution. You can use it to “jump” to another part in the T-SQL code.

The way it works is, you create a label, then you can use GOTO to jump to that label. Any code between GOTO and the label are skipped, and processing continues at the label.

GOTO statements and labels can be used anywhere within a procedure, batch, or statement block. They can also be nested.

Read more