将 TRUE 和 FALSE 都传递给 SQL 函数中的参数
Passing both TRUE and FALSE to a parameter in a SQL function
我有一个基本上像这样的 PostgreSQL 函数...
create or replace function myfunction(myparam boolean)
returns table
language 'sql'
as $BODY$
select * from mytable where myIndicator = myparam
$BODY$
...而且效果很好。但是,我现在被告知可能会要求此函数 return 所有 myparam
是 true
或 false
或两者[=24= 的情况].但是,此代码失败,因为 array
不是可能的参数类型:
create or replace function myfunction(couldBeTrueOrFalseOrBoth array)
returns table
language 'sql'
as $BODY$
select * from mytable where myIndicator in couldBeTrueOrFalseOrBoth
$BODY$
这里有简单的解决方案吗?
选项 1:
使用字符串作为参数,选项为“true”、“false”和“both”。然后在你的函数用例语句中确定它是“真”、“假”还是“两者”。
create or replace function myfunction(myparam string)
returns table
language 'sql'
as $BODY$
CASE
WHEN myParam='true'
THEN select * from mytable where myIndicator = true
WHEN myParam='false'
THEN select * from mytable where myIndicator = false
WHEN myParam='both'
THEN select * from mytable
END
$BODY$
选项 2:
只需调用您的函数两次,所有情况它都需要回答。
您可以为此使用 null
:
create or replace function myfunction(myparam boolean)
returns table (...)
language sql
as $BODY$
select *
from mytable
where myIndicator = myparam
or myparam is null
$BODY$
要获取所有行,请使用:
select *
from myfunction(null)
您还可以使用可选参数:
create or replace function myfunction(myparam boolean default null)
returns table (...)
language sql
as $BODY$
select *
from mytable
where myIndicator = myparam
or myparam is null
$BODY$
那么不带参数调用也是可以的(和传null一样)
select *
from myfunction()
我有一个基本上像这样的 PostgreSQL 函数...
create or replace function myfunction(myparam boolean)
returns table
language 'sql'
as $BODY$
select * from mytable where myIndicator = myparam
$BODY$
...而且效果很好。但是,我现在被告知可能会要求此函数 return 所有 myparam
是 true
或 false
或两者[=24= 的情况].但是,此代码失败,因为 array
不是可能的参数类型:
create or replace function myfunction(couldBeTrueOrFalseOrBoth array)
returns table
language 'sql'
as $BODY$
select * from mytable where myIndicator in couldBeTrueOrFalseOrBoth
$BODY$
这里有简单的解决方案吗?
选项 1:
使用字符串作为参数,选项为“true”、“false”和“both”。然后在你的函数用例语句中确定它是“真”、“假”还是“两者”。
create or replace function myfunction(myparam string)
returns table
language 'sql'
as $BODY$
CASE
WHEN myParam='true'
THEN select * from mytable where myIndicator = true
WHEN myParam='false'
THEN select * from mytable where myIndicator = false
WHEN myParam='both'
THEN select * from mytable
END
$BODY$
选项 2:
只需调用您的函数两次,所有情况它都需要回答。
您可以为此使用 null
:
create or replace function myfunction(myparam boolean)
returns table (...)
language sql
as $BODY$
select *
from mytable
where myIndicator = myparam
or myparam is null
$BODY$
要获取所有行,请使用:
select *
from myfunction(null)
您还可以使用可选参数:
create or replace function myfunction(myparam boolean default null)
returns table (...)
language sql
as $BODY$
select *
from mytable
where myIndicator = myparam
or myparam is null
$BODY$
那么不带参数调用也是可以的(和传null一样)
select *
from myfunction()