Skip to content
Advertisement

INSERT INTO with use CASE – sqlite?

I have a problem with syntax. I need use IF in sqlite, and I replace IF – CASE.
My statement doesn’t work, I don’t know, what is wrong?

CASE
WHEN EXISTS(
  SELECT sql
    FROM sqlite_master 
    WHERE name = 'TEST_TABLE' AND
          type = 'table' AND
          sql LIKE '%aaaa%'
)THEN
  INSERT INTO atabela_new(id, idMain, idHistory, aNew)
  SELECT id, idMain, idHistory, aNew  FROM a_tabela
ELSE
  INSERT INTO atabela_new(id, idMain, idHistory)
  SELECT id, idMain, idHistory FROM a_tabela; 

Advertisement

Answer

Assuming the default for aNew is NULL:

INSERT INTO atabela_new(id, idMain, idHistory, aNew)
SELECT id, 
       idMain, 
       idHistory,  
       CASE
           WHEN EXISTS
              (SELECT sql FROM sqlite_master WHERE name = 'TEST_TABLE' AND type = 'table' AND sql LIKE '%aaaa%')
           THEN aNew 
           ELSE NULL
       END
FROM a_tabela

Otherwise you’ll need to put that logic in your application code.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement