我想在PostgreSQL中使用CASE
语句进行插入。
如果我的结果集的计数等于零,我正在尝试插入。如果它不等于零,那么我只想在该表上选择最大时间。
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
答案 0 :(得分:0)
可以像data-modyfying CTE一样翻译成纯SQL:
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;
填写缺失的信息。 ?
标志着这些景点。
假设x.tablename
是唯一的。否则,您的第二个SELECT
声明将是无意义的。
替代方案是plpgsql函数或DO
语句like @X.L.Ant already hinted in his comment.