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
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Conditional Update/Insert query

Author  Topic 

juicemousezero
Starting Member

10 Posts

Posted - 2005-12-27 : 16:23:00
I've got this query that seems to me like it should work, but I'm no expert. It's supposed to update an existing record or insert a new record accordingly, depending on whether or not the data from the UI matches a row in the table. It does this by looking at the StandingYear column.

It inserts correctly, and the data is passed through correctly when it I try to update but it simply doesn't update the database. I can't see why in the UI's business logic or in the query... anyone see anything in the query?


CREATE PROCEDURE up_TeamStandingsUpdate

@TeamID as int,
@ConfID as int,
@DivID as int,
@StandingYear as int,
@ConfWins as int,
@ConfLosses as int,
@ConfPercentage as float,
@OverallWins as int,
@OverallLosses as int,
@OverallPercentage as float,
@Rating as float,
@UserID as bigint

AS

If Exists
(
Select StandingYear
From TeamStandings
Where StandingYear = @StandingYear
)

Update TeamStandings

Set StandingYear = @StandingYear, ConfWins = @ConfWins, ConfLosses = @ConfLosses, ConfPercentage = @ConfPercentage, OverallWins = @OverallWins,
OverallLosses = @OverallLosses, OverallPercentage = @OverallPercentage, Rating = @Rating, DateLastModified = GetDate(), UserLastModified = @UserID

Where TeamID = @TeamID AND StandingYear = @StandingYear

ELSE

Insert Into TeamStandings (TeamID, ConfID, DivID, StandingYear, ConfWins, ConfLosses, ConfPercentage, OverallWins, OverallLosses, OverallPercentage, Rating, DateCreated,
UserCreated, DateLastModified, UserLastModified)

Values (@TeamID, @ConfID, @DivID, @StandingYear, @ConfWins, @ConfLosses, @ConfPercentage, @OverallWins, @OverallLosses, @OverallPercentage, @Rating, GetDate(),
@UserID, GetDate(), @UserID)

blindman
Master Smack Fu Yak Hacker

2365 Posts

Posted - 2005-12-27 : 16:55:45
Well, your EXISTS test is going to return true if the StandingYear exists for ANY TEAM in the table, not just the one your are trying to update. You need to include TEAMID in your check as well.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-12-28 : 02:14:31
or

Update table ........
If @@Rowcount = 0 then
Insert into ........

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

juicemousezero
Starting Member

10 Posts

Posted - 2005-12-28 : 09:03:22
I got it working. Thanks guys. And thanks, blindman, for pointing out that egregious error with my Exists clause.
Go to Top of Page
   

- Advertisement -