I am creating a database for a fictional school. I have a table Courses (PK Coursecode nvarchar(50), Credits int, FK Teacher nvarchar(50), Name nvarchar(50)), another Teachers, and another named CourseTeachers, referencing the two and storing data about hours worked.
What I want to accomplish is to create a function that takes year as argument and returns a table in the format
FIRST NAME | LAST NAME | course1/period | course2/period | course3/period | course4/period
teacher1 fn | teacher1 ln | hrs worked course1 | ...
Note that the top row is data in the table, not attributes.
For this I created a function getFourCoursesByYear that simply does the following
SELECT TOP 4 CourseTeachers.Course, CourseTeachers.Teacher
FROM CourseTeachers
WHERE CourseTeachers.year = @year
The problems I have:
- How do I insert a row in the specified format using the data from the function?
- How do I calculate the hours worked and return in the proper format?
The solution I have considered so far involves subqueries and is something along the lines of
DECLARE @table TABLE
(
Firstname nvarchar(50),
Lastname nvarchar(50),
c1 nvarchar(50),
c2 nvarchar(50),
c3 nvarchar(50),
c4 nvarchar(50)
);
INSERT INTO @table
VALUES('First Name', 'Last Name',
(SELECT Course FROM getFourCoursesByYear(@year)), ...)
However, as you can see the code is incomplete and doesn't work.