我在SQL Server中有一个过程如下:
我正在尝试编写一个与上面完全相同的postgresql函数。我试过这样的事情:
CREATE OR REPLACE FUNCTION getadmbyyear(IN a integer, IN b character varying)
RETURNS TABLE(monname character varying, mon integer, adm integer, selected integer) AS
$BODY$
DECLARE testtypeid int;
select top 1 testtypeid := typeid from Reports_ReportMenu
where ID = $2
select MonName,Mon,Adm,
case when ROW_NUMBER() OVER(ORDER BY Mon,Adm) = '1' then
cast(1 as int) else cast(0 as int) end as Selected
from eivTestAdms
where test_type_id=testtypeid and "YR"=$1 and Adm is not null
order by Mon,Adm
$BODY$
LANGUAGE sql;
这里我在int的declare语句中遇到语法错误。我是以正确的格式编写函数吗?
答案 0 :(得分:4)
您无法在SQL函数中使用变量,这些变量仅在使用PL / pgSQL时可用。
但无论如何都不需要这个变量。你可以把它放到一个子选择中。
另外cast(1 as int)
没用。 1
已经是一个整数,0
也是如此,因此不需要进行转换。
CREATE OR REPLACE FUNCTION getadmbyyear(IN a integer, IN b character varying)
RETURNS TABLE(monname character varying, mon integer, adm integer, selected integer)
AS
$body$
select MonName,
Mon,
Adm,
case
when ROW_NUMBER() OVER (ORDER BY Mon,Adm) = 1 then 1
else 0
end as Selected
from eivTestAdms
where test_type_id = (select testtypeid
from Reports_ReportMenu
where ID = $2
limit 1)
and "YR"=$1
and Adm is not null
order by Mon,Adm;
$body$
language sql;
但SQL Server的bit
数据类型通常用作穷人的布尔值。所以它应该是Postgres中真正的boolean
。这使得案例陈述更短:
select MonName,
Mon,
Adm,
ROW_NUMBER() OVER (ORDER BY Mon,Adm) = 1 as selected -- this is a boolean expression that will return true or false
from eivTestAdms
然后,您需要将功能签名调整为:
RETURNS TABLE(monname character varying, mon integer, adm integer, selected boolean)