简体   繁体   English

使用T-SQL在游标中使用案例

[英]Using Case in a Cursor with T-SQL

With the code below, I'd like make a "switch", check a field 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? 您想对@Res做什么? And why do you think you need a cursor? 为什么您认为需要光标?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM