Cursor和if - else if语句问题

时间:2018-04-06 14:07:39

标签: sql tsql

我尝试这样做,

DECLARE cursor CURSOR FOR SELECT col1, col2, col3 ... FROM t1 WHERE...
OPEN cursor
FETCH NEXT FROM cursor INTO @col1, @col2, @col3
WHILE @@FETCH_STATUS = 0
    BEGIN   
       IF(@col1 = 1)
       BEGIN
          update u
          set u.col1=2
          from t1 u
          where ...
       END
       ELSE IF(@col1 <> 1)
       BEGIN
         update u
          set u.col1=3
          from t1 u
          where ...
       END
    FETCH NEXT FROM cursor INTO @col1, @col2, @col3
    END
CLOSE cursor_sala_curso
DEALLOCATE cursor_sala_curso    

问题是,当IF(@ col1 = 1)更新记录时,该记录也进入ELSE IF条件并将记录col1更新为3

假设游标的结果集有5条记录,三条记录的col1值为1,两条记录的col1值为2,上面的代码更新t1 10次,而不是5次。

为什么要进入两个陈述?

如果我更新表的一行,光标的结果集会改变吗?

col1  col2    initial result set of cursor
  1    10
  1    11
  1    12
  2    13
  2    13 

col1  col2    final result set with above code
  3    10
  3    11
  3    12
  3    13
  3    13 

 col1  col2    expected result set with above code
  2    10
  2    11
  2    12
  3    13
  3    13 

感谢您的时间。

2 个答案:

答案 0 :(得分:2)

我相信你在这里不需要cursor。试试这个问题:

update t1
set col1 = case when col1 = 1 then 2 else 3 end

答案 1 :(得分:0)

您声称发生的事情是不正确的 还有其他事情发生,但你非常关注

declare @T table (pk int identity primary key, col1 int);
insert into @T (col1) values (1), (2), (1), (3);
select * from @T;
declare @pk int, @col1 int;
DECLARE cursr CURSOR FOR SELECT pk, col1 FROM @T
OPEN cursr
FETCH NEXT FROM cursr INTO @Pk, @col1
WHILE @@FETCH_STATUS = 0
    BEGIN   
       IF(@col1 = 1)
       BEGIN
          update @T 
          set col1 = 2
          where pk = @pk
       END
       ELSE IF(@col1 <> 1)
       BEGIN
          update @T 
          set col1 = 5
          where pk = @pk
       END
    FETCH NEXT FROM cursr INTO @Pk, @col1
    END
CLOSE cursr
DEALLOCATE cursr;
select * from @T;

pk          col1
----------- -----------
1           1
2           2
3           1
4           3

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

pk          col1
----------- -----------
1           2
2           5
3           2
4           5