SQL Cursor DB2

 

To retrieve data with SQL one row at a time you need to use cursor processing.
Not all relational databases support this, but many do. Here I show this with DB2 and embedded SQL, which is SQL that is "embedded" in a program like COBOL, C, or Java.
Cursor processing is done in several steps:
1. Define the rows you want to retrieve. This is called declaring the cursor.
2. Open the cursor. This activates the cursor and loads the data. Note that defining the cursor doesn't load data, opening the cursor does.
3. Fetch the data into host variables.
4. Close the cursor.

Step 1 - declare the cursor

   
 Declare CursorJamesCameron Cursor for
 Select Film_Title
   From Director_Film_Table,
  Where Director_Last_Name equals "Cameron"
    and Director_First_Name equals "James"
  Order By Film_Title;
Note: That this example fetches only one column - Film_Title - but multiple columns can be fetched simultaneously.

Step 2 - open the cursor

   
 Open CursorJamesCameron;
Note: Not much seems to happen in step 2. Quite a bit really does happen behind the scenes, as cursor CursorJamesCameron is loaded with data in step 2.

Step 3 - fetch the data into a host variable

   
 Fetch CursorJamesCameron 
  Into :CameronMovieName;
Result after the first fetch
Host variable :CameronMovieName will equal "Aliens"
The fetch will take the current sequential row and put it into the host variable. It will then set the next sequential row to the current sequential row.
The host variable must be able to accommodate the data that the cursor has defined. If more than one column is fetched each column must have a correlating host variable.
You can repeat doing the fetch until you finish reading each row. When all rows are read the host variable will be set to null or spaces. Usually a special host variable is set by the dbms to indicate that the cursor is empty. In DB2 the SQLCODE is set to +100.

Step 4 - close the cursor

   
 Close CursorJamesCameron;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值