代码之家  ›  专栏  ›  技术社区  ›  Shubashree Ravi

SQL Server:Case表达式返回0而不是空字符串

  •  -1
  • Shubashree Ravi  · 技术社区  · 7 年前

    下面是不使用convert to varchar时返回0的查询。它比较整数值

    SELECT 
        *,
        CASE 
           WHEN Duration IS NULL
              THEN CONVERT(VARCHAR, '') 
              ELSE Duration 
        END AS Duration  
    FROM
        Contribution 
    WHERE 
        CreatedBy = @in_userID  AND ContentStatus = @ContentStatus   
    
    UNION ALL
    
    SELECT 
        *,
        CASE 
           WHEN Duration IS NULL
              THEN CONVERT(VARCHAR, '')  
              ELSE Duration 
        END AS Duration  
    FROM
        Training  
    WHERE 
        CreatedBy = @in_userID  AND ContentStatusValue = @TrainingStatus
    

    在使用union all时,如果不使用convert,则返回0。使用convert时,问题得到解决。

    有人能解释为什么会这样吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Yogesh Sharma    7 年前

    我怀疑你 Duration INT 键入,以便进行对话:

    SELECT c.col1, c.col2, ISNULL(CAST(c.Duration AS VARCHAR(255)),'') Duration  
    FROM Contribution c
    WHERE c.CreatedBy = @in_userID  AND
          c.ContentStatus = @ContentStatus 
    UNION ALL
    SELECT t.col1, t.col2, ISNULL(CAST(t.Duration AS VARCHAR(255), '') 
    FROM Training t 
    WHERE t.CreatedBy = @in_userID AND
          t.ContentStatusValue = @TrainingStatus;
    
        2
  •  0
  •   Zaynul Abadin Tuhin    7 年前

    你也可以使用 COALESCE

    SELECT *,COALESCE(convert( varchar(255),Duration ),'') 
    AS Duration  FROM Contribution WHERE CreatedBy = @in_userID 
    and ContentStatus = @ContentStatus   
    UNION ALL
    
    SELECT *,COALESCE(convert( varchar(255),Duration ),'') AS Duration 
    FROM Training  WHERE CreatedBy = @in_userID  
    and   ContentStatusValue=@TrainingStatus.