I'm trying to write a function that adds values that are selected from two different tables. I need the SUM of one column for a specific id in table 1, added to the SUM of a column for a specific id in table 2.
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;
I get several types of errors when I try to create this function, like incorrect syntax near 'integer', Must declare the scalar variable "@total"., and Incorrect syntax near 'END'.
I've tried several variations and looked at several SO questions, but haven't found one that's fixed this issue for me yet. This is on SQL Server.