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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Replacing data in a table

Author  Topic 

Lionheart
Starting Member

41 Posts

Posted - 2009-08-26 : 10:43:05
I have a table which stores data for a particular analysis by quarter. WHat I would like to do is add something to my stored procedure that will check to see if there is already any rows with that quarters name e.g. '209', delete these rows, and then replace them with the new results set.

Can anybody suggest any code I can add to do this?

Example...

Quarter Loss Date
109 100 12/31/08
209 75 2/12/09

I would like for the code to see that there is already the 209 loss, delete this, and then replace with the new 209 loss figures, but leave the rest of the table intact.

Thanks,

LH

DonAtWork
Master Smack Fu Yak Hacker

2167 Posts

Posted - 2009-08-26 : 13:33:35
How about update instead of delete?

http://weblogs.sqlteam.com/jeffs/archive/2008/05/13/question-needed-not-answer.aspx
How to ask: http://weblogs.sqlteam.com/brettk/archive/2005/05/25.aspx

For ultra basic questions, follow these links.
http://www.sql-tutorial.net/
http://www.firstsql.com/tutor.htm
http://www.w3schools.com/sql/default.asp
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-08-27 : 10:45:51
quote:
Originally posted by Lionheart

I have a table which stores data for a particular analysis by quarter. WHat I would like to do is add something to my stored procedure that will check to see if there is already any rows with that quarters name e.g. '209', delete these rows, and then replace them with the new results set.

Can anybody suggest any code I can add to do this?

Example...

Quarter Loss Date
109 100 12/31/08
209 75 2/12/09

I would like for the code to see that there is already the 209 loss, delete this, and then replace with the new 209 loss figures, but leave the rest of the table intact.

Thanks,

LH



you can simply add a check like this

IF EXISTS (SELECT 1 FROM table WHERE Quarter=@quarter)
BEGIN
UPDATE t
SET t.Loss=@loss,
t.Date=@date
FROM table t
WHERE t.quarter=@quarter
END
ELSE
BEGIN
INSERT INTO Table
VALUES (@quarter,@loss,@date)
END
GO
Go to Top of Page
   

- Advertisement -