首页 > 数据库 > Oracle > 正文

从SQL SERVER 向ORACLE 8迁移的技术实现方案

2024-08-29 13:30:11
字体:
来源:转载
供稿:网友

 不知道从哪里得到这个文档,有用就放上来了 -gwb

 
数据库端sql语法的迁移
以下为常用的sql语法迁移,包括数据类型、id列向sequence迁移、表(主键、外键、check、unique、default、index)、游标、存储过程、函数、触发器、常用sql语法与函数几个方面,考虑sql server的实际情况,没有涉及oracle特有的package、exception等。在以下的描述中,将sql server的transact-sql简称为t-sql。在oracle中,其语法集称为pl/sql。

 
<一> 数据类型的迁移
    <1>、oracle端语法说明

在oracle中,分析其数据类型,大致可分为数字、字符、日期时间和特殊四大类。其中,数字类型有number;字符类型有char与varchar2;日期时间类型只有date一种;除此之外,long、raw、long raw、blob、clob和bfile等数据类型都可视为特殊数据类型。

 

    <2>、sql server端语法说明

在sql server中,参照上面对oracle的划分,数据类型也大致可分为数字、字符、日期时间和特殊四大类。数字类型又可分为精确数值、近似数值、整数、二进制数、货币等几类,其中,精确数值有decimal[(p[, s])]与numeric[(p[, s])];近似数值有float[(n)];整数有int、smallint、tinyint;二进制数有binary[(n)]、varbinary[(n)];货币有money、smallmoney。字符类型有char[(n)]与varchar[(n)]。日期时间类型有datetime、smalldatetime。除此之外,bit、timestamp、text和image、binary varing等数据类型都可视为特殊数据类型。

 

<3>、从sql server向oracle的迁移方案

比较oracle与sql server在数据类型上的不同,当从sql server向oracle迁移时,可以做如下调整:

 

sql server

oracle

数字类型

decimal[(p[, s])]

number[(p[, s])]

numeric[(p[, s])]

number[(p[, s])]

float[(n)]

number[(n)]

int

number

smallint

number

tinyint

number

money

number[19,4]

smallmoney

number[19,4]

字符类型

char[(n)]

char[(n)]

varchar[(n)]

varchar2[(n)]

日期时间类型

datetime

date

smalldatetime

date

其它

text

clob

image

blob

bit

number(1)

方法:

公司原系统中的money 用于金额时转换用number(14,2);用于单价时用 number(10,4)代替;
<二> id列向sequence迁移
    <1>、sql server端语法说明

在sql server中,可以将数据库中的某一字段定义为identity列以做主键识别,如:

    jlbh        numeric(12,0)        identity(1,1)        /*记录编号字段*/

    constraint  pk_tbl_example  primary key  nonclustered (jlbh)  /*主键约束*/

在这里,jlbh是一个id列,在向具有该列的表插入记录时,系统将从1开始以1的步长自动对jlbh的值进行维护。

 

    <2>、oracle端语法说明

但在oracle中,没有这样的id列定义,而是采用另一种方法,即创建sequence。

如:

/*--1、创建各使用地区编码表--*/

drop table lt_area;

create table lt_area

  (

  area_id    number(5,0)      not null,   /*地区编码*/

  area_name    varchar2(20)     not null,   /*地区名称*/

  constraint pk_lt_area primary key(area_id)

 );

 

/*--2、创建sequence,将列area_id 类id化--*/

drop sequence seq_lt_area;

create sequence seq_lt_area increment by 1    /*该sequence以1的步长递增*/

 start with 1 maxvalue 99999;                /*从1开始,最大增长到99999*/

 

/*--3、实际操作时引用sequence的下一个值--*/

insert into lt_area(area_id, area_name) values(seq_lt_area.nextval, '深圳');

insert into lt_area(area_id, area_name) values(seq_lt_area.nextval, '广州');

insert into lt_area(area_id, area_name) values(seq_lt_area.nextval, '北京');

 

/*--4、新插入连续三条记录后,下一条语句运行后,‘上海’地区的area_id为4--*/

insert into lt_area(area_id, area_name) values(seq_lt_area.nextval, '上海');

 

   <3>、从sql server向oracle的迁移方案

 

根据以上分析,当从sql server向oracle迁移时,可以做如下调整:

1、去掉建表语句中有关id列的identity声明关键字;

2、创建sequence,将此sequence与需类id化的列对应;

3、在insert语句中对相应列引用其sequence值:sequencename.nextval

实际上,处理以上情况在oracle中采用的方法为对有自动增长字段的表增加一插入前触发器(具体资料见后“触发器”一节),如下:

create or replace trigger genaerateareaid

before insert on lt_area

for each row

        select seq_lt_area.nextval into :new.id

        from dual;

begin

end genaerateareaid;

genaerateareaid实际上修改了伪记录:new的area_id值。 :new最有用的一个特性----当该语句真正被执行时,:new中的存储内容就会被使用。所以系统每次都能自动生成新的号码。
<三> 表(主键、外键、check、unique、default、index)
    <1>、sql server端语法说明

有如下sql server语句:

/* ------------------------ 创建employee 表------------------------ */

if exists(select 1 from sysobjects where name = ‘employee’

          and type = ‘u’)

        drop table employee

go

 

create table employee

(

    emp_id   empid    /*empid为用户自定义数据类型*/

    /*创建自命名主键约束*/

        constraint pk_employee primary key nonclustered

    /*创建自命名check约束*/

        constraint ck_emp_id check (emp_id like

                     '[a-z][a-z][a-z][1-9][0-9][0-9][0-9][0-9][fm]' or

                     emp_id like '[a-z]-[a-z][1-9][0-9][0-9][0-9][0-9][fm]'),

        /* check约束说明:each employee id consists of three characters that

        represent the employee's initials, followed by a five

        digit number ranging from 10000 to 99999 and then the

        employee's gender (m or f). a (hyphen) - is acceptable

        for the middle initial. */

    fname     varchar(20)      not null,

    minit     char(1)         null,

    lname     varchar(30)      not null,

 

    ss_id     varchar(9)        unique,    /*创建唯一性约束*/

 

job_id    smallint            not null

        default 1,            /*设定default值*/

    job_lvl tinyint

       default 10,            /*设定default值*/

        /* entry job_lvl for new hires. */

    pub_id   char(4)         not null

        default ('9952')        /*设定default值*/

        references publishers(pub_id),  /*创建系统命名外键约束*/

        /* by default, the parent company publisher is the company

        to whom each employee reports. */

    hire_date        datetime       not null

        default (getdate()),        /*设定default值*/

        /* by default, the current system date will be entered. */

    constraint fk_employee_job foreign key (job_id)

        references jobs(job_id)        /*创建自命名外键约束*/

)

go

   

    /* --------------------- 创建employee表上的index --------------------- */

if exists (select 1 from sysindexes

               where name = 'emp_pub_id_ind')

    drop index employee. emp_pub_id_ind

go

 

    create index emp_pub_id_ind

        on employee(pub_id)

go

 

    <2>、oracle端语法说明

在oracle端的语法如下:

    /* ---------------------- 创建employee 表---------------------- */

    drop table employee;

 

create table employee

