如何在 PostgreSQL 中测试 if 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9151863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 23:36:47  来源:igfitidea点击:

How to test an if statement in PostgreSQL?

sqlpostgresqlplpgsql

提问by Stefan Steiger

Question: I want to test an if statement in PostgreSQL:

问题:我想在 PostgreSQL 中测试一个 if 语句:

IF (SELECT COUNT(*) FROM pg_language WHERE lanname = 'plpgsql') > 0 THEN
    PRINT 'Good'
ELSE
    PRINT 'Bad'
END IF;

Now this throws an error at IF.

现在这会在 IF 处引发错误。

As far as I have read, this is because I need to use plpgsql to be able to use if, print, and variables.

据我所知,这是因为我需要使用 plpgsql 才能使用 if、print 和 variables。

So far, I probably also have to use SELECT instead of print as well.

到目前为止,我可能还必须使用 SELECT 而不是打印。

How can I switch the language before executing this statement to plpgsql ?

如何在执行此语句到 plpgsql 之前切换语言?

I want to test it first, BEFORE I put it in a stored procedure. To test code with variables etc.

我想先对其进行测试,然后再将其放入存储过程。用变量等测试代码。



Edit:

Solved by:

编辑:

解决:

DO LANGUAGE plpgsql $$
    BEGIN
        IF (SELECT COUNT(*) FROM pg_language WHERE lanname = 'plpgsql') > 0 THEN 
            RAISE NOTICE 'GOOD';
        ELSE
            RAISE NOTICE 'BAD';
        END IF;
    END;
$$;

回答by mu is too short

If you just want to test code snippets without going through all the hassle of building and dropping a function, then you can use DO:

如果您只想测试代码片段而不经历构建和删除函数的所有麻烦,那么您可以使用DO

=> do language plpgsql $$
    begin
        -- Yes, I have a table called pancakes in my playpen database.
        if (select count(*) from pancakes) > 0 then
            raise notice 'Got some';
        else
            raise notice 'Got none';
        end if;
    end;
$$;

You'll need 9.0+ to use DO.

您需要 9.0+ 才能使用DO.