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 |
|
dirwin26
Yak Posting Veteran
81 Posts |
Posted - 2005-12-14 : 10:56:00
|
| I am trying to insert a row into a table if the input variable doesn't already exist in the table, and if it does exist, I want to do an update of the associated records within the row that correspond to the pre-existing variable. The below code works when it is not within the BEGIN...ELSE...END code, but when it is blocked together, it does add a new record, but it also creates duplicates. ANy suggestions?IF @@rOWcOUNT != 0BEGINInsert into perfor$ (Thedate, Ticker, Shares)values (@thedate, @ticker, @shares)ENDELSEIF @@RowCount = 0BEGINInsert into perfor$ (Thedate, Ticker, Shares)values (@thedate, @ticker, @shares)ENDCheers,Dirwin |
|
|
Srinika
Master Smack Fu Yak Hacker
1378 Posts |
Posted - 2005-12-14 : 11:14:14
|
| Y do u Insert in both cases ? Don't u have to Update in the first condition ?May be this will helpif exists (select * from perfor$ where primaryKeyField = @P1) Update perfor$ set ...... where primaryKeyField = @P1Else Insert into perfor$ (....) values (....) |
 |
|
|
Kristen
Test
22859 Posts |
Posted - 2005-12-14 : 11:14:22
|
You've got two choices I reckon (assuming @thedate is UNIQUE within the [perfor$] table):IF NOT EXISTS (SELECT * FROM [perfor$] WHERE Thedate = @thedate)BEGIN INSERT INTO [perfor$] ...ENDELSE BEGIN UPDATE [perfor$] SET .... WHERE Thedate = @thedateEND orUPDATE [perfor$]SET ....WHERE Thedate = @thedateIF @@ROWCOUNT = 0 -- No update happenedBEGIN INSERT INTO [perfor$] ...END Kristen |
 |
|
|
dirwin26
Yak Posting Veteran
81 Posts |
Posted - 2005-12-14 : 11:37:37
|
| Thanks guys. I ended up using the update then @@RowCount as it was the most similar to my previous code. Cheers! |
 |
|
|
|
|
|
|
|