SQL查询帮助 - 具有2个嵌套条件语句的函数

时间:2014-09-30 07:15:31

标签: sql tsql

我试图编写一个SQL函数,但是遇到了两个嵌套条件的问题。

以下是代码:

CREATE FUNCTION fn_HasAcceptedPolicyDate(@employeeid smallint, @policyid int)
RETURNS TABLE 
AS
BEGIN
--If policy is required
IF  EXISTS (SELECT * FROM fn_getEmployeePolicies(@employeeid) AS EmployeePolicies WHERE EmployeePolicies.PolicyId=@policyid)
    SELECT 
    CASE 
    WHEN (convert(varchar,MAX(HasAcceptedPolicyDate),103)) IS Null then 'NOT ACCEPTED'  
    else convert(varchar,MAX(HasAcceptedPolicyDate),103) 
    end 
    AS 'HasAcceptedPolicyDate'
    FROM policysignoff.EmployeePolicy
    WHERE EmployeeId = @employeeid
    AND PolicyId = @policyid

--If policy is not required
ELSE 
    RETURN "NOT REQUIRED"
END
GO

我想要构建的逻辑是: 1.给定employeeId和PolicyId,返回策略被接受的日期。 2.如果该人不需要该政策,则返回" Not Required" (我正在使用另一个函数检查这个,因此IF EXISTS) 3.政策是否被接受然后返回"不接受" (而不是仅显示NULL)。

我遇到的问题是我无法找到使条件2正常工作的方法,即IF存在。

任何帮助或提示都将不胜感激。

提前致谢!

1 个答案:

答案 0 :(得分:0)

ALTER FUNCTION fn_HasAcceptedPolicyDate(@employeeid smallint, @policyid int)
RETURNS nvarchar(max)
AS
BEGIN
--If policy is required
DECLARE @ReturnValue nvarchar(max) ='NOT REQUIRED'
IF  EXISTS (SELECT * FROM fn_getEmployeePolicies(@employeeid) AS EmployeePolicies WHERE EmployeePolicies.PolicyId=@policyid)
BEGIN   SELECT @ReturnValue =
    CASE 
    WHEN (convert(varchar,MAX(HasAcceptedPolicyDate),103)) IS Null then 'NOT ACCEPTED'  
    else convert(varchar,MAX(HasAcceptedPolicyDate),103) 
    end     
    FROM policysignoff.EmployeePolicy
    WHERE EmployeeId = @employeeid
    AND PolicyId = @policyid
--    return @ReturnValue
END
--If policy is not required
return @ReturnValue
END
GO