您需要记住,一个 alter 语句可以添加多个列。如果您查看为 alter column 语句生成的 XML,您会得到一个更好的主意:
ALTER TABLE dbo.EventTest ADD NewColumn1 INT, NewColumn2 INT;
----------------------------
<EVENT_INSTANCE>
<EventType>ALTER_TABLE</EventType>
<PostTime>2015-06-30T14:28:30.790</PostTime>
<SPID>67</SPID>
<ServerName>XXXXXX</ServerName>
<LoginName>XXXXXX</LoginName>
<UserName>dbo</UserName>
<DatabaseName>XXXXXX</DatabaseName>
<SchemaName>dbo</SchemaName>
<ObjectName>EventTest</ObjectName>
<ObjectType>TABLE</ObjectType>
<AlterTableActionList>
<Create>
<Columns>
<Name>NewColumn1</Name>
<Name>NewColumn2</Name>
</Columns>
</Create>
</AlterTableActionList>
<TSQLCommand>
<SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE" />
<CommandText>ALTER TABLE dbo.EventTest ADD NewColumn1 INT, NewColumn1 INT;</CommandText>
</TSQLCommand>
</EVENT_INSTANCE>
因此,由于您可以添加多个列,因此您需要检查多个列,以获取您可以使用的列列表:
SELECT ColumnName = Cols.value('.', 'SYSNAME')
FROM EVENTDATA().nodes('EVENT_INSTANCE/AlterTableActionList/Create/Columns') x (Cols);
然后您可以简单地使用EXISTS
来检查保留名称等列表,并检查不需要的字符:
IF EXISTS
( SELECT 1
FROM ( SELECT ColumnName = Cols.value('.', 'SYSNAME')
FROM EVENTDATA().nodes('EVENT_INSTANCE/AlterTableActionList/Create/Columns') x (Cols)
) AS t
WHERE PATINDEX('%[.@!-]%', t.ColumnName) > 0 -- USE PATTERN MATCH TO CHECK FOR UNWANTED CHARACTERS
OR EXISTS
( SELECT 1
FROM dbo.ReservedColumnNames AS rc
WHERE rc.Name = t.ColumnName
)
)
BEGIN
RAISERROR(...)
ROLLBACK;
END
要考虑的另一件事是它sp_rename
会触发一个不同的事件,您可能也想跟踪它。此处的 XML 如下所示:
<EVENT_INSTANCE>
<EventType>RENAME</EventType>
....
<SchemaName>dbo</SchemaName>
<ObjectName>NewColumn</ObjectName>
<ObjectType>COLUMN</ObjectType>
<TargetObjectName>EventTest</TargetObjectName>
<TargetObjectType>TABLE</TargetObjectType>
<NewObjectName>NewColumn2</NewObjectName>
<Parameters>
<Param>dbo.EventTest.NewColumn</Param>
<Param>NewColumn2</Param>
<Param>COLUMN</Param>
</Parameters>
<TSQLCommand>
<SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE" />
<CommandText>EXECUTE SP_RENAME 'dbo.EventTest.NewColumn', 'NewColumn2', 'COLUMN';</CommandText>
</TSQLCommand>
</EVENT_INSTANCE>
所以在这里你需要稍微不同地跟踪它,因为它一次只能是一列,你不需要担心节点:
SELECT EVENTDATA().value('EVENT_INSTANCE[1]/NewObjectName[1]', 'SYSNAME')
WHERE EVENTDATA().value('EVENT_INSTANCE[1]/EventType[1]', 'VARCHAR(13)') = 'RENAME'
AND EVENTDATA().value('EVENT_INSTANCE[1]/ObjectType[1]', 'VARCHAR(13)') = 'COLUMN';