Can the SQL Case Statement fall through?

梦想与她 提交于 2019-12-08 15:21:16

问题


Is there a way to make a CASE statement in SQL fall through like the case statement in C#? What I don't want to do is the example below but if that’s my only option I guess I'll go with it.

EXAMPLE:

@NewValue =
   CASE
      WHEN @MyValue = '1' THEN CAST(@MyValue AS int)
      WHEN @MyValue = '2' THEN CAST(@MyValue AS int)
      ELSE NULL
   END

EDIT:

I'm using SQL Server.


回答1:


To answer your specific question: No, it cannot.

See, for example, the MySQL documentation for CASE. Every WHEN must have a THEN result, and there is no way around this. The THEN is not marked as optional. The same applies to all other RDBMS I've used.

Here's another example: Sql Server's CASE expression

You already have a good alternative way to do it posted as a comment, so I won't repeat it here.




回答2:


You can also do it like this:

@NewValue =
   CASE
      WHEN @MyValue in ( '1', '2' ) THEN CAST(@MyValue AS int)
      ELSE NULL
   END

or like this:

CASE @MyValue 
         WHEN '1' THEN CAST(@MyValue AS int)
         WHEN '2' THEN CAST(@MyValue AS int)
         ELSE null
      END

even though in this case the @MyValue in ('1','2') would make more sense.




回答3:


Could alternatively use T-SQL try-catch. However, I'm not sure what kind of negative impact this would have on the server:

SQL:

DECLARE @intVar VARCHAR(MAX), @stringVar VARCHAR(MAX), @default_value INT, @tempVar INT
SET @default_value = NULL
SET @stringVar = 'Hello World!!'
SET @intVar = '550'

PRINT 'Casting @stringVar: '
BEGIN TRY
    SET @tempVar = CAST(@stringVar AS INT)
END TRY
BEGIN CATCH
    SET @tempVar = @default_value
END CATCH
PRINT @tempVar + 20

PRINT ''

PRINT 'Casting @intVar: '
BEGIN TRY
    SET @tempVar = CAST(@intVar AS INT)
END TRY
BEGIN CATCH
    SET @tempVar = @default_value
END CATCH
PRINT @tempVar

Output: Casting @stringVar:

Casting @intVar: 550

Furthermore, I would create user defined functions for those try catch statements that accept a varchar inputString, and int default_value, which returns the integer.



来源:https://stackoverflow.com/questions/2120133/can-the-sql-case-statement-fall-through

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!