akoxi
akoxi

Reputation: 245

SQL insert into select query

I have 2 tables.

Attendance table with 2 columns and Records table with 1 column

+----------------------+
|       Attendance     |
+----------------------+
| EmployeeID   | Hours |
+----------------------+ 

+--------------+
|   Records    |
+--------------+
| EmployeeID   |
+--------------+
|     1        |
|     2        |
|     3        |
+--------------+ 

I want a query that will insert all employeeID from Records table into EmployeeID in the Attendance table with a value of 8 in Hours column.

Like this:

+----------------------+
|       Attendance     |
+----------------------+
| EmployeeID   | Hours |
|----------------------|
|      1       |   8   |
|      2       |   8   |
|      3       |   8   |
+----------------------+

I can't understand the code that I searched so I end up asking :)

By the way, I'm using SQL Server.

Upvotes: 3

Views: 617

Answers (2)

Zanon
Zanon

Reputation: 30800

Just use:

INSERT INTO Attendance (EmployeeID, Hours) 
    SELECT EmployeeID, 8 FROM Records;

Upvotes: 0

zkanoca
zkanoca

Reputation: 9928

Recently, I have made a query like that you want.

INSERT INTO Attendence (EmployeeID, Hours) 
    SELECT EmployeeID, 8 
    FROM Records 
    WHERE EmployeeID > 0

WHERE condition is for SELECT, not for INSERT INTO. This query will copy all EmployeeID's to Attendence table where EmployeeID is greater than 0.

SELECT EmployeeID, 8 FROM Records

will return something like

(1,8),(2,8),(3,8)

Upvotes: 1

Related Questions