all groups > sql server (alternate) > october 2007 >
You're in the

sql server (alternate)

group:

Alternate to cursors


Alternate to cursors srirangam.seshadri NO[at]SPAM gmail.com
10/1/2007 12:12:22 AM
sql server (alternate): 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
Re: Alternate to cursors Roy Harvey (SQL Server MVP)
10/1/2007 10:55:36 AM
In 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
[quoted text, click to view]
AddThis Social Bookmark Button