Question

Let's say we have a query like this (my actual query is similar to this but pretty long)

insert into t1(id1,c1,c2)
select id1,c1,c2 from t2 
where not exists(select * from t1 where t1.id1=t2.id1-1)

Does this query select first and insert all, or insert each selected item one by one? it matters because I'm trying insert a record depending on the previous inserted records and it doesn't seem to work.

Was it helpful?

Solution

First the select query is ran. So it will select all the rows that match your filter. After that the insert is performed. There is not row by row insertion when you use one operation.

Still if you want to do something recursive that will check after each insert you can use CTEs (Common Table Expressions). http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx

OTHER TIPS

This runs a select statement one time and then inserts based on that. It is much more efficient that way.

Since you already know what you will be inserting, you should be able to handle this in your select query rather than looking at what you have already inserted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top