sybase For循环,包含对select语句中获得的每个结果的Query

时间:2015-03-06 07:16:21

标签: sql sybase sybase-ase

SELECT distinct(a.acct_num)
FROM customer_acct a,
customer_acct_history b LIKE "%000%"    
WHERE a.acct_num *= b.acct_num AND acct_type='C'

根据此查询的输出,它返回许多客户帐号。我正在尝试执行一个选择查询,返回每个帐号的前1名。我打算在第二个sql中链接第一个查询的o / p,例如a.acct_num =(第一个Query的输出)。我希望在循环中执行此操作,并为每个帐号选择前1名。任何有关如何进行的帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

是CURSOR使用的好地方:

declare curs cursor
for 
SELECT distinct(a.acct_num)
FROM customer_acct a,
customer_acct_history b LIKE "%000%"    
WHERE a.acct_num *= b.acct_num AND acct_type='C'

OPEN curs 

DECLARE @acct_num INT

fetch curs into @acct_num

/* now loop, processing all the rows
** @@sqlstatus = 0 means successful fetch
** @@sqlstatus = 1 means error on previous fetch
** @@sqlstatus = 2 means end of result set reached
*/
while (@@sqlstatus != 2)
BEGIN
   SELECT Sometning FROM somwhere where @acct_num = ...
   fetch curs into @acct_num
END

GL!