SQL Server - CASE 内的 CASE 检查 NULL

发布于 2024-09-07 20:56:05 字数 827 浏览 1 评论 0原文

我仍在学习 SQL,所以这可能看起来是一个非常奇怪的问题,但这是在 CASE 中使用 CASE 检查 NULL 的最佳方法吗?

@FN_InputDt datetime)
RETURNS varchar(3)
as 
BEGIN

DECLARE  @Result    varchar(3),
         @MonthNo   int 

Set @MonthNo = datepart(m,@FN_InputDt)

Set @Result = 
        CASE WHEN @FN_InputDt IS NOT NULL then
        CASE @MonthNo
            WHEN  1 then 'JAN'                                                  
            WHEN  2 then 'FEB'
            WHEN  3 then 'MAR'
            WHEN  4 then 'APR'
            WHEN  5 then 'MAY'
            WHEN  6 then 'JUN'
            WHEN  7 then 'JUL'                   
            WHEN  8 then 'AUG'
            WHEN  9 then 'SEP'
            WHEN 10 then 'OCT'
            WHEN 11 then 'NOV'
            WHEN 12 then 'DEC'
        END
        END

        RETURN @Result
    END

I am still learning SQL so this may seem a very odd question, but is this the best way to use CASE within a CASE to check for NULL?

@FN_InputDt datetime)
RETURNS varchar(3)
as 
BEGIN

DECLARE  @Result    varchar(3),
         @MonthNo   int 

Set @MonthNo = datepart(m,@FN_InputDt)

Set @Result = 
        CASE WHEN @FN_InputDt IS NOT NULL then
        CASE @MonthNo
            WHEN  1 then 'JAN'                                                  
            WHEN  2 then 'FEB'
            WHEN  3 then 'MAR'
            WHEN  4 then 'APR'
            WHEN  5 then 'MAY'
            WHEN  6 then 'JUN'
            WHEN  7 then 'JUL'                   
            WHEN  8 then 'AUG'
            WHEN  9 then 'SEP'
            WHEN 10 then 'OCT'
            WHEN 11 then 'NOV'
            WHEN 12 then 'DEC'
        END
        END

        RETURN @Result
    END

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九命猫 2024-09-14 20:56:05

如果 @FN_InputDt 为 null,则 @MonthNo 也将为 null,因此您可以跳过检查 @FN_InputDt 是否为 null。

您也可以通过仅使用 @MonthNo 作为索引来选取字符串的一部分来跳过其他情况:

set @Result = substring(
  'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC',
  @MonthNo * 3 - 2,
  3
)

如果 @MonthNo 为 null @Result 也将为 null。

If @FN_InputDt is null then @MonthNo will also be null, so you can just skip checking if @FN_InputDt is null.

You can skip the other case also by just using @MonthNo as index to pick part of a string:

set @Result = substring(
  'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC',
  @MonthNo * 3 - 2,
  3
)

If @MonthNo is null @Result will also be null.

沫尐诺 2024-09-14 20:56:05

Set @Result = Left(DateName(m,@FN_InputDt) , 3)

这会将月份转换为名称,并且仅显示前 3 个字符。

Set @Result = Left(DateName(m,@FN_InputDt) , 3)

This converts the month to the name and only displays the first 3 characters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文