【问题标题】:CASE Statement Force an Error Message as a ConditionCASE 语句强制将错误消息作为条件
【发布时间】:2021-05-26 11:53:02
【问题描述】:

我想实现这种逻辑:

select
     many_columns,
     case
          when something then 'whatever'
          else Generate Error Message and Stop the Query
     end as [whatever]
from
     table_1

这可能吗?

编辑#1:

根据我得到的cmets,我做了一些实验。

drop table if exists #testing;
go

    with whatever as (
        
            select 1 as [num] union
            select 2 union
            select 3 union
            select 4 union
            select 5 union
            select 6 union
            select 7 union
            select 8 union
            select 9 union
            select 10
        
        )
    
declare @counter INT
set @counter = 0

while (@counter <= (select count(*) from #testing))
begin
    IF (@counter) < 5
        print 'hi'
        set @counter = @counter + 1
    else
        select * from #testing
        print 'bye'
        select @counter = @counter + 1
end
go

嗯……If 语句的 else 部分有问题……我得到的只是“不正确的语法”。

【问题讨论】:

  • CASE 在 T-SQL 中是一个返回单个原子值的 表达式(如 a+b)。 NOT 是处理程序流程等的构造 - 为此,您需要使用 IF / ELSE
  • 您需要将错误测试作为对选择的单独操作来执行。或者您可以在选择中添加一个错误列。您如何在查询之外使用它将决定最佳方法。
  • 我以前从未在 SQL 中使用过 IF 语句。我将在一秒钟内编辑我的帖子。有趣的。猜猜谁学到了新东西? #this_guy
  • IF EXISTS (select 1 from #testing where [num] &lt; 5)` ?
  • 我之前没有在 SQL 中实现过这种类型的逻辑。我正在尝试将 If 语句与 while 循环集成一秒钟。

标签: sql-server tsql ssms


【解决方案1】:

似乎我的问题的答案是将while 循环与if 语句结合起来,然后生成我的主查询以查找错误消息。

最后的 if 语句如下所示:

declare @counter INT
set @counter = 0

while (@counter <= (select count(*) from #testing))
begin
    --print @counter
    IF (@counter = (select [num] from #testing where [num] = @counter))
        --print 'hi'
        print cast(@counter as varchar) + ' ' + 'hi'
    else
        --select * from #testing where [num] = @counter
        --print 'bye'
        print cast(@counter as varchar) + ' ' + 'bye'
    select @counter = @counter + 1
end
go

【讨论】:

    【解决方案2】:

    我不能说它比@marc_s 的评论更好:

    CASE 在 T-SQL 中是一个返回单个原子值的表达式(如 a+b)。它不是处理程序流程等的构造 - 为此,您需要使用 IF / ELSE

    ?

    让我们使用你原来的CASE expression 代码:

    case
      when something then 'whatever'
      else Generate Error Message and Stop the Query
    end as [whatever]
    

    作为IF/ELSE(使用BEGIN/END)流:

    IF call_that_a_knife = 'yes'
      BEGIN
        SELECT 'This is a knife' AS yes_i_call_that_a_knife;
      END
    ELSE
      BEGIN
        RAISERROR ('That's not a knife!', 16, 1);
      END
    ;
    

    RAISERROR()

    【讨论】:

    • 最好使用THROW 而不是RAISERROR
    猜你喜欢
    • 2013-04-28
    • 1970-01-01
    • 2016-06-17
    • 2014-08-09
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    相关资源
    最近更新 更多