2

I'm having an issue with SQL Server 2008, I want to write a function that returns the sum of a specific column, the code goes like this:

CREATE FUNCTION [dbo].[GetIssuesSum](@i int)
RETURNS int
AS
BEGIN
    DECLARE @IssueSum int

    SELECT SUM (@IssueSum = Quantity) 
    FROM Issue

    RETURN @IssueSum

END

When I try to execute it, SQL Server 2008 throws this error

Msg 102, Level 15, State 1, Procedure GetIssuesSum, Line 15
Incorrect syntax near '='.

Any suggestions? Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user3804193
  • 113
  • 4
  • 11

1 Answers1

1

You need to use this code:

CREATE FUNCTION [dbo].[GetIssuesSum](@i int)
RETURNS int
AS
BEGIN
    DECLARE @IssueSum int

    SELECT @IssueSum = SUM(Quantity) 
    FROM Issue

    RETURN @IssueSum
END

You need to assign the SUM(Quantity) to your SQL variable - not have the SQL variable inside the SUM() expression

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    thank you so much, this is the right answer, I will choose it as accepted answer after some minutes :) thanks again – user3804193 Sep 12 '14 at 06:46
  • Thanks. Is the parameter `i` as declared as `@i int` ever used in the definition of the function? If not, what is the purpose of defining a parameter which is not going to be used? – Tim May 08 '18 at 17:04