1

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'.

2
  • there is nothing wrong with this code. i.sstatic.net/TwBAh.png Commented Jul 9, 2013 at 13:36
  • Thank you for image, one END was additional :-) Commented Jul 9, 2013 at 13:52

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you it helped.. i rewrite it to this pastebin.com/mpJ9cd6E but now im getting Incorrect syntax near the keyword 'IF'.
@Muflix - pastebin is blocked on my network. Can you include it in a SQLFiddle or modify your question to include the code?
Thank you, now it works i only have to add RETURN before last END because Console says last statement must be return.. but it is necessary if i have IF/ELSE there ? (okay i just deleted ELSE section now its perfect :-)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.