2

It is possible to insert multiple rows in one table using values from select statement?
an example:

INSERT INTO SomeTable (UserID, ModuleID, ModuleRights) VALUES 
      (u.UserId, 1, 15),
      (u.UserId, 2, 1),
      (u.UserId, 4, 3),
      (u.UserId, 8, 7)
SELECT * FROM Users u
1

3 Answers 3

7

Yes, but you need to be careful how you do it. In this case, it appears you want a cross join:

INSERT INTO SomeTable (UserID, ModuleID, ModuleRights)
    SELECT u.UserId, v.ModuleID, v.ModuleRights
    FROM Users u CROSS JOIN
         (VALUES (1, 15), 
                 (2, 1), 
                 (4, 3), 
                 (8, 7)
         ) v(ModuleID, ModuleRights);
Sign up to request clarification or add additional context in comments.

1 Comment

Best answer. Thanks a lot.
0
INSERT INTO SomeTable (UserID, ModuleID, ModuleRights) 
SELECT u.UserID, u.ModuleID, u.ModuleRights FROM Users u;

If your ModuleID and ModuleRights are not part of the users table then insert nulls or dummy values and replace on needed condition.

Comments

-1

insert multiple rows using select statment

insert into tbl_teacher
    (fName,
    lName,
    email,
    cNo)
    select s.fName,
           s.lName,
           s.email,
           s.cNo 
    from tbl_student s

1 Comment

Downvoted because this is too similar to vtuhtan's answer which was submitted 16 minutes earlier. The answer is also poorly formatted, but I wouldn't downvote for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.