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

Is it possible to alter columns by matching them to another temporary table that exist?

我正在 SQL Datawarehouse 的几个数据库中屏蔽个人数据。我已经创建了一个 table,其中包含我想要屏蔽的列,并且想通过像这样的单个脚本

来更改存在于数据库中多个 table 中的这些列
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

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

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

你需要使用循环来使用动态执行你的 DDL 代码 sql

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