Does my Azure SQL Managed Instance has a read-only replica

Here are two SQL scripts you can use to check if your Azure SQL Managed Instance has a read-only replica:

1. Using sys.dm_fts_mirroring_endpoints:

SELECT *
FROM sys.dm_fts_mirroring_endpoints
WHERE mirror_state_desc = 'Synchronizing'
AND is_local = 0;

This script queries the sys.dm_fts_mirroring_endpoints dynamic management view, which contains information about mirroring and read-only replica endpoints. It filters for endpoints that are currently in the “Synchronizing” state and are not local (indicating a remote replica). If any results are returned, then your Managed Instance has at least one read-only replica.

2. Using sys.databases:

SELECT name, is_read_only_replica
FROM sys.databases
WHERE is_read_only_replica = 1;

This script queries the sys.databases system catalog view and filters for databases where the is_read_only_replica column is set to 1. This will directly show you the names of any read-only replica databases on your Managed Instance.

Both scripts will provide you with information about your read-only replicas, if any. The first script gives more details about the endpoint configuration, while the second script simply shows the names of the replica databases. Choose whichever script best suits your needs.

Additional notes:

  • These scripts only work on Azure SQL Managed Instances. They will not work on on-premises SQL Servers.
  • You need to have the necessary permissions to execute these scripts. The minimum required permission is the VIEW SERVER STATE server-level permission.
  • The first script might display results even if you have a secondary replica in a failover group, not a read-only replica. To distinguish between the two, you can check the endpoint_type column in the returned result set. A value of ‘2’ indicates a read-only replica.

I hope this helps!

Check when was last updatestats was done by object name

I was told to find out the last time an update stats was done on an object.

I used this query to show me StatisticsUpdateDate which is the last date/time updatestats was run on the object

--UpdateStats last update
SELECT 
    OBJECT_NAME(object_id) AS [ObjectName],
    [name] AS [StatisticName],
    STATS_DATE([object_id], 
    [stats_id]) AS [StatisticUpdateDate]
FROM 
    sys.stats;

Hope this helps.

Create SQL Script to update stats for all tables in a database with Full Scan

I was asked to run update stats on all the tables in a database with full scan.
And I was to use native SQL code not OLA or another open source.
Additional requirement was to update stats on each table individually listed as a separate line of code.

The database had multiple tables so to list each individual items was going to very burdensome.

Thankfully I found this sql script that will generate an update stat statement for each table in the database. You just have to copy the query output to either a new query window or just put it in a sql job and run it.

SET NOCOUNT ON
GO
 
DECLARE updatestats CURSOR FOR
SELECT table_schema, table_name
FROM information_schema.tables
where TABLE_TYPE = 'BASE TABLE'
OPEN updatestats
 
DECLARE @tableSchema NVARCHAR(128)
DECLARE @tableName NVARCHAR(128)
DECLARE @Statement NVARCHAR(300)
 
FETCH NEXT FROM updatestats INTO @tableSchema, @tableName
 
WHILE (@@FETCH_STATUS = 0)
BEGIN
  SET @Statement = 'UPDATE STATISTICS '  + '[' + @tableSchema + ']' + '.' + '[' + @tableName + ']' + ' WITH FULLSCAN'
  PRINT @Statement -- comment this line out if you want to actually run the query instead of just getting the code for the task.
 --EXEC sp_executesql @Statement -- remove the comment to run the command 
  FETCH NEXT FROM updatestats INTO @tableSchema, @tableName
END
 
CLOSE updatestats
DEALLOCATE updatestats
GO
SET NOCOUNT 

Hope this helps, enjoy!

Backup database to a static file and overwrite the backup file every time the backup job runs

I had a request from a business user to create a job that they want to run on an ad-hoc basis to backup a database to a static file name. And they backup file needed to be deleted/overwritten every time the sql job ran. I used Ola Hallengren’s backup code to take the database backup with a static file name.

EXECUTE [dbo].[DatabaseBackup] 
@Databases = 'DatabaseName', 
@Directory = N'E:\DeployBackups', 
@BackupType = 'FULL', 
@Verify = 'Y', 
@CheckSum = 'Y',
@Compress = 'Y',
@CleanupMode = 'BEFORE_BACKUP',
@Init = 'Y',
@FileName = '{DatabaseName}.{FileExtension}'

@Databases = specify the name of the database
@Directory = the directory where the backup file will be written to
@BackupType = what type of backup – FULL, DIFF or LOG
@Verify = verify the backup file after it is completed
@CheckSum = check the checksum of the database file
@Compress = compress the backup file
@CleanupMode = when should the old backup file will be deleted – before or after the current backup job is completed. If you have limited space on the drive then it is a good option to delete the old backup file before the new backup is started but you run the risk of losing all the backup files incase the current backup job fails.
@Init = ‘Y’, or ‘N’ specifies if the current backup files will be deleted. It is important to note that we need to use this option since we are backing up the database to a static file name. If you do not use this option then the backup will be appended with the new backup and the size of the backup file will be growing.
@FileName = ‘{DatabaseName}.{FileExtension}’ this option specifies the exact name of the database file every time the backup runs.

Hope this helps, good luck.

Search all SQL objects for a specific text

I was tasked to replace all the db mail profile name to a new profile name in all the objects in a database that uses specific old profile name. This can easily turn into a tedious task to manually open/edit all the sql server jobjects in each database.

I wrote this query to quickly find all the sql objects that use the specific db mail profile name. This will give you are list of all the sql objects in the Results window. Now you simply have to go by this list to edit/update each of these specific stored procs with the new db mail profile name.

SELECT OBJECT_NAME(id)  
FROM SYSCOMMENTS  
WHERE [text] LIKE '%@profile_name%'  
--AND OBJECTPROPERTY(id, 'IsProcedure') = 1  
GROUP BY OBJECT_NAME(id)  

Hope this helps.

Command Shell (CMD) to get list of all software installed on the windows machine

I had a request from the auditing team to get a list of all the software installed on a windows machine. We can view all the software installed in control panel but I needed to get a text output of the result so I can put it in a word document and send it to the auditors.

I found this cmd shell script that you can run to get this data. Then copy the data from the command window and paste it to any word document, excel or notepad – your choice.

Make sure you open the command shell window in administrator mode.

Get-WmiObject -Class Win32_Product | Select-Object -Property Name, Version, Vendor, InstallDate

Hope this helps.

Find a specific stored procedure in all databases

Got a request to find a specific stored procedure in all the databases.

Instead of scrolling thru each database and stored procedures manually to find the stored procedure, here is a SQL script that will search all the databases and list the databases that have that stored procedure. Hope this helps.

--Search for a specific stored procedure in all the databases on the sql instance
DECLARE @SQL NVARCHAR(max)
    ,@spName VARCHAR(200) = 'name of stored procedure' -- The name of the procedure you are looking for

