Current Trigger is as follows:
CREATE TRIGGER TestTrigger
ON DATABASE
FOR ALTER_TABLE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @FULL_STATEMENT SYSNAME
SELECT @FULL_STATEMENT = EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
print('The following SQL statement was executed:')
print('')
print (@FULL_STATEMENT)
print('')
print('Next step is to work out how to single out the added column name')
ROLLBACK
END
I then run the following SQL Statement:
USE [a_Database]
ALTER TABLE dbo.TABLE
ADD TestColumn varchar(50)
And it outputs the following:
The following SQL statement was executed:
ALTER TABLE dbo.TABLE
ADD TestColumn varchar(50)
Next step is to work out how to single out the added column name
Msg 3609, Level 16, State 2, Line 2
The transaction ended in the trigger. The batch has been aborted.
The end goal is to single out"TestColumn" to make sure that it doesn't contain specific characters that can break internal programs. "TestColumn" would be a valid name, but "Test.Column" wouldn't, for example.
What would be the best way to single it out and pass it to a new variable ("@ColumnName"?) to check for unwanted characters?
You need to bear in mind that an alter statement can add more than one column. If you look at the XML generated for an alter column statement you will get a better idea:
So since you can add multiple columns, you need to check multiple columns, to get your columns lists you can use:
Then you could simply use
EXISTSto check against a list of reserved names etc, and check for unwanted characters:Another thing to consider is that
sp_renamewill fire a different event, and you probably want to track this too. The XML here looks like:So here you would need to track it slightly differently, since it can only be one column at a time, you don't need to worry about nodes: