SQL CASE输出错误

时间:2016-03-02 09:51:31

标签: sql sql-server-2014

我在sql 2014中使用CASE遇到了这种奇怪的遭遇。

这是我的疑问:

  SELECT (CASE WHEN dbo.GetFunctionAge(C.Birthdate) = 0 
               THEN '' ELSE dbo.GetFunctionAge(C.Birthdate)
          END) AS Age
         ,dbo.GetFunctionAge(C.Birthdate)
         ,c.Birthdate
 FROM Client C
 WHERE ClientID = '34d0d845-e3a6-4078-8936-953ff3378eac'

这是输出:

https://gist.github.com/evadne/5519337

如果你问的话,这是GetFunctionAge函数。

IF EXISTS (
  SELECT * 
  FROM dbo.sysobjects 
  WHERE ID = OBJECT_ID(N'[dbo].[GetFunctionAge]') AND 
        xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[GetFunctionAge]

GO

CREATE FUNCTION [dbo].[GetFunctionAge](@BirthDate DATETIME)
RETURNS INT
AS
BEGIN

DECLARE @Age INT

IF(@BirthDate = '1753-01-01 00:00:00.000')
BEGIN
    SET @Age = 0
END
ELSE
BEGIN
    SET @Age = DATEDIFF(hour,@BirthDate,GETDATE())/8766
END

RETURN @Age
END
GO

问题:
为什么我的输出中的列时间为0,应该是''? 我添加了(No column name)以显示其输出为0,因此我的预期输出基数来自我的案例条件''而非0 我没有收到任何关于数据不一致的错误,那么为什么案例表现如此?

感谢那些能够向我澄清这一点的人。

2 个答案:

答案 0 :(得分:3)

SELECT
      (CASE
            WHEN a.ageint = 0 THEN ''
            ELSE cast(a.ageint as varchar(3))
      END) AS Age
    , a.ageint
    , c.Birthdate
FROM Client as C
      CROSS APPLY (
            SELECT
                  ISNULL(dbo.GetFunctionAge(C.Birthdate), 0) AS ageint
      ) AS a
WHERE ClientID = '34d0d845-e3a6-4078-8936-953ff3378eac'
;

答案 1 :(得分:2)

您可以cast将其转换为varchar,以便您可以返回' '

 SELECT (CASE WHEN dbo.GetFunctionAge(C.Birthdate) = 0 
               THEN '' ELSE Cast(dbo.GetFunctionAge(C.Birthdate) as varchar(5))
          END) AS Age
         ,dbo.GetFunctionAge(C.Birthdate)
         ,c.Birthdate
 FROM Client C
 WHERE ClientID = '34d0d845-e3a6-4078-8936-953ff3378eac'

但是,如果您希望保留Age column数据类型int

您可以使用NULL代替' '