T-sql:无法理解为什么IF子句永远不会被调用

时间:2011-03-11 21:03:25

标签: sql sql-server tsql

我有一张这样的表:

    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]

我有一些INSERT

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)

然后我意识到我需要改变所有得分,其中0.5应为2等。 所以,我用光标来帮助我。像这样:

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 

在您提出更好的解决方案之前,请告诉我原因 这行永远不会被调用:

UPDATE Scores set Score = 2.0 WHERE Id = @id

2 个答案:

答案 0 :(得分:4)

Update Scores
Set Score = 
  case 
    when Score = 0.5 then 2
    when Score = 4.5 then 5
    --etc...
    else Score
  end;

编辑:对不起,错过了它。

答案是因为提取错误。 把

FETCH NEXT FROM myCursor INTO @id, @score

在光标循环的底部。您在循环外部获取第1行,在顶部再次获取第1行(但在打印出值后)。

答案 1 :(得分:0)

舍入错误是可能的。如果您尝试将分数声明为十进制列(和变量)而不是浮点数,会发生什么?