Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Foreach insert statement based on where clause

I have a scenario where I have thousands of Ids (1-1000), I need to insert each of these Ids once into a table with another record.

For example, UserCars – has columns CarId and UserId

I want to INSERT each user in my Id WHERE clause against CarId 1.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

INSERT INTO [dbo].[UserCars]
           ([CarId]
           ,[UserId])
     VALUES
           (
           1,
           **My list of Ids**  
            )

I’m just not sure of the syntax for running this kind of insert or if it is at all possible.

>Solution :

As you write in the comments that my list of Ids is coming from another table, you can simply use select into with a select clause

See this for more information

insert into UserCars (CarID, UserID) 
select CarID, UserID 
from   othertable

In the select part you can use joins and whatever you need, complex queries are allowed as long as the columns in the result match the columns (CarID, UserID)

or even this to keep up with your example

insert into UserCars (CarID, UserID) 
select 1, UserID 
from   dbo.User
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading