用于从三个表中进行选择的存储过程

时间:2012-12-12 10:20:20

标签: sql sql-server stored-procedures

我有这三个表

课程

course ID     course Name     course start time   course end time
1             Math            10:00:00            11:00:00
2             Science         11:00:00            12:00:00
3             geography       09:00:00            10:00:00

student_courses

course ID     student ID      Final cost
1             2               100
2             3               200

学生

student ID     student name
1              AAAA
2              BBBB

我需要在存储过程中放置​​一个select语句,只返回学生未注册的课程的[课程ID],[课程名称]列值(已实现)

AND 检查学生当前课程的开始和结束时间,只返回学生可用的课程(没有课程)

我的select语句只返回学生未注册的课程::

SELECT [Course ID], [Course name] 
FROM Courses
WHERE [Course ID] NOT IN 
 (SELECT Course ID from student_courses WHERE [student ID]=1) 

如何编辑此语句以包含可用的时间条件(知道我想将其放入存储过程中)....

1 个答案:

答案 0 :(得分:1)

这是您需要的查询:

SELECT [Course ID], [Course name] 
FROM Courses 
WHERE [Course ID] NOT IN 
 (SELECT Course ID from student_courses sc
  INNER JOIN Courses c ON sc.[course ID] = c.[course ID] 
  WHERE [student ID] = 1
  AND (c.[course start time] BETWEEN Courses.[course start time] AND Courses.[course end time]
  OR c.[course end time] BETWEEN Courses.[course start time] AND Courses.[course end time]))

我认为没有理由,为什么这应该是stored procedureview可能是合理的。

详细了解views here