SELECT @SQL = STUFF((
            SELECT CHAR(10) + ' UNION ALL '           + CHAR(10) +  
' SELECT ' + quotename(NAME, '''') + ' AS DB_NAME '   + CHAR(10) + 
'         , SCHEMA_NAME(s.schema_id)  AS THE_SCHEMA ' + CHAR(10) + 
'         , s.name  COLLATE Latin1_General_CI_AS AS THE_NAME  ' + CHAR(10) + 
'  FROM ' + quotename(NAME) + '.sys.procedures s '    + CHAR(10) +   
' WHERE s.name = @spName 
  AND s.[type] = ''P'''
            FROM sys.databases
            ORDER BY NAME
            FOR XML PATH('')
                ,TYPE
            ).value('.', 'nvarchar(max)'), 1, 11, '')

--PRINT @SQL

EXECUTE sp_executeSQL @SQL
    ,N'@spName varchar(200)'
    ,@spName

Get size of all tables in database

Sometimes I receive a request from client to get a list of all the tables and it’s data size.

Here is a helpful sql script that will get the info you need.

Copy the results to an excel file.

SELECT 
    t.name AS TableName,
    s.name AS SchemaName,
    p.rows,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
    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 
    TotalSpaceMB DESC, t.name

Hope this helps

Grant access to Azure Synapse

Create the user in the master database

--Use Master Database
CREATE USER [user@domain.com] FROM EXTERNAL PROVIDER
ALTER ROLE dbmanager ADD MEMBER [user@domain.com] ;
ALTER ROLE loginmanager ADD MEMBER [user@domain.com];
Grant Alter any user to [user@domain.com] with GRANT OPTION

Now select the user database from the db drop down menu in SQL Server Management Studio

--Use UserDatabase
CREATE USER [user@domain.com] FROM EXTERNAL PROVIDER
ALTER ROLE db_owner ADD MEMBER [user@domain.com]; --this grants the db permission to the user
Grant Alter any user to [user@domain.com] with GRANT OPTION  --this grants the user permission to modify permissions for other users.
EXEC sp_addrolemember '[schema_name]','user@domain.com' --this adds the user to a specify schema role

Hope this helps you to grant users permission to Azure Synapse Databases.

Database Mail Troubleshooting

Database Mail Troubleshooting

I use the following scritps to troubleshoot database mail issues.

–Get a list of email sent items
SELECT * FROM dbo.sysmail_sentitems

–Another version of the script to get a list of email sent items
USE msdb
SELECT sent_status, *
FROM sysmail_allitems
order by send_request_date desc

–Check to see if broker service is enabled
SELECT is_broker_enabled FROM sys.databases WHERE name = ‘msdb’;

–Check if database mail service is running
EXECUTE msdb.dbo.sysmail_help_status_sp

For SQL 2016 – you will need to have .net 3.5 installed on the server for db mail to work

EXEC msdb.dbo.sysmail_help_configure_sp;

–Get the name of the database profile and account name
EXEC msdb.dbo.sysmail_help_account_sp; –this will show the db mail account name
EXEC msdb.dbo.sysmail_help_profile_sp; –this will show the db mail profile name
EXEC msdb.dbo.sysmail_help_profileaccount_sp;
EXEC msdb.dbo.sysmail_help_principalprofile_sp;

Disable Foreign Keys

I received a request to export data from a table in a database in Production to a similar table in a database in the Development environment. I used the export/import wizard thru SQL Server Management Studio but my export was failing giving me an error that the data cannot be copied because Foreign Key was present in the destination database. In the past I would just script out a drop and create script for all the foreign keys then drop all the Foreign Keys, do the data export and then re-create the Foreign Keys. After some research online I came across a better option to just disable the Foreign Keys instead of dropping and recreating them.

But first lets understand what is a Primary Key and Foreign Key.

In SQL Server, a primary key is a single field that has a unique value to define a record. Fields that are part of the primary key cannot contain a null value. A table can have only one primary key. Usually the primary key is used as an index but this can vary.

A table can have only ONE primary key and this primary key can consist of single or multiple columns (fields).

Since primary key constraints ensure unique data, they are often called identity columns.

When you designate a primary key constraint for a table, the SQL engine enforces data uniqueness by auto create a unique index for the primary key columns.

A foreign key is a column or set of columns that allows developers to establish a referential link between the data in two different tables. This link helps to match the foreign key column data with the data of the referenced table data. The referenced table is called the parent table and the table that involves a foreign key is called the child table. In addition, if a foreign key references another column of the same table, this reference type is called a self-reference.

A FOREIGN KEY is a field (or collection of fields) in one table, that links to the PRIMARY KEY in another table.

The table with the foreign key is called the child table, and the table with the primary key is called the referenced table (parent table).

The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column in the child table, because it has to be one of the values contained in the parent table.

Based on the developer’s coding standard – usually it is a good practice to prefix with FK_{FK name} and the same goes with Primary Keys being prefixed with PK_{PK Name}

The following SQL query creates a FOREIGN KEY on the “PersonID” column in the Persons table when the “Orders” table is created:

CREATE TABLE Orders (

OrderID int NOT NULL,

OrderNumber int NOT NULL,

PersonID int,

PRIMARY KEY (OrderID),

FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)

);

