SQL添加功能

时间:2016-05-19 14:42:02

标签: sql-server

我正在尝试编写一个函数来添加从两个不同表中选择的值。我需要表1中特定ID的一列SUM,添加到表2中特定ID的列的SUM

CREATE FUNCTION dbo.getSum(@id varchar(9)) --Our IDs are strings of length 9
RETURNS integer --I've also tried decimal(x,x) and int
AS
BEGIN
DECLARE @total as integer; -- same here with decimal and int
SELECT @total = 
(
    (select SUM(Amount)
    from table1
    where id = @id)
    +
    (select SUM(amount)
    from table2
    where id = @id)
);
RETURN @total;
END;

我尝试创建此功能时遇到了几种类型的错误,例如incorrect syntax near 'integer'Must declare the scalar variable "@total".Incorrect syntax near 'END'.

我已经尝试了几种变体并查看了几个SO问题,但还没有找到一个能解决这个问题的问题。这是在SQL Server上。

4 个答案:

答案 0 :(得分:1)

如前所述,您的错误原因是您没有为入站参数定义数据类型。

我建议稍微偏离目前的结构。我将使用内联表值函数而不是标量函数。这些方面的东西。

CREATE FUNCTION dbo.getSum(@id int)
RETURNS table
AS RETURN

SELECT SUM(MyAmount)
from
(
    select SUM(Amount) as MyAmount
    from table1
    where id = @id
    UNION ALL
    select SUM(amount)
    from table2
    where id = @id

) x;

答案 1 :(得分:0)

看起来你在函数definiton

中缺少参数类型

尝试使用以下

CREATE FUNCTION dbo.getSum(@id int)
RETURNS integer --I've also tried decimal(x,x)
AS
BEGIN
DECLARE @total as integer; -- same here with decimal
SELECT @total = 
(
    (select SUM(Amount)
    from table1
    where id = @id)
    +
    (select SUM(amount)
    from table2
    where id = @id)
);
RETURN @total;
END;

答案 2 :(得分:0)

我认为您需要声明参数的类型

CREATE FUNCTION dbo.getSum(@id int)

答案 3 :(得分:0)

您的数据类型应为INT,并且存在一般语法错误...请参阅下文。

CREATE FUNCTION dbo.getSum(@id AS INT) -- Declare your paramater AS (datatype)
RETURNS INT  -- No need for AS here, just start your block
BEGIN
DECLARE @total AS INT; 
SELECT @total = 
(
    (select SUM(Amount)
    from TableOne
    where id = @id)
    +
    (select SUM(amount)
    from TableTwo
    where id = @id)
);
RETURN @total;
END;