标量函数中的 Case 语句用法

发布于 2025-01-11 12:59:06 字数 625 浏览 0 评论 0原文

有人可以解释为什么这段代码对我不起作用吗?

create function dbo.fn_dis (@num int)
returns nvarchar(30)
as
begin 
    declare @catch nvarchar(30)

    case 
        when @num = 1 
            then set @catch = 'Active'
        else set @catch = 'Discontinued'
    end

    return @catch 
end

另一方面,if 语句工作得很好:

create function dbo.fn_dis (@num int)
returns nvarchar(30)
as
begin 
    declare @catch nvarchar(30)

    if @num = 1
        set @catch = 'Active'
    else
        set @catch = 'Discontinued'

    return @catch
end

我没有发现在网络上的标量函数中使用 case 语句有任何限制,

非常感谢您的帮助!赞赏:)

Can somebody explain why this code won't work for me?

create function dbo.fn_dis (@num int)
returns nvarchar(30)
as
begin 
    declare @catch nvarchar(30)

    case 
        when @num = 1 
            then set @catch = 'Active'
        else set @catch = 'Discontinued'
    end

    return @catch 
end

On the other hand an if statement works just fine:

create function dbo.fn_dis (@num int)
returns nvarchar(30)
as
begin 
    declare @catch nvarchar(30)

    if @num = 1
        set @catch = 'Active'
    else
        set @catch = 'Discontinued'

    return @catch
end

I didn't find any restriction on using case statements within scalar functions on the web

Thanks a lot for the help ! appreciated :)

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

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

发布评论

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

评论(1

匿名的好友 2025-01-18 12:59:06

如果您确实需要一个函数,那么您至少可以将其简化为一条语句...但是,这似乎是一个简单的
内联案例会更好

create function dbo.fn_dis (@num int)
returns nvarchar(30)
as
begin 
 return case when @num = 1 
             then 'Active'
             else 'Discontinued'
        end

end

只是为了扩展我的内联评论

Declare @num int = 1

select Option1 = case when @num = 1 then 'Active' else 'Discontinued' end
      ,Option2 = IIF(@num=1,'Active','Discontintued')

If you really need a function for this, you can at least bring it down to a single statement... However, it seems like a simple
inline case would be better

create function dbo.fn_dis (@num int)
returns nvarchar(30)
as
begin 
 return case when @num = 1 
             then 'Active'
             else 'Discontinued'
        end

end

Just to expand my inline comment

Declare @num int = 1

select Option1 = case when @num = 1 then 'Active' else 'Discontinued' end
      ,Option2 = IIF(@num=1,'Active','Discontintued')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文