【发布时间】: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] < 5)` ? -
我之前没有在 SQL 中实现过这种类型的逻辑。我正在尝试将 If 语句与 while 循环集成一秒钟。
标签: sql-server tsql ssms