
DECLARE @useSql2019Syntax BIT = CASE
    WHEN CAST(SERVERPROPERTY('productversion')  AS VARCHAR(2)) >= 15 THEN 1
    ELSE 0
END ;

IF @useSql2019Syntax = 1
BEGIN
    EXEC ('
    SELECT SCHEMA_NAME([O].[schema_id]) AS schema_name,
           O.name AS table_name,
           C.name AS column_name,
           [sc].[information_type],
           [sc].[label],
           [sc].[rank],
           [sc].[rank_desc]
           ,''ADD SENSITIVITY CLASSIFICATION TO [''+CAST(SCHEMA_NAME([O].[schema_id]) AS NVARCHAR(100))+''].[''+CAST(o.[name] AS NVARCHAR(100))+''].[''+CAST(c.name AS NVARCHAR(100))+'']  WITH ( LABEL=''''''+CAST(sc.[label] AS NVARCHAR(100))+'''''', INFORMATION_TYPE=''''''+CAST(sc.[information_type] AS NVARCHAR(100))+'''''' ''
           + CASE 
                WHEN sc.[rank_desc] IS NOT NULL THEN '', RANK=''+sc.[rank_desc]
                ELSE ''''
            END 
            +'')''
      FROM sys.sensitivity_classifications sc
      JOIN sys.objects O
        ON [sc].[major_id] = O.object_id
      JOIN sys.columns C
        ON [sc].[major_id] = C.object_id
       AND [sc].[minor_id] = [C].[column_id]
     --WHERE CAST(sc.[information_type] AS VARCHAR(500)) <> ''Other''
     --WHERE [O].[name] LIKE ''[IIICommon_Bank_PTT_Master]''
     ORDER BY CAST([sc].[information_type] AS VARCHAR(500)), [schema_name], [table_name], [column_name];
    ')
END 
ELSE 
BEGIN
    SELECT
        schema_name(O.schema_id) AS schema_name,
        O.[name] AS table_name,
        C.[name] AS column_name,
        [EP].[information_type],
        [EP].[sensitivity_label] 
    FROM
        (
            SELECT
                IT.major_id,
                IT.minor_id,
                IT.information_type,
                L.sensitivity_label 
            FROM
            (
                SELECT
                    major_id,
                    minor_id,
                    value AS information_type 
                FROM sys.extended_properties 
                WHERE NAME = 'sys_information_type_name'
            ) IT 
            FULL OUTER JOIN
            (
                SELECT
                    major_id,
                    minor_id,
                    value AS sensitivity_label 
                FROM sys.extended_properties 
                WHERE NAME = 'sys_sensitivity_label_name'
            ) L 
            ON IT.major_id = L.major_id AND IT.minor_id = L.minor_id
        ) EP
        JOIN sys.objects O
        ON  EP.major_id = O.object_id 
        JOIN sys.columns C 
        ON  EP.major_id = C.object_id AND EP.minor_id = C.column_id
        ;
END 