开发者

Using Case in a Cursor with T-SQL

With the code below, I'd like make a "switch", check a field开发者_JAVA百科 value and set another field depending of the value. I have to do this for each row then it's in a cursor. But something is missing ...

Thanks for your help

DECLARE @Res int
OPEN MyCursor;

 FETCH NEXT FROM MyCursor 
 INTO @field1, @field2, @field3, @field4

 WHILE @@FETCH_STATUS = 0
 BEGIN
  SELECT
  CASE @field1
   WHEN 'A' THEN @Res = 1
   WHEN 'B' THEN @Res = 2
   WHEN 'C' THEN @Res = 3
   WHEN 'D' THEN @Res = 4
   WHEN 'E' THEN @Res = 5
  END

  FETCH NEXT FROM MyCursor 
  INTO @field1, @field2, @field3, @field4

 END

CLOSE MyCursor;


To fix your immediate issue, you'd do this:

SELECT @Res = 
  CASE @field1
   WHEN 'A' THEN 1
   WHEN 'B' THEN 2
   WHEN 'C' THEN 3
   WHEN 'D' THEN 4
   WHEN 'E' THEN 5
  END

What do you want to do with @Res? And why do you think you need a cursor?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