If the Orders table is already created then use this SQL query to create a FOREIGN KEY constraint on the “PersonID” column:

ALTER TABLE Orders

ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

If you need to name a Foreign Key constraint and to specify a Foreign Key constraint on multiple columns, use this SQL Query:

ALTER TABLE Orders

ADD CONSTRAINT FK_PersonOrder

FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

You can disable a Foreign Key in a table using the Alter Table statement in SQL Server Management Studio. Here is the syntax to disable a foreign key in SQL Server (T-SQL):

ALTER TABLE [your_table_name]

NOCHECK CONSTRAINT [your_fk_name];

Parameters/Syntax:

your_table_name

The name of the table where the foreign key has been created.

your_fk_name

The name of the foreign key that you wish to disable.

The above script would use the ALTER TABLE statement to disable the constraint called fk_inyour_fk_name on the your_table_name table.

After you have disabled the Foreign Key then you should be able to do your data load using the Daa with no error.

To disable all constraints

— disable all constraints

EXEC sp_MSforeachtable “ALTER TABLE ? NOCHECK CONSTRAINT all”

To turn the constraints back on – the print command is optional and it is just for listing the database tables.

Run this:

— enable all constraints

exec sp_MSforeachtable @command1=”print ‘?'”, @command2=”ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all”

To disable the constraints is much helpful when you have to copy data from one database to another. I prefer this then dropping constraints.

If you have triggers in the database then you will have to disable the triggers prior to your data load and then add the triggers back on once the data load is completed.

To disable all constraints and triggers run this:

sp_msforeachtable “ALTER TABLE ? NOCHECK CONSTRAINT all”

sp_msforeachtable “ALTER TABLE ? DISABLE TRIGGER all”

To enable all constraints and triggers run this:

exec sp_msforeachtable @command1=”print ‘?'”, @command2=”ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all”

sp_msforeachtable @command1=”print ‘?'”, @command2=”ALTER TABLE ? ENABLE TRIGGER all”

The word of caution is disabling constraints and triggers – to you have make sure there are no new deltas being written to the database by the users because once you disable all the constraints and triggers any new deltas written to the database that might violate the integrity of the database. Hence you have to ensure that all application traffic is stopped.

Also if you need to import a large amount of data, then consider using BULK INSERT because this method does not fire the triggers. However after your bulk insert it completed, you will need to fix any data integrity issues which occurred during your bulk insert that circumvented the trigger policies.

Hope this helps clarify the concept of Primary Keys, Foreign Keys and Constraints.

Unable to open SQL Server Configuration Manager. When I click on Configuration manager I get the error: Cannot connect to WMI provider

I rdp’d to the sql server and to check which sql services are installed on the server – I tried to open SQL Configuration manager but I was unable to open SQL Server Configuration Manager. When I clicked on Configuration manager I get the error: Cannot connect to WMI provider.
You do not have permission or the server is unreachable. Note that you can only manage SQL Server 2005 and later servers with SQL Server Configuration Manager.

The first thing I did was to check if I have admin rights to the server.

How to fix the WMI Provider Error:
Open a command prompt in the location machine (run as administrator)
Then run the following command according to the SQL Server version which was installed on the machine.

SQL Server 2005
mofcomp “%programfiles(x86)%\Microsoft SQL Server\90\Shared\sqlmgmproviderxpsp2up.mof”

SQL Server 2008 / R2
mofcomp “%programfiles(x86)%\Microsoft SQL Server\100\Shared\sqlmgmproviderxpsp2up.mof”

SQL Server 2012
mofcomp “%programfiles(x86)%\Microsoft SQL Server\110\Shared\sqlmgmproviderxpsp2up.mof”

SQL Server 2014
mofcomp “%programfiles(x86)%\Microsoft SQL Server\120\Shared\sqlmgmproviderxpsp2up.mof”

