动态 SQL (EXECUTE) 作为 IF 语句的条件
我想要执行一条动态 SQL 语句,其返回值是 IF
语句的条件:
IF EXECUTE 'EXISTS (SELECT 1 FROM mytable)' THEN
这会生成错误 ERROR: type "execute" does not exit
。
是否可以这样做,或者是否需要在IF语句之前执行SQL到变量中,然后检查该变量作为条件?
I want to execute a dynamic SQL statement, with its returned value being the conditional for an IF
statement:
IF EXECUTE 'EXISTS (SELECT 1 FROM mytable)' THEN
This generates the error ERROR: type "execute" does not exist
.
Is it possible to do this, or is it necessary to execute the SQL before the IF statement into a variable, and then check the variable as the conditional?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这种构造是不可能的:
IF EXECUTE 'EXISTS (SELECT 1 FROM mytable)' THEN ...
您可以简化为:
但您的示例可能已简化。对于通过
EXECUTE
执行的动态 SQL,在此处阅读手册。您可以在执行任何 DML 命令后立即检查特殊变量FOUND
以查看是否有任何行受到影响:但是:
大胆强调我的。对于普通的
EXECUTE
,请执行以下操作:或,如果合适的话 - 特别是只有单行结果 - 使用
INTO
子句EXECUTE
直接从动态查询中获取结果。我在此处引用手册:This construct is not possible:
IF EXECUTE 'EXISTS (SELECT 1 FROM mytable)' THEN ...
You can simplify to:
But your example is probably simplified. For dynamic SQL executed with
EXECUTE
, read the manual here. You can check the special variableFOUND
immediately after executing any DML command to see whether any rows were affected:However:
Bold emphasis mine. For a plain
EXECUTE
do this instead:Or, if opportune - in particular with only single-row results - use the
INTO
clause withEXECUTE
to get a result from the dynamic query directly. I quote the manual here:Matt,
从上面的语法来看,您正在编写 PL/pgSQL,而不是 SQL。根据这个假设,有两种方法可以完成您想要的操作,但是两种方法都需要两行代码:
或者:
“FOUND”是一个特殊变量,用于检查最后一次查询运行是否返回任何行。
Matt,
From the syntax above, you're writing PL/pgSQL, not SQL. On tht assumption, there are two ways to do what you want, but both will require two lines of code:
Or:
"FOUND" is a special variable which checks if the last query run returned any rows.