简体   繁体   English

如何为SQL中的每一行创建一个循环?

[英]How to create a loop for each row in SQL?

I have 3 tables ( Users , CourseUsers and Courses which represent the courses assigned to a single user). 我有3个表格( UsersCourseUsersCourses ,它们代表分配给单个用户的课程)。

I would like to create a procedure which, as soon as I create a new course, will assign this course to every user. 我想创建一个过程,一旦我创建了新课程,就会将该课程分配给每个用户。 What I see I need here is a For each loop to iterate through every user inserting a new row in CourseUsers table 我在这里需要的是一个For每个循环,用于遍历每个用户,在CourseUsers表中插入新行

How do I create a loop in SQL? 如何在SQL中创建循环?

You don't need a loop. 您不需要循环。

DECLARE @CourseId INT;

INSERT INTO Courses(Name) VALUES('Some Course');

SET @CourseId  = SCOPE_IDENTITY();

INSERT INTO CourseUsers(UserId, CourseId)
SELECT UserId, @CourseId
FROM Users;

In this case, you don't. 在这种情况下,您不需要。

You can issue an insert statement that will insert a new row in that CourseUsers table for every User: 您可以发出插入语句,该语句将为每个用户在该CourseUsers表中插入新行:

INSERT INTO CourseUsers(CourseId, UserId)
SELECT @CourseId, UserId
FROM Users

SQL is a set-based language: usually you can work on an entire set of data, without the need for loops. SQL是一种基于集合的语言:通常,您可以处理整个数据集,而无需循环。

You don't need a loop for doing this. 您不需要执行此操作的循环。

You can use an INSERT trigger and access the INSERTED logical table, operating on the results of that. 您可以使用INSERT 触发器并访问INSERTED逻辑表,并对结果进行操作。

Try - 尝试-

INSERT INTO CourseUsers (CourseID,UserID)
SELECT 7, UserID FROM Users

Where 7 is your course id (this would obviously change from course to course!). 其中7是您的课程ID(显然,这会因课程而异!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM