Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL scalar function, how not to use select statement

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
like image 434
ADM Avatar asked Dec 16 '11 14:12

ADM


1 Answers

Just change this line:

SELECT    'Return Value' = @return_value

to

RETURN @return_value;

You do also have to modify the definition of that variable to either be int like so:

DECLARE @return_value int;

Or change the return value of your function to varchar(50) like this:

CREATE FUNCTION [dbo].[getStudentHasElementary] 
( 
    -- paramenter
    @id int
)
RETURNS varchar(50)

You do have to clean up your two queries. Try declaring the @kindofsubject variable and writing the query this way:

DECLARE @kindofsubject varchar(50); -- I'm guessing here...?
-- make sure your constraints ensure only one row will be returned
-- otherwise use TOP 1 (not a great idea, really)
SELECT @kindofsubject = kindOfSubject 
FROM dbo.Subjects
WHERE (studentsid = studentsid);
like image 66
Yuck Avatar answered Sep 26 '22 06:09

Yuck