存储过程无法选择表格

时间:2014-04-11 17:58:34

标签: sql sql-server sql-server-2008 stored-procedures

有人可以告诉我,我在哪里出错:

我在执行此操作时遇到错误:

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;

我的错误是

  

Msg 4104,Level 16,State 1,Procedure EnrollStudent,Line 23
  多部分标识符" dbo.CourseEnrollment.CourseId"无法受约束   Msg 4104,Level 16,State 1,Procedure EnrollStudent,Line 23
  多部分标识符" dbo.CourseEnrollment.StudentId"无法绑定

如何从CourseEnrollment表格中进行选择?我无法做到这一点。

2 个答案:

答案 0 :(得分:3)

您不能在不使用表格的情况下使用表格列:

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

答案 1 :(得分:0)

Yout Code有点不清楚。 在声明并且未设置变量后,检查@stutusID是否为1。

此后,您可以阅读表格的一些数据。

我认为您正在尝试检查表格中是否已有学生。 你应该做那样的事情:

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;