0

というわけで、学校の宿題です。SQL クエリが数値を返す理由がわかりません。8 つのテーブルが作成されました。興味のある主なものは学生です

CREATE TABLE    Student
(
    Number  INT     NOT NULL    IDENTITY(130001, 1),
    Name    CHAR(55)    NOT NULL,

    PRIMARY KEY (Number)
)

それに 36 人の名前を挿入しました (これが生徒の数です)。しかし、クエリを実行すると

SELECT COUNT(Student.Name) AS 'Total number of students'
FROM Student

144 を返します。ここで指定されたコードと関係があると言いたいです。

DECLARE @totalProgram   INT
DECLARE @totalStudent   INT
DECLARE @i              INT

SET @totalProgram = (SELECT COUNT(*) FROM Program)
SET @totalStudent = (SELECT COUNT(*) FROM Student)
SET @i = 1

WHILE @i <= @totalStudent
    BEGIN
    INSERT INTO ProgramGraduate
        (
            ProgramID, 
            StudentNumber
        )
        VALUES
        (
            FLOOR(RAND() * @totalProgram + 1),
            FLOOR(RAND() * @totalStudent + 130001)
        )
    SET @i = @i + 1
    END
GO

その目的は、プログラム内の学生の総数をランダム化することだと思いますか? 最初の 6 行が変数を宣言し、変数に値を与えていることは理解していますが、その WHILE ループが始まると混乱します。コードで何が起こっているのかを分析するのを手伝ってくれたら、本当に感謝します。ありがとう!

ハンナ

4

1 に答える 1

0
DECLARE @totalProgram   INT   --<-- Declaration of variables
DECLARE @totalStudent   INT
DECLARE @i              INT

SET @totalProgram = (SELECT COUNT(*) FROM Program) --<-- @totalProgram storing total number of rows in Program table 
SET @totalStudent = (SELECT COUNT(*) FROM Student) --<-- @totalStudent storing total number of rows in Student table 
SET @i = 1                                        --<-- Hardcoding value to 1

WHILE @i <= @totalStudent    --<-- "While loop Condition" Execute this while until value of @i is Less than or equal to the value of  @totalStudent
    BEGIN
    INSERT INTO ProgramGraduate      --<-- Insert Statement for the ProgramGraduate table 
        (
            ProgramID,                 --<-- Column Name 1
            StudentNumber               --<-- Column Name 2
        )
        VALUES
        (
            FLOOR(RAND() * @totalProgram + 1),          --<-- Generating a Random Number Between 1 and @totalProgram
            FLOOR(RAND() * @totalStudent + 130001)      --<-- Generating a Random Number Between 130001 and @totalStudent 
        )
    SET @i = @i + 1    --<-- Increasing the value of @i by one everytime this loop executes "Eventually to make the while loop condition ture and break the loop otherwise it will be an idefinite loop"
    END
GO
于 2013-11-09T19:11:32.027 に答える