SQL 嵌套 if else 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15900532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested if else statement
提问by Ramesh Sivaraman
I am creating a function to return '0' or '1' depending on the result of nested if else statements. Using MSSQL.
我正在创建一个函数,根据嵌套的 if else 语句的结果返回“0”或“1”。使用 MSSQL。
ALTER FUNCTION udf_check_names_starting_with_quotationmark
(@string NVARCHAR(100))
RETURNS INT
AS
BEGIN
DECLARE @condition INT
SET @string = LTRIM(@string)
SET @string = RTRIM(@string)
IF (PATINDEX('"%', @string) !=0)
BEGIN
SET @condition = 1
END
ELSE IF (PATINDEX('%"%', @string) !=0)
BEGIN
SET @condition=1
END
ELSE IF (PATINDEX('%"', @string) !=0)
BEGIN
SET @condition = 1
END
ELSE
BEGIN
SET @condition=0
END
RETURN @condition
END
Everything is working fine with this. Is there a better way to achieve this (I have tried using OR but SQL editor showing an error, not recognizing the OR).
一切正常。有没有更好的方法来实现这一点(我曾尝试使用 OR 但 SQL 编辑器显示错误,无法识别 OR)。
回答by muhmud
SET @condition = (case when PATINDEX('"%', @string) !=0 or
PATINDEX('%"%', @string) !=0 or
PATINDEX('%"', @string) !=0 then 1 else 0 end)
回答by muhmud
Surely this can be simplified to:
当然,这可以简化为:
IF (PATINDEX('%"%', @string) !=0)
BEGIN
SET @condition=1
END
ELSE
BEGIN
SET @condition=0
END
- since PATINDEX('%"%', @string)
will be > 0 where either PATINDEX('"%', @string)
or PATINDEX('%"', @string) are > 0?
- 因为PATINDEX('%"%', @string)
将 > 0PATINDEX('"%', @string)
或 PATINDEX('%"', @string) > 0?