I need to iterate through the fields on a table and do something if its value does not equal its default value.
I'm in a trigger and so I know the table name. I then loop through each of the fields using this loop:
select @field = 0, @maxfield = max(ORDINAL_POSITION) from
INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName
while @field < @maxfield
begin
...
I can then get the field name on each iteration through the loop:
select @fieldname = COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = @TableName
and ORDINAL_POSITION = @field
And I can get the default value for that column:
select @ColDefault = SUBSTRING(Column_Default,2,LEN(Column_Default)-2)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE Table_Name = @TableName
AND Column_name = @fieldname
I have everything I need but I can't see how to then compare the 2. Because I don't have the field name as a constant, only in a variable, I can't see how to get the value out of the 'inserted' table (remember I'm in a trigger) in order to see if it is the same as the default value (held now in @ColDefault as a varchar).