question

user-470 avatar image
user-470 asked

How to Raiserror from default of CASE statement?

In C#, I frequently use the defensive technique of throwing an exception if I get to the default case of a switch statement. In t-sql (specifically SQL Server 2005), there is a similar construct called CASE.

I would like to be able to use the same technique in t-sql, e.g.

SELECT (
CASE
  WHEN Blah IN ('A', 'B') THEN 3
  WHEN Blah IN ('C', 'D') THEN 2
  ELSE raiserror('unhandled blah type', 16, 1)
END) As Halb

However, t-sql gives the error:

Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'raiserror'.
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near ')'.

Is there any way to accomplish this type of scenario or is there another, more common, t-sql approach to this pattern?

sql-server-2005t-sql
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Kev Riley avatar image
Kev Riley answered

CASE isn't used as control-flow in T-SQL, it is a conditional expression valuation construct.

If you really want to do this, then maybe consider setting a variable in the else condition, (in another CASE) and then check the value of the variable after the select has completed. This won't break out of the select, but at least will give you some control after it has executed.

Alternatively, validate all your values before the select, and throw the exception then.


edit: some examples to illustrate

declare @error bit

SELECT 
    (CASE
      WHEN Blah IN ('A', 'B') THEN 3
      WHEN Blah IN ('C', 'D') THEN 2
    END) As Halb
from ....

select
    @error = CASE
      WHEN Blah IN ('A', 'B') THEN @error
      WHEN Blah IN ('C', 'D') THEN @error
      ELSE 1
    END
from ...

select @error --do something here depending on the value
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Oleg avatar image Oleg commented ·
If you really need to throw that error then why not just SELECT (CASE WHEN Blah IN ('A', 'B') THEN 3 WHEN Blah IN ('C', 'D') THEN 2 ELSE 1 / 0 END) As Halb
1 Like 1 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.