0

Wants to create a function of the average product standardcost for the same color, and using 'red' to test . But NULL returned. If only run the SELECT,FROM,WHERE,GROUP BY, it will work file and return a value.

Here's my code :

CREATE FUNCTION avgv (@Color CHAR)
RETURNS CHAR 
AS 
BEGIN
        DECLARE @AVG CHAR ;
        SET @AVG = (SELECT P.Color  AVG(P.StandardCost)  
        FROM AdventureWorksLT.SalesLT.Product P
        WHERE P.Color = @Color
        GROUP BY Color)

        Return @AVG

END
GO
SELECT dbo.avgv('red') 

Please let me know how to fix, thanks!

2
  • 1
    You forgot to specify length in both input parameter and returned result. Also, I assume, you should use VARchar. CHAR same as VARCHAR withoud explicitly defined length means length=1 (one symbol). Commented Nov 3, 2016 at 8:06
  • And as already mentioned - your result does nor look like character since you are computing AVG. Commented Nov 3, 2016 at 8:08

1 Answer 1

1

Input parameter: char -> varchar(100)
Returns -> char -> int for integer result /decimal(18, 2) for float result
Remove Group By

Function

CREATE FUNCTION avgv (@Color varchar(100))
RETURNS real
AS 
BEGIN
        DECLARE @AVG real;
        SET @AVG = (SELECT AVG(ISNULL(P.StandardCost, 0))  
        FROM AdventureWorksLT.SalesLT.Product P
        WHERE P.Color = @Color)

        Return @AVG

END
GO
SELECT dbo.avgv('red') 

Procedure

CREATE PROCEDURE avgv (@Color varchar(100))
AS 
BEGIN
        SELECT AVG(ISNULL(P.StandardCost, 0))  
        FROM AdventureWorksLT.SalesLT.Product P
        WHERE P.Color = @Color
END
Sign up to request clarification or add additional context in comments.

3 Comments

But, still NULL returned.
SELECT AVG(ISNULL(P.StandardCost, 0))
this works after using RETURN REAL, also, can you help me to convert it to the create procedures? I want to call it from other language, so we need procedure can hold the parameter(COLOR) to be entered.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.