sql - Execute stored procedure in OUTER APPLY block -
why can not use stored procedure in outer apply
block? need int value stored procedure dbo.getteacherid
, use in where
clause. here code:
use [studentsdb] declare @teacheridout int; select studentlastname, studentfirstname, studentmiddlename, lessonname, score, tlastname, tfirstname, tmiddlename 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 error select teachers.teacherlastname, teachers.teacherfirstname, teachers.teachermiddlename teachers teachers.teacherid=@teacheridout )t(tlastname, tfirstname, tmiddlename) score <=3
and there other way value stored procedure? here stored procedure 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 begin set nocount on; select @teacherid=groupteachers.teacherid groupteachers groupteachers.lessonid=@lessonid , groupteachers.groupid=@groupid end
stored procedure not designed kind of usage, can perform operations other selecting data, can work without returning data or can return different set in different scenarios.
unlike stored procedures, functions suited used inline other queries.
you have 2 options:
a) create scalar function return teacherid
, use in where
create function udfgetteacherid ( @lessonid int, @groupid int ) returns int begin declare @teacherid int; select @teacherid = groupteachers.teacherid groupteachers groupteachers.lessonid=@lessonid , groupteachers.groupid=@groupid; return @teacherid; end go
b) create table-valued function can data needed , can join (apply) on it.
create function udfgetteachername ( @lessonid int, @groupid int ) returns table return ( select t.teacherlastname, t.teacherfirstname, t.teachermiddlename teachers t inner join groupteachers g on t.teacherid = g.teacherid g.lessonid=@lessonid , g.groupid=@groupid ) go
here reading: difference between stored procedure , function in sql server
Comments
Post a Comment