SQL标量函数,如何不使用select语句
我正在构建第一个标量函数 (MS SQL Server),但收到此错误:
“函数中包含的 Select 语句无法将数据返回到客户端。”
我知道我不能使用 select 语句,但是我如何获取信息呢?
该函数显示学生是否已经学习并通过了基础科目,其工作方式如下:
参数 id 是一个通用 id,它为我提供了来自学生表的学生 ID。 然后,从“主题”表中我得到主题类型。给定 kindOfSubject 参数的函数 getKindOfSubjectStudied 将显示学生传递的主题是否是初级的。如果是这样,结果将为 1,否则将为 0。
所有单独测试的查询都有效,没有错误。
下面是功能代码的解释。
多谢
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需更改此行:
到
您还必须将该变量的定义修改为
int
,如下所示:或将函数的返回值更改为
varchar(50)
像这样:你必须清理你的两个查询。尝试声明
@kindofsubject
变量并以这种方式编写查询:Just change this line:
to
You do also have to modify the definition of that variable to either be
int
like 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
@kindofsubject
variable and writing the query this way: