Jcat
宠辱不惊,闲看庭前花开花落~~
posts - 173,comments - 67,trackbacks - 0

1.  top N 问题
在sql server中,top N 问题很容易解决,如下例:从表stbdbdj中选取排序后的第一行数据进行赋值。

在sql中解决方法很简单,在select 后面加上:top n 即可,其中 n 代表行数。

select top 1 @entrust_date = entrust_date,
@entrust_no = entrust_no
from run2k..stbdbdj
where entrust_date = @date
and entrust_no > @entrust_no_q
and report_status = '1'
order by entrust_date,entrust_no;


在oracle中,没有top n这个命令,我们采取把两层查询方式解决:首先,把需要查找的字段值直接进行排序,然后在外面进行第二次查询,并使用rownum决定行数。

select entrust_date,entrust_no
into @entrust_date@entrust_no
from ( select entrust_date,entrust_no
from stbdbdj
where entrust_date = @date
and entrust_no > @entrust_no_q
and report_status = '1'
order by entrust_date,entrust_no )
where rownumber <=1 ;



2. 如何解决结果集返回时,* 和变量同时存在的问题
下面例子表示,在用游标返回结果集时,同时返回一个变量的值,在
sql server 中代码如下所示:
select a.*,b.organ_id
from run2k..stbbp a,run2k..stkaccoarg b
where a.date = @entrust_date
and a.serial_no = @serial_no
and a.branch_no = b.branch_no
and a.exchange_type = b.exchange_type;

但在oracle中却没有这种用法,’*’后面必需跟from。解决方法如下:
1)我们可以把 '*' 变成所需要选择的字段,就是说采用表中需要显示的全部字段表示*。
例如:

open  p_cursor  for
select  branch_no,...,organ_id
where ...

2)如果这个字段或者说变量是从另外一张表中取出来的,同样可以采用下面的办法。

open p_cursor for
select a.*,b.organ_id;
from stkaccoentrust a, stkaccoarg b
where a.branch_no = b.branch_no
and a.exchange_type = b.exchange_type
and a.init_date = v_entrust_date
and a.serial_no = v_serial_no;

3. 外联接问题
sql
<---> oracle
a = *b <---> a(+)= b
a *= b <---> a = b(+)

4. 多条记录求和问题
select sum(A+B+C)
into D
from ...
where ...
group by ...

单条记录求和
select A+B
into C
from ...
where ...

5. case 问题转换
sql:
case client_status
when '0' then '正常'
when '1' then '冻结'
when '2' then '挂失'
when '3' then '销户'
else '未知'
end

oracle:
decode(client_status,'0','正常,'1','冻结','2','挂失','3','销户','未知');

6. char 和 varchar 类型区别:
char 尾部补空格,varchar 尾部不补空格。

7. convert转换问题

sql
---> oracle
convert(char(5),branch_no) ---> to_char(branch_no,'99999')
convert(char(19),count(*)) ---> lpad(to_char(count(*)),19)
convert(varchar(20),serial_no) ---> to_char(serial_no,'999...9' )
总共20个9
lpad(to_char(serial_no),20)


8. charindex(substring,string) ---> instr(string,substring)
子串 父串 ---> 父串 子串

posted on 2007-09-13 15:42 Jcat 阅读(2395) 评论(0)  编辑  收藏 所属分类: Database

只有注册用户登录后才能发表评论。


网站导航: