Thursday, March 29, 2012

Alternate to cursors

Hi,
I have a situation where I am loading data into a staging
table for multiple data sources. My next step is to pick up the
records from the staging table and compare with the data in the
database and based on the certain conditions, decide whether to insert
the data into the database or update an existing record in the
database. I have to do this job as an sp and schedule it to run on the
server as per the requirements. I thought that cursors are the only
option in this situation. Can anyone suggest if there is any other way
to achieve this in SQL 2005 please.

Thanks

SeshadriIn general this is done with two commands, an UPDATE of existing rows
followed by an INSERT of new rows. Very generally:

UPDATE Target
SET cola = A.cola,
colb - A.colb
FROM Staging as A
WHERE Target.keycol = Staging.keycol

INSERT Target
SELECT keycol, cola, colb
FROM Staging as A
WHERE NOT EXISTS
(SELECT * FROM Target as B
WHERE A.keycol = B.keycol)

Whether this fits your requirements is unknown because you didn't
provide much information. It would require knowing at least the table
definitions and keys, as well as the "certain conditions".

Roy Harvey
Beacon Falls, CT

On Mon, 01 Oct 2007 00:12:22 -0700, srirangam.seshadri@.gmail.com
wrote:

Quote:

Originally Posted by

>Hi,
I have a situation where I am loading data into a staging
>table for multiple data sources. My next step is to pick up the
>records from the staging table and compare with the data in the
>database and based on the certain conditions, decide whether to insert
>the data into the database or update an existing record in the
>database. I have to do this job as an sp and schedule it to run on the
>server as per the requirements. I thought that cursors are the only
>option in this situation. Can anyone suggest if there is any other way
>to achieve this in SQL 2005 please.
>
>Thanks
>
>Seshadri

No comments:

Post a Comment