INSERT INTO and UNION

  • Hi all,

    Not a problem more of a 'why does it do that'

    I have a script that does this:

    SELECT

    some stuff

    INTO

    new table

    FROM

    source

    WHERE

    filters

    UNION

    Another Select etc here

    INSERT INTO

    same table as above

    SELECT

    From, where etc

    Now the question.

    The UNION is not doing it's distinct thing on the last INSERT INTO. I know this because I have 2 exact same records in the resulting table

    No bad thing, this is exactly what I wanted it to do.

    Excuse my ignorance but is the INSERT INTO ignoring what happens before it ?

  • From the little sampling of data you provided, it looks like the script is doing exactly what you want it to do. The first Select..Into clause is using the Union statement, so any duplicates will be filtered out. The second statement (Insert Into) is just inserting records into the same table. The UNION statement doesn't affect this statement since it's not in it. If you can provide some table layouts, sample data and expected results, we can see what exactly you're doing

    For better, quicker answers, click on the following...
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

    For better answers on performance questions, click on the following...
    http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • Thanks Mike.

    You have answered my question.

    I realise now that the INSERT INTO is the start of a new SQL statement so the UNION has nothing to do with it.

    Time to do a bit more RTFM 🙂

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply