Reputation: 23
I have a table like this:
CREATE TABLE [dbo].[Scores](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Score] [float] NULL,
CONSTRAINT [PK_Scores] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
And I have some INSERTs
INSERT INTO Scores (Score) VALUES ( 0.5)
INSERT INTO Scores (Score) VALUES ( 2)
INSERT INTO Scores (Score) VALUES ( 3)
INSERT INTO Scores (Score) VALUES ( 4.5)
Then I realize that I need to change all scores where 0.5 should be 2 etc. So, I use a cursor to help me with that. Like this:
DECLARE @id int
DECLARE @score float
DECLARE myCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT Id, Score
FROM [dbo].[Scores]
OPEN myCursor FETCH NEXT FROM myCursor INTO @id, @score
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Id: ' PRINT @id
PRINT 'Score: ' PRINT @score
-- do your tasks here
FETCH NEXT FROM myCursor INTO @id, @score
IF @score = 2
BEGIN
UPDATE Scores set Score = 3.0 WHERE Id = @id
END
IF @score = 3
BEGIN
UPDATE Scores set Score = 4.0 WHERE Id = @id
END
IF @score = 0.5
BEGIN
UPDATE Scores set Score = 2.0 WHERE Id = @id
END
IF @score = 4.5
BEGIN
UPDATE Scores set Score = 5.0 WHERE Id = @id
END
END
CLOSE myCursor DEALLOCATE myCursor
Before you propose a nicer solution, please tell me why this row never gets called:
UPDATE Scores set Score = 2.0 WHERE Id = @id
Upvotes: 2
Views: 99
Reputation: 52788
Update Scores
Set Score =
case
when Score = 0.5 then 2
when Score = 4.5 then 5
--etc...
else Score
end;
Edit: Sorry, missed the point of it.
Answer is because the fetches are wrong. Put the
FETCH NEXT FROM myCursor INTO @id, @score
At the bottom of the cursor loop. You are fetching row 1 once outside the loop and once again at the top (but after printing out the values).
Upvotes: 4
Reputation: 14447
Rounding error is a possibility. What happens if you try declaring Score as a decimal column (and variable) rather than as a float?
Upvotes: 0