如何在Select Query中使用函数

时间:2017-04-13 10:23:29

标签: sql sql-server-2008

我需要在select查询中使用一个函数。下面是我的函数和选择查询的代码。

示例功能:

CREATE FUNCTION GetASRPlanCurrentStatus(@ChvnPlanNo nvarchar(50)) RETURNS NVARCHAR(50)

AS
BEGIN

 Declare
 @ChvnStatus nvarchar(50) = NULL,
 @PlanStatus nvarchar(50) = 'Not yet initiated for process'


 SET @ChvnStatus =
                  CASE
                       WHEN (SELECT
                                 COUNT(*)
                            FROM Evaluation
                            WHERE PlanNo = @chvnPlanNo
                            AND ISNULL(IsFreezed, 0) = 1
                            AND ISNULL(SendForRecruiter, 0) = 1
                            AND ISNULL(IsPEScoreUploaded, 0) = 1
                            AND ISNULL(SentForTeamLeaderApproval, 0) = 1)
                            = (SELECT
                                 COUNT(*)
                            FROM Evaluation
                            WHERE PlanNo = @ChvnPlanNo) THEN 'Approved'
                  END
 SET @PlanStatus = ISNULL(@ChvnStatus, @PlanStatus)
 RETURN @PlanStatus

END

我的选择查询:

   SELECT 
     '0' AS ResultTag,
      GetASRPlanCurrentStatus('ASR2017 - 3') AS Overallstatus,
      6' AS ProcessOrder

以上查询无效。我不知道出了什么问题。有人指导我解决这个问题。提前致谢

要求输出:

----------  ----------     ----------
Result Tag  Overallstatus  ProcessOrder
----------  ----------     ----------
0            Approved        6

2 个答案:

答案 0 :(得分:1)

请尝试将方案放在您的功能前

SELECT 
 '0' AS ResultTag,
  dbo.GetASRPlanCurrentStatus('ASR2017 - 3') AS Overallstatus,
  6' AS ProcessOrder
...

答案 1 :(得分:0)

使用以下查询来调用SELECT子句中的函数:

 SELECT '0' AS ResultTag,'6' AS ProcessOrder,
        [dbo].[GetASRPlanCurrentStatus]('ASR2017 - 3') AS Overallstatus,
        ----------
        ----------