使用基于参数的返回值创建UDF

时间:2016-11-07 05:34:36

标签: sql-server function return

我收到此错误但不确定该怎么做。 另外,如何根据参数@empId返回当前工资。例如,如果我调用像dbo.getBonus(3)这样的函数,它应该返回:5600.000

以下是运行查询时创建的表:

EmpId  Bonus
3   5600.000
4   18500.000
5   15600.000
6   7600.000 

错误讯息:

Msg 444,Level 16,State 2,Procedure getBonus,188行 函数中包含的Select语句不能将数据返回给客户端。

感谢。

CREATE FUNCTION dbo.getBonus(@empId INT)
RETURNS numeric(10,2)
AS
BEGIN
SELECT C.[Emp Id], 
    (Salary.Emp_Salary * .1) AS 'Bonus'
        FROM
        (
        SELECT
            e.Emp_Id AS "Emp Id",
            MAX(Emp_Salary_Change_Year) AS "Change Year"
            FROM Employee_Details AS e

        INNER JOIN Country AS co ON e.Emp_Country_Id = co.Country_Id
        INNER JOIN State AS s ON e.Emp_State_Id = s.State_Id
        INNER JOIN Designation AS d ON e.Desig_Id = d.Desig_Id
        INNER JOIN Salary AS sa ON e.Emp_Id = sa.Emp_Id

        GROUP BY e.Emp_Id) AS C
        INNER JOIN Salary ON C.[Change Year] =          
Salary.Emp_Salary_Change_Year;
    RETURN 2
END

1 个答案:

答案 0 :(得分:2)

将结果放入变量并返回结果:

CREATE FUNCTION dbo.getBonus(@empId INT)
RETURNS numeric(10,2)
AS
BEGIN
DECLARE @res numeric(10, 2)
SELECT @res = 
    (Salary.Emp_Salary * .1) 
        FROM
        (
        SELECT
            e.Emp_Id AS "Emp Id",
            MAX(Emp_Salary_Change_Year) AS "Change Year"
            FROM Employee_Details AS e

        INNER JOIN Country AS co ON e.Emp_Country_Id = co.Country_Id
        INNER JOIN State AS s ON e.Emp_State_Id = s.State_Id
        INNER JOIN Designation AS d ON e.Desig_Id = d.Desig_Id
        INNER JOIN Salary AS sa ON e.Emp_Id = sa.Emp_Id

        GROUP BY e.Emp_Id) AS C
        INNER JOIN Salary ON C.[Change Year] =          
Salary.Emp_Salary_Change_Year;
    RETURN @res
END