1

I need to create a static "copy" of values from one table and store them in another.

The best way I know how to do this is to get the values from the db to my application, loop through them and concatenate multiple INSERT statements, then execute the query.

Is there a way to do this without the round trip between application and database?

I was hoping something like this would work:

INSERT INTO dbo.StudentProject 
VALUES (SELECT StudentID, ProjectID 
        FROM dbo.StudentProjectSimulation
        WHERE SimulationID = 1)

but it doesn't.

(everything is an int so no worries there)

1

3 Answers 3

2

You're very close:

INSERT INTO dbo.StudentProject 
SELECT StudentID, ProjectID 
FROM dbo.StudentProjectSimulation
WHERE SimulationID = 1
Sign up to request clarification or add additional context in comments.

2 Comments

It is is poor practice to ever do an insert without defining the columns you want the insert to affect. If the table changes your code breaks. @BZN_DBer has the answer that should have been accepted.
I agree, but I was simply making as few changes to the OP's query as was needed to answer his question.
2

Just drop values from the insert into clause.

Insert Into dbo.StudentProject 
Select StudentID, ProjectID  
From dbo.StudentProjectSimulation 
Where SimulationID = 1;

1 Comment

i liked your formatting better, though not much different than the others.
2

Alternatively to explicitly define the columns to insert into use the following where you substitute Student_Col and ProjectID_Col for appropriate column names in dbo.StudentProject

Insert Into dbo.StudentProject 
  (
    Student_Col,
    ProjectID_Col
  )
Select 
  StudentID, 
  ProjectID 
From dbo.StudentProjectSimulation 
Where SimulationID = 1

Comments

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.