SQL Server 2016
mofcomp “%programfiles(x86)%\Microsoft SQL Server\130\Shared\sqlmgmproviderxpsp2up.mof”

SQL Server 2017
mofcomp “%programfiles(x86)%\Microsoft SQL Server\140\Shared\sqlmgmproviderxpsp2up.mof”

SQL Server 2019
mofcomp “%programfiles(x86)%\Microsoft SQL Server\150\Shared\sqlmgmproviderxpsp2up.mof”

SQL Server 2022
mofcomp “%programfiles(x86)%\Microsoft SQL Server\160\Shared\sqlmgmproviderxpsp2up.mof”

If you run the above script for the correct sql version that is installed on your server then you will get the following message:

Hope this helps people resolve the issue they get when they try to open SQL Server configuration manager and get a WMI error.

VIEW SERVER STATE

There are occasions when database users will reach out to me get elevated database permissions to run DMVs. Members of sysadmin roles can view the results of Dynamic Management Objects but sometimes it There are occasions when database users will reach out to me get elevated database permissions to run DMVs. Members of sysadmin roles can view the results of Dynamic Management Objects but sometimes it is helpful to grant this permission to non-dba personnel if they need to do any performance troubleshooting.

Dynamic management views and functions return server state information that can be used to monitor the health of a server instance, diagnose sql server problems, and tune databae performance.

There are two different types of DMVs and functions:

Server-scoped DMVs and functions – These require VIEW SERVER STATE permission on the SQL Server level.
Database-scoped DMVs and functions – These require VIEW DATABASE STATE permission on each of the database.

VIEW SERVER STATE is a server level permission that grants non-sysadmin users the ability to view results of Dynamic Management Views.

Beginning with SQL Server 2005 dynamic management objects are database views or functions that shows specific information or the state of the SQL Server instance for the overall SQL Server or for a Beginning with SQL Server 2005 dynamic management objects are database views or functions that shows specific information or the state of the SQL Server instance for the overall SQL Server or for a given database instance at a given time. Since DMVs were introduces in SQL Server 2005 and with each new release of SQL Server, Microsoft has been adding additional DMVs (Dynamic Management Views) to help troubleshoot the performance of the SQL Servers. These objects are helpful to monitor the database server in an efficient and controlled manner.

DMVs come in two subsets – Dynamic Management Views (DMVs) and DMFs (Dynamic Management Functions) and are classified as Dynamic Management Objects (DMOs).
DMVs are like any other views where you can select data from them. DMVs require values to be passed to the function just like any other functions. I will go into the details of DMFs in a separate blog.

If the user does not have sysadmin priveleges or has been granted VIEW SERVER STATE permission and tries to run the following as an example:

SELECT * FROM sys.dm_os_wait_stats

The user will see an error like this one:
Msg 297, Level 16, State 1, Line 1
The user does not have permission to perform this action.

We run the following query to grant the user the access to the entire SQL Server Instance:

GRANT VIEW SERVER STATE TO dbuser1

This needs to be run on the master database.
Once the above script is executed successfully then that specific user will be able to view Dynamic Management Objects to do any type of performance troubleshooting.

In the case of a individual database scoped access, a user might have data reader access to the database but when the users runs this query:


SELECT * FROM sys.dm_db_partition_stats

They get an error, because this query is trying to access a DMV in the specific database.

WE need to grant VIEW DATABASE STATE for this.

We run the following query to grant the user the access to a specific database:
grant VIEW DATABASE STATE to []

USE [DatabaseName]
grant VIEW DATABASE STATE to [<DBUSer>]

Once you run the above script then the user will be able to get a result from:

SELECT * FROM sys.dm_db_partition_stats

