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 回答