简体   繁体   中英

Is the query result set of the select sub-query static in a T-Sql Insert Into select..?

source_tbl: email_addr, role

target_tbl: email_addr, roles

source_tbl can have many email addresses. target_tbl can have one distinct email address (the role in source_tbl is consolidated into roles in target_tbl - just fyi)

My concern is not duplicating email address in target_tbl (no constraints are in place by dba setup)

I have a suspicion that the the sub-query inside a Insert into Select is done once, and that result set is then used by the insert. If this is the case then a query like this won't work:

insert into target_tbl 
 ( email_addr, roles)
select 
 src.email_addr,
 src.role
from source_tbl src
where src.email_address not in ( select email_addr from target_tbl)

can't find anything that confirms my suspicion, checking to see if someone can point me to documentation that gives me this confirmation

Are you asking whether the following sub query is re-evaluated for each row, and so takes into account email addresses previously added by the same statement?

 where src.email_address not in ( select email_addr from target_tbl)

If so the answer is "no".

It will be evaluated at the start and spooled somewhere as a result of Halloween Protection (unless SQL Server manages to come up with a plan that guarantees these semantics without a spool but the answer is still the same).

So if the SELECT query returns, say, 3 rows for abc@dfg.com and that email address doesn't already exist in the target table all three rows will be inserted.

You can either change the SELECT to only pick one row per email or add a unique constraint to the table with ignore_dup_key on to just preserve the first (arbitrary) one encountered. Likely the first option is more useful as it gives you control over which one is kept.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM