Oracle Migration Workbench: Reference Guide For SQL Server and Sybase Adaptive Server Migrations
Oracle Migration Workbench: Reference Guide For SQL Server and Sybase Adaptive Server Migrations
Oracle Migration Workbench: Reference Guide For SQL Server and Sybase Adaptive Server Migrations
Reference Guide for SQL Server and Sybase Adaptive Server Migrations
September 2002
Part Number: B10254-01
This reference guide describes how to migrate from Microsoft SQL Server 6.5,
Microsoft SQL Server 7.0, Microsoft SQL Server 2000, Sybase Adaptive Server
11, and Sybase Adaptive Server 12 to Oracle9i or Oracle8i.
Migration Workbench Reference Guide for SQL Server and Sybase Adaptive Server Migrations, Release
9.2.0 for Microsoft Windows 98/2000/NT and Microsoft Windows XP.
Part Number: B10254-01
Copyright 1998, 2002 Oracle Corporation. All rights reserved.
The Programs (which include both the software and documentation) contain proprietary information of
Oracle Corporation; they are provided under a license agreement containing restrictions on use and
disclosure and are also protected by copyright, patent and other intellectual and industrial property
laws. Reverse engineering, disassembly, or decompilation of the Programs, except to the extent required
to obtain interoperability with other independently created software or as specified by law, is prohibited.
The information contained in this document is subject to change without notice. If you find any problems
in the documentation, please report them to us in writing. Oracle Corporation does not warrant that this
document is error free. Except as may be expressly permitted in your license agreement for these
Programs, no part of these Programs may be reproduced or transmitted in any form or by any means,
electronic or mechanical, for any purpose, without the express written permission of Oracle Corporation.
If the Programs are delivered to the U.S. Government or anyone licensing or using the programs on
behalf of the U.S. Government, the following notice is applicable:
Restricted Rights Notice Programs delivered subject to the DOD FAR Supplement are "commercial
computer software" and use, duplication, and disclosure of the Programs, including documentation,
shall be subject to the licensing restrictions set forth in the applicable Oracle license agreement.
Otherwise, Programs delivered subject to the Federal Acquisition Regulations are "restricted computer
software" and use, duplication, and disclosure of the Programs shall be subject to the restrictions in FAR
52.227-19, Commercial Computer Software - Restricted Rights (June, 1987). Oracle Corporation, 500
Oracle Parkway, Redwood City, CA 94065.
The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently
dangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup,
redundancy, and other measures to ensure the safe use of such applications if the Programs are used for
such purposes, and Oracle Corporation disclaims liability for any damages caused by such use of the
Programs.
Oracle is a registered trademark, and Oracle8, Oracle8i, Oracle9i, SQL*Plus, PL/SQL, and Pro*C are
trademarks or registered trademarks of Oracle Corporation. Other names may be trademarks of their
respective owners.
Contents
Send Us Your Comments ................................................................................................................... ix
Preface............................................................................................................................................................ xi
Audience ................................................................................................................................................ xii
What You Should Already Know....................................................................................................... xii
How this Reference Guide is Organized ........................................................................................... xii
Using This Reference Guide................................................................................................................ xiii
Documentation Accessibility .............................................................................................................. xiii
Accessibility of Code Examples in Documentation......................................................................... xiii
Related Documentation ....................................................................................................................... xiii
Conventions.......................................................................................................................................... xiv
Overview
Introduction .........................................................................................................................................
Product Description............................................................................................................................
Features .................................................................................................................................................
Glossary ................................................................................................................................................
1-1
1-1
1-2
1-3
2-1
2-1
2-3
2-3
2-3
iii
2-6
2-7
2-7
2-7
2-8
2-9
2-21
2-21
2-26
2-27
2-28
2-35
2-36
2-37
2-39
2-40
2-40
2-44
2-44
2-45
2-45
2-46
2-46
2-48
2-49
2-51
2-52
2-52
2-55
2-56
2-57
iv
Stored Procedures.........................................................................................................................
Methods Used to Send Data to Clients ..............................................................................
Individual SQL Statements ................................................................................................
Logical Transaction Handling ...........................................................................................
Error Handling within the Stored Procedure..................................................................
Data Types..........................................................................................................................................
Local Variable..............................................................................................................................
Server Data Types.......................................................................................................................
Composite Data Types...............................................................................................................
Schema Objects .................................................................................................................................
Procedure.....................................................................................................................................
Function .......................................................................................................................................
Package.........................................................................................................................................
Package Body ..............................................................................................................................
T/SQL Versus PL/SQL Constructs .................................................................................................
CREATE PROCEDURE Statement ...................................................................................
Parameter Passing ...............................................................................................................
DECLARE Statement ..........................................................................................................
IF Statement..........................................................................................................................
RETURN Statement ............................................................................................................
RAISERROR Statement ......................................................................................................
EXECUTE Statement...........................................................................................................
WHILE Statement................................................................................................................
GOTO Statement .................................................................................................................
@@Rowcount and @@Error Variables ..............................................................................
ASSIGNMENT Statement ..................................................................................................
SELECT Statement ..............................................................................................................
SELECT Statement as Part of the SELECT List ...............................................................
SELECT Statement with GROUP BY Clause...................................................................
Column Aliases....................................................................................................................
UPDATE with FROM Statement.......................................................................................
DELETE with FROM Statement ........................................................................................
Temporary Tables................................................................................................................
Result Set (Converted Using a Cursor Variable) ............................................................
Cursor Handling..................................................................................................................
3-3
3-4
3-13
3-14
3-15
3-16
3-17
3-17
3-17
3-17
3-18
3-24
3-28
3-32
3-36
3-38
3-39
3-40
3-41
3-45
3-46
3-47
3-48
3-53
3-54
3-55
3-56
3-59
3-61
3-62
3-63
3-65
3-67
3-68
3-70
Distributed Environments
Distributed Environments ................................................................................................................
Accessing Remote Databases in a Distributed Environment .................................................
Oracle and Remote Objects ..................................................................................................
Microsoft SQL Server and Sybase Adaptive Server and Remote Objects ............................
Replication .....................................................................................................................................
Application Development Tools ......................................................................................................
4-1
4-1
4-2
4-2
4-3
4-4
vi
3-72
3-73
3-73
3-76
3-77
3-79
3-80
3-80
3-80
3-80
3-81
3-82
5-1
5-2
5-4
5-4
5-5
5-6
5-7
5-7
5-7
5-7
5-7
5-8
5-8
5-10
5-11
5-11
Index
vii
viii
Oracle Corporation welcomes your comments and suggestions on the quality and usefulness of this
publication. Your input is an important part of the information used for revision.
If you find any errors or have any other suggestions for improvement, please indicate the chapter,
section, and page number (if available). You can send comments to us in the following ways:
ix
Preface
The Oracle Migration Workbench Reference Guide for SQL Server and Sybase Adaptive
Server Migrations provides detailed information about migrating a database from
Microsoft SQL Server 6.5, Microsoft SQL Server 7.0, Microsoft SQL Server 2000,
Sybase Adaptive Server 11, and Sybase Adaptive Server 12 to Oracle9i or Oracle8i.
It is a useful guide regardless of the conversion tool you are using to perform the
migration, but the recommended tool for such migrations is Oracle Migration
Workbench (Migration Workbench). This reference guide describes several
differences between Microsoft SQL Server and Sybase Adaptive Server and Oracle
and outlines how those differences are handled by the Migration Workbench during
the conversion process.
This chapter contains the following sections:
Audience
Documentation Accessibility
Related Documentation
Conventions
xi
Audience
This guide is intended for anyone who is involved in converting a Microsoft SQL
Server and Sybase Adaptive Server database to Oracle using the Migration
Workbench.
xii
Documentation Accessibility
Our goal is to make Oracle products, services, and supporting documentation
accessible, with good usability, to the disabled community. To that end, our
documentation includes features that make information available to users of
assistive technology. This documentation is available in HTML format, and contains
markup to facilitate access by the disabled community. Standards will continue to
evolve over time, and Oracle Corporation is actively engaged with other
market-leading technology vendors to address technical obstacles so that our
documentation can be accessible to all of our customers. For additional information,
visit the Oracle Accessibility Program Web site at
http://www.oracle.com/accessibility/
Related Documentation
For more information, see these Oracle Migration Workbench resources:
xiii
If you already have a user name and password for OTN, then you can go directly to
the Migration Workbench documentation section of the OTN Web site at:
http://otn.oracle.com/tech/migration/workbench
Conventions
This section describes the conventions used in the text and code examples of the this
documentation. It describes:
Conventions in Text
Conventions in Text
We use various conventions in text to help you more quickly identify special terms.
The following table describes those conventions and provides examples of their use.
Convention
Meaning
Bold
Italics
UPPERCASE
monospace
(fixed-width font)
xiv
Example
Convention
Meaning
Example
lowercase
monospace
(fixed-width font)
The following table describes typographic conventions used in code examples and
provides examples of their use.
Convention
Meaning
Example
Square Brackets [ ]
Curly Braces { }
{ENABLE | DISABLE}
Vertical Line |
{ENABLE | DISABLE}
[COMPRESS | NOCOMPRESS]
Ellipses ...
Italics
CONNECT SYSTEM/system_password
xv
Convention
Meaning
Example
UPPERCASE
lowercase
xvi
sqlplus hr/hr
1
Overview
This chapter introduces the Oracle Migration Workbench (Migration Workbench)
under the following headings:
Introduction
Product Description
Features
Glossary
Introduction
The Migration Workbench is a tool that simplifies the process of migrating data and
applications from an Microsoft SQL Server and Sybase Adaptive Server
environment to an Oracle9i or Oracle8i destination database. The Migration
Workbench allows you to quickly and easily migrate an entire application system,
that is the database schema including triggers and stored procedures, in an
integrated, visual environment.
Note: Microsoft SQL Server is used in this document to refer to
both Microsoft SQL Server 6.5, Microsoft SQL Server 7.0, and
Microsoft SQL Server 2000 unless otherwise stated.
Product Description
The Migration Workbench allows you to migrate a Microsoft SQL Server and
Sybase Adaptive Server database to an Oracle9i or Oracle8i database. The Migration
Workbench employs an intuitive and informative User Interface and a series of
Overview 1-1
Features
Features
The Migration Workbench release 9.2.0 is a wizard-driven tool. It is composed of
core features and Microsoft SQL Server and Sybase Adaptive Server migration
specific features. The Migration Workbench allows you to:
1-2
Migrate a complete Microsoft SQL Server and Sybase Adaptive Server database
to an Oracle9i or Oracle8i database.
Migrate groups, users, tables, primary keys, foreign keys, unique constraints,
indexes, rules, check constraints, views, triggers, stored procedures,
user-defined types, and privileges to Oracle.
Migrate multiple Microsoft SQL Server and Sybase Adaptive Server source
databases to a single Oracle database.
Customize the parser for stored procedures, triggers, or views.
Generate the Oracle SQL*Loader and SQL Server BCP scripts for offline data
loading.
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Glossary
Glossary
The following terms are used to describe the Migration Workbench:
Application System is the database schema and application files that have been
developed for a database environment other than Oracle, for example, Microsoft
SQL Server and Sybase Adaptive Server.
Capture Wizard is an intuitive wizard that takes a snapshot of the data dictionary of
the source database, loads it into the Source Model, and creates the Oracle Model.
Dependency is used to define a relationship between two migration entities. For
example, a database view is dependent upon the table it references.
Destination Database is the Oracle database to which the Migration Workbench
migrates the data dictionary of the source database.
Migration Component is part of an application system that can be migrated to an
Oracle database. Examples of migration components are tables and stored
procedures.
Migration Entity is an instance of a migration component. The table EMP would be a
migration entity belonging to the table MIGRATION COMPONENT.
Migration Wizard is an intuitive wizard that helps you migrate the source database
to Oracle.
Migration Workbench is the graphical tool that allows migration of an application
system to an Oracle database environment.
Navigator Pane is the part of the Migration Workbench User Interface that contains
the tree views representing the Source Model and the Oracle Model.
Oracle Model is a a series of Oracle tables that is created from the information in the
Source Model. It is a visual representation of how the source database looks when
generated in an Oracle environment.
Properties Pane is the part of the Migration Workbench User Interface that displays
the properties of a migration entity that has been selected in one of the tree views in
the Navigator Pane.
Progress Window is the part of the Migration Workbench User Interface that contains
informational, error, or warning messages describing the progress of the migration
process.
Software Development Kit (SDK) is a set of well-defined application programming
interfaces (APIs) that provide services that a software developer can use.
Overview 1-3
Glossary
Source Database is the database containing the data dictionary of the application
system being migrated by the Migration Workbench. The source database is a
database other than Oracle, for example, Microsoft SQL Server and Sybase
Adaptive Server.
Source Model is a replica of the data dictionary of the source database. It is stored in
the Oracle Migration Workbench Repository and is loaded by the Migration Workbench with the contents of the data dictionary of the source database.
Workbench Repository is the area in an Oracle database used to store the persistent
information necessary for the Migration Workbench to migrate an application
system.
1-4
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
2
Microsoft SQL Server, Sybase Adaptive
Server, and Oracle Compared
This chapter contains information comparing the Microsoft SQL Server and Sybase
Adaptive Server database and the Oracle database. It includes the following
sections:
Schema Migration
Data Types
Schema Migration
The schema contains the definitions of the tables, views, indexes, users, constraints,
stored procedures, triggers, and other database-specific objects. Most relational
databases work with similar objects.
The schema migration topics discussed here include the following:
2-1
Schema Migration
Table 21 Schema Objects in Oracle and Microsoft SQL Server and Sybase Adaptive
Server
2-2
Oracle
Database
Database
Schema
Tablespace
Database
User
User
Role
Group/Role
Table
Table
Temporary tables
Temporary tables
Cluster
N/A
Column-level check
constraint
Column default
Column default
Unique key
Primary key
Primary key
Foreign key
Foreign key
Index
Non-unique index
PL/SQL Procedure
PL/SQL Function
Packages
N/A
AFTER triggers
Triggers
BEFORE triggers
Complex rules
N/A
Synonyms
N/A
Sequences
Snapshot
N/A
View
View
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Migration
Data Types
Check Constraints
Data Types
This section outlines conversion considerations for the following data types:
Microsoft SQL Server and Sybase Adaptive Server User-Defined Data Types
2-3
Schema Migration
precision of 1/100000000th of a second. Oracle also has a DATE data type that
stores date and time values accurate to one second. The Migration Workbench has a
default mapping to the DATE data type.
For applications that require finer date/time precision than seconds, the
TIMESTAMP data type should be selected for the datatype mapping of date data
types in Microsoft SQL Server and Sybase Adaptive Server. The databases store
point-in-time values for DATE and TIME data types.
As an alternative, if an Microsoft SQL Server and Sybase Adaptive Server
application uses the DATETIME column to provide unique IDs instead of
point-in-time values, replace the DATETIME column with a SEQUENCE in the
Oracle schema definition.
In the following examples, the original design does not allow the DATETIME
precision to exceed seconds in the Oracle table. This example assumes that the
DATETIME column is used to provide unique IDs. If millisecond precision is not
required, the table design outlined in the following example is sufficient:
Original Table Design
Microsoft SQL Server and Sybase Adaptive Server:
CREATE TABLE example_table
(datetime_column
datetime
text_column
text
varchar_column
varchar(10)
not null,
null,
null)
Oracle:
CREATE TABLE example_table
(datetime_column
date
text_column
long
varchar_column
varchar2(10)
not null,
null,
null)
The following design allows the value of the sequence to be inserted into the
integer_column. This allows you to order the rows in the table beyond the allowed
precision of one second for DATE data type fields in Oracle. If you include this
column in the Microsoft SQL Server and Sybase Adaptive Server table, you can
keep the same table design for the Oracle database.
Revised Table Design
Microsoft SQL Server and Sybase Adaptive Server:
CREATE TABLE example_table
2-4
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Migration
(datetime_column
integer_column
text_column
varchar_column
datetime
int
text
varchar(10)
not null,
null,
null,
null)
Oracle:
CREATE TABLE example_table
(datetime_column
date
integer_column
number
text_column
long
varchar_column
varchar2(10)
not null,
null,
null,
null)
For the Microsoft SQL Server and Sybase Adaptive Server database, the value in the
integer_column is always NULL. For Oracle, the value for the field integer_column
is updated with the next value of the sequence.
Create the sequence by issuing the following command:
CREATE SEQUENCE datetime_seq
2-5
Schema Migration
2-6
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Migration
Check Constraints
Check constraints can be defined in a CREATE TABLE statement or an ALTER
TABLE statement in Microsoft SQL Server and Sybase Adaptive Server. Multiple
check constraints can be defined on a table. A table-level check constraint can
reference any column in the constrained table. A column can have only one check
constraint. A column-level check constraint can reference only the constrained
column. These check constraints support complex regular expressions.
Oracle defines check constraints as part of the CREATE TABLE or ALTER TABLE
statements. A check constraint is defined at the TABLE level and not at the
COLUMN level. Therefore, it can reference any column in the table. Oracle,
however, does not support complex regular expressions.
SQL Server Rule:
create rule phone_rule
as
@phone_number like
"([0-9][0-9][0-9])[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]"
This rule passes all the phone numbers that resemble the following:
(650)506-7000
2-7
Data Types
This rule failes all the phone numbers that resemble the following:
650-506-7000
650-GET-HELP
There are a few ways to implement this INTEGRITY constraint in Oracle:
Table-level check constraints from Microsoft SQL Server and Sybase Adaptive
Server databases map one-to-one with Oracle check constraints. You can implement
the column-level check constraints from the Microsoft SQL Server and Sybase
Adaptive Server database to Oracle table-level check constraints. While converting
the regular expressions, convert all simple regular expressions to check constraints
in Oracle. Microsoft SQL Server and Sybase Adaptive Server check constraints with
complex regular expressions can be either reworked as check constraints including
a combination of simple regular expressions, or you can write Oracle database
triggers to achieve the same functionality.
Data Types
This chapter provides detailed descriptions of the differences in data types used by
Microsoft SQL Server and Sybase Adaptive Server and Oracle databases.
Specifically, this chapter contains the following information:
2-8
A table showing the base Microsoft SQL Server and Sybase Adaptive Server
data types available and how they are mapped to Oracle data types
Recommendations based on the information listed in the table
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Data Types
Description
Oracle
Comments
INTEGER
Four-byte integer, 31
bits, and a sign. May be
abbreviated as "INT"
(this abbreviation was
required prior to
version 5).
NUMBER(10)
SMALLINT
TINYINT
NUMBER(3)
2-9
Data Types
Description
Oracle
Comments
FLOAT
2-10
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Data Types
Description
Oracle
Comments
FLOAT
2-11
Data Types
Description
Oracle
Comments
Floating-point numbers can
be specified in Oracle using
FLOAT[(b)], where [(b)] is
the binary precision [(b)]
and can range from 1 to 126.
[(b)] defaults to 126.To check
what a particular binary
precision is in terms of
decimal precision multiply
[(b)] by 0.30103 and round
up to the next whole
number.
If they are outside of the
range, large floating-point
numbers will overflow, and
small floating-point
numbers will underflow.
BIT
2-12
A Boolean 0 or 1 stored
NUMBER(1)
as one bit of a byte. Up to
8-bit columns from a
table may be stored in a
single byte, even if not
contiguous. Bit data
cannot be NULL, except
for Microsoft SQL Server
7.0, where null is allowed
by the BIT data type.
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Data Types
Description
Oracle
Fixed-length string of
CHAR(n)
exactly n 8-bit characters,
blank padded. Synonym
for CHARACTER.
0 < n < 256 for Microsoft
SQL Server and Sybase
Adaptive Server.
0 < n < 8000 for Microsoft
SQL Server 7.0.
Comments
Pro*C client programs must
use mode=ansi to have
characters interpreted
correctly for string
comparison, mode=oracle
otherwise.
A CHAR datatype with a
range of 2001 to 4000 is
invalid. The Migration
Workbench automatically
converts a CHAR datatype
with this range to
VARCHAR2.
VARCHAR(n)
TEXT
CLOB
IMAGE
BLOB
2-13
Data Types
Description
Oracle
Comments
2-14
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Data Types
Description
Oracle
Comments
The precision of DATE in
2-15
Data Types
Description
Comments
MONEY
A monetary value
NUMBER(19,4)
represented as an integer
portion and a decimal
fraction, and stored as
two 4-byte integers.
Accuracy is to the nearest
1/10,000. When
inputting Data of this
type it should be
preceded by a dollar sign
($). In the absence of the
"$" sign, Microsoft SQL
Server and Sybase
Adaptive Server create
the value as a float.
Monetary data values
can range from
-922,337,203,685,477.5808
to
922,337,203,685,477.5807,
with accuracy to a
ten-thousandth of a
monetary unit. Storage
size is 8 bytes.
2-16
Oracle
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Data Types
Description
Oracle
Comments
Fixed-length character
CHAR(n*2)
data type which uses the
UNICODE UCS-2
character set. n must be a
value in the range 1 to
4000. SQL Server storage
size is two times n.
Note: Microsoft SQL
Server storage size is two
times n. The Oracle
Migration Workbench
maps columns sizes
using byte semantics,
and the size of Microsoft
SQL Server NCHAR data
types appear in the
Oracle Migration
Workbench Source
Model with "Size"
specifying the number of
bytes, as opposed to the
number of Unicode
characters. Thus, a SQL
Server column
NCHAR(1000) will
appear in the Source
Model as NCHAR(2000).
2-17
Data Types
Description
Oracle
Comments
2-18
NUMBER(10,4)
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Data Types
Description
Oracle
Comments
TIMESTAMP
TIMESTAMP is defined
as VARBINARY(8) with
NULL allowed. Every
time a row containing a
TIMESTAMP column is
updated or inserted, the
TIMESTAMP column is
automatically
incremented by the
system. A TIMESTAMP
column may not be
updated by users.
NUMBER
SYSNAME
VARCHAR(30) in
Microsoft SQL Server
and Sybase Adaptive
Server.
VARCHAR2(30)
and
VARCHAR2(12
8) respectively.
NVARCHAR(128) in
Microsoft SQL Server 7.0.
TEXT and IMAGE data types in Microsoft SQL Server and Sybase Adaptive Server
follow the rules listed below:
The column cannot be used in the GROUP BY, ORDER BY, HAVING, and
DISTINCT clauses.
IMAGE and TEXT data types can be referred to in the WHERE clause with the
LIKE construct.
IMAGE and TEXT data types can also be used with the SUBSTR and LENGTH
functions.
In Microsoft SQL Server and Sybase Adaptive Server only columns with
variable-length data types can store NULL values. When you create a column that
allows NULLs with a fixed-length data type, the column is automatically converted
2-19
Data Types
CHAR
VARCHAR
NCHAR
NVARCHAR
BINARY
VARBINARY
DATETIME,
SMALLDATETIME
DATETIMN
FLOAT
FLOATN
INT, SMALLINT,
TINYINT
INTN
DECIMAL
DECIMALN
NUMERIC
NUMERICN
MONEY, SMALLMONEY
MONEYN
2-20
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
A table comparing the data storage concepts of Microsoft SQL Server and
Sybase Adaptive Server, and Oracle databases
Recommendations based on the information listed in the table
Datafiles:
Page:
Data Block:
Many pages constitute a database device. Each One data block corresponds to a specific
page contains a certain number of bytes.
number of bytes, of physical database
space, on the disk. The size of the data
block can be specified when creating the
database. A database uses and allocates
free database space in Oracle data blocks.
Extent:
Extent:
2-21
Table 24 Data Storage Concepts in Oracle and Microsoft SQL Server and Sybase
Adaptive Server (Cont.)
Microsoft SQL Server and Sybase Adaptive
Server
Oracle
N/A
Segments:
A segment is a set of extents allocated for a
certain logical structure. The extents of a
segment may or may not be contiguous on
disk, and may or may not span the
datafiles.
Tablespace Extent:
The following segments are created along with
An extent is a specific number of
the database:
contiguous data blocks within the same
System segment
tablespace.
Stores the system tables.
Tablespace Segments:
Log segment
A segment is a set of extents allocated for a
Stores the transaction log.
certain logical database object. All the
Default segment
segments assigned to one object must be in
All other database objects are stored on
the same tablespace. The segments get the
this segment unless specified otherwise.
extents allocated to them as and when
needed.
Segments are subsets of database devices.
There are four different types of segments
as follows:
2-22
Data segment
Each table has a data segment. All of
the table's data is stored in the extents
of its data segments. The tables in
Oracle can be stored as clusters as well.
A cluster is a group of two or more
tables that are stored together. Each
cluster has a data segment. The data of
every table in the cluster is stored in
the cluster's data segment.
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Table 24 Data Storage Concepts in Oracle and Microsoft SQL Server and Sybase
Adaptive Server (Cont.)
Microsoft SQL Server and Sybase Adaptive
Server
Oracle
Tablespace Segments (Cont):
Index segment
Each index has an index segment that
stores all of its data.
Rollback segment
One or more rollback segments are
created by the DBA for a database to
temporarily store "undo" information.
This is the information about all the
transactions that are not yet
committed. This information is used to
generate read-consistent database
information during database recovery
to rollback uncommitted transactions
for users.
Temporary segment
Temporary segments are created by
Oracle when a SQL statement needs a
temporary work area to complete
execution. When the statement finishes
execution, the extents in the temporary
segment are returned to the system for
future use.
Log Devices:
2-23
Table 24 Data Storage Concepts in Oracle and Microsoft SQL Server and Sybase
Adaptive Server (Cont.)
Microsoft SQL Server and Sybase Adaptive
Server
Oracle
Database Devices:
N/A
N/A
2-24
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Table 24 Data Storage Concepts in Oracle and Microsoft SQL Server and Sybase
Adaptive Server (Cont.)
Microsoft SQL Server and Sybase Adaptive
Server
Oracle
N/A
Control Files:
Each database has a control file. This file
records the physical structure of the
database. It contains the following
information:
database name
names and locations of a database's
datafiles and redo log files
time stamp of database creation
Recommendations:
The conceptual differences in the storage structures do not affect the conversion
process directly. However, the physical storage structures need to be in place before
conversion of the database begins.
Oracle, Microsoft SQL Server and Sybase Adaptive Server all have a way to control the
physical placement of a database object. In Microsoft SQL Server and Sybase
Adaptive Server, you use the ON SEGMENT clause and in Oracle you use the
TABLESPACE clause.
An attempt should be made to preserve as much of the storage information as
possible when converting from Microsoft SQL Server and Sybase Adaptive Server
to Oracle. The decisions that were made when defining the storage of the database
objects for Microsoft SQL Server and Sybase Adaptive Server should also apply for
Oracle. Especially important are initial object sizes and physical object placement.
2-25
SELECT Statement
INSERT Statement
UPDATE Statement
DELETE Statement
Operators
2-26
Comparison Operators
Arithmetic Operatorss
String Operators
Set Operators
Bit Operators
Built-In Functions
Character Functions
Date Functions
Mathematical Functions
Locking
Read Consistency
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
Syntax:
Syntax:
USE database_name
CONNECT user_name/password
SET role
Description:
A default database is assigned to each
user. This database is made current
when the user logs on to the server. A
user executes the USE DATABASE_
NAME command to switch to another
database.
Recommendations:
This concept of connecting to a database is conceptually different in the Microsoft
SQL Server and Sybase Adaptive Server, and Oracle databases. An Microsoft SQL
Server and Sybase Adaptive Server user can log on to the server and switch to
another database residing on the server, provided the user has privileges to access
that database. An Oracle Server controls only one database, so here the concept of a
user switching databases on a server does not exist. Instead, in Oracle a user
executes the SET ROLE command to change roles or re-issues a CONNECT
command using a different user_name.
2-27
SELECT Statement
The statement in the following table retrieves rows from one or more tables or
views.
2-28
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
Syntax:
Syntax:
SELECT [ALL | DISTINCT]
{select_list}
[INTO [owner.]table]
[FROM [owner.]{table |
view}[alias] [HOLDLOCK]
[,[owner.]{table | view
}[alias]
[HOLDLOCK]]...]
[WHERE condition]
[GROUP BY [ALL] aggregate_
free_expression [, aggregate_
free_expression]...]
[HAVING search_condition]
[UNION [ALL] SELECT...]
[ORDER BY {[[owner.]{table |
view }.]column | select_list_
number | expression}
[ASC | DESC]
[,{[[owner.]{table | view
}.]column | select_list_
number | expression}
[ASC | DESC]...]
[COMPUTE row_
aggregate(column)
[,row_aggregate(column)...]
[BY column [, column...]]]
[FOR BROWSE]
The individual element in
the select list is as
follows:
[alias = ]
{* | [owner.]{table |
view}.* | SELECT ... |
{[owner.]table.column |
constant_literal |
expression}
[alias]}
2-29
Oracle
Description:
Description:
Server and Sybase Adaptive Server directly after the selected COLUMN.
2-30
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
Oracle does not support SELECTs without FROM clauses. However, Oracle
provides the DUAL table which always contains one row. Use the DUAL table to
convert constructs such as the one above.
Translate the above query to:
SELECT sysdate FROM dual;
2-31
2-32
Year
Quantity
Amount
1993
1.3
1993
1.4
1993
1993
2.3
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
sales
year =
sales
year =
sales
year =
sales
year =
s.year),
s.year),
s.year),
s.year)
Oracle:
In this example, replace the SELECT statements with DECODE so that the query
functions as normal. The DECODE function is much faster than Microsoft SQL
Server and Sybase Adaptive Server subqueries. Translate the above query to the
following for Oracle:
SELECT year,
DECODE( qtr, 1,
DECODE( qtr, 2,
DECODE( qtr, 3,
DECODE( qtr, 4,
FROM sales s;
amt,
amt,
amt,
amt,
0
0
0
0
)
)
)
)
q1,
q2,
q3,
q4
If you cannot convert the query using the above method, create views and base the
query on the views rather than on the original tables.
For example, consider the following query in Microsoft SQL Server and Sybase
Adaptive Server:
SELECT name,
sumlength = (SELECT sum(length) FROM syscolumns WHERE id = t.id),
count_indexes = (SELECT count(*) FROM sysindexes WHERE id = t.id)
FROM sysobjects t
This query returns the sum of the lengths of the columns of a table and the number
of indexes on that table. This is best handled in Oracle by using some views.
Convert this to the following in Oracle:
CREATE view V1 ( sumlength, oid ) as
SELECT sum(length), id FROM syscolumns
2-33
GROUP BY
id
2-34
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Column Aliases:
Convert column aliases from the following Microsoft SQL Server and Sybase
Adaptive Server syntax:
SELECT employees=col1 FROM tab1e
2-35
Table 27 SELECT with GROUP BY Statement in Oracle and Microsoft SQL Server
and Sybase Adaptive Server
Microsoft SQL Server/Server
Oracle
Syntax:
Syntax:
Description:
Description:
INSERT Statement
The statements illustrated in the following table add one or more rows to the table
or view.
Table 28 INSERT Statement in Oracle and Microsoft SQL Server and Sybase
Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
INSERT [INTO]
[[database.]owner.] {table |
view}[(column [,
column]...)]{VALUES
(expression [,expression]...)
| query}
Description:
Description:
INTO is optional.
INTO is required.
Recommendations:
INSERT statements in Microsoft SQL Server and Sybase Adaptive Server must be
changed to include an INTO clause if it is not specified in the original statement.
The values supplied in the VALUES clause in either database may contain
functions. The Microsoft SQL Server-specific functions must be replaced with the
equivalent Oracle constructs.
2-36
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Note: Oracle lets you create functions that directly match most
UPDATE Statement
The statement illustrated in the following table updates the data in a table or the
data in a table referenced by a view.
Table 29 UPDATE Statement in Oracle and Microsoft SQL Server and Sybase
Adaptive Server
Microsoft SQL Server
Oracle
Syntax:
Syntax:
Description:
Description:
2-37
Recommendations:
There are two ways to convert UPDATE statements with FROM clauses as indicated
below.
Method 1 - Convert UPDATE statements with FROM clauses:
Use the subquery in the SET clause if columns are being updated to values coming
from a different table.
Convert the following in Microsoft SQL Server and Sybase Adaptive Server:
update titles
SET pub_id = publishers.pub_id
FROM titles, publishers
WHERE titles.title LIKE 'C%'
AND publishers.pub_name = 'new age'
2-38
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
DELETE Statement
The statement illustrated in the following table removes rows from tables and rows
from tables referenced in views.
Table 210 DELETE Statement in Oracle and Microsoft SQL Server and Sybase
Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
DELETE [FROM]
[[database.]owner.]{table |
view}
[FROM
[[database.]owner.]{table |
view}
[, [[database.]owner.]{table
| view}]...]
[WHERE where_clause]
Description:
Description:
FROM is optional.
2-39
Remove the second FROM even if the WHERE contains a multi-column JOIN.
Convert the following Microsoft SQL Server and Sybase Adaptive Server query:
DELETE
FROM sales
FROM sales, table_x
WHERE sales.a = table_x.a
AND sales.b = table_x.b
AND table_x.c = 'd'
Operators
Comparison Operators
The following table compares the operators used in the Microsoft SQL Server and
Sybase Adaptive Server, and Oracle databases. Comparison operators are used in
WHERE clauses and COLUMN check constraints/rules to compare values
2-40
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Table 211 Comparison Operators in Oracle and Microsoft SQL Server and Sybase
Adaptive Server
Same in All
Three
Databases
Operator
Equal to
Microsoft SQL
Server and Sybase
Adaptive Server
Only
Oracle Only
Not equal to
!=
^=
<>
Less than
<
Greater than
>
<=
!>
>=
!<
BETWEEN x
AND y
NOT BETWEEN
x AND y
Pattern Matches
LIKE 'a%'
LIKE'a[x-z]'
LIKE 'a\%'
a followed by 0 or more
LIKE 'a_'
LIKE'a[^x-z]'
ESCAPE '\'
characters
NOT LIKE
No value exists
IS NULL
A value exists
IS NOT NULL
EXISTS
(query)
NOT EXISTS
(query)
IN
=ANY
= SOME
2-41
Table 211 Comparison Operators in Oracle and Microsoft SQL Server and Sybase
Adaptive Server (Cont.)
Operator
Not equal to a member of set
Same in All
Three
Databases
Microsoft SQL
Server and Sybase
Adaptive Server
Only
Oracle Only
NOT IN
!= ANY
<> ANY
!= SOME
SOME
< ANY
< SOME
> ANY
> SOME
<= ANY
>= ANY
=ALL
!= ALL
<> ALL
< ALL
> ALL
<= ALL
>= ALL
!> ANY
!< ANY
<>
<= SOME
>= SOME
!> ALL
!< ALL
Recommendations:
1.
2-42
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
like
like
like
like
like
like
'A%'
'B%'
'C%'
'D%'
'E%'
'F%')
Table 212
NULL Construct
Oracle
FALSE
TRUE
TRUE
FALSE
If you have the following in Microsoft SQL Server and Sybase Adaptive Server:
WHERE col1 = NULL
2-43
Arithmetic Operators
Table 213 Arithmetic Operators in Oracle and Microsoft SQL Server and Sybase
Adaptive Server
Operator
Add
Subtract
Multiply
Divide
Modulo
Microsoft SQL
Server and Sybase
Adaptive Server
Only
Oracle Only
mod(x, y)
Recommendations:
Replace any Modulo functions in Microsoft SQL Server and Sybase Adaptive Server
with the mod() function in Oracle.
String Operators
Table 214 String Operators in Oracle and Microsoft SQL Server and Sybase Adaptive
Server
Operator
Concatenate
Identify Literal
'this is a string'
Microsoft SQL
Server and Sybase
Adaptive Server
Only
+
Oracle Only
||
Recommendations:
Replace all addition of strings with the || construct.
Replace all double quotes string identifiers with single quote identifiers.
2-44
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
In Microsoft SQL Server and Sybase Adaptive Server, an empty string ('') is
interpreted as a single space in INSERT or assignment statements on VARCHAR
data. In concatenating VARCHAR, CHAR, or TEXT data, the empty string is
interpreted as a single space. The empty string is never evaluated as NULL. You
must bear this in mind when converting the application.
Set Operators
Table 215
Server
Set Operators in Oracle and Microsoft SQL Server and Sybase Adaptive
Microsoft SQL
Server and Sybase
Same in All
Adaptive Server
Three Databases Only
Operator
Oracle Only
UNION ALL
INTERSECT
MINUS
Bit Operators
Table 216
Server
Bit Operators in Oracle and Microsoft SQL Server and Sybase Adaptive
Microsoft SQL Server
Same in All
and Sybase Adaptive
Three Databases Server Only
Operator
bit and
&
bit or
bit exclusive or
bit not
Oracle Only
Recommendations:
Oracle enables you to write the procedures to perform bitwise operations.
2-45
If you have the following Microsoft SQL Server and Sybase Adaptive Server
construct:
X | Y :(Bitwise OR)
You could write a procedure called dbms_bits.or (x,y) and convert the above
construct to the following in Oracle:
dbms_bits.or(x,y)
Built-In Functions
Character Functions
Table 217 Character Functions in Oracle and Microsoft SQL Server and Sybase
Adaptive Server
2-46
Oracle
Description
ascii(char)
ascii(char)
char(integer_expression)
chr(integer_expression)
charindex(specified_exp,
char_string)
instr(specified_exp, char_
string, 1, 1)
datalength(expression)
difference(character_exp,
character_exp)
isnull(variable, new_value)
nvl(variable, new_value)
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Table 217 Character Functions in Oracle and Microsoft SQL Server and Sybase
Adaptive Server (Cont.)
Microsoft SQL Server and
Sybase Adaptive Server
Oracle
Description
lower(char_exp)
lower(char_exp)
ltrim(char_exp)
ltrim(char_exp)
patindex(pattern,
column_name)
replicate(char_exp, n)
rpad(char_exp,
length(char_exp)*n, '')
reverse(char_string)
right(char_exp, n)
substr(char_exp,
(length(char_exp)
rtrim(char_exp)
rtrim(char_exp)
soundex(exp)
soundex(exp)
space(int_exp)
str(float_exp, length)
to_char(float_
exp)stuff(char_exp, start,
length, replace_
str)substr(char_exp, 1,
start) ||replace_str
||substr(char_exp,
start+length)
2-47
Table 217 Character Functions in Oracle and Microsoft SQL Server and Sybase
Adaptive Server (Cont.)
Microsoft SQL Server and
Sybase Adaptive Server
Oracle
Description
substring(char_exp, start,
length)
substr(char_exp, start,
length)
textptr(column_name)
Returns a pointer as a
varbinary(16) data type for a
named IMAGE or TEXT
column.
textvalid("column_name",
text_pointer)
upper(char_exp)
upper(char_exp)
Miscellaneous Functions
Table 218 Comparison Operators in Oracle and Microsoft SQL Server and Sybase
Adaptive Server
Microsoft SQL Server and
Sybase Adaptive Server
Oracle
Description
datalength(expression)
lengthb
isnull(variable, new_value)
nvl(variable, new_value)
Note: The above functions tables list all the Microsoft SQL Server
2-48
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Date Functions
Table 219
Server
Microsoft SQL Server and
Sybase Adaptive Server
Date Functions in Oracle and Microsoft SQL Server and Sybase Adaptive
Oracle
Description
dateadd(dd, int_
exp,datetime_var)
date+int_exp
requires conversion of
int_exp to a number of
days
dateadd(mm, int_
exp,datetime_var)
add_months(date, int_
exp)
or
date+int_exp requires
conversion of int_exp to
a number of days
dateadd(yy, int_
exp,datetime_var)
date+int_exp
requires conversion of
int_exp to a number of
days
datediff(dd,
datetime1,datetime2)
date2-date1
datediff(mm,
datetime1,datetime2)
months_between
( date2, date1)
datediff(yy,
datetime1,datetime2)
(date2-date1) /365.254
2-49
Table 219 Date Functions in Oracle and Microsoft SQL Server and Sybase Adaptive
Server (Cont.)
Microsoft SQL Server and
Sybase Adaptive Server
datename (datepart, date)
Oracle
to_char(date, format)
Description
Returns the specified part of the date as
an integer. The Microsoft SQL Server
and Sybase Adaptive Server DATETIME
has a higher precision than Oracle
DATE. For this reason, it is not always
possible to find an equivalent format
string in Oracle to match the datepart in
to_char(date, format)
getdate()
sysdate
Recommendations:
The above table lists all the Microsoft SQL Server and Sybase Adaptive Server date
manipulation functions. It does not list all the Oracle date functions. There are many
more Oracle date manipulation functions that you can use.
It is recommended that you convert most date manipulation functions to "+" or "-"
in Oracle.
Oracle adds the ability to define functions. With this feature you can create Oracle
functions that match the name and functionality of all Microsoft SQL Server and
Sybase Adaptive Server functions. This is a useful feature, where users can call a
PL/SQL function from a SQL statement's SELECT LIST, WHERE clause, ORDER BY
clause, and HAVING clause. With the parallel query option, Oracle executes the
PL/SQL function in parallel with the SQL statement. Hence, users create parallel
logic.
2-50
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Mathematical Functions
Table 220 Mathematical Functions in Oracle and Microsoft SQL Server and Sybase
Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
abs(n)
abs(n)
acos(n)
acos(n)
asin(n)
atan(n)
atan(n)
atn2(n,m)
ceiling(n)
ceil(n)
cos(n)
cos(n)
cot(n)
degrees(n)
exp(n)
exp(n)
floor(n)
floor(n)
log(n)
ln(n)
log10(n)
log(base,number)
pi()
power(m,n)
power(m,n)
radians(n)
rand(n)
round(n[,m])
round(n[,m])
sign(n)
sign(n)
sin(n)
sin(n)
sqrt(n)
sqrt(n)
tan(n)
tan(n)
Recommendations:
2-51
The above table lists all the Microsoft SQL Server and Sybase Adaptive Server
number manipulation functions. It does not list all the Oracle mathematical
functions. There are many more Oracle number manipulation functions that you
can use.
Oracle adds the ability to define functions. With this feature you can create Oracle
functions that match the name and functionality of all Microsoft SQL Server and
Sybase Adaptive Server functions. This is the most flexible approach. Users can
write their own functions and execute them seamlessly from a SQL statement.
Oracle functions listed in the table work in SQL as well as PL/SQL.
2-52
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Table 221
Locking in Oracle and Microsoft SQL Server and Sybase Adaptive Server
Oracle
Microsoft SQL Server and Sybase Adaptive Oracle locking is fully automatic and does not
Server locking is fully automatic and does require intervention by users. Oracle features
not require intervention by users.
the following categories of locks:
Microsoft SQL Server and Sybase Adaptive
Server apply exclusive locks for INSERT,
UPDATE, and DELETE operations. When
an exclusive lock is set, no other transaction
can obtain any type of lock on those objects
until the original lock is in place.
For non-update or read operations, a
shared lock is applied. If a shared lock is
applied to a table or a page, other
transactions can also obtain a shared lock
on that table or page. However, no
transaction can obtain an exclusive lock.
Therefore, Microsoft SQL Server and
Sybase Adaptive Server reads block the
modifications to the data.
2-53
Table 221
Locking in Oracle and Microsoft SQL Server and Sybase Adaptive Server
Oracle
Table-level data locks can be held in any of the
following modes:
Row share table lock (RW):
This indicates that the transaction holding the
lock on the table has locked rows in the table
and intends to update them. This prevents
other transactions from obtaining exclusive
write access to the same table by using the
LOCK TABLE table IN EXCLUSIVE MODE
statement. Apart from that, all the queries,
inserts, deletes, and updates are allowed in
that table.
Row exclusive table lock (RX):
This generally indicates that the transaction
holding the lock has made one or more
updates to the rows in the table. Queries,
inserts, deletes, updates are allowed in that
table.
Share lock (SL):
Share row exclusive lock(SRX)
Exclusive lock (X):
The dynamic performance table V$LOCK
keeps the information about locks.
Recommendations:
In Microsoft SQL Server and Sybase Adaptive Server, SELECT statements obtain
shared locks on pages/rows. This prevents other statements from obtaining an
exclusive lock on those pages/rows. All statements that update the data need an
exclusive lock. This means that the SELECT statement in Microsoft SQL Server and
Sybase Adaptive Server blocks the UPDATE statements as long as the transaction
that includes the SELECT statement does not commit or rollback. This also means
that two transactions are physically serialized whenever one transaction selects the
data and the other transaction wants to change the data first and then select the data
again. In Oracle, however, SELECT statements do not block UPDATE statements,
2-54
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
since the rollback segments are used to store the changed data before it is updated
in the actual tables. Also, the reader of the data is never blocked in Oracle. This
allows Oracle transactions to be executed simultaneously.
If Microsoft SQL Server and Sybase Adaptive Server logical transactions are
automatically translated to Oracle logical transactions, the transactions explained
above that execute properly in Microsoft SQL Server and Sybase Adaptive Server as
they are serialized causes a deadlock in Oracle. These transactions should be
identified and serialized to avoid the deadlock. These transactions are serialized in
Microsoft SQL Server and Sybase Adaptive Server as INSERT, UPDATE, and
DELETE statements block other statements.
Oracle
Oracle has a row-locking feature. Only one row is
locked when a DML statement is changing the row.
2-55
Recommendations:
No changes are required to take advantage of the row-level locking feature of
Oracle.
Read Consistency
Table 223 Read Consistency in Oracle and Microsoft SQL Server
and Sybase Adaptive Server
Microsoft SQL Server
Oracle
2.
2-56
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
2-57
Table 224 Logical Transaction Handling in Oracle and Microsoft SQL Server and
Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
When a CHECKPOINT occurs, the
completed transactions are written to the
database device. A CHECKPOINT writes all
dirty pages to the disk devices that have
been modified since last checkpoint
Recommendations:
Transactions are not implicit in Microsoft SQL Server and Sybase Adaptive Server.
Therefore, applications expect that every statement they issue is automatically
committed it is executed.
Oracle transactions are always implicit, which means that individual statements are
not committed automatically. When converting an Microsoft SQL Server and Sybase
Adaptive Server application to an Oracle application, care needs to be taken to
determine what constitutes a transaction in that application. In general, a COMMIT
work statement needs to be issued after every "batch" of statements, single
statement, or stored procedure call to replicate the behavior of Microsoft SQL Server
and Sybase Adaptive Server for the application.
2-58
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
In Microsoft SQL Server and Sybase Adaptive Server, transactions may also be
explicitly begun by a client application by issuing a BEGIN TRAN statement during
the conversion process.
2-59
2-60
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
3
Triggers and Stored Procedures
This chapter includes the following sections:
Introduction
Data Types
Schema Objects
Introduction
Microsoft SQL Server and Sybase Adaptive Server store triggers and stored
procedures with the server. Oracle stores triggers and stored subprograms with the
server. Oracle has three different kinds of stored subprograms, namely functions,
stored procedures, and packages. For detailed discussion on all these objects, see the
PL/SQL User's Guide and Reference, Release 1 (9.0.1).
The following topics are discussed in this section:
Triggers
Stored Procedures
Triggers
Microsoft SQL Server and Sybase Adaptive Server database triggers are AFTER
triggers. This means that triggers are fired after the specific operation is performed.
For example, the INSERT trigger fires after the rows are inserted into the database.
If the trigger fails, the operation is rolled back.
3-1
Introduction
Microsoft SQL Server and Sybase Adaptive Server allow INSERT, UPDATE, and
DELETE triggers. Triggers typically need access to the before image and after image
of the data that is being changed. Microsoft SQL Server and Sybase Adaptive Server
achieve this with two temporary tables called INSERTED and DELETED. These two
tables exist during the execution of the trigger. These tables and the table for which
the trigger is written have the exact same structure. The DELETED table holds the
before image of the rows that are undergoing change because of the
INSERT/UPDATE/DELETE operation, and the INSERTED table holds the after
image of these rows. If there is an error, the triggers can issue a rollback statement.
Most of the Microsoft SQL Server and Sybase Adaptive Server trigger code is
written to enforce referential integrity. Microsoft SQL Server and Sybase Adaptive
Server triggers are executed once per triggering SQL statement (such as INSERT,
UPDATE, or DELETE). If you want some actions to be performed for each row that
the SQL statement affects, you must code the actions using the INSERTED and
DELETED tables.
Oracle has a rich set of triggers. Oracle also provides triggers that fire for events
such as INSERT, UPDATE, and DELETE. You can also specify the number of times
that the trigger action is to be executed. For example, once for every row affected by
the triggering event (such as might be fired by an UPDATE statement that updates
many rows), or once for the triggering statement (regardless of how many rows it
affects).
A ROW trigger is fired each time that the table is affected by the triggering event.
For example, if an UPDATE statement updates multiple rows of a table, a row
trigger is fired once for each row affected by the UPDATE statement. A
STATEMENT trigger is fired once on behalf of the triggering statement, regardless
of the number of rows in the table that the triggering statement affects.
Oracle triggers can be defined as either BEFORE triggers or AFTER triggers.
BEFORE triggers are used when the trigger action should determine whether the
triggering statement should be allowed to complete. By using a BEFORE trigger,
you can avoid unnecessary processing of the triggering statement and its eventual
rollback in cases where an exception is raised.
As combinations, there are four different types of triggers in Oracle:
3-2
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Introduction
In the following example, the group function AVG is used to calculate the average
salary:
SELECT AVG(inserted.salary)
FROM inserted a, deleted b
WHERE a.id = b.id;
This would be converted to Oracle by creating an AFTER ROW trigger to insert all
the updated values into a package, and an AFTER STATEMENT trigger to read
from the package and calculate the average.
For examples of Oracle triggers, see the Oracle9i Application Developer's Guide Fundamentals, Release 1 (9.0.1).
Stored Procedures
Stored procedures provide a powerful way to code the application logic that can be
stored with the server. Microsoft SQL Server and Sybase Adaptive Server and
Oracle all provide stored procedures.
The language used to code these objects is a database-specific procedural extension
to SQL. In Oracle it is PL/SQL and in Microsoft SQL Server and Sybase Adaptive
Server it is Transact SQL (T/SQL). These languages differ to a considerable extent.
The individual SQL statements and the procedural constructs, such as
if-then-else, are similar in both versions of the procedural SQL. Considerable
differences can be found in the following areas discussed in this section:
This section also considers various components of typical Microsoft SQL Server and
Sybase Adaptive Server stored procedures and suggests ways to design them in
order to avoid conversion problems. By applying the standards described below to
3-3
Introduction
the coding, you can convert your stored procedures from Microsoft SQL Server and
Sybase Adaptive Server to Oracle.
Output Variables
Results Sets: Microsoft SQL Server and Sybase Adaptive Server Method of
Sending Data to the Client
Microsoft SQL Server and Sybase Adaptive Server: Multiple Results Sets
Output Variables
Microsoft SQL Server and Sybase Adaptive Server and Oracle can all send data to
clients by means of output variables.
Results Sets: Microsoft SQL Server and Sybase Adaptive Server Method of Sending Data to the
Client
Many Microsoft SQL Server and Sybase Adaptive Server applications rely on the
SQL Server-specific stream-based data return method called "result sets". Oracle is
optimized to return data more efficiently when the data is requested using an
ANSI-standard SQL SELECT statement, as compared to any proprietary stored
procedure method. Therefore, the best design decision is to use stored procedures
for data processing and SELECT statements for queries.
In Oracle, the use of cursor variables allows client programs to retrieve
well-structured result sets.
3-4
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Introduction
To send even a single row back to the client from the stored procedure, Microsoft
SQL Server and Sybase Adaptive Server can use result sets instead of an
ANSI-standard method.
For example:
CREATE PROCEDURE get_emp_rec @empid INT
AS
SELECT fname, lname, loginid, addr, title, dept, mgrid
FROM employee
WHERE empid = @empid
Output variables are a structured way of sending data from server to client. Output
variables allow the caller to see the results in a predictable manner, as the structure
of the output variable is predefined. This method also allows encapsulation of
behavior of the stored procedures.
Output variables offer the following benefits:
If a third-party user interface product uses the result set capability of Microsoft SQL
Server and Sybase Adaptive Server, make sure that the same functionality can be
3-5
Introduction
made available to the Oracle database. For example, PowerBuilder can use result
sets to populate the data windows.
Although many client programs, such as Oracle Call Interface (OCI), precompilers,
SQL*Module, and SQL*Plus, recognize cursor variables, most Open Database
Connectivity (ODBC) drivers cannot recognize cursor variables. One solution when
using ODBC drivers is to identify the code that produces the result set, and move
this code online in the client program. The Oracle9i and Oracle8i ODBC Driver
release 8.1.5.4.0 and later releases support result sets.
In the following example, an Microsoft SQL Server and Sybase Adaptive Server
stored procedure returns a result set with multiple rows:
CREATE PROCEDURE make_loginid
BEGIN
update employee
set loginid = substring(fname,1,1) + convert(varchar(7),empid)
select fname, lname, loginid from employee
END
This procedure sends all the qualifying rows to the client as a continuous data
stream. To further process the rows, the client program must retrieve the rows one
after another from the communication channel.
The following piece of the DB-Library/C code executes the above procedure and
prints each row to the screen.
main()
{
/*
3-6
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Introduction
You can migrate Microsoft SQL Server and Sybase Adaptive Server stored
procedures to the Oracle PL/SQL stored procedures or packages in different ways,
as follows:
1.
Place the final SELECT statement, which should return the result rows, in
the client program. The Oracle client can fetch the result rows from the
server as a multi-row array, and the entire process is very efficient.
2.
Make use of PL/SQL tables. The SELECT statement in this case is part of
the stored procedure code and the columns in the result rows are stored in
PL/SQL tables. These tables are available to the client program as output
variables from the stored procedures.
3.
This method is the default method used by the Migration Workbench. This
method is applicable only when it is extremely necessary to simulate the
looping mechanism of the Microsoft SQL Server and Sybase Adaptive
Server client to retrieve the result rows. This process is not recommended in
Oracle because for each row that has to be retrieved, a FETCH request must
be sent to the server from the client, thus creating more network traffic. In
this case, an Microsoft SQL Server and Sybase Adaptive Server stored
procedure is converted to a package and a member procedure. A cursor is
defined with the package body; this cursor is equivalent to the SELECT
statement associated with the result set. The first call to the procedure
opens the cursor. Subsequent calls fetch and send the next row back to the
client in the form of output parameters. Once the last row has been fetched,
the cursor is closed.
Examples of these different Oracle solutions to the result set problem are presented
below:
1.
If the SELECT statement is made part of the client code, the PL/SQL code for
the make_loginid procedure is as follows:
CREATE OR REPLACE PROCEDURE make_loginid
AS
BEGIN
3-7
Introduction
update employee
set loginid = substr(lname,1,1)
||
substr(to_char(empid),1,7);
END;
EmpLnameTabType,
OUT
EmpLoginidTabType)
AS
DECLARE i BINARY_INTEGER := 0;
3-8
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Introduction
BEGIN
update employee
set loginid = substr(fname,1,1)
||
substr(to_char(empid),1,7);
FOR emprec IN (select fname,lname,loginid
from employee) LOOP
i := i + 1;
emp_fname_tab[i] = emprec.fname;
emp_lname_tab[i] = emprec.lname;
emp_loginid_tab[i] = emprec.loginid;
END LOOP;
END make_loginid;
END make_loginid_pkg;
This procedure updates the PL/SQL tables with the data. This data is then
available to the client after the execution of this packaged procedure.
2.
The following packaged procedure sends the rows one after the other to the
client upon each call to the packaged procedure. The make_loginid_
pkg.update_loginid procedure must be executed once and the make_
loginid_pkg.fetch_emprec procedure must be executed in a loop to fetch
the rows one after another from the client program.
The package definition is as follows:
CREATE OR REPLACE PACKAGE make_loginid_pkg
IS
BEGIN
PROCEDURE update_loginid;
PROCEDURE fetch_emprec
done_flag
IN OUT INTEGER,
nrows
IN OUT INTEGER,
fname
OUT
VARCHAR2,
lname
OUT
VARCHAR2,
loginid OUT
VARCHAR2);
END make_loginid_pkg;
3-9
Introduction
PROCEDURE update_loginid
IS
BEGIN
update employee
set loginid =
substr(fname,1,1) ||
substr(to_char(loginid),1,7);
END update_loginid;
PROCEDURE fetch_emprec
done_flag
IN OUT INTEGER,
nrows
IN OUT INTEGER,
fname
OUT
VARCHAR2,
lname
OUT
VARCHAR2,
loginid OUT
VARCHAR2)
IS
BEGIN
IF NOT emprec%ISOPEN THEN
OPEN emprec;
nrows := 0;
END IF;
done_flag := 0;
FETCH emprec INTO fname, lname, loginid;
IF emprec%NOTFOUND THEN
CLOSE emprec;
done_flag := 1;
ELSE
nrows := nrows + 1;
ENDIF;
END fetch_emprec;
END make_loginid_pkg;
3-10
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Introduction
SELECT statement to a calling client program. Cursor variables can even be the
return value of a function. The cursor variables preserve well-structured
programming concepts while allowing the client routine to retrieve result sets.
Typically, the cursor would be declared in a client program (for example, OCI,
precompilers, SQL*Module, or SQL*Plus) and then passed as an IN OUT parameter
to the PL/SQL procedure. The procedure then opens the cursor based on a SELECT
statement. The calling program performs the FETCHs from the cursor, including the
possibility of using ARRAY FETCH to retrieve multiple rows in one network
message, and closes the cursor when it is done.
Pro*C Client:
...
struct emp_record {
char ename[11];
float sal;
}emp_record;
SQL_CURSOR c;
EXEC SQL EXECUTE
BEGIN
emp_package.open_emp(:c,1);
END;
END-EXEC;
...
/* fetch loop until done */
EXEC SQL FETCH :c INTO :emp_record;
...
CLOSE :c;
...
Oracle Server:
CREATE OR REPLACE PACKAGE emp_package IS
TYPE emp_part_rec IS RECORD
(ename emp.ename%type, sal emp.sal%type);
TYPE emp_cursor IS REF CURSOR
RETURN emp_part_rec;
PROCEDURE open_emp (c_emp IN OUT emp_cursor,
select_type IN NUMBER);
END emp_package;
CREATE OR REPLACE PACKAGE BODY emp_package IS
PROCEDURE open_emp (c_emp IN OUT emp_cursor,
Introduction
select_type IN NUMBER) IS
BEGIN
IF select_type=1 THEN
OPEN c_emp FOR SELECT ename, sal FROM EMP
WHERE COMM IS NOT NULL;
ELSE
OPEN c_emp FOR SELECT ename, sal FROM EMP;
END IF;
END open_emp;
END emp_package;
Microsoft SQL Server and Sybase Adaptive Server: Multiple Results Sets
Microsoft SQL Server and Sybase Adaptive Server stored procedures can return
multiple different result sets to the calling routine.
For example, consider the following procedure:
CREATE PROCEDURE example_proc
AS
BEGIN
SELECT empno, empname, empaddr FROM emp
WHERE empno BETWEEN 1000 and 2000
SELECT empno, deptno, deptname FROM emp, dept
WHERE emp.empno = dept.empno
AND emp.empno BETWEEN 1000 and 2000
END
This procedure returns two different result sets. The client is responsible for
processing the results. To convert Microsoft SQL Server and Sybase Adaptive Server
multiple result sets to Oracle, pass one more cursor variable to the stored procedure
to open a second cursor; the client program then looks at both cursor variables for
data. However, it can be difficult to track all the result sets in a single procedure. It
is recommended that you just use one result set, that is, one cursor variable per
procedure, if possible.
Microsoft SQL Server and Sybase Adaptive Server: Cursors
Cursors allow row-by-row operations on a given result set. Microsoft SQL Server
and Sybase Adaptive Server provide ANSI-standard SQL syntax to handle cursors.
The additional DECLARE CURSOR, OPEN, FETCH, CLOSE, and DEALLOCATE
CURSOR clauses are included in T/SQL. Using these statements you can achieve
3-12
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Introduction
The manual intervention required to convert statements such as this can be seen in
the following examples:
Microsoft SQL Server and Sybase Adaptive Server:
DELETE sales
FROM sales, titles
WHERE sales.title_id = titles.title_id
AND titles.type = 'business'
Oracle:
DELETE
FROM sales
WHERE title_id IN
(SELECT title_id
Introduction
FROM titles
WHERE type = 'business'
)
Oracle:
UPDATE titles O
SET price = (
SELECT (O.price + I.author_royalty)
FROM title_author I
WHERE I.title_id = O.title_id)
WHERE EXISTS
(SELECT 1
FROM title_author
WHERE title_author.title_id = O.title_id) ;
All the ANSI-standard SQL statements can be converted from one database to
another using automatic conversion utilities.
3-14
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Introduction
Data Types
In this code example, if the first SELECT statement does not return any rows, the
value of @x could be UNDEFINED. If the control is passed on to the next statement
without raising an exception, the second statement returns incorrect results because
it requires the value of @x to be set by an earlier statement. In a similar situation,
Oracle PL/SQL raises a NO_DATA_FOUND exception if the first statement fails.
RAISERROR Statement
The Microsoft SQL Server and Sybase Adaptive Server RAISERROR statement does
not return to the calling routine. The error code and message is passed to the client,
and the execution of the stored procedure continues further. The Oracle RAISE_
APPLICATION_ERROR statement returns to the calling routine. As a standard, a
RETURN statement must appear after the RAISERROR statement in Microsoft SQL
Server and Sybase Adaptive Server, so that it can be converted to the Oracle RAISE_
APPLICATION_ERROR statement.
Customized Error Messages
Microsoft SQL Server and Sybase Adaptive Server allow you to customize the error
messages using a system table. The system procedures allow the user to add error
messages to the system. Adding error messages to the Microsoft SQL Server and
Sybase Adaptive Server system table is not desirable because there is no equivalent
on the Oracle system. This can be avoided by maintaining a user-defined error
messages table, located in the centralized database. Standard routines can be
written to add the error message to the table and retrieve it whenever necessary.
This method serves a two-fold purpose: it ensures that the system is more portable
across different types of database servers, and it gives the administrator centralized
control over the error messages.
Data Types
This section provides information about data types under the following headings:
3-16
Local Variable
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Local Variable
T/SQL local variables can be any server data type except TEXT and IMAGE.
PL/SQL local variables can be any server data type including the following:
BINARY_INTEGER
BOOLEAN
PL/SQL local variables can also be either of the following composite data types
allowed by PL/SQL:
RECORD
TABLE
Comments
RECORD
TABLE
Schema Objects
This section compares the following Microsoft SQL Server and Sybase Adaptive
Server and Oracle schema objects:
Procedure
Function
Schema Objects
Package
Package Body
Each schema object is compared in separate tables based on create, drop, execute
and alter, where applicable. The tables are divided into the following four sections
Syntax
Description
Permissions
Examples
Procedure
This section provides the following tables for the schema object Procedure :
Create
Drop
Execute
Alter
Create
Table 32 Comparison of Creating the Procedure Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
3-18
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Oracle
Description:
Description:
Permissions:
Schema Objects
Oracle
Example:
Example:
Recommendations:
Functionally identical parts can be identified in the T/SQL procedure and PL/SQL
procedure structure. Therefore, you can automate the conversion of most of the
constructs from Microsoft SQL Server and Sybase Adaptive Server to Oracle.
OR REPLACE keywords in an Oracle CREATE PROCEDURE statement provide an
elegant way of recreating the procedure. In Microsoft SQL Server and Sybase
Adaptive Server, the procedure must be dropped explicitly before replacing it.
Drop
Table 33 Comparison of Dropping the Procedure Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
3-20
Description:
Description:
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Oracle
Permissions:
Permissions:
Example:
Example:
Recommendations:
The above statement does not have any effect on the conversion process. This
information is provided for reference only.
Execute
Table 34 Comparison of Executing the Procedure Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
procedure
[([{actual_parameter |
constant_literal |
formal_parameter =>
{actual_parameter |
constant_literal}
}]
[,{actual_parameter |
constant_literal |
formal_parameter =>
{actual_parameter |
constant_literal}
}] ....
)]
Schema Objects
Oracle
Description:
Description:
Positional notation:
The actual parameters are supplied to the
procedure in the same order as the formal
parameters in the procedure definition.
Positional notation:
The actual parameters are supplied to the
procedure in the same order as the formal
parameters in the procedure definition.
Named notation:
The actual parameters are supplied to the
procedure in an order different than that of
the formal parameters in the procedure
definition by using the name of the formal
parameter as:
Named notation:
The actual parameters are supplied to the
procedure in an order different than that of the
formal parameters in the procedure definition
by using the name of the formal parameter as:
@formal_parameter = @actual_
parameter
3-22
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Oracle
Permissions:
Permissions
Example:
Example:
Positional notation:
Positional notation:
Named notation:
EXEC UpdateEmpSalary
@Employee = @EmpName,
@Employee_Id = @EmpID
Named notation:
credit (acc_no => accno, acc =>
accname, amount => amt,
return_status => retstat)
Mixed notation:
EXEC UpdateEmpSalary
@EmpName, @Employee_Id = @EmpID
EXEC UpdateEmpSalary
@Employee = @EmpName, @EmpID
Schema Objects
Alter
Table 35 Comparison of Altering the Procedure Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
Description:
Description:
Permissions:
Permissions:
The owner of the procedure can issue this The procedure must be in the user's schema or
command
the user must have the ALTER ANY
PROCEDURE privilege to use this command
Example:
sp_recompile my_proc
Example:
ALTER PROCEDURE sam.credit COMPILE;
Function
This section provides the following tables for the schema object Function:
3-24
Create
Drop
Execute
Alter
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Create
Table 36 Comparison of Creating the Function Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
Description:
The OR REPLACE keywords replace the
function with the new definition if it already
exists.
Parameters passed to the PL/SQL function can
be specified as "IN" (input), "OUT" (output), or
"IN OUT" (input and output). In the absence of
these keywords the parameter is assumed to be
IN.
Permissions:
To create a function in your own schema, you
must have the CREATE PROCEDURE system
privilege. To create a function in another user's
schema, you must have the CREATE ANY
PROCEDURE system privilege.
Schema Objects
Oracle
N/A
Example:
CREATE FUNCTION get_bal
(acc_no IN NUMBER)
RETURN NUMBER
IS
acc_bal NUMBER(11,12);
BEGIN
SELECT balance
INTO acc_bal
FROM accounts
WHERE account_id = acc_no;
RETURN(acc_bal);
END;
Drop
Table 37 Comparison of Dropping the Function Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
N/A
Syntax:
DROP FUNCTION [schema.]function
N/A
Description:
When a function is dropped, Oracle invalidates
all the local objects that reference the dropped
function.
N/A
Permissions:
The function must be in the schema of the user
or the user must have the DROP ANY
PROCEDURE system privilege to execute this
command
N/A
Example:
DROP FUNCTION sam.credit;
3-26
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Execute
Table 38 Comparison of Executing the Function Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
N/A
Syntax:
function [({actual_parameter | constant_
literal}...)]
N/A
Description:
Functions can return an atomic value to the
calling routine using the RETURN statement.
A function can be called as part of an
expression. This is a very powerful concept. All
the Microsoft SQL Server and Sybase
Adaptive Server built-in functions can be
coded using PL/SQL, and these functions can
be called like any other built-in functions in an
expression, starting with Oracle.
N/A
Permissions:
You should have the EXECUTE privilege on the
function to execute the named function. You
need not have explicit privileges to access the
underlying objects that are referred to within
the PL/SQL function.
N/A
Example:
1) IF sal_ok (new_sal, new_title) THEN
....
END IF;
2) promotable:=
sal_ok(new_sal, new_title) AND
(rating>3);
Schema Objects
Alter
Table 39 Comparison of Altering the Function Schema Object in Oracle and
Microsoft SQL Server 7.0
Microsoft SQL Server
Oracle
N/A
Syntax:
ALTER FUNCTION [schema.]function COMPILE
N/A
Description:
This command causes the recompilation of a
function. Functions become invalid if the objects
that are referenced from within the function are
dropped or altered. Functions that become
invalid for some reason should be recompiled
explicitly using this command. Explicit
recompilation eliminates the need for implicit
recompilation and prevents associated runtime
compilation errors and performance overhead.
N/A
Permissions:
The function must be in the user's schema or the
user must have the ALTER ANY PROCEDURE
privilege to use this command
N/A
Example:
ALTER FUNCTION sam.credit COMPILE
Package
This section provides the following tables for the schema object Package:
3-28
Create
Drop
Alter
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Create
Table 310 Comparison of Creating the Package Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server
and Sybase Adaptive
Server
Oracle
Syntax:
Syntax:
END [package]
N/A
Description:
This is the external or public part of the package.
CREATE PACKAGE sets up the specification for a PL/SQL
package which can be a group of procedures, functions,
exception, variables, constants, and cursors.
Functions and procedures of the package can share data
through variables, constants, and cursors.
The OR REPLACE keywords replace the package by the new
definition if it already exists. This requires recompilation of the
package and any objects that depend on its specification.
N/A
Permissions:
To create a package in the user's own schema, the user must
have the CREATE PROCEDURE system privilege. To create a
package in another user's schema, the user must have the
CREATE ANY PROCEDURE system privilege.
Schema Objects
Table 310 Comparison of Creating the Package Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server (Cont.)
Microsoft SQL Server
and Sybase Adaptive
Server
Oracle
N/A
Example:
CREATE PACKAGE emp_actions AS
-- specification
TYPE EmpRecTyp IS RECORD (emp_id INTEGER, salary
REAL);
CURSOR desc_salary (emp_id NUMBER) RETURN EmpRecTyp;
PROCEDURE hire_employee
(ename CHAR,
job CHAR,
mgr NUMBER,
sal NUMBER,
comm NUMBER,
deptno NUMBER);
PROCEDURE fire-employee (emp_id NUMBER);
END emp_actions;
Drop
Table 311 Comparison of Dropping the Package Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
concept.
3-30
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Table 311 Comparison of Dropping the Package Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server (Cont.)
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
N/A
Description:
The BODY option drops only the body of the
package. If you omit BODY, Oracle drops both
the body and specification of the package. If you
drop the body and specification of the package,
Oracle invalidates any local objects that depend
on the package specification.
Permissions:
The package must be in the schema of the user or
the user must have the DROP ANY
PROCEDURE system privilege to execute this
command.
N/A
Example:
DROP PACKAGE emp_actions;
Alter
Table 312 Comparison of Altering the Package Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
concept.
Schema Objects
Table 312 Comparison of Altering the Package Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server (Cont.)
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
N/A
Description:
Packages that become invalid for some reason
should be recompiled explicitly using this
command.
This command causes the recompilation of all
package objects together. You cannot use the
ALTER PROCEDURE or ALTER FUNCTION
commands to individually recompile a
procedure or function that is part of a package.
PACKAGE, the default option, recompiles the
package body and specification.
BODY recompiles only the package body.
Explicit recompilation eliminates the need for
implicit recompilation and prevents associated
runtime compilation errors and performance
overhead.
N/A
Permissions:
The package must be in the user's schema or the
user must have the ALTER ANY PROCEDURE
privilege to use this command.
N/A
Example:
ALTER PACKAGE emp_actions COMPILE PACKAGE
Package Body
This section provides the following tables for the schema object Package Body:
3-32
Create
Drop
Alter
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Create
Table 313 Comparison of Creating the Package Body Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
Description:
This is the internal or private part of the
package.
CREATE PACKAGE creates the body of a
stored package.
OR REPLACE recreates the package body if it
already exists. If you change a package body,
Oracle recompiles it.
schema. is the schema to contain the package. If
omitted, the package is created in your current
schema.
Permissions:
To create a package in your own schema, you
must have the CREATE PROCEDURE privilege.
To create a package in another user's schema,
you must have the CREATE ANY PROCEDURE
privilege.
Schema Objects
Table 313 Comparison of Creating the Package Body Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server (Cont.)
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
N/A
Example:
CREATE PACKAGE BODY emp_actions AS
-- body
CURSOR desc_salary (emp_id NUMBER)
RETURN EmpRecTyp IS
SELECT empno, sal FROM emp
ORDER BY sal DESC;
PROCEDURE hire_employee
(ename
CHAR,
job
CHAR,
mgr
NUMBER,
sal
NUMBER,
comm
NUMBER,
deptno
NUMBER) IS
BEGIN
INSERT INTO emp VALUES
(empno_seq.NEXTVAL, ename,
job, mgr, SYSDATE, sal,
comm, deptno);
END hire_employee;
PROCEDURE fire_employee
(emp_id
NUMBER) IS
BEGIN
DELETE FROM emp
WHERE empno = emp_id;
END fire_employee;
END emp_actions;
3-34
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Schema Objects
Drop
Table 314 Comparison of Dropping the Package Body Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server
and Sybase Adaptive
Server
Oracle
Syntax:
Syntax:
concept.
N/A
Description:
The BODY option drops only the body of the package. If you
omit BODY, Oracle drops both the body and specification of the
package. If you drop the body and specification of the package,
Oracle invalidates any local objects that depend on the package
specification.
schema. is the schema containing the package. If you omit
Permissions:
The package must be in the your own schema or you must
have the DROP ANY PROCEDURE system privilege to
execute this command.
N/A
Example:
DROP PACKAGE BODY emp_actions;
Alter
Table 315 Comparison of Altering the Package Body Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Syntax:
Syntax:
Table 315 Comparison of Altering the Package Body Schema Object in Oracle and
Microsoft SQL Server and Sybase Adaptive Server (Cont.)
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
N/A
Description:
Packages that become invalid for some reason
should be recompiled explicitly using this
command.
This command causes the recompilation of all
package objects together. You cannot use the
ALTER PROCEDURE or ALTER FUNCTION
commands to individually recompile a
procedure or function that is part of a package.
PACKAGE, the default option, recompiles the
package body and specification.
BODY recompiles only the package body.
Explicit recompilation eliminates the need for
implicit recompilation and prevents associated
runtime compilation errors and performance
overhead.
N/A
Permissions:
The package must be your own schema or you
must have the ALTER ANY PROCEDURE
privilege to use this command.
N/A
Example:
ALTER PACKAGE emp_actions COMPILE
BODY
3-36
Parameter Passing
DECLARE Statement
IF Statement
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
RETURN Statement
RAISERROR Statement
EXECUTE Statement
WHILE Statement
GOTO Statement
ASSIGNMENT Statement
SELECT Statement
Column Aliases
Temporary Tables
Cursor Handling
Listed is the syntax for the Microsoft SQL Server and Sybase Adaptive Server
constructs and their Oracle equivalents, as well as comments about conversion
considerations.
The procedures in the Oracle column are the direct output of the Migration
Workbench. These PL/SQL procedures have more lines of code compared to the
source Microsoft SQL Server and Sybase Adaptive Server procedures because these
PL/SQL procedures are converted to emulate Microsoft SQL Server and Sybase
Adaptive Server functionality. The PL/SQL procedures written from scratch for the
same functionality in Oracle would be much more compact. The PL/SQL
procedures generated by the Migration Workbench indicate the manual conversion
required by adding appropriate commands. In general, the Migration Workbench
deals with the Microsoft SQL Server and Sybase Adaptive Server T/SQL constructs
in one of the following ways:
Oracle
CREATE OR REPLACE FUNCTION PROC1
RETURN INTEGER
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
BEGIN
RETURN 0;
END PROC1;
/
Comments
An Microsoft SQL Server and Sybase Adaptive Server stored procedure can be
converted to a stored procedure, a function, or a package in Oracle. The output
depends upon the option used when running the Migration Workbench.
The Migration Workbench automatically adds what is necessary to simulate
Microsoft SQL Server and Sybase Adaptive Server functionality. In the example in
Table 3-16 above, the Migration Workbench added the following three variables:
StoO_selcnt
StoO_error
StoO_rowcnt
3-38
INTEGER;
INTEGER;
INTEGER;
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
These variables are needed in the EXCEPTION clause in the PL/SQL procedures
that must be added for each SQL statement to emulate Microsoft SQL Server and
Sybase Adaptive Server functionality. See the SELECT Statement topic in this
section for clarification of the purpose of these variables.
Note: The REPLACE keyword is added to replace procedure,
function, or package if it already exists.
Parameter Passing
Table 317 Comparison of Parameter Passing in Oracle and Microsoft SQL Server
and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
CREATE PROC proc1
@x int=-1,
@y money,
@z bit OUT,
@a char(20) = 'TEST'
AS
RETURN 0
Oracle
CREATE OR REPLACE FUNCTION PROC1(
x
INTEGER DEFAULT -1,
y
NUMBER ,
z
IN OUT NUMBER,
a
CHAR DEFAULT 'TEST')
RETURN INTEGER
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
BEGIN
RETURN 0;
END PROC1;
/
Comments
Parameter passing is almost the same in Microsoft SQL Server and Sybase Adaptive
Server and Oracle. By default, all the parameters are INPUT parameters, if not
specified otherwise.
The value of the INPUT parameter cannot be changed from within the PL/SQL
procedure. Thus, an INPUT parameter cannot be assigned any values nor can it be
DECLARE Statement
Table 318 Comparison of DECLARE Statement in Oracle and Microsoft SQL Server
and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
/
Comments
Microsoft SQL Server and Sybase Adaptive Server and Oracle follow similar rules
for declaring local variables.
The Migration Workbench overrides the scope rule for variable declarations. As a
result, all the local variables are defined at the top of the procedure body in Oracle.
3-40
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
IF Statement
Table 319 Comparison of IF Statement in Oracle and Microsoft SQL Server and
Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Example 1:
Example 1:
Table 319 Comparison of IF Statement in Oracle and Microsoft SQL Server and
Sybase Adaptive Server (Cont.)
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Example 2:
Example 2:
3-42
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
x
INTEGER;
BEGIN
IF (PROC1.Flag = ' ') THEN
PROC1.x := -1;
ELSE
IF (PROC1.Flag = 'a') THEN
PROC1.x := 10;
ELSE
IF (PROC1.Flag = 'b') THEN
PROC1.x := 20;
END IF;
END IF;
END IF;
END;
/
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Table 319 Comparison of IF Statement in Oracle and Microsoft SQL Server and
Sybase Adaptive Server (Cont.)
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Example 3:
Example 3:
Table 319 Comparison of IF Statement in Oracle and Microsoft SQL Server and
Sybase Adaptive Server (Cont.)
Microsoft SQL Server and Sybase
Adaptive Server
Oracle
Example 4:
Example 4:
3-44
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Comments
IF statements in Microsoft SQL Server and Sybase Adaptive Server and Oracle are
nearly the same except in the following two cases:
If EXISTS(...) in Microsoft SQL Server and Sybase Adaptive Server does not have an
equivalent PL/SQL construct. Therefore, it is converted to a SELECT INTO
WHERE EXISTS clause and an IF statement as shown in Example 3 above.
IF (SELECT... ) with comparison does not have an equivalent PL/SQL construct.
Therefore, it is converted to a SELECT INTO...WHERE... clause, as shown in
Example 4 above.
RETURN Statement
Table 320 Comparison of RETURN Statement in Oracle and Microsoft SQL Server
and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
CREATE PROC proc1
@x int
AS
IF @x = -1
RETURN 25022
ELSE
RETURN 25011
Oracle
CREATE OR REPLACE FUNCTION PROC1(
x
INTEGER )
RETURN INTEGER
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
BEGIN
IF PROC1.x = -1 THEN
RETURN 25022;
ELSE
RETURN 25011;
END IF;
END PROC1;
/
Comments
A RETURN statement is used to return a single value back to the calling program
and works the same in both databases. Microsoft SQL Server and Sybase Adaptive
Server can return only the numeric data type, while Oracle can return any of the
server data types or the PL/SQL data types.
In a PL/SQL procedure, a RETURN statement can only return the control back to
the calling program without returning any data. For this reason, the value is
commented out if the Microsoft SQL Server and Sybase Adaptive Server procedure
is converted to a PL/SQL procedure, but not commented out if converted to a
PL/SQL function. The Migration Workbench does this automatically.
RAISERROR Statement
Table 321 Comparison of RAISERROR Statement in Oracle and Microsoft SQL
Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
CREATE PROC proc1
AS
RAISERROR 12345 "No Employees
found"
Oracle
CREATE OR REPLACE PROCEDURE PROC1
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
BEGIN
raise_application_error(-20999, 12345 ||
'-' || "No Employees Found");
END PROC1;
/
Comments
Microsoft SQL Server and Sybase Adaptive Server use RAISERROR to notify the
client program of any error that occurred. This statement does not end the execution
of the procedure, and the control is passed to the next statement.
PL/SQL provides similar functionality with RAISE_APPLICATION_ERROR
statements.However, it ends the execution of the stored subprogram and returns the
control to the calling program. It is equivalent to a combination of RAISERROR and
a RETURN statement.
The Migration Workbench copies the error code and error message from a
RAISERROR statement and places them in the RAISE_APPLICATION_ERROR
statement appended to the error message.
3-46
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
EXECUTE Statement
Table 322 Comparison of EXECUTE Statement in Oracle and Microsoft SQL Server
and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
CREATE PROC proc1
AS
EXEC SetExistFlag
EXEC SetExistFlag yes=@yes, @Status
OUT
EXEC @Status = RecordExists
EXEC SetExistFlag @yes
Oracle
CREATE OR REPLACE PROCEDURE PROC1
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
BEGIN
BEGIN
SETEXISTFLAG;
EXCEPTION
WHEN OTHERS THEN
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
BEGIN
SETEXISTFLAG(=>PROC1.yes,
PROC1.Status);
EXCEPTION
WHEN OTHERS THEN
StoO_error :=
SQLCODE;
StoO_errmsg :=
SQLERRM;
END;
BEGIN
PROC1.Status:=RECORDEXISTS;
EXCEPTION
WHEN OTHERS THEN
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
BEGIN
SETEXISTFLAG(PROC1.yes);
EXCEPTION
WHEN OTHERS THEN
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
END PROC1;
/
Comments
The EXECUTE statement is used to execute another stored procedure from within a
procedure. In PL/SQL, the procedure is called by its name within the PL/SQL
block. If a procedure is converted to a PL/SQL function, make sure to assign the
RETURN value to a variable when calling it (see the call to RecordExists in Table
3-22 above).
The Migration Workbench converts the parameter-calling convention to be either
positional, named, or mixed. For information on parameter-calling conventions, see
the Schema Objects section in this chapter.
WHILE Statement
Table 323 Comparison of WHILE Statement in Oracle and
Microsoft SQL Server and Sybase Adaptive Server
Microsoft SQL Server and
Sybase Adaptive Server
Oracle
Example 1:
Example 1:
3-48
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
Example 2:
Example 2:
Oracle
Example 3:
Example 3:
3-50
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
Example 4:
Example 4:
Oracle
StoO_rowcnt := SQL%ROWCOUNT;
EXCEPTION
WHEN OTHERS THEN
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
END;
END LOOP;
END PROC1;
/
Comments
The Migration Workbench can convert most WHILE constructs. However, the
CONTINUE within a WHILE loop in Microsoft SQL Server and Sybase Adaptive
Server does not have a direct equivalent in PL/SQL. It is simulated using the GOTO
statement with a label. Because the Migration Workbench is a single-pass parser, it
adds a label statement at the very beginning of every WHILE loop (see Example 2 in
Table 3-23 above).
3-52
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
GOTO Statement
Table 324 Comparison of GOTO Statement in Oracle and Microsoft SQL Server and
Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
CREATE PROC proc1 @Status int
AS
DECLARE @j int
IF @Status = -1
GOTO Error
SELECT @j = -1
Error:
SELECT @j = -99
Oracle
CREATE OR REPLACE PROCEDURE PROC1(
Status INTEGER )
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
j
INTEGER;
BEGIN
IF PROC1.Status = -1 THEN
GOTO ERROR;
END IF;
PROC1.j := -1;
<<ERROR>>
PROC1.j := 99;
END PROC1;
/
Comments
The GOTO <label> statement is converted automatically. No manual changes are
required.
Oracle
CREATE OR REPLACE PROCEDURE proc1
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
i_x INTEGER;
BEGIN
BEGIN
SELECT count(*)
INTO i_x
FROM emp;
StoO_rowcnt := SQL%ROWCOUNT;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
StoO_rowcnt := 2;
WHEN OTHERS THEN
StoO_rowcnt := 0;
StoO_selcnt := 0;
StoO_error := SQLCODE;
END;
IF StoO_rowcnt = 0 THEN
DBMS_OUTPUT.PUT_LINE
('No rows found.') ;
END IF;
IF StoO_error = 0 THEN
DBMS_OUTPUT.PUT_LINE('No errors.') ;
END IF;
END;
/
Comments
@@rowcount is converted to StoO_rowcnt, which takes its value from the PL/SQL
cursor attribute SQL%ROWCOUNT.
@@error is converted to StoO_error, which contains the value returned by the
SQLCODE function. The value returned by SQLCODE should only be assigned
within an exception block; otherwise, it returns a value of zero. This requires that
the Migration Workbench add a local exception block around every SQL statement
3-54
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
and a few PL/SQL statements. Other global variables are converted with a warning
message. These may need to be converted manually.
ASSIGNMENT Statement
Table 326 Comparison of ASSIGNMENT Statement in Oracle and Microsoft SQL
Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
CREATE PROC proc1
AS
DECLARE @x int
SELECT @x = -1
SELECT @x=sum(salary) FROM
employee
Oracle
CREATE OR REPLACE PROCEDURE PROC1
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
x
INTEGER;
BEGIN
PROC1.x := -1;
BEGIN
StoO_rowcnt := 0;
StoO_selcnt := 0;
StoO_error := 0;
SELECT
SUM(SALARY)
INTO PROC1.x FROM
EMPLOYEE;
StoO_rowcnt :=
SQL%ROWCOUNT;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
StoO_rowcnt := 2;
WHEN OTHERS THEN
StoO_rowcnt := 0;
StoO_selcnt := 0;
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
END PROC1;
/
Comments
Assignment in Microsoft SQL Server and Sybase Adaptive Server is done using the
SELECT statement as illustrated in Table 3-26.
PL/SQL assigns values to a variable as follows:
It uses the assignment statement to assign the value of a variable or an expression to
a local variable. It assigns a value from a database using the SELECT..INTO clause.
This requires that the SQL returns only one row, or a NULL value is assigned to the
variable as can be seen in the following example:
SELECT empno INTO empno
FROM employee
WHERE ename = 'JOE RICHARDS'
SELECT Statement
Table 327 Comparison of SELECT Statement in Oracle and Microsoft SQL Server
and Sybase Adaptive Server
Microsoft SQL Server
Oracle
Example 1:
Example 1:
3-56
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Table 327 Comparison of SELECT Statement in Oracle and Microsoft SQL Server
and Sybase Adaptive Server (Cont.)
Microsoft SQL Server
Oracle
Example 2:
Example 2
Comments
Because of the differences in their architectures, Microsoft SQL Server and Sybase
Adaptive Server stored procedures return data to the client program in a different
way than Oracle.
Microsoft SQL Server and Sybase Adaptive Server and Oracle can all pass data to
the client using output parameters in the stored procedures. Microsoft SQL Server
and Sybase Adaptive Server use another method known as result sets to transfer the
data from the server to client. The examples discussed here do not return multiple
rows to the client.
In Example 1, the procedure returns a single row result set to the client which is
converted to a PL/SQL procedure that returns a single row using the output
parameters.
Example 1:
A SELECT statement is converted into a SELECT...INTO clause and the extra
parameter "i_oval1" is added to the procedure definition. Since the Migration
Workbench does not currently look up the data types on the Oracle server, it sets the
default data type to VAR1CHAR2.
Note: In Oracle, the query should return only one row or the
3-58
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
CREATE OR REPLACE PROCEDURE PROC1
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
x
INTEGER;
y
CHAR(20);
t_var1
VARCHAR2(255);
BEGIN
/****** Subqueries in select list is not supported in
Oracle. *******/
/****** MANUAL CONVERSION MIGHT BE REQUIRED *******/
BEGIN
StoO_error := 0;
StoO_rowcnt := 0;
SELECT NAME
INTO t_var1
FROM EMP;
StoO_rowcnt := SQL%ROWCOUNT;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
StoO_StoO_rowcnt := 2;
WHEN OTHERS THEN
StoO_StoO_rowcnt := 0;
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
BEGIN
StoO_rowcnt := 0;
StoO_selcnt := 0;
StoO_error := 0;
SELECT COL1, t_var1
INTO PROC1.x, PROC1.y FROM TABLE1;
StoO_rowcnt := SQL%ROWCOUNT;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
StoO_rowcnt := 2;
WHEN OTHERS THEN
StoO_rowcnt := 0;
StoO_selcnt := 0;
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
END PROC1;
/
Comments
The Microsoft SQL Server and Sybase Adaptive Server SELECT statement with a
subquery as part of the SELECT list cannot be converted to PL/SQL using the
Migration Workbench. Manual changes are needed to convert this type of SELECT
statement.
The Migration Workbench writes appropriate comments in the output PL/SQL
procedures and the subqueries are omitted.
3-60
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
CREATE OR REPLACE PROCEDURE PROC1
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
ename
CHAR(20);
salary INTEGER;
BEGIN
BEGIN
StoO_rowcnt := 0;
StoO_selcnt := 0;
StoO_error := 0;
SELECT
ENAME, SALARY
INTO PROC1.ename,
PROC1.salary FROM EMP
WHERE SALARY > 100000
GROUP BY DEPTNO;
StoO_rowcnt := SQL%ROWCOUNT;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
StoO_rowcnt := 2;
WHEN OTHERS THEN
StoO_rowcnt := 0;
StoO_selcnt := 0;
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
END PROC1;
Comments
T/SQL allows GROUP BY statements where the column used in the GROUP BY
clause does not need to be part of the SELECT list. PL/SQL does not allow this type
of GROUP BY clause.
The Migration Workbench converts this type of SELECT statement to PL/SQL.
However, the equivalent PL/SQL statement returns an error in Oracle.
Column Aliases
Table 330 Comparison of Column Aliases in Oracle and Microsoft SQL Server and
Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
CREATE PROC proc1
@Status int=0
AS
SELECT x=sum(salary)
FROM employee
Oracle
CREATE OR REPLACE PROCEDURE PROC1(
Status INTEGER DEFAULT 0,
RC1
IN OUT PROC1Pkg.RCT1)
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
BEGIN
OPEN RC1 FOR
SELECT SUM(SALARY) "X" FROM
EMPLOYEE;
END PROC1;
/
Comments
The Migration Workbench can convert Microsoft SQL Server-specific column aliases
to the equivalent Oracle format. No manual changes are required.
3-62
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
CREATE OR REPLACE PROCEDURE proc1
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
BEGIN
BEGIN
UPDATE table1
SET
col1 = 1 /* FROM table1,table2 -MANUAL CONVERSION */
WHERE table1.id = table2.id;
StoO_rowcnt := SQL%ROWCOUNT;
EXCEPTION
WHEN OTHERS THEN
StoO_error := SQLCODE;
END;
END;
Comments
An UPDATE with a FROM clause cannot be converted. Instead, the Migration
Workbench provides a comment indicating that manual conversion is required.
There are two ways to convert UPDATE with a FROM statements, and these are
illustrated below.
Method 1:
Use the subquery in the SET clause if columns are being updated to values coming
from a different table. For example, consider the following T/SQL statement:
UPDATE titles
SET pub_id = publishers.pub_id
FROM titles, publishers
WHERE titles.title like 'C%'
AND publishers.pub_name = 'new age'
Method 2:
Use the subquery in the WHERE clause for all other UPDATEFROM statements.
For example, consider the following T/SQL statement:
UPDATE shippint_parts
SET qty = 0
FROM shipping_parts sp, suppliers s
WHERE sp.supplier_num = s.supplier_num
AND s.location = "USA"
3-64
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
CREATE OR REPLACE PROCEDURE PROC1
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
UF1_rowid
ROWID;
UF1_oval1
TABLE1.COL1%TYPE;
CURSOR UF1_cursor IS
SELECT TABLE1.ROWID, 1 FROM
TABLE1, TABLE2
WHERE TABLE1.ID = TABLE2.ID
FOR UPDATE OF TABLE1.COL1;
BEGIN
OPEN UF1_cursor;
LOOP
FETCH UF1_cursor INTO UF1_rowid, UF1_
oval1;
EXIT WHEN UF1_cursor%NOTFOUND;
BEGIN
StoO_error
:= 0;
StoO_rowcnt := 0;
UPDATE TABLE1 SET COL1 = UF1_oval1
WHERE ROWID = UF1_rowid;
StoO_rowcnt := SQL%ROWCOUNT;
EXCEPTION
WHEN OTHERS THEN
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
END LOOP;
CLOSE UF1_cursor;
END PROC1;
/
Comments
A DELETE with FROM..FROM clause must be converted manually.
While converting DELETE with FROM..FROM clause, remove the second FROM
clause. For example consider the following T/SQL statement:
DELETE
FROM sales
FROM sales,titles
WHERE sales.title_id = titles.title_id
AND titles.type = 'business'
3-66
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Temporary Tables
Table 333 Comparison of Temporary Tables in Oracle and Microsoft SQL Server and
Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
CREATE PROC proc1
AS
SELECT col1, col2
INTO #Tab
FROM table1
WHERE table1.id = 100
Oracle
CREATE OR REPLACE PROCEDURE PROC1
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
BEGIN
/*CONVERTING SELECT INTO t_Tab*/
/*TO INSERT INTO t_Tab*/
BEGIN
StoO_rowcnt := 0;
StoO_selcnt := 0;
StoO_error := 0;
INSERT INTO t_Tab
SELECT
USERENV('SESSIONID'), COL1, COL2 FROM
TABLE1
WHERE TABLE1.ID = 100;
StoO_rowcnt := SQL%ROWCOUNT;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
StoO_rowcnt := 2;
WHEN OTHERS THEN
StoO_rowcnt := 0;
StoO_selcnt := 0;
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
END PROC1;
/
Comments
Temporary tables are supported by Oracle9i and Oracle8i. The Migration
Workbench utilizes this feature in Oracle9i and Oracle8i.
Oracle
CREATE OR REPLACE PACKAGE PROC1Pkg
AS
TYPE RT1 IS RECORD (
COL1
TABLE1.COL1%TYPE,
COL2
TABLE1.COL2%TYPE
);
TYPE RCT1 IS REF CURSOR RETURN RT1;
END;
/
CREATE OR REPLACE PROCEDURE PROC1(
RC1
IN OUT PROC1Pkg.RCT1)
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
BEGIN
OPEN RC1 FOR
SELECT COL1, COL2 FROM
TABLE1;
END PROC1;
/
3-68
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Comments
Convert an Microsoft SQL Server and Sybase Adaptive Server procedure that
returns a multi-row result set to a PL/SQL packaged function by selecting the
appropriate parse option in the property sheet for a stored procedure.
The T/SQL SELECT statement is converted to a cursor and a cursor variable is
added as an OUT parameter to return the data back to the calling program. Use the
cursor referenced by the cursor variable to fetch the result rows.
For more details on how Result Sets are handled by the Migration Workbench, see
T/SQL and PL/SQL Language Elements section in this chapter.
Note: The conversion to a packaged function does not work in all
cases. Carefully check the input source and decide whether it can
be converted to a packaged function. Also check the output for
accuracy.
Cursor Handling
Table 335 Comparison of Cursor Handling Result Set in Oracle and Microsoft SQL
Server and Sybase Adaptive Server
Microsoft SQL Server and Sybase
Adaptive Server
CREATE PROC cursor_demo
AS
DECLARE @empno
INT
DECLARE @ename
CHAR(100)
DECLARE @sal
FLOAT
DECLARE cursor_1 CURSOR
FOR SELECT empno, ename, sal
FROM emp
OPEN cursor_1
FETCH cursor_1 INTO @empno,
@ename, @sal
Oracle
CREATE OR REPLACE PROCEDURE CURSOR_
DEMO
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
empno
INTEGER;
ename
CHAR(100);
sal
NUMBER;
CURSOR CURSOR_1 IS
SELECT EMPNO, ENAME, SAL
FROM EMP;
CLOSE cursor_1
BEGIN
DEALLOCATE CURSOR cursor_1
OPEN CURSOR_1;
CURSOR_1 INTO
cursor_demo.empno, cursor_
demo.ename, cursor_demo.sal;
IF CURSOR_1%NOTFOUND THEN
StoO_sqlstatus := 2;
ELSE
StoO_sqlstatus := 0;
END IF;
CLOSE CURSOR_1;
/*[SPCONV-ERR(xxx)]:Deallocate Cursor
is not supported*/
NULL;
END CURSOR_DEMO;
/
3-70
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Comments
Microsoft SQL Server and Sybase Adaptive Server introduced cursors in T/SQL.
Syntactical conversion of cursors from Microsoft SQL Server and Sybase Adaptive
Server to Oracle is very straightforward.
Note: In PL/SQL, deallocation of cursors is not required as it
happens transparently.
Oracle
CREATE OR REPLACE FUNCTION PROC1
RETURN INTEGER
AS
StoO_selcnt
INTEGER;
StoO_error
INTEGER;
StoO_rowcnt
INTEGER;
StoO_errmsg
VARCHAR2(255);
StoO_sqlstatus INTEGER;
BEGIN
SAVEPOINT TRAN1;
BEGIN
StoO_error
:= 0;
StoO_rowcnt := 0;
UPDATE TABLE1
SET ID = ID + 1
WHERE NAME = 'Event';
StoO_rowcnt := SQL%ROWCOUNT;
EXCEPTION
WHEN OTHERS THEN
StoO_error := SQLCODE;
StoO_errmsg := SQLERRM;
END;
IF StoO_rowcnt != 1 THEN
BEGIN
ROLLBACK TO SAVEPOINT TRAN1;
RETURN 25700;
END;
END IF;
COMMIT WORK;
RETURN 0;
END PROC1;
/
Comments
3-72
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Operators
Built-in Functions
DDL Constructs within Microsoft SQL Server and Sybase Adaptive Server
Stored Procedures
The following SET command sets the isolation level to the desired level:
set transaction isolation level {1|3}
The explicit transaction mode allows nested transactions. However, the nesting is
only syntactical. Only outermost BEGIN TRANSACTION and COMMIT
TRANSACTION statements actually create and commit the transaction. This could
be confusing as the inner COMMIT TRANSACTION does not actually commit.
The following example illustrates the nested transactions:
BEGIN TRANSACTION
/* T/SQL Statements */
BEGIN TRANSACTION
/* T/SQL Statements */
BEGIN TRANSACTION account_tran
/* T/SQL Statements */
IF SUCCESS
COMMIT TRANSACTION account_tran
ELSE
3-74
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Oracle
BEGIN TRAN
BEGIN TRAN tran_1
SAVEPOINT tran_1
COMMIT TRAN
COMMIT
COMMIT
ROLLBACK
At the time of conversion, the Migration Workbench cannot determine the nest level
of the current transaction-handling statement. The variable @@trancount is a
runtime environment variable.
Table 3-38 shows the currently implemented Microsoft SQL Server and Sybase
Adaptive Server to Oracle conversion strategy for the transaction-handling
statements
3-76
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Table 338
Oracle
/*BEGIN TRAN
SAVEPOINT tran_1;
COMMIT TRAN
COMMIT WORK;
COMMIT WORK;
COMMIT WORK;
COMMIT WORK;
ROLLBACK WORK;
SAVEPOINT tran_1
Because of the difference in the way the two databases handle transactions, you
may want to consider some reorganization of the transactions.
Try to design client/server applications so that the transaction-handling statements
are part of the client code rather than the stored procedure code. This strategy
should work because the logical transactions are almost always designed by the
user and should be controlled by the user.
For the conversion of stored procedures, consider setting a SAVEPOINT at the
beginning of the procedures, and roll back only to the SAVEPOINT. In Microsoft
SQL Server and Sybase Adaptive Server, make the changes so that at least the
outermost transaction is controlled in the client application.
HANDLER routine is invoked as a call-back routine if any server error occurs, and
the error conditions can be handled in the call back routine.
Stored procedures use the RAISERROR statement to notify the client of any error
condition. This statement does not cause the control to return to the calling routine.
Microsoft SQL Server and Sybase Adaptive Server allow you to customize the error
messages using a system table. The system procedures allow the user to add error
messages to this table.
Oracle
In Oracle, each SQL statement is automatically checked for errors before proceeding
with the next statement. If an error occurs, control immediately jumps to an
exception handler if one exists. This frees you from needing to check the status of
every SQL statement. For example, if a SELECT statement does not find any row in
the database, an exception is raised. The corresponding exception handler part of
the block should include the code to deal with this error. The built-in RAISE_
APPLICATION_ERROR procedure notifies the client of the server error condition
and returns immediately to the calling routine.
Oracle places an implicit SAVEPOINT at the beginning of a procedure. The built-in
RAISE_APPLICATION_ERROR procedure rolls back to this SAVEPOINT or the last
committed transaction within the procedure. The control is returned to the calling
routine.
The Oracle RAISE_APPLICATION_ERROR statement allows the user to customize
the error message. If an exception is raised, SQLCODE is returned automatically by
PL/SQL to the caller. It keeps propagating until it is handled.
Recommendations
To simulate Microsoft SQL Server and Sybase Adaptive Server behavior in Oracle,
you must enclose each SQL statement in an equivalent PL/SQL block. This block
must deal with the exceptions that need to be trapped for the SQL statement.
See the T/SQL Versus PL/SQL Constructs section in this chapter for more
information about the extra code required to simulate Microsoft SQL Server and
Sybase Adaptive Server behavior.
If the RAISERROR statement in an Microsoft SQL Server and Sybase Adaptive
Server stored procedure is immediately followed by the RETURN statement, these
two statements can be converted to the Oracle RAISE_APPLICATION_ERROR
statement.
You can customize error messages with the help of a user-defined table. You can
write standard routines to add and retrieve error messages to this table. This
3-78
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
method serves a two-fold purpose: it ensures that the system is portable, and it
gives the administrator centralized control over the error messages.
The server error code indicating the execution status of the most recently executed
T/SQL statement. For code examples, see the @@Rowcount and @@Error Variables
topic.
@@identity:
Returns the last identity value generated by the statement. It does not revert to a
previous setting due to ROLLBACKS or other transactions.
@@rowcount:
The number of rows affected by the most recently executed T/SQL statement. For
code examples, see the @@Rowcount and @@Error Variables topic.
@@servername:
The name of the local Microsoft SQL Server and Sybase Adaptive Server server.
@@sqlstatus:
The status information resulting from the last FETCH statements.
@@tranchained:
The current transaction mode of the T/SQL procedure. If @@tranchained returns 1,
the TL/SQL procedure is in chained, or implicit transaction mode.
@@trancount:
Keeps track of the nesting level for the nested transactions for the current user.
@@transtate:
The current state of the transaction.
Oracle
SQLCODE:
The server error code indicating the execution status of the most recently executed
PL/SQL statement.
SQL%ROWCOUNT:
The variable attached to the implicit cursor associated with each SQL statement
executed from within the PL/SQL procedures. This variable contains the number of
rows affected by the execution of the SQL statement attached to the implicit cursor.
Recommendations:
The @@error variable has a direct equivalent in Oracle, and that is the SQLCODE
function. The SQLCODE function returns the server error code.
The SQL%ROWCOUNT variable in Oracle is functionally equivalent to @@rowcount.
There are many more special global variables available with PL/SQL. Not all those
variables are listed here. There are more special global variables available in T/SQL
also. Not all those variables are listed here because they do not play a major role in
the conversion process.
Operators
See the Data Manipulation Language section in Chapter 2 for a discussion of
Microsoft SQL Server and Sybase Adaptive Server and Oracle operators.
Built-in Functions
See the Data Manipulation Language section in Chapter 2 for a discussion of
built-in functions in Microsoft SQL Server and Sybase Adaptive Server and Oracle.
3-80
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
SELECT "YES"
ELSE
SELECT "NO"
END
Recommendations
Some alternatives to simulating the result set in PL/SQL procedures are presented
below:
equivalent to the result set in Microsoft SQL Server and Sybase Adaptive
Server.
Procedure or function that populates a temporary table with result set rows
This temporary table has an additional column to hold the SESSION_ID of the
current session to keep the rows separate for each session of the user. The client
program can then retrieve the rows from this temporary table with a simple
SELECT statement.
The Migration Workbench adopts the third option to convert the result set.
This procedure executes two T/SQL blocks before executing the SELECT statement
associated with the result set. The procedure is converted to an Oracle package as
follows:
CREATE OR REPLACE PACKAGE BODY test_proc_pkg
AS
BEGIN
FUNCTION test_proc;
END;
CREATE OR REPLACE PACKAGE BODY test_proc_pkg
AS
BEGIN
cursor declaration for the SELECT statement associated with the result
set in the source T/SQL procedure;
FUNCTION test_proc
RETURN INTEGER
AS
3-82
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
BEGIN
PL/SQL version of T/SQL block1;
PL/SQL version of T/SQL block2;
FETCH loop for the cursor declared in the package body;
END;
END;
The two T/SQL blocks in the source T/SQL procedure are executed only once
when the procedure is called, and the result set is sent to the client.
In Oracle client, to simulate the fetching of the result set, the TEST_PROC_
PKG.TEST_PROC function must be called repeatedly until all the rows from the
cursor are fetched. The two PL/SQL blocks in the function are executed with each
call to the function. This behavior differs from that in the source application.
You must manually separate the code associated with the FETCH loop for the
cursor for the result set from the remaining code in the procedure. Changes to the
client have to be made so that the rest of the procedure's code is called in accurate
sequence with the repeated calls to the function returning rows from the result set.
The final Oracle package should be as follows:
CREATE OR REPLACE PACKAGE BODY test_proc_pkg
AS
BEGIN
PROCEDURE proc1;
FUNCTION test_proc;
END;
CREATE OR REPLACE PACKAGE BODY test_proc_pkg
AS
BEGIN
cursor declaration for the SELECT statement associated with the result
set in the source T/SQL procedure;
PROCEDURE proc1
AS
BEGIN
PL/SQL version of T/SQL block1;
PL/SQL version of T/SQL block2;
END;
FUNCTION test_proc
RETURN INTEGER
AS
BEGIN
FETCH loop for the cursor declared in the package body;
END;
END;
DDL Constructs within Microsoft SQL Server and Sybase Adaptive Server Stored
Procedures
Microsoft SQL Server and Sybase Adaptive Server allow DDL constructs to be part
of the stored procedures. Oracle allows DDL statements as part of the dynamic SQL.
Oracle issues an implicit COMMIT statement after each DDL statement.
Most of the T/SQL DDL constructs give syntax errors. You must remove the DDL
statements from the T/SQL source to convert the T/SQL procedure to PL/SQL
using the Migration Workbench.
The following DDL statements are ignored by the Migration Workbench. The
statements appear commented in the output with a message "statement ignored."
CREATE TABLE
DROP TABLE
CREATE VIEW
DROP VIEW
CREATE INDEX
DROP INDEX
3-84
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
4
Distributed Environments
This chapter includes the following sections:
Distributed Environments
Distributed Environments
A distributed environment is chosen for various applications where:
Distributed Environments
4-1
Distributed Environments
A distributed database system can be configured so that each database within the
system has a unique database name, thereby providing "effective" global object
names.
Furthermore, by defining synonyms for remote object names, you can eliminate
references to the name of the remote database. The synonym is an object in the local
database that refers to a remote database object. Synonyms shift the responsibility of
distributing data from the application developer to the DBA. Synonyms allow the
DBA to move the objects as desired without impacting the application.
The synonym can be defined as follows:
CREATE PUBLIC SYNONYM emp FOR
scott.emp@sales.division3.acme.com;
Using this synonym, the SQL statement outlined above can be changed to the
following:
SELECT * FROM emp;
Microsoft SQL Server and Sybase Adaptive Server and Remote Objects
Microsoft SQL Server and Sybase Adaptive Server require schema objects
throughout a distributed database to be referenced in SQL statements by fully
qualifying the object names. The complete name of a schema object has the
following format:
server_name.database_name.object_owner_name.object_name
4-2
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Distributed Environments
Microsoft SQL Server and Sybase Adaptive Server do not support the concept of
synonyms or location transparency. In a distributed environment, objects cannot be
moved around without impacting the application, as the developers must include
the location of the object in the application code.
Most of the static queries tend to include the references to the remote server and
remote database. Some applications maintain a user table to map the complete
object names (including the remote server name and the database name) to dummy
object names. The queries refer to these dummy object names. The translations are
performed in real-time with the help of the map in the user table. This limitation
precludes any common scheme of referring to remote objects that can work for
Oracle and Microsoft SQL Server and Sybase Adaptive Server.
The Microsoft SQL Server and Sybase Adaptive Server Omni SQL Gateway server
allows location transparency, but this requires that the schema definitions of all the
databases participating in the distribution must be available with the Omni SQL
Gateway server.
Replication
Replication functionality in Microsoft SQL Server and Sybase Adaptive Server has
the following characteristics:
Unidirectional
In addition to the characteristics listed above, Microsoft SQL Server 7.0 replication
provides heterogeneous replication through ODBC.
Oracle replication has richer replication functionality, which includes the following:
Bi-directional
Automatic resynchronization
Distributed Environments
4-3
applications from Microsoft SQL Server and Sybase Adaptive Server to Oracle is
feasible.
4-4
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
5
Migrating Temporary Tables to Oracle
Temporary tables are available in Oracle9i and Oracle8i. However, because Oracle9i
and Oracle8i temporary tables differ from Microsoft SQL Server temporary tables
you should still replace or emulate temporary tables within Oracle to ease
migrations from Microsoft SQL Server.
The emulation of temporary tables has been simplified by using temporary tables
instead of permanent tables. See the Oracle9i and Oracle8i temporary table syntax
for Example 2 in the Implementation of Temporary Tables as Permanent Tables
section.
This chapter discusses temporary tables under the following headings:
Definition of t_table_catalog
Simplify Coding
Simplify Coding
Instead of writing complicated multi-table join queries, temporary tables allow a
query to be broken into different queries, where result sets of one query are stored
in a temporary table and subsequent queries join this temporary table with actual
database tables.
This type of code can be converted to Oracle as follows:
5-2
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
AND
t1.col2 = t5.col2
AND
t2.col4 between @start_col4 and @end_col4
AND
t3.col5 between @start_col5 and @end_col5
AND
t3.col12 = @flag2
AND
t2.col13 = @flag1
AND
t4.col2 like @col2
AND
t4.col14 = @flag3
AND
t4.col12 = @flag2
AND
t2.col1 = t4.col1
AND
t3.col1 = t2.col1
AND
t4.col1 = t3.col1
AND
t5.col2 like @col2
AND
t4.col2 = t5.col2
AND
t4.col15 = t5.col15
AND
t5.col3 like @var1
AND
t2.col6 <= @end_dt
AND
(t2.col7 >= @start_dt OR t2.col7 = NULL)
AND
t4.col8 <=@end_dt
UPDATE TABLE4
SET
t4.col2 = col16
FROM
#TEMP2 t1, db2..TABLE4 t4
WHERE
t1.col1 = t4.col1
AND
t4.col12 = @flag2
AND
t4.col14 = @flag4
end loop
Oracle:
FOR emp_rec IN (SELECT name, emp_id FROM emp WHERE dept = 10)
LOOP /*process emp_rec.name and emp_rec.emp_id*/
END LOOP
5-4
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
See the sample code provided in the To Simplify Coding section for more
information in this regard.
Oracle:
SELECT
FROM
WHERE
AND
AND
AND
UNION
SELECT
emp.empno
dept.dept_no
location.location_code
emp.start_date
emp.end_date
emp,
dept ,
location
emp.empno = location.empno
dept.deptno = emp.deptno
dept.deptno = location.deptno
emp.start_date BETWEEN i_start_date AND i_end_date
10000,
10,
15,
SYSDATE,
NULL
FROM
DUAL
Oracle:
SELECT
FROM
WHERE
5-6
emp.empno
dept.dept_no
emp.start_date
emp.end_date
emp,
dept ,
emp.empno = dept.deptno
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
AND
emp.start_date BETWEEN i_start_date AND i_end_date ;
/* The above join has to be performed every time one needs to get this result set
*/
To collect data
multiple instance is not possible in Oracle, you should attach the SESSION_ID to
the table name to make it unique. The result is a variable table name, which requires
that all accesses to that table must be created with dynamic SQL. This process
would complicate all types of migration tools.
As all DDL operations have an implicit commit, the creation of a temporary table
would disturb the transactional behavior of the migrated application. The programs
would have to be changed so that the creation of a temporary table always occurs at
the start of a transaction. This process would also complicate migration tools.
Example 2
SELECT aaufromdt date
from anforord aau, order ord, case cas, casetype ctp
where ctp.ctp_id = CtpId
5-8
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
You should modify all commands that create temporary tables as follows:
When you have completed these steps, Example 1 type statements may be executed.
For statements of the same type as Example 2, you must also perform the following
steps:
Remove all bind variables, such as CtpId, and replace them with constants.
Oracle9i and Oracle8i temporary table data is not visible across sessions so the
SESSION_ID column is not required.
The Oracle9i and Oracle8i temporary table syntax for Example 2 is as follows:
create table global temporary t_<temptable> on commit preserve rows
as select * from (<original statement>)
where 1=0
The Migration Workbench does the following when it encounters a temporary table
in a stored procedure or trigger:
Adds the SESSION_ID column (if Oracle9i and Oracle8i temporary tables
are not being used)
With this setup, you can use the table tmpfromdate as if it is available once per
session.
5-10
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
---
---
----
procedure cleanup_session;
Find all temporary table usages of the session, delete or truncate
the temporary table and unregister the usage.
This procedure commits!
----
END;
Definition of t_table_catalog
create table t_table_catalog
(session_id number,
table_name varchar2(30),
constraint t_table_catalog_pk
primary key (session_id, table_name))
---
5-12
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
end;
--
);
sql_stmt := NULL;
end if;
end;
begin
if ( use_dbms_output ) then
sel_table := upper (table_name);
else
sel_table := 't_' || upper (table_name);
end if;
-- Rename the table to t_XXX
---
--
---
---
----
5-14
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
add
add
add
add
('before insert');
('on t_' || table_name);
('begin');
(' t_table.register (''' || upper (table_name) ||
''');');
add ('end;');
execute_immediate;
end;
procedure register (table_name in varchar2)is
------
varchar2(1);
number;
number;
begin
Check if we just registered the table
if last_table = table_name then
return;
end if;
last_table := table_name;
-- Check if we have ever registered the table for our session
begin
select 'x' into dummy
from
t_table_catalog ttc
where ttc.table_name = register.table_name
and
session_id = userenv ('sessionid');
exception
when no_data_found then
-- If it is not registered, register the usage
--
5-16
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
6
Disconnected Source Model Loading
The Disconnected Source Model Load feature of the Migration Workbench allows
consultants to work on a customers database migration without having to install
and run the Migration Workbench at the customer site.
To perform the disconnected source model load option a customer must generate
delimited flat files containing schema metadata from the database to be migrated.
You generate the flat file by running a predefined Migration Workbench script
against the source database. The flat files are sent to a consultant who uses the
Migration Workbench to load the metadata files into a source and Oracle model.
You can then map this schema to Oracle.
6-1
Table 61 Location and Name of Script Files and Name of Associated Files
Plug-in
Directory Location
Microsoft SQL
Server 6.5
%ORACLE_HOME%\DSML_ SS6_DSML_SCRIPT.BAT
scripts\sqlserver6
Associated Files
CREATE_SS65_INDEX_
TABLES.SQL
DROP_SS65_INDEX_
TABLES.SQL
Microsoft SQL
Server 7
%ORACLE_HOME%\DSML_ SS7_DSML_SCRIPT.BAT
scripts\sqlserver7
Not Applicable
Microsoft SQL
Server 2000
%ORACLE_HOME%\DSML_ SS2K_DSML_SCRIPT.BAT
scripts\sqlserver20
00
Not Applicable
Sybase Adaptive
Server 11
%ORACLE_HOME%\DSML_ SYBASE11_DSML_SCRIPT.BAT
scripts\ybase11
CREATE_SYBASE_
INDEX_TABLES.SQL
DROP_SYBASE_INDEX_
TABLES.SQL
Sybase Adaptive
Server 12
%ORACLE_HOME%\DSML_ SYBASE12_DSML_SCRIPT.BAT
scripts\sybase12
CREATE_SYBASE_
INDEX_TABLES.SQL
DROP_SYBASE_INDEX_
TABLES.SQL
For example, to run the Microsoft SQL Server 2000 script file to generate metadata
flat files, use the following command:
SS2K_DSML_SCRIPT <database> <password> <server>
6-2
Reference Guide for Microsoft SQL Server and Sybase Adaptive Server Migrations
Index
control files, 2-25
converting multiple result sets, 3-12
CREATE PROCEDURE statement, 3-38
cursor handling, 3-70
cursor variables, 3-4
cursor variables, return query results, 3-10
customized error messages, 3-16
A
accessing remote databases, 4-1
AFTER triggers, 3-1
application development tools, 4-4
arithmetic operators, 2-44
ARRAY FETCH, 3-11
ASSIGNMENT statement, 3-55
B
BEGIN TRAN statement, 3-14
BEGIN TRANSACTION statement,
bit operators, 2-45
BLOBs, 2-6
built-in functions, 2-46, 3-80
byte-stream, 3-4
3-14
C
Capture Wizard, 1-3
changing NULL constructs, 2-43
CHAR(n) data type, 2-13
character functions, 2-46
check constraints, 2-7
column aliases, 3-62
column names, 2-3
column-level CHECK constraint, 2-7
COMMIT TRAN statement, 3-14
COMMIT TRANSACTION statement,
comparison operators, 2-40
connecting to a database, 2-27
3-14
Index-1
E
emulate temporary tables, 5-7
entity integrity constraints, 2-6
error handling, 3-15
error-handling semantics, 3-77
exception-handling semantics, 3-77
EXECUTE statement, 3-47
explicit transaction model, 3-73
extent, 2-21
features, 1-2
FETCH request, 3-4
Flat File Generation Scripts, 6-1
FLOAT data type, 2-11
function, schema object, 3-24
functions, defining in Oracle, 2-49
P
package body, 3-32
package, schema object, 3-28
page, 2-21
page-level locking, 2-55
parameter passing, 3-39
permanent tables, 5-8
PL/SQL and T-SQL constructs, comparison, 3-36
PL/SQL and T-SQL, language elements, 3-73
PL/SQL tables as output variables, 3-7
procedure, schema object, 3-18
product description, 1-1
G
global variables, 3-54, 3-79
GOTO statement, 3-53
I
IF statement, 3-41
IMAGE data type, 2-6
implicit transaction model, 3-73
IN OUT parameter, 3-11
individual SQL statements, 3-13
INSERT statement, 2-36
INSERT triggers, 3-2
L
locking concepts, 2-52
logical transaction, 3-14
logical transaction handling,
2-57
M
maintenance of temporary tables,
mathematical functions, 2-51
metadata flat files
Index-2
generating, 6-1
Migration Wizard, 1-3
miscellaneous functions, 2-48
multiple queries, 5-5
multiple result sets, 3-81
multiple results sets, 3-12
multi-row array, 3-7
multi-row query, 3-10
multi-table joins, performance, 5-4
5-10
4-2
S
schema migration, 2-1
schema object similarities, 2-1
segments, 2-22
SELECT INTO statement, 2-32
SELECT statement, 2-28, 3-56
SELECT statement, part of SELECT list, 3-59
SELECT statement, result sets, 3-7
SELECT statement, with GROUP BY clause, 3-61
SELECT statements without FROM clauses, 2-31
SELECT with GROUP BY statement, 2-35
set operators, 2-45
single result set, 3-80
source database, 1-4
Source Model, 1-4
special global variables, 3-79
stored procedures, SQL Server, 3-1
stored subprograms, Oracle, 3-1
string operators, 2-44
subqueries, 2-34
SYSNAME data type, 2-19
U
unique keys, 2-7
UPDATE statement, 2-37
UPDATE triggers, 3-2
UPDATE with FROM statement, 3-63
user-defined types, SQL Server, 2-6
V
VARCHAR(n) data type,
2-13
W
WHILE statement,
3-48
T
t_table_catalog
definition, 5-11
table design considerations, 2-3
table-level CHECK constraint, 2-7
tablespace, 2-22
temporary table usage, 5-1
temporary tables, comparison, 3-67
temporary tables, creating dynamically,
temporary tables, emulate, 5-7
temporary tables, maintenance, 5-10
temporary tables, replace, 5-7
TEXT data type, 2-6
5-7
Index-3
Index-4