CREATE FUNCTION IN SQL select into
Posted
技术标签:
【中文标题】CREATE FUNCTION IN SQL select into【英文标题】: 【发布时间】:2020-04-14 20:27:58 【问题描述】:我正在尝试创建以下函数,但我不能
CREATE function pse_consecutivosiif (
@empresa NUMERIC
, @comprobante NUMERIC
, @tercero NUMERIC
)
returns NUMERIC
as
BEGIN
DECLARE i_consecutividad NUMERIC(5);
select max(consecutividad)
into i_consecutividad
from (
select hojaIdenti cedula
, dense_rank() over (order by hojaIdenti) as consecutividad
FROM movimiento MO
INNER JOIN VISTADOS VIS ON MO.identifica = VIS.identifica
AND MO.empresa = VIS.empresa
WHERE MO.comprobante = @comprobante
AND MO.empresa = @empresa
)
where cedula = @tercero
);
return i_consecutividad;
end;
【问题讨论】:
为什么要同时标记 SQL Server 和 Oracle? 我删除了oracle
标记,因为这显然只是 SQL Server
你为什么不能?包含错误消息以帮助对问题进行分类。
【参考方案1】:
注意事项:
-
你需要声明以@开头的变量
赋值不像select into,而是像下面的代码
如果使用子查询创建,总是需要提供表名
在下面找到工作函数
CREATE function pse_consecutivosiif ( @empresa NUMERIC, @comprobante NUMERIC, @tercero NUMERIC)
returns NUMERIC
as
BEGIN
DECLARE @i_consecutividad NUMERIC(5);
select @i_consecutividad=max(consecutividad)
from (select hojaIdenti cedula, dense_rank() over (order by hojaIdenti) as consecutividad
FROM movimiento MO INNER JOIN VISTADOS VIS ON MO.identifica = VIS.identifica
AND MO.empresa = VIS.empresa
WHERE MO.comprobante = @comprobante
AND MO.empresa = @empresa) y
where y.cedula = @tercero
return @i_consecutividad;
end;
【讨论】:
我相信还有一个多余的最后括号? "提供表名" - 表别名。【参考方案2】:目前尚不清楚您的程序的目的是什么。但是,这里有一个更新版本,可以在 SQL Server 中正确编译。
create function pse_consecutivosiif (@empresa numeric, @comprobante numeric, @tercero numeric)
returns numeric
as
begin
declare @i_consecutividad numeric;
select @i_consecutividad = max(consecutividad)
from (
select
hojaidenti,
cedula,
dense_rank() over (order by hojaidenti) as consecutividad
from movimiento mo
inner join vistados vis on mo.identifica = vis.identifica and mo.empresa = vis.empresa
where mo.comprobante = @comprobante
and mo.empresa = @empresa
) t
where cedula = @tercero;
return @i_consecutividad;
end;
对原始代码的更改:
变量声明时应以@
开头
您在查询的select
子句中为带有=
的变量赋值; select ... into ...
是为了创建一个新表,而不是分配给一个标量变量
子查询需要别名
代码末尾有一个多余的右括号
适当的格式和缩进使代码更易于阅读
【讨论】:
谢谢!!!!!!!这就是答案!!!!我需要在子查询中添加一个“别名”。非常感谢! @ÁlvaroAlfonsoParraRodríguez:欢迎。考虑accepting 您收到的答案之一。这会奖励您和回答者,并向社区表明您的问题已得到解决。以上是关于CREATE FUNCTION IN SQL select into的主要内容,如果未能解决你的问题,请参考以下文章
CREATE FUNCTION 引发 SQL 错误 (1064) (42000)
通过dbcp链接池对数据库操作报 Cannot create PoolableConnectionFactory (Could not create connection to database se
通过dbcp链接池对数据库操作报 Cannot create PoolableConnectionFactory (Could not create connection to database se
SQL CREATE VIEW 与 for in for 和 SELECTS
mysqldump: Couldn't execute 'SET OPTION SQL_QUOTE_SHOW_CREATE=1': You have an error in y
Sql Server Function函数 is not a recognized built-in function name