服务器查询以查找员工的当前指定

时间:2020-11-12 16:57:10

标签: sql sql-server function

表员工:

ID, Designation, PromotionDate

代码:

ALTER FUNCTION GetTheDesignationEmployee
    (@EmpID INT)
RETURNS VARCHAR(MAX) 
AS
BEGIN
    DECLARE @Designation VARCHAR(25) = ''

    SELECT @Designation = Designation  
    FROM Employee
    WHERE PromotionDate = (SELECT MAX(PromotionDate) 
                           FROM Employee
                           WHERE ID = @EmpID)

    RETURN(@Designation)
END

如果我运行代码,则应该获得该雇员的当前指定。我传递了ID,并且应该获取相应的当前名称。

SELECT dbo.GetTheDesignationEmployee(5346) 

但是我得到一个错误而不是答案。

1 个答案:

答案 0 :(得分:1)

最有可能;如果我正确地解释了您的最后一条评论,那么您会得到一个带有适当日期的名称-但由于您忘记限制了外部SELECT才能使用传递的@EmpID它,可能是其他人(具有相同的PromotionDate)....

尝试一下:

ALTER FUNCTION GetTheDesignationEmployee
    (@EmpID INT)
RETURNS VARCHAR(MAX) 
AS
BEGIN
    DECLARE @Designation VARCHAR(25) = ''

    SELECT @Designation = Designation  
    FROM EmployeeDetails 
    WHERE PromotionDate = (SELECT MAX(PromotionDate) 
                           FROM EmployeeDetails 
                           WHERE ID = @EmpID)
      -- you need to also include the @EmpID here!
      AND ID = @EmpID;

    RETURN(@Designation)
END

或者您可以更简单地编写整个函数:

ALTER FUNCTION GetTheDesignationEmployee
    (@EmpID INT)
RETURNS VARCHAR(MAX) 
AS
BEGIN
    DECLARE @Designation VARCHAR(25) = ''

    SELECT TOP (1) @Designation = Designation  
    FROM EmployeeDetails 
    WHERE ID = @EmpID
    ORDER BY PromotionDate DESC;

    RETURN(@Designation)
END

警告语:众所周知,进行数据访问的标量函数会降低性能-因此,也许您想考虑另一种在查询中获取“最近指定”的方法,以避免出现首先要编写和使用此功能。