0

I'm trying to create a stored function called func_GetMenuItemsForMenu.

For this function, I need to pass the ID of the menu to it. The function will find all MenuItems that are on the menu. It will return a table.

Here is what I have tried:

CREATE FUNCTION [dbo].[func_GetMenuItemsForMenu] 
    (@MenuItemMenuItemID NVARCHAR(200))
RETURNS TABLE
AS
   RETURN (SELECT Menu.MenuID 
           FROM Menu, MenuItem
           WHERE MenuItem.MenuID LIKE @MenuItemMenuItemID + '%'
             AND MenuItem.MenuID = Menu.MenuID)
GO

Here is my table structure:

Table Structure

I'm only getting the MenuID and it's not returning the menu item as well that's on the specific menu.

4
  • 2
    Because only have Menu.MenuID in the SELECT list.... you should also use explicit joins. Your old-style join has really, really old. Commented Feb 7, 2019 at 22:02
  • My bad, I'm really new to stored functions and procedures. Commented Feb 7, 2019 at 22:03
  • 1
    No problem, but this would be the same for any select statement. Only the columns listed between select and from would be returned. Change SELECT Menu.MenuID FROM Menu... to SELECT Menu.MenuID, MenuItem.MenuItemTitle FROM Menu... or what ever column you want to return. Commented Feb 7, 2019 at 22:04
  • Yeah, that makes sense thanks. Commented Feb 7, 2019 at 22:07

1 Answer 1

1

You did not select the columns you need and that is why you only get MenuID. I add MenuItemTitle here.

CREATE FUNCTION [dbo].[func_GetMenuItemsForMenu] 
(
    @MenuItemMenuItemID NVARCHAR(200)
)
RETURNS TABLE
AS
RETURN (
    SELECT 
        Menu.MenuID, 
        MenuItem.MenuItemTitle 
    FROM Menu
    INNER JOIN 
        MenuItem ON 
        MenuItem.MenuID = Menu.MenuID
    WHERE
        MenuItem.MenuID LIKE @MenuItemMenuItemID + '%')
GO
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.