简体   繁体   中英

SQL Server : basic if condition in function

I have problem with basic if condition in function.. I have something like this

IF  LEFT(@text, 1) = '#'
        BEGIN
            /* trim first character if is '#' */
            RETURN RIGHT(@text,LEN(@text)-1)
        END
    ELSE
        BEGIN
            RETURN @text
        END
    END

Console output show me this

Incorrect syntax near the keyword 'IF'. Incorrect syntax near the keyword 'END'.

I wonder where the problem is. Can I simplify the if condition like this?

IF  LEFT(@text, 1) = '#'  RETURN RIGHT(@text,LEN(@text)-1)
ELSE RETURN @text

Thank you

edit: now I have that if in function

CREATE FUNCTION Trimming (@text VARCHAR(255))
RETURNS VARCHAR(255)
AS
BEGIN
    DECLARE @TrimText AS VARCHAR(255) ;

    SET @TrimText=LTRIM(RTRIM(@text)
    IF  LEFT(@TrimText, 1) = '#'
        BEGIN
            RETURN RIGHT(@TrimText,LEN(@TrimText)-1)
        END
    ELSE
        BEGIN
            RETURN @TrimText
        END
END

and console says

Incorrect syntax near the keyword 'IF'.

The last END is not necessary since an IF does not require an END . Also, since you only have one statement inside the IF and another one inside the ELSE , you don't need to write BEGIN and END .

You have an additional END statement, your query should look like:

IF  LEFT(@text, 1) = '#'
BEGIN
     /* trim first character if is '#' */
      RETURN RIGHT(@text,LEN(@text)-1)
END
ELSE
BEGIN
      RETURN @text
END

http://sqlfiddle.com/#!6/270ca/4

From your edit

SET @TrimText=LTRIM(RTRIM(@text)

You are missing a )

SET @TrimText=LTRIM(RTRIM(@text))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM