SQL函数的条件返回

时间:2016-11-17 09:36:10

标签: sql sql-server tsql sql-server-2014 user-defined-functions

我能够运行这个

  USE AdventureWorks2012;
    GO
    IF OBJECT_ID(N'dbo.GetJobData', N'IF') IS NOT NULL
    DROP FUNCTION dbo.GetJobData;
    GO
    CREATE FUNCTION dbo.GetJobData (@title NVARCHAR(25))
    RETURNS TABLE
    WITH SCHEMABINDING
    AS
    RETURN
    (
      SELECT COUNT(*) AS TotalEmps
      FROM HumanResources.Employee
      WHERE JobTitle = @title
      GROUP BY JobTitle
    );
    GO

但我想基于 @title 添加一些条件,所以我想要这样的东西。

      USE AdventureWorks2012;
        GO
        IF OBJECT_ID(N'dbo.GetJobData', N'IF') IS NOT NULL
        DROP FUNCTION dbo.GetJobData;
        GO
        CREATE FUNCTION dbo.GetJobData (@title NVARCHAR(25))
        RETURNS TABLE
        WITH SCHEMABINDING
        AS
        RETURN
        (
WHEN (@title = 'Developer')
THEN
          SELECT COUNT(*) AS TotalEmps
          FROM HumanResources.Employee
          WHERE JobTitle = @title
          GROUP BY JobTitle
ELSE
      SELECT COUNT(*) AS TotalEmps
      FROM HumanResources.Employee
      WHERE JobTitle = @title+'Role'
      GROUP BY JobTitle

    );
    GO

但无法做到......你能帮忙吗,我正在使用MS SQL Server 2014

2 个答案:

答案 0 :(得分:2)

Case子句处理where语句,如下所示。您正在使用sql server 2014,因此您可以使用Concat功能。而不是@title+'role'。添加了JobTitle也使其更有意义。

 IF OBJECT_ID(N'dbo.GetJobData', N'IF') IS NOT NULL
        DROP FUNCTION dbo.GetJobData;
        GO
        CREATE FUNCTION dbo.GetJobData (@title NVARCHAR(25))
        RETURNS TABLE
        WITH SCHEMABINDING
        AS
        RETURN
        (

          SELECT COUNT(*) AS TotalEmps,JobTitle
          FROM HumanResources.Employee
          WHERE JobTitle = Concat(@title,(CASE WHEN @title <> 'Developer' THEN 'Role' END))
          GROUP BY JobTitle)
END

答案 1 :(得分:0)

可能不如过滤Where条款那样有效(Buddi的答案),但效果不错

SELECT JobTitle,
       Count(CASE
               WHEN ( JobTitle = @title
                      AND @title = 'Developer' )
                     OR ( JobTitle = @title + 'Role'
                          AND @title <> 'Developer' ) THEN 1
             END) AS TotalEmps
FROM   HumanResources.Employee
GROUP  BY JobTitle 

注意:我已将JobTitle添加到select以确定JobTitle的计数值