2

I have MySQL function with 2 parameters namely user_id and post_id

Here's my function:

CREATE FUNCTION isliked(pid INT, uid INT)
RETURN TABLE
AS
RETURN (EXISTS (SELECT 1 FROM likedata ld WHERE post_id = pid AND user_id = uid
       )) as is_liked
END

I tried to call it with below query:

SELECT posts.id, posts.title, isliked(111,123)
FROM posts

It returns the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'RETURN TABLE
AS
RETURN (EXISTS (SELECT 1 FROM likedata ld WHERE post_id = pid AN' at line 2

It should be return results like this http://sqlfiddle.com/#!9/91040/5 I'm new to sql, any help will be great, thanks in advance

6
  • your function have syntax problem. go the office mysql site and find the syntax of what's actual does syntax and make the appropriate changes Commented May 28, 2018 at 5:35
  • Don't you have 2 '(' in your function but 3 ')' ? Commented May 28, 2018 at 5:36
  • You probably want to return a Boolean/bit rather than a table. You only need one value and it looks like you want to use it in the select clause. Commented May 28, 2018 at 5:43
  • Yes please check my code and help @Horia Coman Commented May 28, 2018 at 5:47
  • What is the expected output? What do you want isliked function to return? Commented May 28, 2018 at 6:24

1 Answer 1

1

If you want the function to return Boolean value use:

CREATE FUNCTION isliked(pid INT, uid INT)
RETURNS BIT
   RETURN ( EXISTS ( SELECT 1 FROM likedata ld WHERE post_id = pid AND user_id = uid ) )
Sign up to request clarification or add additional context in comments.

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.