Search code examples
sqlsql-serverkey-valueentity-attribute-value

Can I use a trigger to create a column?


As an alternative to anti-patterns like Entity-Attribute-Value or Key-Value Pair tables, is it possible to dynamically add columns to a data table via an INSERT trigger on a parameter table?

Here would be my tables:

CREATE TABLE [Parameters]
(
    id int NOT NULL 
        IDENTITY(1,1) 
        PRIMARY KEY,
    Parameter varchar(200) NOT NULL,
    Type varchar(200) NOT NULL
)
GO

CREATE TABLE [Data]
(
    id int NOT NULL
        IDENTITY(1,1)
        PRIMARY KEY,
    SerialNumber int NOT NULL
)
GO

And the trigger would then be placed on the parameter table, triggered by new parameters being added:

CREATE TRIGGER [TRG_Data_Insert]
    ON [Parameters]
    FOR INSERT 
AS BEGIN            
            -- The trigger takes the newly inserted parameter
            -- record and ADDs a column to the data table, using
            -- the parameter name as the column name, the data type
            -- as the column data type and makes the new column 
            -- nullable.
END
GO

This would allow my data mining application to get a list of parameters to mine and have a place to store that data once it mines it. It would also allow a user to add new parameters to mine dynamically, without having to mess with SQL.

Is this possible? And if so, how would you go about doing it?


Solution

  • I think the idea of dynamically adding columns will be a ticking time bomb, just gradually creeping towards one of the SQL Server limits.

    You will also be putting the database design in the hands of your users, leaving you at the mercy of their naming conventions and crazy ideas.

    So while it is possible, is it better than an EAV table, which is at least obvious to the next developer to pick up your program؟