2013-04-09 286 views
7

我正在創建一個函數,根據嵌套的if else語句的結果返回'0'或'1'。使用MSSQL。嵌套if else語句

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 

一切工作正常與此。有沒有更好的方法來實現這一目標(我曾嘗試使用OR,但SQL編輯器顯示錯誤,無法識別OR)。

回答

6
SET @condition = (case when PATINDEX('"%', @string) !=0 or 
          PATINDEX('%"%', @string) !=0 or 
          PATINDEX('%"', @string) !=0 then 1 else 0 end) 
+0

謝謝?你這麼多的幫助..我正在玩Case,但無法得到它的工作,我的壞..謝謝.. – 2013-04-09 11:31:14

3

當然這可以簡化爲:

IF (PATINDEX('%"%', @string) !=0) 
    BEGIN 
     SET @condition=1 
    END 
    ELSE 
    BEGIN 
     SET @condition=0 
    END 

- 因爲PATINDEX('%"%', @string)將是> 0,其中任一或PATINDEX('"%', @string) PATINDEX( '%'「,@string)是> 0

+0

謝謝你的幫助.. – 2013-04-09 11:58:49