Now lets talk about the security risks for granting VIEW SERVER STATE permission.
Yes, there is a risk in providing VIEW SERVER STATE to non-dba and non-sysadmin personnel since they aren’t supposed to see this level of intricate database information on the sql instance.
As an example: sys.dm_exec_connections, sys.dm_exec_cached_plans, sys.dm_exec_requests, sys.dm_exec_query_stats, all provide information about execution contexts and plans, and when the user uses these with sys.dm_exec_sql_text() or sys.dm_exec_query_plan(), it will give this user information about the sql code and objects in the databases. This is usually a security violation in some organizations.

The VIEW SERVER STATE permission gives the database user unrestricted access to this information when using these DMVs. Althought they cannot change anything in the database, but they can get detailed database execution info that may not be allowed to view based on the user’s organizational responsibilites. I would analyze this type of access request with a grain of salt and ask some questions as to the security implications of this user requesting access having access to the database execution info. Also the user will be able to use DMV’s to look at queries. If the queries or some query parameters can contain confidential information that the user wouldn’t otherwise be able to see prior to granting this access – allowing VIEW SERVER STATE would allow them to do so (dateofbirth or socialscecurity #s)

Hope this helps clarify the differences between VIEW SERVER STATE and VIEW DATABASE STATE permission grants.

Find a schema in all databases

So what is a Schema?
A SQL Server database contains multiple objects: tables, views, stored procedures, functions, indexes, triggers.

SQL Server Schemas are a logical collection of database objects. A user that owns a schema in the database are known as Schema owners. There is no restrictions on the number of objects can be in a schema.

If you need to find that default schema for a user – you need to be logged into SSMS with that user and then run the following query:

SELECT SCHEMA_NAME();

If you need to retrieve all the schema and their owners in a database, use this SQL query:

SELECT s.name AS schema_name, 
       s.schema_id, 
       u.name AS schema_owner
FROM sys.schemas s
     INNER JOIN sys.sysusers u ON u.uid = s.principal_id
ORDER BY s.name;

On some occasion, a business user will give me a sql script to run on a database that does not have a USE clause in the script and they have no idea on which database it needs to be run on. And in most cases there are 50+ databases on the sql instance.

Here is an example of a script:

Select * from schema_name.table_name

Now usually the schema name is dbo but in some rare occasions they have a unique name for the schema. Since the user does now know which database the sql script on I use msforeachdb to find the schema name in all the databases and then I can find out in which database the schema resides on and then I can run the script the business user gave me on that database and provide the user the information they requested.

Here is the sql script to find a schema in all databases:

--This query will return a listing of all tables that matches a schema name on a SQL instance: 
DECLARE @command varchar(1000) 
SELECT @command = 'USE ? SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE "%prdobj%"' 
EXEC sp_MSforeachdb @command

This has helped me tremendously in numerous occasion of tedious work on finding on which database the schema resides on. Hope this helps.

Email Alert when SQL Server is restarted

As a DBA we need to be notified when a SQL Server is restarted so that we can take a proactive reaction to identify the cause of the restart which could be an indication of underlining issues with the Server OS or the SQL Server Engine.

I have used this several years now and it has helped me avoid Severity 1 outages a few cases.

Just put this code in a sql job and make sure you change the db mail portion that pertains to your environment.

Declare @Title varchar(max)
Declare @Ebody varchar(max)
Declare @TableHead varchar(max)
Declare @TableTail varchar(max)

Select @Title = 'SQL Server Restarted - ' + @@SERVERNAME
Set NoCount On;
Set @TableTail= '</body></html>';

---HTML Layout--

Set @TableHead = '<html><head>' +
'<H4 style="color: #000000">**********This is an informational message only**********</H4>' +
 '</head>' +
 '<body>' + 'SQL Server Services have been RESTARTED : '+ '<strong>' + @@SERVERNAME + '</strong>' +
 '<p>' + ' If this was not planned, check the Server' + '</p>'

select @TableHead = @TableHead + @TableTail

WAITFOR DELAY '00:00:30'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DB_Admins',
@recipients = 'db_admins@yourdomain.com',
@body = @TableHead,
@body_format = HTML,
@subject = @Title;

Hope this helps you avoid any outages as it has helped me.