1

I have one staging table and want to insert data to Main table, so i want to check while inserting data from staging to Main table, if exists then update the records else insert as new records. Here the issue is both the staging as well as Main table does not have any key column based on which i can compare values.

Is it possible to do without having key columns i.e. primary key on both the tables? if yes, please, suggest me how.

Thanks in advance.

11
  • 1
    Do you mean that there isn't a primary key created on those tables, or that there is no "logical" primary key on wich to identified every row?
    – Lamak
    Dec 12, 2011 at 15:01
  • 1
    I would recommend having unique identifiers on all your tables just for this kind of situation. You cannot check safely and precisely without them.
    – CSharpened
    Dec 12, 2011 at 15:02
  • 1
    How will you know if you should update or insert if you don't have any columns that you can use to compare with? Dec 12, 2011 at 15:02
  • 2
    @Anders UP It's a database table in the "physical" sense, that it's an object called a table in a DBMS. But in a "logical" sense, it is not a relational table. en.wikipedia.org/wiki/Table_%28database%29 - "Each row is identified by the values appearing in a particular column subset which has been identified as a candidate key."
    – N West
    Dec 12, 2011 at 15:22
  • 2
    @AndersUP: a table without a primary key is just a (steaming) pile of data - not what I call a real table. That might be OK for a temporary / intermediate / staging table, e.g. for loading data - but anything you store permanently just needs a primary key...
    – marc_s
    Dec 12, 2011 at 15:26

2 Answers 2

4

If there is no unique key or set of data within a row to define uniqueness, then no.

The set of data can be a combination of the data in each column, creating a sum of parts which will provide uniqueness; however without exposure to your data you would need to make that decision.

0

You write the WHERE-clause to include all the fields that make your record unique (ie. the fields that decide whether the record is new or should be updated.)

Take a look at this article (http://blogs.msdn.com/b/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx) for hints on how to construct it.

If you are using SQL Server 2008r2, you could also use the MERGE statement - I haven't tried it on tables without keys, so I don't know whether it would work for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.