0

Here's a very simple function to return student id by name.The function works but I have trouble getting use of it:

--function to find student id by name (works)
create function findStudent (@name nvarchar(15), @familyName nvarchar(15))
returns tinyint
as
begin
    declare @id tinyint
    select @id = (select teaID from Tea where teaFirstName = @name and teaLastName = @familyName)
    return @id
end;

--using the function (doesn't work)
declare @id tinyint
select @id = (execute findStudent 'Arash', 'Mitooie')
print @id
1
  • 2
    Where did you find example syntax that you execute a function or that you pass arguments without parens? Try SELECT @id = dbo.findStudent(N'Arash'. N'Mitooie'); Commented Jul 16, 2020 at 15:40

1 Answer 1

1

You have a function. No execute is necessary. Just plug it into a select:

declare @id tinyint;
select @id = dbo.findStudent('Arash', 'Mitooie');
print @id;

You can also define this as a stored procedure. In that case, I would advise passing the @id in as an OUTPUT parameter and assigning the value in the procedure.

You should also review the differences between stored procedures and stored functions, because you seem to be confusing the two. At the simplest, stored functions return either a single value or a result set and are intended to be used in queries. Stored procedures cannot be used in queries (with the exception of insert under some special circumstances that I don't recommend using).

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Gordon. I do intend to use it in queries, but unfortunately it doesn't work your way either . . . BTW: Are all those semicolons necessary in SQL?
@Arash No they are not strictly necessary today, but they may be someday, so it is just a good idea. See this post. Also re: dbo. prefix see this one. What does "doesn't work the way you've written it" mean?
@ArashMitooie . . . That is because functions have to include the schema name in SQL Server.
actually you can execute functions, and in the case of exec the schema is not required. I don't recommend that though. stackoverflow.com/questions/5207036/…
@Gordon, @Aron Thanks guys. A dbo. before function name solved it.

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.