Stylock
Stylock

Reputation: 1499

check if a column exists before altering the table

How would I execute such a query? Here's an example query that adds a new column.

ALTER TABLE [users] ADD COLUMN [description] VARCHAR(255) NOT NULL DEFAULT ''

Whenever that query is executed again, it produces the following error.

SQLiteManager: Likely SQL syntax error: ALTER TABLE [users] ADD COLUMN [description] VARCHAR(255) NOT NULL DEFAULT '' [ duplicate column name: description ] Exception Name: NS_ERROR_FAILURE Exception Message: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [mozIStorageConnection.createStatement]

I'd like to eliminate that error if possible. For example, the following query doesn't produce any errors when executed multiple times.

CREATE TABLE IF NOT EXISTS [users] ([id_users] INTEGER PRIMARY KEY AUTOINCREMENT)

But SQLite doesn't support IF condition at the beginning of a query, so I'm pretty much clueless as what to do. I've also tried using CASE expression, but failed. Any help is greatly appreciated.

Upvotes: 0

Views: 1853

Answers (1)

CL.
CL.

Reputation: 180060

It is not possible to do this with a single ALTER TABLE statement.

You could check if the column exists with another command (like PRAGMA table_info(users)).

Upvotes: 2

Related Questions