0

I would like to insert multiple rows into table, but value of each row will be got from subquery.

Here is pseudo code what do I want:

INSERT INTO Entries VALUES
                (
                    @Date,
                    (SELECT Users.ID 
                    FROM Users),
                    @Enter,
                    @Leave
                )

Where Users has multiple rows of course.

How can I do it?

Tomasz
  • 2,051
  • 3
  • 31
  • 64

2 Answers2

3

You want the insert . . . select form of insert:

INSERT INTO Entries
    SELECT @Date, Users.ID , @Enter, @Leave
    FROM Users;

You should get in the habit of explicitly listing the columns as well; this is good practice when using SQL. Something like:

INSERT INTO Entries(Date, UserId, Enter, Leave)
    SELECT @Date, Users.ID , @Enter, @Leave
    FROM Users;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Try this untested query:

INSERT INTO Entries (SELECT @Date,Users.ID , @Enter,  @Leave FROM Users)
Jens
  • 67,715
  • 15
  • 98
  • 113