Gorden Gram
Gorden Gram

Reputation: 981

SQLite if column exists solution?

I want to create a trigger that dealing with some column in a table.

The trigger must handle the error that would occur if such a column doesn't exist.

Is it possible? I searched the web with no such solution because "if exists" command doesn't exists in SQLite.

EDIT: Example for a trigger (requested in the comment):

    CREATE TRIGGER trigger_name 
    AFTER UPDATE ON table_1
    BEGIN
       IF exist (select col_1 from table_1) 
          BEGIN 
            update table_1 set col_1='1' where id = '2'
          END
    END

If col_1 doesn't exists it will make an error.

Upvotes: 0

Views: 459

Answers (1)

CL.
CL.

Reputation: 180060

In SQLite, triggers can execute only normal SELECT/INSERT/UPDATE/DELETE commands; there are not any programming constructs like IF.

If you do want to execute dynamic code, you have to register your own user-defined function (how this is done depends on what language/driver you're using), and call it from the trigger:

CREATE TRIGGER name
AFTER UPDATE ON table_1
BEGIN
    SELECT my_custom_function();
END

In your function, you can then check the table structure with a PRAGMA table_info query and execute the UPDATE query.

Upvotes: 2

Related Questions