如何在SQL中插入多个行值

时间:2014-07-21 10:37:12

标签: sql sql-server

我有以下3个表格:

CREATE TABLE Tests (
    Test_ID INT,
    TestName VARCHAR(50));

INSERT INTO Tests VALUES (1, 'SQL Test');
INSERT INTO Tests VALUES (2, 'C# Test');
INSERT INTO Tests VALUES (3, 'Java Test');


CREATE TABLE Users (
    [User_ID] INT,
    UserName VARCHAR(50));

INSERT INTO Users VALUES (1, 'Joe');
INSERT INTO Users VALUES (2, 'Jack');
INSERT INTO Users VALUES (3, 'Jane');



CREATE TABLE UserTests (
    ID INT,
    [User_ID] INT,
    Test_ID INT,
    Completed INT);

INSERT INTO UserTests VALUES (1, 1, 1, 0);
INSERT INTO UserTests VALUES (2, 1, 2, 1);
INSERT INTO UserTests VALUES (3, 1, 3, 1);
INSERT INTO UserTests VALUES (4, 2, 1, 0);
INSERT INTO UserTests VALUES (5, 2, 2, 0);
INSERT INTO UserTests VALUES (6, 2, 3, 0);
INSERT INTO UserTests VALUES (7, 3, 1, 1);
INSERT INTO UserTests VALUES (8, 3, 2, 1);
INSERT INTO UserTests VALUES (9, 3, 3, 1);

我想创建一些规则/触发器,以便在将新用户添加到Users表时,每个Test的条目和该用户的Id将添加到{{1表格。

如果新用户ID为5,则类似这样:

UserTests

这种语法当然是错误的,但要想一想我期望发生什么。

所以我希望该语句将这些值添加到INSERT dbo.UserTest (USER_ID, TEST_ID, Completed) VALUES (5, SELECT TEST_ID FROM Tests, 0) 表中:

UserTests

2 个答案:

答案 0 :(得分:1)

您可以在触发后使用用户表。

Create Trigger tr_user on Users 
After Insert 
AS Begin
   INSERT UserTest(USER_ID, TEST_ID, Completed)
   Select I.USER_ID, t.TEST_ID, 0
   From Inserted I, Tests t
END

答案 1 :(得分:0)

这是一个SQL小提琴,可以找到丢失的记录并插入它们。

SQL Fiddle

SELECT

select u.user_id, t.test_id, 0 as Completed
from users u 
cross join tests t
where not exists (
        select 1 
        from usertests ut 
        where ut.user_id = u.user_id and ut.test_id = t.test_id)

在select之前添加insert into UserTests (User_Id, Test_Id, Completed)将插入这些记录。

如果需要,您可以在where子句中添加用户ID,以便为单个用户执行此操作。它是可重新运行的,因此它不会为已经拥有它们的用户重新插入测试ID,但如果引入了新测试,则会添加新的测试ID。