在OUTER APPLY块中执行存储过程

时间:2013-10-28 09:11:02

标签: sql sql-server-2008 stored-procedures apply outer-join

为什么我不能在OUTER APPLY块中使用存储过程? 我需要从存储过程dbo.GetTeacherId获取int值并在WHERE子句中使用它。这是我的代码:

USE [StudentsDb]

DECLARE @teacherIdOut int;

SELECT   StudentLastName, StudentFirstName, StudentMiddleName, LessonName, Score, TLastName, TFirstName, TMiddleName
FROM     Scores
JOIN Students
ON Scores.StudentId=Students.StudentId
JOIN Lessons
ON Scores.LessonId=Lessons.LessonId
OUTER APPLY
(
    EXECUTE dbo.GetTeacherId 0, 0, @teacherId=@teacherIdOut -- here I get error
    SELECT Teachers.TeacherLastName, Teachers.TeacherFirstName, Teachers.TeacherMiddleName
    FROM Teachers
    WHERE Teachers.TeacherId=@teacherIdOut
)T(TLastName, TFirstName, TMiddleName)
WHERE Score <=3

还有其他方法可以从存储过程中获取值吗? 这是我的存储过程dbo.GetTeacherId

USE [StudentsDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetTeacherId] @lessonId int, @groupId int, @teacherId int OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    SELECT @teacherId=GroupTeachers.TeacherId
    FROM GroupTeachers
    WHERE GroupTeachers.LessonId=@lessonId AND GroupTeachers.GroupId=@groupId
END

1 个答案:

答案 0 :(得分:3)

存储过程不是为这种用法而设计的,因为它可以执行除选择数据之外的操作,它可以在不返回数据的情况下工作,也可以在不同的场景中返回不同的集合。

与存储过程不同,函数非常适合与其他查询一起使用。

您有两种选择:

A)创建一个标量函数,该函数只返回TeacherID并在WHERE

中使用它
CREATE FUNCTION udfGetTeacherID
(
    @lessonId int, @groupId int
)
RETURNS int
AS
BEGIN

    DECLARE @teacherId INT;

    SELECT @teacherId = GroupTeachers.TeacherId
    FROM GroupTeachers
    WHERE GroupTeachers.LessonId=@lessonId AND GroupTeachers.GroupId=@groupId;


    RETURN @teacherId;

END
GO

B)创建表值函数,可以获得所需的所有数据,你可以加入(应用)它。

CREATE FUNCTION udfGetTeacherName
(
    @lessonId int, @groupId int
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT t.TeacherLastName, t.TeacherFirstName, t.TeacherMiddleName
    FROM Teachers t
    INNER JOIN GroupTeachers g ON  T.TeacherID = g.TeacherID
    WHERE g.LessonId=@lessonId AND g.GroupId=@groupId
)
GO

以下是一些阅读: Difference between Stored Procedure and Function in SQL Server