I’m building my first scalar function (MS SQL Server) and I get this error:
“Select statements included within a function cannot return data to a client.”
I understand that I cannot use select statements, but how do I get the info then?
The function shows if a student has studied and passed elementary subjects, and works this way:
the parameter id is a general id which gives me the studentid from table Students.
Then, from table Subjects I get the kind of subject. The function getKindOfSubjectStudied given kindOfSubject parameter will show if the subject passed by the student is elementary. If so the result will be 1, otherwise it’ll be 0.
All the queries tested separately work, no errors.
Below is the function code explained.
Thanks a lot
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
USE MYDBASE
GO
CREATE FUNCTION [dbo].[getStudentHasElementary]
(
-- paramenter
@id int
)
RETURNS INTEGER
AS
BEGIN
DECLARE @Result AS INTEGER
DECLARE @return_value varchar (50)
SELECT studentsid
FROM dbo.Students
WHERE (id = id)
SELECT kindOfSubject
FROM dbo.Subjects
WHERE (studentsid = studentsid)
--- I use this function to know if the subject is elementary
EXEC @return_value = [dbo].[getKindOfSubjectStudied]
@id = id,
@kindOfSubject = kindOfSubject;
SELECT 'Return Value' = @return_value
IF (@return_value = 'elementary')
BEGIN
SET @Result = 1
END
ELSE
BEGIN
SET @Result = 0
END
RETURN @Result
END
Just change this line:
to
You do also have to modify the definition of that variable to either be
intlike so:Or change the return value of your function to
varchar(50)like this:You do have to clean up your two queries. Try declaring the
@kindofsubjectvariable and writing the query this way: