简体   繁体   中英

Stored procedure can't select table

Can someone please tell me where am I going wrong in this:

I'm getting a error on doing this:

CREATE PROCEDURE dbo.EnrollStudent ( @CourseID  AS INTEGER,
                                     @StudentID AS VARCHAR(20), 
                                     @Status AS VARCHAR(50) OUTPUT ) AS
BEGIN
   DECLARE @StutusID INTEGER

   IF @StutusID = 1
   BEGIN  
       SET @Status = 'The Student is already Enrolled'
   END;

   ELSE IF @StutusID = 2
   BEGIN 
       SET @Status = 'Cannot enroll until faculty is selected' 
   END

   ELSE IF @StutusID = 3
   BEGIN 
       SET @Status = 'Student Enrolled' 
   END

   IF (dbo.CourseEnrollment.CourseId = @CourseID AND 
       dbo.CourseEnrollment.StudentId LIKE @StudentID)
   BEGIN
      SET @StutusID = 1
   END
END;

My error is

Msg 4104, Level 16, State 1, Procedure EnrollStudent, Line 23
The multi-part identifier "dbo.CourseEnrollment.CourseId" could not be bound.
Msg 4104, Level 16, State 1, Procedure EnrollStudent, Line 23
The multi-part identifier "dbo.CourseEnrollment.StudentId" could not be bound​

How can I select from the CourseEnrollment table? I'm not able to do that.

You can't just use a column of a table without using the table:

IF EXISTS (SELECT 1 FROM dbo.CourseEnrollment WHERE CourseId=@CourseID 
           AND StudentId LIKE '%' + @StudentID + '%')
BEGIN
SET @StutusID=1
END

Yout Code ist somewhat unclear. You check if @stutusID is 1 after declaring and not setting the varaible.

Thereafter you may read some data of a table.

I think you are trying to check wether or not a studentid is already in the table. You should do somthing like that:

CREATE PROCEDURE dbo.EnrollStudent ( @CourseID  AS INTEGER,
                                 @StudentID AS VARCHAR(20), 
                                 @Status AS VARCHAR(50) OUTPUT ) AS
BEGIN
   DECLARE @StutusID INTEGER

   SELECT COUNT(*) INTO @StutisID FROM dbo.CourseEnrollment WHERE dbo.CourseEnrollment.CourseId = @CourseID AND 
       dbo.CourseEnrollment.StudentId LIKE @StudentID

   IF @StutusID = 1
   BEGIN  
       SET @Status = 'The Student is already Enrolled'
   END;

       ELSE IF @StutusID = 2
   BEGIN 
       SET @Status = 'Cannot enroll until faculty is selected' 
   END

   ELSE IF @StutusID = 3
   BEGIN 
       SET @Status = 'Student Enrolled' 
   END
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM