是否可以通过将列与另一个存在的临时表匹配来更改列?

时间:2019-02-18 14:23:16

标签: sql sql-server data-masking sql-data-warehouse

我正在屏蔽SQL Datawarehouse中几个数据库中的个人数据。我已经创建了一个表,其中包含要屏蔽的列,并希望通过这样的单个脚本来更改数据库中多个表中存在的这些列

IF EXISTS(SELECT *
          FROM INFORMATION_SCHEMA.COLUMNS
          WHERE TABLE_NAME = 'TableName' and 
          COLUMN_NAME = 'BirthDate' OR COLUMN_NAME = 'EmailAddress' OR COLUMN_NAME = 'FirstName' OR COLUMN_NAME = 'LastName' OR COLUMN_NAME = 'MiddleName' OR COLUMN_NAME = 'Name.First' OR COLUMN_NAME = 'MName.Last' OR COLUMN_NAME = 'PhoneNumber'
          )
BEGIN
ALTER TABLE TABLE_NAME
ALTER COLUMN [COLUMN_NAME] NVARCHAR(200) MASKED WITH (FUNCTION = 'default()') NULL
END

这不起作用。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您必须使用Dynamic SQL来执行此操作。使用对Information_Schema的查询来动态生成所需的ALTER TABLE语句,然后执行它们。

答案 1 :(得分:0)

您需要使用循环来使用动态SQL执行DDL代码

DECLARE @tmp TABLE (ID int identity, TableName varchar(100), ColumnName varchar(100)

INSERT @tmp
SELECT QUOTENAME(TABLE_NAME), QUOTENAME(COUMN_NAME)
          FROM INFORMATION_SCHEMA.COLUMNS
          WHERE TABLE_NAME = 'TableName' and 
          COLUMN_NAME = 'BirthDate' OR COLUMN_NAME = 'EmailAddress' OR COLUMN_NAME = 'FirstName' OR COLUMN_NAME = 'LastName' OR COLUMN_NAME = 'MiddleName' OR COLUMN_NAME = 'Name.First' OR COLUMN_NAME = 'MName.Last' OR COLUMN_NAME = 'PhoneNumber'
          )
DECLARE @ID int, @TableName varchar(100), @ColumnName varchar(100)
DECLARE @SQL varchar(MAX)
WHILE EXISTS (SELECT 1 FROM @tmp)
BEGIN
    SELECT TOP 1 @ID = ID, @TableName = TableName, @ColumnName = ColumnName

    SET @SQL = '
    ALTER TABLE ' + @TableName + '
    ALTER COLUMN ' + @ColumnName + ' NVARCHAR(200) MASKED WITH (FUNCTION = ''default()'') NULL
    '
    EXEC(@SQL)
    DELETE @tmp WHERE ID = @ID
END