Selecting Data based on a specific condition,这是最佳解决方案,使用sql语句或在sybase中使用游标的存储过程

Selecting Data based on a specific condition ,which is the optimal solution using sql statement or stored procedure using cursor in sybase

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'

此查询将 return 表格中的帐户号码列表。基于这个输出。我计划 运行 另一个查询和 select 来自其他表的各种数据。第二个查询包含各种连接以及一个分组依据和排序依据。对于第一个查询中的每个帐号,我只想 select 此查询中的前 1 个数据我没有将其粘贴到此处,因为它是大查询。

我打算使用带有 For 循环的 Cursor 来执行该过程。它是高效的还是仅使用 Sql statements aand Loops 就可以完成。任何 Synatx 都有助于以优化和节省时间的方式完成该过程。

您可以创建一个临时 table 并将第一个 query.Put 标识列中的所有帐号分配给您的临时 table 以便循环遍历 table.

  create table #tmp_account(ID int identity not null,acct_num varchar(100)not null)

现在使用 ID 作为计数器遍历 table。

Declare @vc_id int     
SELECT @vc_id=1 
set rowcount 1
WHILE EXISTS (SELECT  1 FROM #tmp_account  )
begin
select @ac_nm=acct_num from #tmp_account where ID=@vc_id

-- put your 2nd query here..you can insert resultset into another temp table.
delete from #tmp_account where ID=@vc_id
select @vc_id=@vc_id+1
end
set rowcount 0

考虑使用游标。

可在此处找到示例。

http://infocenter.sybase.com/help/in...ses/X61512.htm

declare c_account 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'

@acc_num integer -- or whatever the column type is

begin

create table #foo ( col1 int, col2 varchar(255), col3 datetime)

open c_account 

fetch c_account into @acc_num 

while @@sqlstatus = 0
begin

insert into #foo (col1, col2, col3)
select top 1
col1, col2, col3
from
other_table ot
where
ot.col = @acc_num

fetch c_account into @acc_num
end

close c_account

deallocate c_account

end 
go

希望对您有所帮助,但我怀疑如果您将其作为一系列联接执行此操作可能会更快。