-3

I want to do an insert using a CASE statement in PostgreSQL.

I am trying to do an insert if the count of my result set is equal to zero. If it isn't equal to zero, then I just want to do a select of the max time on that table.

select
    case
        when (select count(*) from x where TableName = 'p' ) > 0
              then
             (select    MaxDataDate from    x where TableName = 'p' ) 
        when (select count(*) from s where TableName = 'p') = 0
              then
             (insert into x values('p','1900-01-01'))
end
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228

1 Answers1

0

Could be translated to pure SQL with a data-modyfying CTE like this:

WITH sel AS (SELECT maxdatadate FROM x where tablename = 'p')
,    ins AS (
    INSERT INTO x (?column_name1?, ?column_name2?)
    SELECT 'p'::?type1?, '1900-01-01'::?type2?
    WHERE  NOT EXISTS (SELECT 1 FROM ins)
    AND    EXISTS (SELECT 1 FROM s WHERE tablename = 'p')
    )
SELECT * FROM ins;

Fill in missing information. ? marks the spots.

Assuming x.tablename is unique. Otherwise, your 2nd SELECT statement would be nonsense.

The alternative would be a procedural solution in a plpgsql function or a DO statement like @X.L.Ant already hinted in his comment.

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228