sys.types returns 错误的数据类型

sys.types returns wrong data type

我的目标是编写脚本并导出 Dynamic Data Masking。

为此,我创建了一个允许我动态创建代码的查询:

SELECT 
schema_name(tbl.schema_id) AS schema_name,
tbl.name as table_name, 
mc.name AS column_name, 
mc.is_masked
, [Type]         = 
    CASE 
      WHEN tp.[name] IN ('varchar', 'char') THEN tp.[name] + '(' + IIF(mc.max_length = -1, 'max', CAST(mc.max_length AS VARCHAR(25))) + ')' 
      WHEN tp.[name] IN ('nvarchar','nchar') THEN tp.[name] + '(' + IIF(mc.max_length = -1, 'max', CAST(mc.max_length / 2 AS VARCHAR(25)))+ ')'      
      WHEN tp.[name] IN ('decimal', 'numeric') THEN tp.[name] + '(' + CAST(mc.[precision] AS VARCHAR(25)) + ', ' + CAST(mc.[scale] AS VARCHAR(25)) + ')'
      WHEN tp.[name] IN ('datetime2') THEN tp.[name] + '(' + CAST(mc.[scale] AS VARCHAR(25)) + ')'
      ELSE tp.[name]
    END,
mc.masking_function
,'ALTER TABLE '
+ schema_name(tbl.schema_id) + '.' + tbl.name +
' ALTER COLUMN '
+ mc.name +  ' ' + 
    CASE 
      WHEN tp.[name] IN ('varchar', 'char') THEN tp.[name] + '(' + IIF(mc.max_length = -1, 'max', CAST(mc.max_length AS VARCHAR(25))) + ')' 
      WHEN tp.[name] IN ('nvarchar','nchar') THEN tp.[name] + '(' + IIF(mc.max_length = -1, 'max', CAST(mc.max_length / 2 AS VARCHAR(25)))+ ')'      
      WHEN tp.[name] IN ('decimal', 'numeric') THEN tp.[name] + '(' + CAST(mc.[precision] AS VARCHAR(25)) + ', ' + CAST(mc.[scale] AS VARCHAR(25)) + ')'
      WHEN tp.[name] IN ('datetime2') THEN tp.[name] + '(' + CAST(mc.[scale] AS VARCHAR(25)) + ')'
      ELSE tp.[name]
    END
+ ' MASKED WITH (FUNCTION = ''' 

-- + mc.masking_function
+ CAST(mc.masking_function COLLATE Latin1_General_CI_AI AS nvarchar(100))
+ ''');'

FROM sys.masked_columns AS mc  
JOIN sys.tables AS tbl ON mc.[object_id] = tbl.[object_id]  
JOIN sys.types tp ON mc.user_type_id = tp.user_type_id
WHERE mc.is_masked = 1; 

问题是这段代码在 AdventureWorks 上只工作了一半 returns 我的数据类型 NamePhone 不是该列的实际数据类型:

schema_name table_name column_name is_masked Type masking_function (No column name)
Person Person FirstName 1 Name partial(2, "xxxx", 0) ALTER TABLE Person.Person ALTER COLUMN FirstName Name MASKED WITH (FUNCTION = 'partial(2, "xxxx", 0)');
Person Person LastName 1 nvarchar(50) default() ALTER TABLE Person.Person ALTER COLUMN LastName nvarchar(50) MASKED WITH (FUNCTION = 'default()');
Person PersonPhone PhoneNumber 1 Phone partial(5, "XXXXXXX", 0) ALTER TABLE Person.PersonPhone ALTER COLUMN PhoneNumber Phone MASKED WITH (FUNCTION = 'partial(5, "XXXXXXX", 0)');
Person EmailAddress EmailAddress 1 nvarchar(50) email() ALTER TABLE Person.EmailAddress ALTER COLUMN EmailAddress nvarchar(50) MASKED WITH (FUNCTION = 'email()');

我有一个 查询,但它正在连接 INFORMATION_SCHEMA.COLUMNSsys.* 表,这不是最佳做法。

为什么有些数据类型的前缀是NamePhone

如何为每列设置正确的数据类型?

如果你想查询return系统数据类型nvarchar(50)(而不是用户定义的数据类型Name),你应该将JOIN更改为sys.types这样:

JOIN sys.types tp ON tp.user_type_id = mc.system_type_id