Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
PeterG
Posting Yak Master
156 Posts |
Posted - 2010-02-22 : 18:20:37
|
| I have Table1:id position status1 teacher active2 teacher disabled2 support activewith id and position as primary keys.I'd like to insert a set of data into this table. My problem is I cannot insert a duplicate record because of the primary keys.I have 2 sets of records that I get via select statements. One contains all the records and the other just the existing records in Table1. My set of all records look like this:id position status1 teacher active1 support inactive1 student disabled2 teacher disabled2 support active2 student activeHow do I do this via SQL? all records minus existing records equals records that don't exist in the table (records in red) |
|
|
Bustaz Kool
Master Smack Fu Yak Hacker
1834 Posts |
Posted - 2010-02-22 : 19:58:55
|
| [CODE]insert into <TargetTable>select <columns>from <SourceTable>left outer join <TargetTable>on <sourceTable.<PrimaryKey> = <TargetTable>.<PrimaryKey>where <TargetTable>.<PrimaryKey> is NULL[/CODE]BTW...1) The same thing can be done using a NOT EXISTS predicate2) The case where the primary key does exist is potentially an UPDATE condition depending on your business rules3) In SQL 2008 the MERGE statement can handle both the INSERT and UPDATE in a single query=======================================Few things are harder to put up with than the annoyance of a good example. (Mark Twain) |
 |
|
|
|
|
|