Collection 游标允许您访问集合变量的单个元素。 要声明 Collection 游标,请使用 DECLARE 语句并包括在您将其与游标关联的 INSERT 语句中的“集合派生的表”段。一旦您以 OPEN 语句打开 Collection 游标,该游标可将元素放在集合变量中。
CREATE TABLE children ( age SMALLINT, name VARCHAR(30), fav_colors SET(VARCHAR(20) NOT NULL) );
EXEC SQL BEGIN DECLARE SECTION; client collection child_colors; char *favorites[] ( "blue", "purple", "green", "white", "gold", 0 ); int a = 0; char child_name[21]; EXEC SQL END DECLARE SECTION; EXEC SQL allocate collection :child_colors; /* 获取 fav_colors 列的结构,对于 untyped * child_colors 集合变量 */ EXEC SQL select fav_colors into :child_colors from children where name = :child_name; /* 为 child_colors 集合变量声明插入游标 * 并打开此游标 */ EXEC SQL declare colors_curs cursor for insert into table(:child_colors) values (?); EXEC SQL open colors_curs; /* 使用 PUT 来将 favorite-color 值收集 * 到游标内 */ while (fav_colors[a])
{ EXEC SQL put colors_curs from :favorites[:a]; a++ ... } /* 刷新游标内容到集合变量 */ EXEC SQL flush colors_curs; EXEC SQL update children set fav_colors = :child_colors; EXEC SQL close colors_curs; EXEC SQL deallocate collection :child_colors;
在 FLUSH 语句执行之后,集合变量 child_colors 包含元素 {"blue", "purple", "green", "white", "gold"}。在此程序片断的末尾的 UPDATE 语句将新的集合保存到数据库的 fav_colors 列内。没有此 UPDATE 语句,就不会将新的集合插入到集合列。