Search code examples
sqlsql-servert-sqlsql-insertselect-into

Insert into combined with select where


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.


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