Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3236964
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T17:40:58+00:00 2026-05-17T17:40:58+00:00

How do I loop through the results of a SELECT statement in SQL? My

  • 0

How do I loop through the results of a SELECT statement in SQL? My SELECT statement will return just 1 column but n results.

I have created a fictional scenario below complete with the Pseudo code of what I’m trying to do.

Scenario:

Students are registering for their classes. They submit a form with multiple course selections (ie. select 3 different courses at once). When they submit their registration I need to ensure there is still room left int the courses they have selected (note I will do a similar check before presenting them with course selection UI but I need to verify afterwards in case somebody else has gone in and swipped up the remaining spots).

Pseudo Code:

DECLARE @StudentId = 1
DECLARE @Capacity = 20

-- Classes will be the result of a Select statement which returns a list of ints
@Classes = SELECT classId FROM Student.CourseSelections
WHERE Student.CourseSelections = @StudentId

BEGIN TRANSACTION
DECLARE @ClassId int
foreach (@classId in @Classes)
{
   SET @SeatsTaken = fnSeatsTaken @classId

   if (@SeatsTaken > @Capacity)
   {
       ROLLBACK;  -- I'll revert all their selections up to this point
       RETURN -1;
   }
   else
   {
       -- set some flag so that this student is confirmed for the class
   }
}

COMMIT
RETURN 0

My real problem is a similar “ticketing” problem. So if this approach seems very wrong please feel free to recommend something more practical.

EDIT:

Attempting to implement the solution below. At this point it doesn’t work. Always returns “reserved”.

DECLARE @Students TABLE
(
 StudentId int
,StudentName nvarchar(max)
)

INSERT INTO @Students
 (StudentId ,StudentName)
VALUES
 (1, 'John Smith')
 ,(2, 'Jane Doe')
 ,(3, 'Jack Johnson')
 ,(4, 'Billy Preston')

-- Courses
DECLARE @Courses TABLE
(
 CourseId int
,Capacity int
,CourseName nvarchar(max)
)

INSERT INTO @Courses
 (CourseId, Capacity, CourseName)
VALUES
 (1, 2, 'English Literature'),
 (2, 10, 'Physical Education'),
 (3, 2, 'Photography')


-- Linking Table
DECLARE @Courses_Students TABLE
(
 Course_Student_Id int
,CourseId int
,StudentId int
)

INSERT INTO @Courses_Students
 (Course_Student_Id, StudentId, CourseId)
VALUES
 (1, 1, 1),
 (2, 1, 3),
 (3, 2, 1),
 (4, 2, 2),
 (5, 3, 2),
 (6, 4, 1),
 (7, 4, 2)

SELECT Students.StudentName, Courses.CourseName FROM @Students Students INNER JOIN
@Courses_Students Courses_Students ON Courses_Students.StudentId = Students.StudentId INNER JOIN
@Courses Courses ON Courses.CourseId = Courses_Students.CourseId

DECLARE @StudentId int = 4

-- Ideally the Capacity would be database driven
-- ie. come from the Courses.Capcity.
-- But I didn't want to complicate the HAVING statement since it doesn't seem to work already.
DECLARE @Capacity int = 1 

IF EXISTS (Select *
 FROM
  @Courses Courses INNER JOIN
  @Courses_Students Courses_Students ON Courses_Students.CourseId = Courses.CourseId
 WHERE
  Courses_Students.StudentId = @StudentId
 GROUP BY
  Courses.CourseId
 HAVING
  COUNT(*) > @Capacity)
BEGIN
 SELECT 'full' as Status
END
ELSE BEGIN
 SELECT 'reserved' as Status
END
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T17:40:59+00:00Added an answer on May 17, 2026 at 5:40 pm

    No loop needed. You’re looking at a standard aggregate with COUNT and GROUP.

    Of course, some details are needed but the principle is this…

    DECLARE @StudentId = 1
    DECLARE @Capacity = 20
    
    -- Classes will be the result of a Select statement which returns a list of ints
    IF EXISTS (SELECT *
        FROM
            Student.CourseSelections CS
            JOIN
            ---this is where you find out course allocations somehow
            ClassTable C ON CS.classId = C.classId 
        WHERE
            Student.CourseSelections = @StudentId
        GROUP BY  --change this, it depends on where you find out course allocations
            ClassID
        HAVING
            COUNT(*) > @Capacity)
       'no'
    ELSE
       'yes'
    

    Edit:

    I’ve changed the link table. Course_Student_ID is usually not needed in link tables.

    The JOIN now

    • gets the courses for that student
    • then looks at all students on this course and compares to capacity

    Cut down version of above:

    ...
    -- Linking Table
    DECLARE @Courses_Students TABLE (
    ,CourseId int
    ,StudentId int)
    
    INSERT INTO @Courses_Students
     (StudentId, CourseId)
    VALUES (1, 1), (1, 3), (2, 1), (2, 2), (3, 2), (4, 1), (4, 2)
    
    DECLARE @StudentId int = 4
    
    --straight list
    SELECT
         C.CourseName, C.Capacity, COUNT(*)
     FROM
      @Courses_Students CSThis
      JOIN
      @Courses C ON CSThis.CourseId = C.CourseId
      JOIN
      @Courses_Students CSOthers ON CSOthers.CourseId = C.CourseId
     WHERE
      CSThis.StudentId = @StudentId
     GROUP BY
      C.CourseName, C.Capacity
    
    --oversubscribed list
      SELECT
         C.CourseName, C.Capacity, COUNT(*)
     FROM
      @Courses_Students CSThis
      JOIN
      @Courses C ON CSThis.CourseId = C.CourseId
      JOIN
      @Courses_Students CSOthers ON CSOthers.CourseId = C.CourseId
     WHERE
      CSThis.StudentId = @StudentId
     GROUP BY
      C.CourseName, C.Capacity
      HAVING
          COUNT(*) > C.Capacity
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How to loop through a select statement results to have a formatted text? for
I need to loop through all the matches in say the following string: <a
I'm trying to loop through items of a checkbox list. If it's checked, I
I would like to be able to loop through all of the defined parameters
A query that is used to loop through 17 millions records to remove duplicates
I'm using the following code to loop through a directory to print out the
I'd like a loop that uses a UInt16 (ushort) to loop through all of
I would like to know how to loop through each line in a text
I'm using the following syntax to loop through a list collection: For Each PropertyActor
In the following code I loop through a map and test if an element

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.