2013-04-09 23 views
7

Tworzę funkcję zwracania "0" lub "1" w zależności od wyniku zagnieżdżonych instrukcji else. Korzystanie z MSSQL.Zagnieżdżona instrukcja 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 

Wszystko działa dobrze z tym. Czy istnieje lepszy sposób osiągnięcia tego celu (próbowałem użyć OR, ale edytor SQL pokazujący błąd, nie rozpoznając OR).

Odpowiedz

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

Thank? bardzo ci na tę pomoc .. Grałem z Case'em, ale nie mogłem go uruchomić, moje złe .. Dzięki .. –

3

Z pewnością można uprościć do:

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

- od PATINDEX('%"%', @string) będzie> 0, albo gdy PATINDEX('"%', @string) lub PATINDEX ('%'', @string) jest> 0

+0

Dzięki za pomoc .. –