The Problem
I have a script that I need to execute on both SQL Server 2016 and SQL Server 2019. If executing on Server 2019+, I want to use syntax that is only supported on that version (specifically, Data Classification).
What I want is something like this, where we simply skip Data Classification if running on a version before 2019:
DECLARE @compatibility_level TINYINT = 0;
SELECT @compatibility_level = compatibility_level FROM sys.databases WHERE name = 'MyDatabase';
PRINT CONCAT('Database compatibility level is: ', @compatibility_level);
IF @compatibility_level >= 150
BEGIN
ADD SENSITIVITY CLASSIFICATION TO
MyTable.Forename,
MyTable.Surname
WITH (LABEL='Confidential - GDPR', INFORMATION_TYPE='Name', RANK=MEDIUM);
-- More classifications would be here
END
ELSE
BEGIN
PRINT 'Data Classification will not be performed, as the compatibility level is not high enough';
END
If I run this on SQL Server 2019+, it works as expected. But if I run it on older version, it fails with Incorrect syntax near 'SENSITIVITY', because it's parsing the whole script before executing it.
Restrictions
I should add that this is part of a set of database migration scripts that are being executed automatically, so I can't simply execute different scripts for different versions (not without a lot of work).
Potential Solutions
One solution I thought of is to build the SQL dynamically, inside the IF block. Something like:
DECLARE @sql NVARCHAR(MAX) = '';
@sql += 'ADD SENSITIVITY CLASSIFICATION TO MyTable1.Column1 ... ;';
@sql += 'ADD SENSITIVITY CLASSIFICATION TO MyTable2.Column1 ... ;';
EXEC sp_executesql @sql;
I haven't tried this, but presume it would work. It feels pretty ugly though - are there any other ways to achieve this in a single script?