0

I need a way to run some sql commands ONLY IF a record doesn't already exist in my db.
I have the following .sql file so far:

PRAGMA foreign_keys=OFF;    
BEGIN TRANSACTION;

IF NOT EXISTS (SELECT * FROM widgets WHERE name="123")
BEGIN
ALTER TABLE table2 ADD COLUMN mynewcolumn VARCHAR(255);    
INSERT INTO table2 ("abc", "def")
END
COMMIT;

But this fails with a syntax error.
I know that IF does exist in sqlite but it seems it's only a part of the CREATE statement.
Declare variable in sqlite and use it

I'm wondering if you can suggest a different way I can accomplish the task above?

Community
  • 1
  • 1
Happydevdays
  • 1,982
  • 5
  • 31
  • 57
  • `CREATE TABLE IF NOT EXISTS` is special syntax for `CREATE TABLE`, not a general thing. – Schwern Jan 25 '17 at 21:12
  • @Schwern yeah i guess you just added this comment as I was updating my entire question. – Happydevdays Jan 25 '17 at 21:13
  • how do i contest the "duplicate" comment? This is not the same question – Happydevdays Jan 25 '17 at 21:20
  • Address a comment to @CL explaining why it isn't a duplicate. But it is, the first answer states "*SQLite has almost no control logic; as an embedded database, it is designed to be used together with a 'real' programming language.*" You can't do what you're asking in pure SQLite, even with `CASE`. – Schwern Jan 25 '17 at 21:21
  • @Schwern ok. yeah, i guess that makes sense. – Happydevdays Jan 25 '17 at 21:24

0 Answers0