Big_Dwarf90
Big_Dwarf90

Reputation: 77

Sub-query returned more than 1 value: executing UDF

I'm using AdventureWorks 2007 for this sample, trying to enter the employee birthdate and return their age

CREATE FUNCTION UDF_EmpAge  (@BusinessEntityID  VARCHAR(50))
RETURNS VARCHAR(50)
AS
BEGIN
    DECLARE @Emp_Age VARCHAR(50)
    SET @Emp_Age = (SELECT  DATEDIFF(YY,[BirthDate],GETDATE()) FROM HumanResources.Employee)
    RETURN  
    (
        SELECT @Emp_Age 
        FROM HumanResources.Employee 
        WHERE BusinessEntityID = @BusinessEntityID
    )
END
GO

when I try to run it for example

SELECT  dbo.UDF_EmpAge(2)

Msg 512, Level 16, State 1, Line 50
Subquery returned more than 1 value. This is not permitted when the subquery
follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Upvotes: 0

Views: 107

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270493

You don't need any variables at all. You can just return the result of the query:

CREATE FUNCTION UDF_EmpAge (@BusinessEntityID  VARCHAR(50))
RETURNS INT
AS
BEGIN
    RETURN(SELECT DATEDIFF(YEAR, BirthDate, GETDATE()) 
           FROM Employee 
           WHERE BusinessEntityID = @BusinessEntityID
          );
END;

Here is a db<>fiddle. Note that "age" is more properly thought of as a number; and datediff() returns an integer. It doesn't make sense to return this value as a string.

Upvotes: 1

GMB
GMB

Reputation: 222582

Your first query returns multiple rows, so you cannot assign that to a scalar variable.

I don't see the point for that intermediate query anyway. You can directly filter the table using the parameter, and assign the result of the date function to the variable (which should be an integer rather than a string).

Consider:

CREATE FUNCTION UDF_EmpAge(@BusinessEntityID VARCHAR(50))
RETURNS INT
AS
BEGIN
    DECLARE @Emp_Age INT;

    SELECT @Emp_Age = DATEDIFF(YY, [BirthDate] ,GETDATE()) 
    FROM HumanResources.Employee
    WHERE BusinessEntityID = @BusinessEntityID;

    RETURN @Emp_Age;
END

Note that this assumes that BusinessEntityID is a unique key in HumanResources.Employee table (or its primary key).

Upvotes: 2

Related Questions