简体   繁体   中英

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.

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM