所以这是一个学校作业。我不明白为什么我的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循环开始时,我感到困惑。如果您想帮助我剖析一下了解代码中发生了什么,我真的很感激。谢谢!
汉娜
答案 0 :(得分: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