在T-SQL中,您不能在case语句中引发错误吗?我总是遇到SQL case语句的问题:/
begin try
declare @i int
--set @i = (select COUNT(1) from table_name)
select Item_Num =
CASE (select COUNT(1) from table_name)
when 1 then (select Item_Num from table_name)
when 0 then (raiserror('No records in database', 0, 0))
ELSE (raiserror('Multiple records in database', 0, 0))
END
from table_name
end try
begin catch
declare @errormsg nvarchar(1024),
@severity int,
@errorstate int;
select @errormsg = error_message(),
@severity = error_severity(),
@errorstate = error_state();
raiserror(@errormsg, @severity, @errorstate);
end catch发布于 2014-05-15 02:50:49
将Case/When看作是对单个数据的操作。如果你这样想,你的很多问题都会消失。
If/Then用于控制逻辑流程。
这样的东西对你来说应该是有效的。
declare @i int
set @i = (select COUNT(1) from table_name)
If @i = 1
Begin
Print "1 row"
End
Else If @i = 0
Begin
Print "no rows"
End
Else
Begin
Print "too many rows"
End发布于 2020-04-09 04:06:40
通过将错误字符串转换为int,可以从case表达式引发错误。
select case (select count(*) from mytable)
when 1 then 100
when 2 then 200
else convert(int, 'ERROR')
end这会给出一条错误消息,如
Conversion failed when converting the varchar value 'ERROR' to data type int.
这就是你能得到的最好的结果了。
并非所有失败的转换都会在错误消息中提供输入字符串。例如,转换为datetime就不需要。因此,如果case表达式返回datetime,您仍然需要通过字符串到整数的转换来触发错误:
select case (select count(*) from mytable)
when 1 then getdate()
else convert(datetime, convert(int, 'ERROR'))
end更糟糕的是:如果要返回日期,则不能显式地将其从int转换,因此必须求助于
convert(date, convert(char(1), convert(int, 'ERROR')))这很可怕,但在我看来,唯一比干净的代码更重要的是信息丰富的错误消息,所以我接受了它。
发布于 2014-05-14 23:57:19
正如我在注释中所说的,我认为简单地创建一个在CASE语句的作用域之外检查的标志会更容易。大致是这样的:
--- code before the TRY...
BEGIN TRY
DECLARE @i int
-- declare a variable to act as a flag
DECLARE @my_flag as int
-- than change your statement to simply fill the value of the flag
CASE (SELECT COUNT(1) FROM table_name)
WHEN 1 THEN SET @my_flag = 1
WHEN 0 THEN SET @my_flag = 0
ELSE SET @my_flag = -1
END
IF (NOT @my_flag in (-1, 0))
BEGIN
SET @Item_Num = (SELECT Item_Num FROM table_name) -- consider a filter here
END
ELSE
BEGIN
IF (-1 = @my_flag) RAISERROR('too many records', 0, 0)
IF (0 = @my_flag) RAISERROR('no records', 0, 0)
END
END TRY
BEGIN CATCH
--- rest of the code goes here.... https://stackoverflow.com/questions/23659141
复制相似问题