(

    emp_id    varchar2(9)  /*根据用户自定义数据类型的定义调整为varchar2(9)*/

    /*创建自命名主键约束*/

        constraint pk_employee primary key nonclustered

    /*创建自命名check约束*/

        constraint ck_emp_id check (emp_id like

                     '[a-z][a-z][a-z][1-9][0-9][0-9][0-9][0-9][fm]' or

                     emp_id like '[a-z]-[a-z][1-9][0-9][0-9][0-9][0-9][fm]'),

        /* check约束说明:each employee id consists of three characters that

        represent the employee's initials, followed by a five

        digit number ranging from 10000 to 99999 and then the

        employee's gender (m or f). a (hyphen) - is acceptable

        for the middle initial. */

    fname     varchar2(20)     not null,

    minit     varchar2(1)      null,

    lname     varchar2(30)     not null,

 

    ss_id     varchar2(9)      unique,    /*创建唯一性约束*/

 

job_id    number(5,0)      not null

        /*这里考虑了smallint的长度,也可调整为number*/

        default 1,            /*设定default值*/

    job_lvl     number(3,0)

        /*这里考虑了tinyint的长度,也可调整为number*/

       default 10,            /*设定default值*/

        /* entry job_lvl for new hires. */

    pub_id  varchar2(4)        not null

        default ('9952')        /*设定default值*/

        references publishers(pub_id),  /*创建系统命名外键约束*/

        /* by default, the parent company publisher is the company

        to whom each employee reports. */

    hire_date        date            not null

        default sysdate,        /*设定default值*/

        /*这里,sql server的getdate()调整为oracle的sysdate*/

        /* by default, the current system date will be entered. */

    constraint fk_employee_job foreign key (job_id)

        references jobs(job_id)        /*创建自命名外键约束*/

);

   

    /* -------------------- 创建employee表上的index -------------------- */

drop index employee. emp_pub_id_ind;

    create index emp_pub_id_ind on employee(pub_id);

 

<3>、从sql server向oracle的迁移方案

比较这两段sql代码,可以看出,在创建表及其主键、外键、check、unique、default、index时,sql server 与oracle的语法大致相同,但时迁移时要注意以下情况:

    (1) oracle定义表字段的default属性要紧跟字段类型之后,如下:

    create table mz_ghxx

  ( ghlxh  number primay key ,

    rq     date   default sysdate not null,

  ….

  )

  而不能写成

    create table mz_ghxx

  ( ghlxh  number primay key ,

    rq     date   not null default sysdate,

  ….

  )

(2)t-sql定义表结构时,如果涉及到用默认时间和默认修改人员,全部修改如下:

 zhxgrq     date   default sysdate null,

 zhxgr      char(8) default ‘futian’ null,

(3)如表有identity定段,要先将其记录下来,建完表之后,马上建相应的序列和表触发器,并作为记录。
<四> 游标
    <1>、sql server端语法说明

1、declare cursor语句

       语法:

           declare cursor_name [insensitive] [scroll] cursor

    for select_statement

  [for {read only | update [of column_list ]}]

       例:

       declare  authors_cursor  cursor  for

        select  au_lname, au_fname

          from  authors

         where  au_lname like ‘b%’

      order by  au_lname, au_fname

 

2、open语句

   语法:

       open  cursor_name

       例:

       open authors_cursor

 

