• Are you creating your

    "SELECT     COUNT(DISTINCT dbo.course_enrolments.student_fk) AS Expr1

     FROM         dbo.course_enrolments INNER JOIN

                  dbo.Course ON dbo.course_enrolments.course_fk = dbo.Course.uid AND dbo.course_enrolments.courseversion = dbo.Course.version INNER JOIN

                          @StudentDerived ON dbo.course_enrolments.student_fk = @StudentDerived.student_fk

     WHERE     (dbo.course_enrolments.course_fk = @courseID)"

    as dynamic SQL and then using sp_executesql or EXECUTE then you won't be able to use table variables. What BOL is saying is that if you create a table variable you can only use it in the area you have created it. even though sp_executesql and execute are in the same SP they are like calling out to another procedure. So just like other variables the stored procedures you call can't reference the variables declared in the calling SP.

    I hope that helps.

    Not sure why you need dynamic SQL from your code above.


    Simon Sabin
    SQL Server MVP

    http://sqlblogcasts.com/blogs/simons