3、fetch语句

   语法:

       fetch

             [ [ next | prior | first | last | absolute n | relative n ]

           from  cursor_name

         [into @variable_name1, @variable_name2,… ]

       例:

       fetch next from authors_cursor

                  into @au_lname, @au_fname

 

4、close语句

   语法:

       close  cursor_name

       例:

       close authors_cursor

 

5、deallocate语句

   语法:

       deallocate  cursor_name

       例:

       deallocate authors_cursor

 

6、游标中的标准循环与循环终止条件判断

   (1)fetch next from authors_cursor into @au_lname, @au_fname

 

   (2)-- check @@fetch_status to see if there are any more rows to fetch.

        while @@fetch_status = 0

        begin

           -- concatenate and display the current values in the variables.

           print "author: " + @au_fname + " " +  @au_lname

 

           -- this is executed as long as the previous fetch succeeds.

               fetch next from authors_cursor into @au_lname, @au_fname

        end

 

   (3)close authors_cursor

7、隐式游标

mssqlserver中对于数据操纵语句受影响的行数,有一个全局的变量:@@rowcount,其实它是一个隐式的游标,它记载了上条数据操纵语句所影响的行数,当@@rowcount小于1时,表时,上次没有找到相关的记录,如下:

update students set lastname = ‘john’ where student_id = ‘301’

if @@rowcount < 1 then

insert into students values (‘301’,’stdiv’,’john’,’996-03-02’)

表示如果数据表中有学号为“301”的记录,则修改其名字为“john”,如果找不到相应的记录,则向数据库中插入一条“john”的记录。

8、示例:

-- declare the variables to store the values returned by fetch.

declare @au_lname varchar(40), @au_fname varchar(20)

 

declare  authors_cursor  cursor  for

 select  au_lname, au_fname

   from  authors

  where  au_lname like ‘b%’

   order by  au_lname, au_fname

 

open authors_cursor

 

-- perform the first fetch and store the values in variables.

-- note: the variables are in the same order as the columns

-- in the select statement.

 

fetch next from authors_cursor into @au_lname, @au_fname

 

-- check @@fetch_status to see if there are any more rows to fetch.

while @@fetch_status = 0

 

begin

  -- concatenate and display the current values in the variables.

      print "author: " + @au_fname + " " +  @au_lname

 

      -- this is executed as long as the previous fetch succeeds.

      fetch next from authors_cursor into @au_lname, @au_fname

end

 

close authors_cursor

 

deallocate authors_cursor

 

    <2>、oracle端语法说明

1、  declare cursor语句

       语法:

    cursor  cursor_name  is  select_statement;

       例:

           cursor  authors_cursor  is

       select  au_lname, au_fname

         from  authors

        where  au_lname like ‘b%’

     order by  au_lname, au_fname;

 

2、  open语句

   语法:

       open  cursor_name

       例:

       open authors_cursor;

 

3、  fetch语句

   语法:

       fetch  cursor_name  into  variable_name1 [, variable_name2,… ] ;

       例:

       fetch  authors_cursor  into  au_lname, au_fname;

 

4、  close语句

   语法:

       close  cursor_name

       例:

       close authors_cursor;

 

5、简单游标提取循环结构与循环终止条件判断

   1> 用%found做循环判断条件的while循环

     (1)fetch  authors_cursor  into  au_lname, au_fname ;

     (2)while authors_cursor%found loop

             -- concatenate and display the current values in the variables.

                 dbms_output.enable;

             dbms_output.put_line( ‘author: ‘ || au_fname || ‘ ‘ || au_lname) ;

             fetch  authors_cursor  into  au_lname, au_fname ;

          end loop ;

     (3)close authors_cursor ;

 

   2> 用%notfound做循环判断条件的简单loop...end loop循环

     (1)open authors_cursor;

     (2)loop

             fetch  authors_cursor  into  au_lname, au_fname ;

                 -- exit loop when there are no more rows to fetch.

             exit  when  authors_cursor%notfound ;

             -- concatenate and display the current values in the variables.

             dbms_output.enable;

             dbms_output.put_line( ‘author: ‘ || au_fname || ‘ ‘ || au_lname) ;

          end loop ;

     (3)close authors_cursor ;

3>用游标式for循环,如下:

declare

                cursor c_historystudents is

                select id,first_name,last_name

                from students

                where major = ‘history’

begin

              for v_studentdata in c_historystudents loop

              insert into registered_students

(student_id,first_name,last_name,department,course)

values(v_studentdata.id,v_studentdata.first_name, v_studentdata.last_name,’his’,301);

              end loop;

commit;

end;

首先,记录v_studentdata没有在块的声明部分进行声明,些变量的类型是c_historystudents%rowtype,v_studentdata的作用域仅限于此for循环本身;其实,c_historystudents以隐含的方式被打开和提取数据,并被循环关闭。

6、隐式游标sql%found 与sql%notfound

        与mssql server 一样,oracle也有隐式游标,它用于处理insert、delete和单行的select..into语句。因为sql游标是通过pl/sql引擎打开和关闭的,所以open、fetch和close命令是无关的。但是游标属性可以被应用于sql游标,如下:

begin

        update rooms

          set number_seats = 100

        where room_id = 9990;

--如果找不相应的记录,则插入新的记录

        if sql%notfound then

            insert into rooms(room_id,number_seats)

            values (9990,100)

end if

    end;

7、示例:

-- declare the variables to store the values returned by fetch.

-- declare the cursor authors_cursor.

declare

   au_lname  varchar2(40) ;

   au_fname  varchar2(20) ;

       cursor  authors_cursor  is

   select  au_lname, au_fname

     from  authors

    where  au_lname like ‘b%’

 order by  au_lname, au_fname;

 

begin

   open authors_cursor;

   fetch  authors_cursor  into  au_lname, au_fname ;

   while authors_cursor%found loop

      -- concatenate and display the current values in the variables.

          dbms_output.enable;

      dbms_output.put_line( ‘author: ‘ || au_fname || ‘ ‘ || au_lname) ;

      fetch  authors_cursor  into  au_lname, au_fname ;

   end loop ;

 

   close authors_cursor ;

end ;

 

    <3>、从sql server向oracle的迁移方案

        比较上述sql代码,在迁移过程中要做如下调整:

        (1)t-sql对cursor的声明在主体代码中,而pl/sql中对cursor的声明与变

             量声明同步,都要在主体代码(begin关键字)之前声明,所以在迁移时要

             将游标声明提前,mssql server的cursor定义后的参数省去;

        (2)对cuosor操作的语法中pl/sql没有t-sql里deallocate cursor这一部分,

             迁移时要将该部分语句删除。

        (3)pl/sql 与t-sql对游标中的循环与循环终止条件判断的处理不太一样,根

             据前面的讨论并参考后面对两种语法集进行控制语句对比分析部分的叙述,

             建议将t-sql中的游标提取循环调整为pl/sql中的while游标提取循环结

             构,这样可保持循环的基本结构大致不变,同时在进行循环终止条件判断时

             要注意将t-sql中的对@@fetch_status全局变量的判断调整为对

             cursor_name%found语句进行判断。

        (4)对于t-sql,没有定义语句结束标志,而pl/sql用“;”结束语句。

(5)对于原mssql server类型的游标,如果游标取出的值没有参与运算的,全部采用for循环方式来替换;而对于取出的值还要进行其它运算的,可以采用直接在定义变量位置定义变量。

 (6)mssql中对于同一游标重复定义几次的情况在oracle中可通过游标变量来解决.如下:

mssql server 中:

declare cur_ypdm cursor for

select * from yp

open cur_yp

fetch cur_yp into @yp,@mc …

while @@fetch_status <> -1

begin

  if @@fetch_status <> -2

  begin

    ….

  end

  fetch cur_yp into @yp,@mc …

end

close cur_ypdm

deallocate cur_ypdm

..

declare cur_ypdm cursor for

select * from yp where condition 1

open cur_yp

fetch cur_yp into @yp,@mc …

while @@fetch_status <> -1

begin

  if @@fetch_status <> -2

  begin

    ….

  end

  fetch cur_yp into @yp,@mc …

end

close cur_ypdm

deallocate cur_ypdm

..

declare cur_ypdm cursor for

select * from yp  where condition 2

open cur_yp

fetch cur_yp into @yp,@mc …

while @@fetch_status <> -1

begin

  if @@fetch_status <> -2

  begin

    ….

  end

  fetch cur_yp into @yp,@mc …

end

close cur_ypdm

deallocate cur_ypdm

..

在程序中,三次定义同一游标cur_yp

在迁移过程中,最好先定义一游标变量,在程序中用open打开,如下:

declare

  type cur_type is ref  cur_type;

  cur_yp cur_type;

  …

begin

  open cur_yp for select * from yp;

  loop

    fetch cur_yp into yp,mc …

    exit when cur_yp%notfound;

    ….

  end loop;

  close cur_yp;

  open cur_yp for select * from yp where condition1;

  loop

    fetch cur_yp into yp,mc …

    exit when cur_yp%notfound;

    ….

  end loop;

  close cur_yp;

  open cur_yp for select * from yp where condition2;

  loop

    fetch cur_yp into yp,mc …

    exit when cur_yp%notfound;

    ….

  end loop;

  close cur_yp;

end;

(7)请注意,游标循环中中一定要退出语名,要不然执行时会出现死循环。

<五> 存储过程/函数

    <1>、sql server端语法说明

    1、语法:

           create proc[edure] [owner.]procedure_name [;number]

             [ (parameter1[, parameter2]…[, parameter255])]

             [ {for replication} | {with recompile}

             [ {[with] | [ , ] } encryption ] ]

           as

             sql_statement [...n]

           其中,parameter = @parameter_name datatype [=default] [output]

 

       说明:t-sql中存储过程的结构大致如下

           create procedure procedure_name

               /*输入、输出参数的声明部分*/

           as

               declare

               /*局部变量的声明部分*/

           begin

               /*主体sql语句部分*/

              /*游标声明、使用语句在此部分*/

           end

 

    2、示例:

       if exists(select 1 from sysobjects

                 where name = 'titles_sum' and type = 'p')

          drop procedure titles_sum

       go

 

       create procedure titles_sum

              @title varchar(40) = '%', @sum money output

       as

       begin

          select  'title name' = title

            from  titles

           where  title  like  @title

          select  @sum = sum(price)

            from  titles

           where  title  like  @title

       end

 

    <2>、oracle端procedure语法说明

    1、语法:

           create [or replace] procedure procedure_name

             [ (parameter1 [ {in | out | in out } ] type ,

               …

               parametern [ {in | out | in out } ] type ) ]

           { is | as }

           [begin]

             sql_statement [...n] ;

           [end] ;

      

       说明:pl/sql中存储过程的结构大致如下

           create or replace procedure procedure_name

              (  /*输入、输出参数的声明部分*/  )

           as

               /*局部变量、游标等的声明部分*/

           begin

               /*主体sql语句部分*/

               /*游标使用语句在此部分*/

           exception

               /*异常处理部分*/

           end ;

 

    2、示例:

       create or replace procedure  drop_class

          ( arg_student_id  in         varchar2,

            arg_class_id    in      varchar2,

            status          out     number   )

       as

          counter     number ;

       begin

          status := 0 ;

          -- verify that this class really is part of the student’s schedule.

          select  count (*)  into  counter

            from  student_schedule

           where  student_id  =  arg_student_id

             and  class_id    =  arg_class_id ;

         

          if  counter  =  1  then

             delete  from  student_schedule

              where  student_id  =  arg_student_id

                and  class_id    =  arg_class_id ;

             status := -1 ;

          end if ;

       end ;

<3>oracle端function语法说明

(1)  语法

create [or replace] function function_name

[(argument [{in | out | in out }] ) type,



[(argument [{in | out | in out }] ) type

return return_type {is | as}

begin



end;

关键字return 指定了函数返回值的数据类型。它可以是任何合法的pl/sql数据类型。每个函数都必须有一个return 子句,因为在定义上函数必须返回一个值给调用环境。

(2)示例

create or replace function blanace_check(person_name in varchar2)

return number

is

balance number(10,2);

begin

              select sum(decode(acton,’bought’,amount,0))

              into balance

              from ledger

              where person = person_name;

              return (balance);

end;

(3)过程与函数的区别

函数可以返回一个值给调用环境;而过程不能,过程只能通过返回参数(带“out”或“in out”)传回去数据。

<4>从sql server向oracle的迁移方案

通过比较上述sql语法的差异,在迁移时必须注意以下几点:

1、对于有返回单值的mssql存储过程,在数据库移值最好转换成oralce的函数;对于mssql有大量数据的处理而又不需返回值的存储过程转换成oracle的过程

       2、在t-sql中,输入、输出参数定义部分在“create…”和“as”之间,前后

          没有括号;而在pl/sql中必须有“(”和“)”与其他语句隔开。

       3、在t-sql中,声明局部变量时,前面要有declare关键字;

          而在pl/sql中不用declare关键字。

       4、在t-sql中,参数名的第一个字符必须是“@”,并符合标识符的规定;

          而在pl/sql中,参数名除符合标识符的规定外没有特殊说明,t-sql中,对于参数可其数据类型及其长度和精度;但是pl/sql中除了引用%type和%rowtype之外,不能在定义参数数据类型时给出长度和精度,如下:

      create or replace  procedure proc_sele_ys

       (ysdm  char(6),gz number(14,4))

      as

      begin

        …

      end;

     是错误的,应如下定义

      create or replace  procedure proc_sele_ys

       (ysdm  char,gz number)

      as

      begin

        …

      end;

     或者

      create or replace  procedure proc_sele_ys

       (ysdm  ysdmb.ysdm%type,gz ysdmb.gz%type)

      as

      begin

        …

      end;

 

       5、对于t-sql,游标声明在主体sql语句中,即声明与使用语句同步;

          而在pl/sql中,游标声明在主体sql语句之前,与局部变量声明同步。

       6、对于t-sql,在主体sql语句中用如下语句对局部变量赋值(初始值或

          数据库表的字段值或表达式):

           “select 局部变量名 =  所赋值(初始值或数据库表的字段值或表达式)”;

          而在pl/sql中,将初始值赋给局部变量时,用如下语句:

           “局部变量名 : =  所赋值(初始值或表达式);” ,

          将检索出的字段值赋给局部变量时,用如下语句:

           “select 数据库表的字段值 into 局部变量名 …” 。

       7、在pl/sql中,可以使用%type来定义局部变量的数据类型。说明如下:

          例如,students表的first_name列拥有类型varchar2(20),基于这点,

          我们可以按照下述方式声明一个变量:

              v_firstname    varchar2(20) ;

          但是如果改变了first_name列的数据类型则必须修改该声明语句,因此可以采

          用%type进行变量数据类型声明:

             v_firstname     students.first_name%type ;

          这样,该变量在存储过程编译时将由系统自动确定其相应数据类型。

8、对于t-sql,没有定义语句结束标志,而pl/sql用“end <过程名>;”结束语句。

9、存储过程的调用要注意:在mssqlserver中的格式为“exec procedure_name {arg1,arg2,…},但在oracle中直接引用过程名即可,如要执行存储过程defaltno,其参数为“9”,则执行时为 default(“9”)。

10、oracle 数据库的存储过程不支持用select 子句直接返回一个数据集,要做到通过程产生一记录集有两种方案:

方案一:采用包和游标变量

第一步,创建一个包,定义一个游标变量

create package p_name
is
type cursor_name is ref cursor;
end;

第二步,创建过程,但是基返回参数用包中的游标类型
create procedure procedure_name(s in out p_name.cursor_name) is
begin
open s for select * from table_name...;
end;

这样,通过存储过程就可以返回一个数据集了,但用到这种情况,过程的参数中只这返回结果的游标参数可以带关键字”out”,其它不能带”out”,否则,系统会出现导常。

方案二:通过中间表,建一中间表,其表格的列为所需数据列再加上一个序列字段。过程的处理为将数据插入到中间表中,同时通过

select userenv(‘sessionid’) from dual;取得当前连接会话的序号,将取得的序号值放置到序列字段中,同时存储过程返回连接会话的序号,前台pb程序直接访问中间表,数据窗口在检索时通过序号参数可将所需的数据检索出来。
<六> 触发器
    <1>、sql server端语法说明

    1、语法:

           create trigger [owner.]trigger_name

           on [owner.]table_name

           for { insert, update, delete }

             [with encryption]

           as

             sql_statement [...n]

       或者使用if update子句:

           create trigger [owner.]trigger_name

           on [owner.]table_name

           for { insert, update }

             [with encryption]

           as

             if update (column_name)

             [{and | or} update (column_name)…]

             sql_statement [ ...n]

 

     2、示例:

        if exists (select 1 from sysobjects

                   where name = 'reminder' and type = 'tr')

          drop trigger reminder

        go

 

        create trigger employee_insupd

               on employee

              for insert, update

        as

        /* get the range of level for this job type from the jobs table. */

        declare @min_lvl tinyint,

                    @max_lvl tinyint,

                    @emp_lvl tinyint,

                    @job_id  smallint

         select @min_lvl = min_lvl,

                    @max_lvl = max_lvl,

                    @emp_lvl = i.job_lvl,

                    @job_id  = i.job_id

           from employee e, jobs j, inserted i

          where e.emp_id = i.emp_id and i.job = j.job_id

        if (@job_id = 1) and (@emp_lvl <> 10)

        begin

               raiserror ('job id 1 expects the default level of 10.', 16, 1)

              rollback transaction

        end

        else

        if not (@emp_lvl between @min_lvl and @max_lvl)

        begin

             raiserror ('the level for job_id:%d should be between %d and %d.',

                         16, 1, @job_id, @min_lvl, @max_lvl)

             rollback transaction

        end

        go

 

    <2>、oracle端语法说明

    1、语法:

           create [or replace] trigger trigger_name

           { before | after } triggering_event on  table_name

           [ for each row ]

           [ when trigger_condition ]

           trigger_body ;

    2、使用说明与示例:

       (1)、上语法中,trigger_event 是对应于dml的三条语句insert、update、

             delete;table_name是与触发器相关的表名称;for each row是可选

             子句,当使用时,对每条相应行将引起触发器触发;condition是可选的

             oracle boolean条件,当条件为真时触发器触发;trigger_body是触发

             器触发时执行的pl/sql块。

 

       (2)、oracle触发器有以下两类:

             1> 语句级(statement-level)触发器,在create trigger语句中不

                包含for each row子句。语句级触发器对于触发事件只能触发一次,

                而且不能访问受触发器影响的每一行的列值。一般用语句级触发器处理

                有关引起触发器触发的sql语句的信息——例如,由谁来执行和什么时

                间执行。

             2> 行级(row-level)触发器,在create trigger语句中

                包含for each row子句。行级触发器可对受触发器影响的每一行触

                发,并且能够访问原列值和通过sql语句处理的新列值。行级触发器的

                典型应用是当需要知道行的列值时,执行一条事务规则。

 

        (3)在触发器体内,行级触发器可以引用触发器触发时已存在的行的列值,这些

             值倚赖于引起触发器触发的sql语句。

             1> 对于insert语句,要被插入的数值包含在new.column_name,这里的

                column_name是表中的一列。

             2> 对于update语句,列的原值包含在old.column_name中,数据列的新

                值在new.column_name中。

             3> 对于delete语句,将要删除的行的列值放在old.column_name中。

触发语句

:old

:new

insert

无定义——所有字段都是null

当该语句完成时将要插入的数值

update

在更新以前的该行的原始取值

当该语句完成时将要更新的新值

delete

在删除行以前的该行的原始取值

未定义——所有字段都是null

             4> 在触发器主体中,在new和old前面的“:”是必需的。而在触发器的

                when子句中,:new和:old记录也可以在when子句的condition内部

                引用,但是不需要使用冒号。例如,下面checkcredits触发器的主体仅

                当学生的当前成绩超过20时才会被执行:

                create or replace trigger checkcredits

                   before insert or update of current_credits on students

                   for each row

                   when (new.current_credits > 20)

                begin

                   /*trigger body goes here. */

                end ;

                但checkcredits也可以按下面方式改写:

                create or replace trigger checkcredits

                   before insert or update of current_credits on students

                   for each row

                begin

                   if  :new.current_credits > 20  then

                      /*trigger body goes here. */

                   end if ;

                end ;

                注意,when子句仅能用于行级触发器,如果使用了它,那么触发器主体

                仅仅对那些满足when子句指定的条件的行进行处理。

 

        (4)触发器的主体是一个pl/sql块,在pl/sql块中可以使用的所有语句在触

             发器主体中都是合法的,但是要受到下面的限制:

             1> 触发器不能使用事务控制语句,包括commit、rollback或

                savepoint。oracle保持这种限制的原因是:如果触发器遇到错误时,

                由触发器导致的所有数据库变换均能被回滚(roll back)取消;但如果

                触发器确认(commit)了对数据库进行的部分变换,oracle就不能完全

                回滚(roll back)整个事务。

             2> 在触发器主体中调用到的存储过程的实现语句里也不能使用事务控制语

                句。

             3> 触发器主体不能声明任何long或long raw变量。而且,:new和:old

                不能指向定义触发器的表中的long或long raw列。

             4> 当声明触发器的表中有外键约束时,如果将定义触发器的表和需要作为

                delete cascade参考完整性限制的结果进行更新的表称为变化表,

                将外键相关联的表称为限制表,则在此触发器主体中的sql语句不允许

                读取或修改触发语句的任何变化表,也不允许读取或修改限制表中的主

                键、唯一值列或外键列。

 

        (5)以下是建立一个事前插入触发器的示例:

             create or replace trigger credit_charge_log_ins_before

                before insert on credit_charge_log

                for each row

             declare

                total_for_past_3days     number ;

             begin

                -- check the credit charges for the past 3 days.

                -- if they total more than $1000.00, log this entry

                -- int the credit_charge_attempt_log for further handling.

                select sum ( amount ) into total_for_past_3days

                  from credit_charge_log

                 where card_number = :new.card_number

                   and transaction_date >= sysdate – 3;

                if total_for_past_3days > 1000.00 then

                   insert into credit_charge_attemp_log

                     (card_number, amount, vendor_id, transaction_date)

                   values

                     (:new.card_number, :new.amount,

                      :new.vendor_id, :new.transaction_date);

                end if ;

             end ;

 

<3>、从sql server向oracle的迁移方案

 

         1、通过比较上面sql语法的不同并考虑现有sql server的实际编程风格,在从

            t-sql向pl/sql迁移时,要遵守下面规则:

            1> 在create trigger定义中采用after关键字,即调整为事后触发器。

            2> 在create trigger定义中采用for each row关键字,即调整为行级触发

               器。

            3> 将触发器主体中的“inserted”调整为“:new”,将“deleted”调整为“:old”。

            4> 在触发器主体中禁用cursor操作:new与:old。

            5> 在触发器主体中禁用commit、rollback、savepoint等事务控制语句。

 

         2、用触发器解决id列向sequence迁移的问题:

            下面的generatestudentid触发器使用了:new。这是一个before insert触

            发器,其目的是使用student_sequence序列所产生的数值填写

            students表的id字段。

            例:

            create or replace trigger generatestudentid

               before insert on students

               for each row

            begin

               select student_sequence.nextval

                 into :new.id

                 from dual;

            end;

            在上面的触发器主体中,generatestudentid实际上修改了:new.id的值。这

            是:new最有用的一个特性——当该语句真正被执行时,:new中的存储内容就

            将被使用。有了这个触发器,我们就可以使用下面这样的insert语句,而不

            会产生错误:

               insert into students (first_name, last_name)

               values (‘luo’, ‘tao’) ;

            尽管我们没有为主键列id(这是必需的)指定取值,触发器将会提供所需要

            的取值。事实上,如果我们为id指定了一个取值,它也将会被忽略,因为触

            发器修改了它。如果我们使用下面的语句:

               insert into students (id, first_name, last_name)

               values (-789, ‘luo’, ‘tao’) ;

            其处理结果还是相同的。无论在哪种情况下,student_sequence.nextval都

            将用作id列值。

 

            由此讨论,可以采用这种方法处理sql server中id列向oracle的sequence

            转换的问题。

 

            另外,由于上面的原因,我们不能在after行级触发器中修改 :new,因为该

            语句已经被处理了。通常,:new仅仅在before行级触发器中被修改,而:old

            永远不会被修改,仅仅可以从它读出数据。

 

            此外,:new和:old记录仅仅在行级触发器内部是有效的。如果试图要从语句

            级触发器进行引用,将会得到一个编译错误。因为语句级触发器只执行一次

            ——尽管语句要处理许多行——所以:new和:old是没有意义的,因为怎么确

            定它们引用的会是哪一行呢?

            
<七> 常用sql语法与函数
    <1>、sql server端常用语法说明

    1、使用局部变量:

       1> 变量定义:

              declare @variable_name datatype [,…]

          例:

              declare

                 @name    varchar(30),

                 @type   int

       2> 给变量赋值:

         方法一:

              例:

                  declare @int_var    int

                  select @int_var = 12

         方法二:

              例:

                  declare

                     @single_auth    varchar(40),

                     @curdate        datetime

                  select @single_auth = au_lname,

                         @curdate     = getdate()

                    from authors

                   where au_id = ‘123-45-6789’

 

2、使用t-sql标准控制结构:

       1> 定义语句块

          语法:

              begin

                 statements

              end

 

       2> if ... else语句

          语法:

              if boolean_expression

                 { statement | statement_block }

              else

                 { statement | statement_block }

          示例:

              if (select avg(price) from titles where type = ‘business’) > $19.95

                  print ‘the average price is greater then $19.95’

              else

                  print ‘the average price is less then $19.95’

 

       3> if exists语句

          语法:

              if [not] exists (select_statement)

                 { statement | statement_block }

              [else

                 { statement | statement_block }]

          示例:

              declare

                 @lname      varchar(40),

                 @msg        varchar(255)

              select @lname = ‘smith’

              if exists(select * from titles where au_lname = @lname)

                 begin

                    select @msg = ‘there are authors named’ + @lname

                    print @msg

                 end

              else

                 begin

                    select @msg = ‘there are no authors named’ + @lname

                    print @msg

                 end

 

       4> 循环语句:

          while

          语法:

              while boolean_condition

                 [{ statement | statement_block }]

              [break]

              [condition]

          示例:

              declare

                 @avg_price              money,

                 @max_price              money,

                 @count_rows             int,

                 @times_thru_the_loop int

              select @avg_price            = avg(price),

                     @max_price            = max(price),

                     @count_rows           = count(*),

                     @times_thru_the_loop = 0

                from titles

              while @avg_price < $25 and (@count_rows < 10 or @max_price < $50)

              begin

                 select @avg_price          = avg(price) * 1.05,

                        @max_price          = max(price) * 1.05,

                        @time_thru_the_loop = @time_thru_the_loop + 1

              end

              if @time_thru_the_loop = 0

                 select @time_thru_the_loop = 1

              update titles

                 set price = price * power(1.05, @time_thru_the_loop)

 

       4> goto语句

          语法:

              goto label

              ...

              label:

          示例:

              begin transaction

                 insert tiny(c1) values(1)

                 if @@error != 0 goto error_handler

                 commit transaction

                 return

              error_handler:

                 rollback transaction

                 return

 

       5> return语句

          语法:

              return

          (1)用于无条件退出一个批处理、存储过程或触发器。

               示例:

                   if not exists(select 1 from inventory

                                  where item_num = @item_num)

                   begin

                      raiseerror 51345 ‘not found’

                      return

                   end

                   print ‘no error found’

                   return

          (2)用于存储过程中返回状态值。

               示例:

                   create procedure titles_for_a_pub

                          (@pub_name varchar(40) = null)

                   as

                   if @pub_name is null

                      return 15

                   if not exists(select 1 from publishers

                                  where pub_name = @pub_name)

                      return –101

                   select t.tile from publishers p, titles t

                    where p.pub_id = t.pub_id

                      and pub_name = @pub_name

                   return 0

 

    3、t-sql中的游标提取循环语句:

   (1)fetch [next from] cursor_name into @variable_1, [email protected]_n

   (2)while @@fetch_status = 0

        begin

           other_statements

           fetch [next from] cursor_name into @variable_1, [email protected]_n

        end

   (3)close cursor_name

 

    4、t-sql中的事务处理语句:

       1> 开始一个事务:

          begin tran[saction [transaction_name]]

 

       2> 提交一个事务:

          commit tran[saction [transaction_name]]

 

       3> 回滚一个事务:

          rollback tran[saction [transaction_name]]

 

       4> 使用事务保存点:

          begin tran[saction [transaction_name]]

             save tran[saction] savepoint_name

             rollback tran[saction] savepoint_name

          commit tran[saction [transaction_name]]

 

    5、t-sql中可用于错误判断或其它处理的全局变量:

       1>  @@rowcount:        前一条命令处理的行数

       2>  @@error:           前一条sql语句报告的错误号

       3>  @@trancount:        事务嵌套的级别

       4>  @@transtate:        事务的当前状态

       5>  @@tranchained:  当前事务的模式(链接的(chained)或非链接的)

       6>  @@servername:    本地sql server的名称

       7>  @@version   :        sql server和o/s的版本级别

       8>  @@spid:            当前进程的id

       9>  @@identity:        上次insert操作中使用的identity值

       10> @@nestlevel:        存储过程/触发器中的嵌套层

       11> @@fetch_status: 游标中上条fetch语句的状态

 

    6、使用标准内置错误消息发送函数:

       函数说明:

           raiserror ({msg_id | msg_str}, severity, state

           [, argument1 [,argument2][,...] )

           [with log]

 

       其中,msg_id表示错误号,用户定义错误消息的错误号在50001到2147483647之

       间,特定的消息会引起错误50000。msg_str是错误消息正文,最多可有255个字

       符。severity描述了与这个消息关联的用户定义的严重性级别,取值包括0和10

       至25之间的任何整数。state描述了错误的“调用状态”,它是1到127之间的整

       数值。argument定义用于代替在msg_str中定义的变量或对应与msg_id的消息的

       参数。with log表示要在服务器错误日志和事件日志中记录错误。

       例1:

          raiseerror( ‘invalid customer id in order.’, 16, 1)

          则返回:

              msg 50000, level 16, state 1

              invalid customer id in order.

       例2:

          sp_addmessage 52000, 16, ‘invalid customer id %s in order’

          raiseerror( 52000, 16, 1, ‘id52436’)

          则返回:

              msg 52000, level 16, state 1

              invalid customer id id52436 in order.

   

    <2>、oracle端常用语法说明

    1、使用局部变量:

       1> 定义变量:

          variable_name   data type   [ := initial value ] ;

          例:定义变量

              v_num       number;

              v_string    varchar2(50);

          例:定义变量并赋初值

              v_num       number := 1 ;

              v_string    varchar2(50) := ‘hello world!’ ;

       2> 给变量赋值:

         方法一:

              例:

                  v_num      := 1;

                  v_string := ‘hello world!’;

         方法二:

              例:

                  select first_name into v_string

                    from students

                   where id = v_num ;

 

    2、使用pl/sql标准控制结构:

       1> 定义语句块

          语法:

              begin

                 statements ;

              end ;

 

       2> if ... then ... else语句

          语法:

              if boolean_expression then

                 { statement | statement_block } ;

              [elsif boolean_expression then      /*注意此处的写法—— elsif */

                 { statement | statement_block } ;]

              ...

              [else

                 { statement | statement_block } ;]

              end if ;

 

          示例:

              v_numberseats rooms.number_seats%type;

              v_comment varchar2(35);

              begin

              /* retrieve the number of seats in the room identified by id 99999.

                 store the result in v_numberseats. */

                select number_seats

                  into v_numberseats

                  from rooms

                 where room_id = 99999;

                if v_numberseats < 50 then

                   v_comment := 'fairly small';

                elsif v_numberseats < 100 then

                   v_comment := 'a little bigger';

                else

                   v_comment := 'lots of room';

                end if;

              end;

 

       3> 循环语句:

         (1)简单循环语句:

              语法:

                  loop

                     { statement | statement_block } ;

                     [exit [when condition] ;]

                  end loop ;

                  其中,语句exit [when condition];等价于

                      if condition then

                         exit ;

                      end if ;

              示例1:

                  v_counter binary_integer := 1;

                  begin

                    loop

                      -- insert a row into temp_table with the current value of the

                      -- loop counter.

                      insert into temp_table

                           values (v_counter, 'loop index');

                      v_counter := v_counter + 1;

                      -- exit condition - when the loop counter > 50 we will

                      -- break out of the loop.

                      if v_counter > 50 then

                         exit;

                      end if;

                    end loop;

                  end;

 

              示例2:

                  v_counter binary_integer := 1;

                  begin

                    loop

                      -- insert a row into temp_table with the current value of the

                      -- loop counter.

                      insert into temp_table

                           values (v_counter, 'loop index');

                      v_counter := v_counter + 1;

                      -- exit condition - when the loop counter > 50 we will

                      -- break out of the loop.

                      exit when v_counter > 50;

                    end loop;

                  end;

 

         (2)while循环语句:

              语法:

                  while condition loop

                     { statement | statement_block } ;

                  end loop ;

 

              示例1:

                  v_counter binary_integer := 1;

                  begin

                    -- test the loop counter before each loop iteration to

                    -- insure that it is still less than 50.

                    while v_counter <= 50 loop

                      insert into temp_table

                           values (v_counter, 'loop index');

                      v_counter := v_counter + 1;

                    end loop;

                  end;

 

              示例2:

                  v_counter binary_integer;

                  begin

                    -- this condition will evaluate to null, since v_counter

                    -- is initialized to null by default.

                    while v_counter <= 50 loop

                      insert into temp_table

                           values (v_counter, 'loop index');

                      v_counter := v_counter + 1;

                    end loop;

                  end;

 

         (3)数字式for循环语句:

              语法:

                  for loop_counter in [reverse] low_bound..high_bound loop

                     { statement | statement_block } ;

                  end loop ;

                  这里,loop_counter是隐式声明的索引变量。

 

              示例1:

                  for循环的循环索引被隐式声明为binary_integer。在循环前面没有

                  必要声明它,如果对它进行了声明,那么循环索引将屏蔽外层的声明,

                  如下所示

                  v_counter  number := 7;

                  begin

                    -- inserts the value 7 into temp_table.

                    insert into temp_table (num_col)

                      values (v_counter);

                    -- this loop redeclares v_counter as a binary_integer, which

                    -- hides the number declaration of v_counter.

                    for v_counter in 20..30 loop

                      -- inside the loop, v_counter ranges from 20 to 30.

                      insert into temp_table (num_col)

                        values (v_counter);

                    end loop;

                    -- inserts another 7 into temp_table.

                    insert into temp_table (num_col)

                      values (v_counter);

                  end;

 

              示例2:

                  如果在for循环中有reverse关键字,那么循环索引将从最大值向最

                  小值进行循环。请注意语法是相同的——仍然首先书写的是最小值,

                  如下所示

                  begin

                    for v_counter in reverse 10..50 loop

                      -- v_counter will start with 50, and will be decremented

                      -- by 1 each time through the loop.

                      null;

                    end loop;

                  end;

 

              示例3:

                  for循环中的最大值和最小值没有必要必须是数字型文字,它们可以

                  是能够被转换为数字值的任何表达式,如下所示

                  v_lowvalue      number := 10;

                  v_highvalue    number := 40;

                  begin

                    for v_counter in reverse v_lowvalue..v_highvalue loop

                      inser into temp_table

                          values (v_counter, ‘dynamically sqecified loop range’);

                    end loop;

                  end;

 

       4> goto语句

          语法:

              goto label;

              ...

              <<label>>

              ...

 

          示例:

              v_counter  binary_integer := 1;

              begin

                loop

                  insert into temp_table

                    values (v_counter, 'loop count');

                  v_counter := v_counter + 1;

                  if v_counter > 50 then

                    goto l_endofloop;

                  end if;

                end loop;

             

                <<l_endofloop>>

                insert into temp_table (char_col)

                  values ('done!');

              end;

 

       5> exit语句

          语法:

              exit;

          参见上面的pl/sql标准控制结构之循环语句说明部分。

 

    3、pl/sql中的游标提取循环语句:

       1> 简单循环

          此循环采用简单的循环语法(loop..end loop),如下所示

            -- declare variables to hold information about the students

            -- majoring in history.

            v_studentid   students.id%type;

            v_firstname   students.first_name%type;

            v_lastname    students.last_name%type;

            -- cursor to retrieve the information about history students

            cursor c_historystudents is

            select id, first_name, last_name

              from students

             where major = 'history';

          begin

            -- open the cursor and initialize the active set

            open c_historystudents;

            loop

              -- retrieve information for the next student

              fetch c_historystudents into v_studentid, v_firstname, v_lastname;

              -- exit loop when there are no more rows to fetch

              exit when c_historystudents%notfound;

              -- process the fetched rows.  in this case sign up each

              -- student for history 301 by inserting them into the

              -- registered_students table. record the first and last

              -- names in temp_table as well.

              insert into registered_students (student_id, department, course)

                values (v_studentid, 'his', 301);

              insert into temp_table (num_col, char_col)

                values (v_studentid, v_firstname || ' ' || v_lastname);

            end loop;

            -- free resources used by the cursor

            close c_historystudents;

            -- commit our work

            commit;

          end;

          请注意,exit when语句的位置是紧跟在fetch语句的后边。在检索完最后一

          个行以后,c_historystudents%notfound变为true,该循环退出。exit when

          语句的位置也在数据处理部分的前面,这样做是为了确保该循环过程不处理任

          何重复行。

 

       2> while循环

          此循环采用while .. loop的循环语法,如下所示

            -- declare cursor to retrieve the information about history students

            cursor c_historystudents is

            select id, first_name, last_name

              from students

             where major = 'history';

 

            -- declare a record to hold the fetched information.

            v_studentdata  c_historystudents%rowtype;

          begin

            -- open the cursor and initialize the active set

            open c_historystudents;

            -- retrieve the first row, to set up for the while loop

            fetch c_historystudents into v_studentdata;

            -- continue looping while there are more rows to fetch

            while c_historystudents%found loop

              -- process the fetched rows, in this case sign up each

              -- student for history 301 by inserting them into the

              -- registered_students table. record the first and last

              -- names in temp_table as well.

              insert into registered_students (student_id, department, course)

                values (v_studentdata.id, 'his', 301);

              insert into temp_table (num_col, char_col)

                values (v_studentdata.id,

                        v_studentdata.first_name || ' '

                                                 || v_studentdata.last_name);

              -- retrieve the next row. the %found condition will be checked

              -- before the loop continues again.

              fetch c_historystudents into v_studentdata;

            end loop;

            -- free resources used by the cursor

            close c_historystudents;

            -- commit our work

            commit;

          end;

          请注意,fetch语句出现了两次——一次是在循环的前面,另一次是在循环处

          理的后面,这样做是为了使循环条件(c_historystudents%found)对每一次循

          环叠代都求值以确保该循环过程不处理任何重复行。

 

       3> 游标式for循环

          因与迁移关系不大,此处略。

 

    4、pl/sql中的事务处理语句:

       在pl/sql中,事务的开始位置是从前一个事务结束以后执行的第一条sql语句,

       或者在连接到该数据库以后所执行的第一条sql语句。事务的结束是使用commit

       或rollback语句标识的。

       1> commit的语法是:

              commit [work];

              可选的关键字work用来提高可读性。

       2> rollback的语法是:

              rollback [work];

              可选的关键字work用来提高可读性。

       3> rollback语句会撤消整个事务,如果使用savepoint命令,那么只有部分的事

          务需要被撤消,其语法是:

              savepoint name;

              这里name是保存点的名字。

       4> 示例:

              v_numiterations   number;

              begin

                -- loop from 1 to 500, inserting these values into temp_table.

                -- commit every 50 rows.

                for v_loopcounter in 1..500 loop

                  insert into temp_table (num_col) values (v_loopcounter);

                  v_numiterations := v_numiterations + 1;

                  if v_numiterations = 50 then

                    commit;

                    v_numiterations := 0;

                  end if;

                end loop;

              end;

 

    5、使用标准内置错误消息发送函数:

       与t-sql中raiseerror对应,pl/sql中有这样一个内置函数

       函数说明:

           raise_application_error (error_number, error_message, [keep_errors]) ;

       这里,error_number是从-20,000到-20,999之间的参数;error_message是与此

       错误相关的正文,error_message必须不多于512个字节;而keep_errors是一个

       可选的布尔值参数,其为true则新的错误将被添加到已经引发的错误列表中(如

       果有的话),其为false(这是缺省的设置)则新的错误将替换错误的当前列表。

       例:

           raise_application_error(-20000, ‘can’t find any record.’) ;

 

    <3>、t-sql与pl/sql常用函数比较(以下的exp为expression的缩写)

t-sql

pl/sql

字符类函数

ascii(char_exp)

ascii(str_exp)

char(int_exp)

chr(int_exp)

datalength(char_exp)

length(str_exp)

substring(exp, start, length)

substr(exp, start, length)

upper(char_exp)

upper(str_exp)

lower(char_exp)

lower(str_exp)

stuff(char_exp1,start,length,

      char_exp2)

translate(str_exp,from_str,to_str)

ltrim(char_exp)

ltrim(str_exp1 [,str_exp2])

rtrim(char_exp)

rtrim(str_exp1 [,str_exp2])

日期类函数

getdate()

sysdate

数学类函数

abs(numeric_exp)

abs(number_exp)

ceiling(numeric_exp)

ceil(number_exp)

exp(float_exp)

exp(number_exp)

floor(numeric_exp)

floor(number_exp)

power(numeric_exp,int_exp)

power(number_exp1,number_exp2)

round(numeric_exp,int_exp)

round(number_exp1 [,number_exp2])

sign(int_exp)

sign(number_exp)

sqrt(float_exp)

sqrt(number_exp)

转换函数

convert(datatype[(length)],exp,format)

to_char(datatype,str_format)

convert(datatype[(length)],exp,format)s

to_date(str_exp,date_format)

convert(datatype[(length)],exp,format)

to_number(str_exp,num_format)

其它函数

avg([all | distinct] col)

avg([all | distinct] col)

count({[all | distinct] col] | *})

count({[all | distinct] col} | *))

max([all | distinct] col)

max([all | distinct] col)

min([all | distinct] col)

min([all | distinct] col)

sum([all | distinct] col)

sum([all | distinct] col)

stdev(col)

stddev(col)

var(col)

variance(col)

isnull(check_exp, replace_value)

nvl(check_exp, replace_value)

case

deccode

 

<4>mssql与oracle比较注意几个语法转换

(1)isnull与 nvl

  在mssql中为了替换空值常用isnull函数,如isnull(@dno,”00”)表示当变量@dno的值为空时,则用”00”替换其值;在oracle 中,同样的功能用nvl实现,如上述例可以用nvl(dno,”00”)来替换。

(2)case 与 deccode

case在mssql中可以用以对某个值进行多个判断分支进行处理,简化了代码如下:

update student set class = (case inyear when “1993” then “8” when “1994” then “7” when “1995 then “6” else “0”)

      相同的功能在oracle中可以用deccode来实现,如上例在oracle应作如下处理:

              update student set class=deccode (inyeare,’1993’,’8’,’1994’,’7’,’1995’,’6’,’0 ‘) ;

 (3)日期运算

在mssql中对于日期的处理不能数值型有很大区,其主要实现的函数有dateadd、datediff;而在oracle中把日期当作数值来处理,其主要处理函数有add_month、month_between、d1(+-*/)d2等,下面列出其替换方法

dateadd(year,1,pubdate)

add_months(d1,12)

dateadd(month,3,pubdate)

add_months(d1,3)

dateadd(day,13,pubdate)

d1 + 13

dateadd(day,-3,pubdate)

d1 – 3

dateadd(hour,6,pubdate)

d1 + 6/24

dateadd(minutes,24,pubdate)

d1 + 24/1440

datediff(minute, d1, d2)

(d2-d1)*1440

datediff(hour, d1, d2)

(d2-d1)*24

datediff(month, d1, d2)

months_between(d1,d2)

datename(month, getdate())

to_char(sysdate,’month’)

datename(year, getdate())

to_char(sysdate,’year’)

datename(day,getdate())

to_char(sysdate,’day’)

datedart(month,getdate())

to_char(sysdate,’mm’)

datedart(year,getdate())

to_char(sysdate,’yyyy’)

datedart(day,getdate())

to_char(sysdate,’dd’)

getdate()

sysdate

 

<4>、从t-sql向pl/sql迁移方案

    通过上述讨论,在从t-sql向pl/sql迁移时,在常用语法与函数方面要逐一细致比较

    后再行调整,特别要注意常用函数怎么进行替换和主体控制结构怎么进行调整。

   (1)将所有的getdate全部转换成为sysdate;

   (2)将所有的selct @var = column from table where condition 改成

               select column into var from table where condition;

       将所有的selct @var1 = @var2  改成

               var1 :=var2;

   (3)将所有的convert全部转换成为 to_char 或 trunc

   例一:

   declare rq1 datetime,rq2 datetime

   …

       select  je from sr where rq > = convert (char(10),rq1,111)

         and rq < convert(char(10),rq2,111)

   应改成:

   date rq1;

   date rq2;

      select sr into je where rq > = trunc(rq1) and  rq < trunc(rq2);

   例二:

   declare rq1 datetime,rq2 datetime

   …

   select  je from sr where convert(char(10),rq,111) > = convert (char(10),rq1,111)

      and rq < convert(char(10),rq2,111)

   应改成:

   date rq1;

   date rq2;

      select sr into je where trunc(rq)> = trunc(rq1) and  trunc(rq) < trunc(rq2);

  或:

   date rq1;

   date rq2;

      select sr into je where  to_char(rq,’yyyy/mm/dd’)> =to_char(rq1,’yyyy/mm/dd’)      and  to_char(rq,’yyyy/mm/dd’) < to_char(rq2,’yyyy/mm/dd’);

(3)pl/sql不支付时间字段与规则字符串的直接比例

 如在t-sql中的

  select @je = sr where rq > ‘2001.01.01’是可以的。

而在pl/sql中

  select sr into je where rq > ‘2001.01.01’;是行不通的,如果要实现比例,则应改成;

  select sr into je where rq > to_date(‘2001.01.01’,’yyyy.mm.dd’);或

  select sr into je where to_char(rq,’yyyy.mm.dd’) > ‘2001.01.01’;

(4)将t-sql中的datediff全部改成trunc(d1-d2),months_between

   如select @ts = datediff(day,date1,date2),在pl/sql中应改为:

     ts = trunc(date2 – date1);

   如select @ys = datediff(month,date1,date2),在pl/sql中应改为:

     ts = months_between(date1 – date2);

(5)dateadd全部改为d+n 或add_months

   如select date2 = dateadd(day,date1,3),在pl/sql中应改为:

      date2 :=date1 + 3;

   如select date2 = dateadd(month,date1,6),在pl/sql中应改为:

      date2 :=add_months(date1 ,6);

(6)
<八> 临时表问题
oralce8i以上的版本才支持临时表,其创建语法为:

create global temporary table table_name

(clomn1 type,column2 type);而对于oralce8i以下的版本不支持,综合考虑,在从sql server向oracle迁移时,对于临时表,采用以下方案:

    1、将t-sql语句中的临时表在后台实际化——即将之创建为正式表,在其本身的列中增加一列作为序号用于标识不同的操作。

2、在将临时表实际化时对所有这样的表都要加“tmp_”前缀。
<九> oracle特别处
<1>、dual的使用

在oracle中可以用这样的语法从后台服务器提取时间值:

        select sysdate into :varible from dual ;

    <2>、oracle不能在存储过程中建数据表
<十>连接远程的数据库(包括不同服务器)
数据库链接(database link)与分布式数据库功能紧密相连。数据库链接允许用户处理远程数据库而不用知道数据是在什么地方。当建立了一个数据库链接之后,提供对远程数据的登录信息。每当使用数据库链接时,在分布式网络上初始化一个对话(session),以解决对远程数据库对象的引用。

(1)  先创建一个远程数据库的别名,用oracle8 net easy config,也在在文件tnsnames.ora中加入以下格式内容:

别名.world =

(description =

    (address = (protocol = nmp)(server = 远程数据服务器名称)(pipe = orapipe))

(connect_data = (sid = 远程数据库名称)))

(2)  创建一数据库链接

语法:

create or replace [public] database link connect_name

connect to username identified by password

using ‘connect_string’;

       创建数据库链接时具体使用的语法取决于下面两个条件:

n         数据库链接的“公共”或“私有”状态;

n         使用缺省还是显式方式登录远程数据库。

 

如果建立的数据库链接是公共所用,则在创建时应指明关键字 public;无此参数系统默认为私有;

可以为数据库链接指定用户和密码,如下:

create or replace database link db_link_1

connect to ‘scott’ identified by ‘tiger’

using ‘hq’

则在当前数据库创建了一个指向远程数据库”hq”的链接,连接时所用的用户名和密码为“tiger”;

如果不指定用户和密码,则在应用数据库链接,系统会使用当时的用户进行尝试连接,创建过程如下:

create or replace database link db_link_1

using ‘hq’

(3)远程数据库对象的引用

创建数据库链接以后,在当前数据库就可以访问远程数据库中具有访问权限的对象,引用的方法为将数据库链接名称添加到任何可以访问远程帐号的表或视图上。当将数据库链接名称加添加到表或视图名称上时,必须在数据库链接名称之前使用一个“@”,如:

select * from [email protected]_connect;

(3)  使用同义词对远程对象进行访问

对于已创建了数据库链接的远程数据中对象,可以在本地数据库创建其同义词,达到在访问在逻辑上相当天本地数据库对象,使语法简洁,如下:

create synonym worker_syn

 for [email protected]_connect;

创建后,对于远程数据库remote_connect的worker表的访问就可以变成如下:

select * from worker_syn;
 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表