Beruflich Dokumente
Kultur Dokumente
Getting Started
PART ONE
Moving to Adaptive Server Anywhere 7.0 ....................... 1
iii
5 Upgrading Version 5 Applications ................................. 55
Understanding upgrades......................................................... 56
Review of SQL Anywhere Version 5 architecture................... 58
Upgrading Embedded SQL applications................................. 61
Upgrading ODBC applications ................................................ 66
Using the compatibility library ................................................. 71
Capturing dbclient command-line information ........................ 77
Upgrading databases.............................................................. 79
Upgrading SQL Remote installations...................................... 80
PART TWO
Database Concepts ......................................................... 83
PART THREE
Working with Databases ............................................... 119
iv
10 Connecting Your Application to its Database.............. 139
Introduction to connections ................................................... 140
Referencing data sources ..................................................... 141
Creating an ODBC Data Source ........................................... 142
v
15 Selecting Data Using Subqueries................................. 199
Introducing subqueries.......................................................... 200
Preparing to use subqueries ................................................. 201
A simple subquery ................................................................ 202
Comparisons using subqueries ............................................ 204
Using subqueries instead of joins ......................................... 206
Index............................................................................... 227
vi
About this Manual
Subject This book describes how to build simple databases and database applications
using Adaptive Server Anywhere.
Audience This manual is for beginning users of Adaptive Server Anywhere, and for
users of previous versions who want to find out what is new and different in
Adaptive Server Anywhere version 7.0.
Before you begin This manual assumes some familiarity with basic programming concepts. It
also assumes a working knowledge of the operating system on which you
will be using Adaptive Server Anywhere.
vii
Using this book
Part I is for users of previous versions of the software. It describes new
features in Adaptive Server Anywhere 7.0, and information you need to
know if you are upgrading from an earlier version.
It also describes how to use structured query language (SQL) to access and
modify the data in your database.
This book does not exhaust the possibilities of Adaptive Server Anywhere. It
is intended for people who need only to develop simple applications, or who
are unfamiliar with Adaptive Server Anywhere.
viii
Related books
This book provides information you need to get started with Adaptive Server
Anywhere. More detailed information is available in other books in the
Adaptive Server Anywhere documentation set:
♦ Adaptive Server Anywhere User’s Guide This book provides the
most thorough and in-depth information on all aspects of Adaptive
Server Anywhere. It includes material on designing and building
databases, using SQL, administering databases, and other aspects of
Adaptive Server Anywhere operation.
♦ Adaptive Server Anywhere Programming Interfaces Guide Some
aspects of database programming are specific to the programming
interface you work with. The Programming Interfaces Guide provides
material on each of the programming interfaces you can use to access
Adaptive Server Anywhere databases.
This book is not required for users of Application Development tools
with built-in ODBC support, such as Sybase PowerBuilder or PowerJ.
♦ Adaptive Server Anywhere Reference Manual A complete reference
to Adaptive Server Anywhere. This book describes the database server,
the administration utilities, SQL, and error messages.
The format of these books (printed or online) may depend on the product in
which you obtained Adaptive Server Anywhere.
Depending on which package you have purchased, you may have additional
books describing other components of your product.
ix
Documentation conventions
The following icons are used in this documentation:
Icon Meaning
A client application.
If the icon is used to represent a particular application
or kind of application, the name is indicated in the
bottom right corner.
A database.
In some high-level diagrams, the icon may be used to
represent both the database and the database server
that manages it.
x
Installed files
The following terms are used throughout the manual:
♦ Installation directory The directory into which you install Adaptive
Server Anywhere. The default installation directory is
c:\Program Files\Sybase\SQL Anywhere 7
♦ Executable directory The executables and other files for each
operating system are stored in a subdirectory of the installation
directory. This subdirectory has the following name:
♦ Windows NT and Windows 95/98 win32
♦ UNIX bin
♦ NetWare and Windows CE The executables are held in the
Adaptive Server Anywhere installation directory itself on these
platforms.
xi
xii
P A R T O N E
Moving to
Adaptive Server Anywhere 7.0
1
2
C H A P T E R 1
About this chapter This chapter provides an overview of the new features and behavior changes
introduced in Adaptive Server Anywhere version 7.0.
Contents
Topic Page
About version 7.0 4
New features overview 5
Behavior changes 15
Upgrade issues 19
3
About version 7.0
4
Chapter 1 Adaptive Server Anywhere Version 7.0
5
New features overview
dbisql /?
The Windows version of Interactive SQL is also included in case you
require access to a feature not yet implemented in the new Interactive
SQL.
No new features are being added to the Windows version, which is now
named dbisqlc.exe.
♦ New validation features Additional validation of databases is
provided by the new VALIDATE INDEX statement and by
enhancements to the VALIDATE TABLE statement. This statement is
called both by the Validation utility, and by the sa_validate system
procedure. The enhancements are available through all these routes.
$ For more information, see "VALIDATE INDEX statement" on
page 627 of the book ASA Reference, and "VALIDATE TABLE
statement" on page 628 of the book ASA Reference.
♦ Lock troubleshooting A new system procedure, sa_locks, provides
information on locks in the database. If lock issues are identified,
information on the connection processes involved can be found using the
AppInfo connection property.
$ For more information, see "sa_locks system procedure" on
page 941 of the book ASA Reference, and "AppInfo connection
parameter" on page 46 of the book ASA Reference.
♦ Unloading result sets The new UNLOAD SQL statement allows
query result sets to be unloaded into a comma-delimited text file.
$ For more information, see "UNLOAD statement" on page 618 of
the book ASA Reference.
♦ Validate backup copies of databases If you backup a database using
the WAIT BEFORE START clause, the backup copy is created in such
a fashion that it can be started in read-only mode and validated.
$ For more information, see "BACKUP statement" on page 389 of
the book ASA Reference.
♦ Default global autoincrement This feature provides an easy way to
generate integer keys which are unique across all databases in a
SQL Remote replication environment.
Integration with ♦ Distributed transactions and three-tiered computing Distributed
distributed transactions include operations on more than one server in a single
computing transaction. A transaction server controls the commit and rollback
architectures behavior of distributed transactions.
6
Chapter 1 Adaptive Server Anywhere Version 7.0
7
New features overview
8
Chapter 1 Adaptive Server Anywhere Version 7.0
In previous releases, primary and foreign keys have had a single index
automatically associated with them, which describes all primary key
values and all the related foreign key entries. In some situations, this
architecture lead to poor performance. The new index organization
separates these indexes, which leads to improved performance in some
situations.
$ For more information on key indexes, see "Using keys to improve
query performance" on page 789 of the book ASA User’s Guide.
Your database must be unloaded and reloaded to take advantage of
variable hash size indexes, and separate key indexes. Running the
upgrade utility is not sufficient. For instructions, see "Upgrade issues"
on page 19.
♦ Separate storage for long values The physical storage of long values
(LONG BINARY, LONG VARCHAR, TEXT, IMAGE) has been
reorganized. Long values are now stored on separate database pages.
This change produces performance improvements, especially on queries
requiring scans of tables storing long values.
Your database must be unloaded and reloaded to take advantage of this
feature.
♦ New database page-sizes In addition to 1K, 2K, and 4K page sizes,
you can now create databases with page sizes of 8K, 16K or 32K.
Large page sizes can improve performance in some cases, particularly
for large databases. However, there are additional memory requirements
with large page sizes, and so they should only be used after investigation
of the costs and benefits.
$ For more information, see "The dbinit command-line utility" on
page 93 of the book ASA Reference, and "CREATE DATABASE
statement" on page 415 of the book ASA Reference.
$ For information on the number of indexes per table and how it
depends on page size, see "Size and number limitations" on page 932 of
the book ASA Reference.
♦ Optimizer tuning You can use the OPTIMIZATION_GOAL option to
instruct the optimizer to optimize for the time it takes to return the first
row of a query, or the overall time it takes to return all rows. The default
is to optimize for the first row. If you are using applications such as
PowerBuilder DataWindow applications, which require a complete
result set, you may wish to change this option setting.
$ For more information, see "OPTIMIZATION_GOAL option" on
page 189 of the book ASA Reference.
9
New features overview
10
Chapter 1 Adaptive Server Anywhere Version 7.0
11
New features overview
12
Chapter 1 Adaptive Server Anywhere Version 7.0
13
New features overview
14
Chapter 1 Adaptive Server Anywhere Version 7.0
Behavior changes
This section lists deprecated and unsupported features, and behavior changes
from previous versions of the software.
♦ UltraLite behavior changes For a list of UltraLite behavior changes,
see "Behavior changes" on page 16 of the book UltraLite Developer’s
Guide.
Deprecated and This list includes features that are no longer supported and that impact
unsupported existing applications.
features
♦ Windows 3.x and Windows CE 2.0 no longer supported Windows
3.1 and Windows 3.11 are no longer supported. Windows CE 2.0 is no
longer supported.
♦ DDE protocol no longer supported The DDE protocol was used to
communicate from 16-bit Windows 3.x applications to a Windows 95/98
database server on the same machine. It is no longer required: Windows
3.x applications based on older versions of the software can use TCP/IP
to communicate with the version 7.0 database server.
♦ IPX protocol deprecated Although communications using IPX are
still supported in the present release, it is highly recommended that you
use the SPX protocol instead. The communications parameters are the
same as for IPX, and performance is better. Support for IPX will be
dropped in a future release.
By default, both the database server and the client software do not start
the IPX protocol unless you instruct it to do so explicitly using the –x
command-line option or the CommLinks connection parameter. The
SPX protocol is started by default.
$ For information on using SPX from the client side, see
"CommLinks connection parameter" on page 50 of the book ASA
Reference. For information on using SPX from the server side, see "–x
command-line option" on page 37 of the book ASA Reference.
♦ NUMBER function deprecated Although it is supported in the current
release, the NUMBER function will not be supported in future versions
of Adaptive Server Anywhere.
♦ Deprecated network communication parameters The Broadcast
and CommAutoStop communication parameters are still allowed, but
have no effect. They will not be supported in future versions of Adaptive
Server Anywhere.
♦ No dbclient compatibility executable In version 6, the dbcli6.exe
command-line utility provided easier compatibility with version 5 client
connection methods. There is no comparable utility in version 7.
15
Behavior changes
Behavior changes This list includes behavior changes in existing features that may impact
applications or have an impact during development or database management.
♦ Interactive SQL changes The new version of Interactive SQL has
some changes from previous versions. As it is an interactive tool, most
do not need documentation.
The supported formats for INPUT and OUTPUT statements have
changed, and now include:
♦ INPUT ASCII, DBASE, DBASEII, DBASEIII, EXCEL, FIXED,
FOXPRO, LOTUS
♦ OUTPUT ASCII, DBASE, DBASEII, DBASEIII, EXCEL,
FIXED, FOXPRO, HTML, LOTUS, SQL
♦ Server name space change It is now disallowed for more than one
database server with the same name to be running on TCP/IP anywhere
on the network. Previously, multiple servers with the same name were
allowed as long as they were on separate ports.
♦ No separate network ports library There is no longer a client-side
library named dbport6.dll. The network communication functionality that
was in this DLL is now included in the client libraries.
For clients using IPX, a separate DLL is still required (dbipx7.dll). This
library is not required if you are using the SPX protocol, which is now
recommended over SPX/IPX networks.
♦ Path settings If you use the command-line utilities and you have
Adaptive Server Anywhere 6.0 installed as well as Adaptive Server
Anywhere version 7.0, you must ensure that the version 7.0 directory
occurs ahead of the Adaptive Server Anywhere 6.0 directory in your
path. Otherwise, the Version 6 application starts, rather than the
version 7.0 application.
♦ Connection behavior change Same-machine connections use a
shared-memory communication protocol. In version 7, connections over
shared memory are attempted only if CommLinks is not specified in the
connection string or DSN. In previous releases, a connection string
containing the following parameters:
eng=myengine;links=tcpip
would attempt to find myengine over TCP/IIP, and if this failed would
attempt a shared memory connection. In version 7, no shared memory
link is attempted.
$ For more information on the current behavior, see "CommLinks
connection parameter" on page 50 of the book ASA Reference.
16
Chapter 1 Adaptive Server Anywhere Version 7.0
17
Behavior changes
18
Chapter 1 Adaptive Server Anywhere Version 7.0
Upgrade issues
Adaptive Server Anywhere includes new features affecting the database
server, client/server communications, administration utilities, and
synchronization setups using both SQL Remote and MobiLink.
19
Upgrade issues
♦ New features that rely on new database options or system table changes,
such as scheduling and event handling, or using the version 7 debugger.
To access these features you must upgrade your database. You can
upgrade a database using the Upgrade utility or the ALTER
DATABASE statement.
♦ New features that rely on a changed file format for the database. To use
any of these features you must unload and reload your database.
In version 7.0, these features include the following:
♦ Variable hash size indexes
♦ Separate primary and foreign key indexes
♦ Reorganized storage for blobs.
♦ GLOBAL DEFAULT AUTOINCREMENT columns.
The database storage reorganization enhances the performance of some
operations.
Upgrading a Upgrading a database adds system tables to support new features such as
database event handling, and also adds new database options.
20
Chapter 1 Adaptive Server Anywhere Version 7.0
Client/server compatibility
Version 6.0.0, 6.0.1, 6.0.2, and 6.0.3 database servers support connections
from Version 7 clients. Version 7 database servers support connections from
version 6.0.0, 6.0.1, 6.0.2, or 6.0.3 client applications.
Command-line tools
If you have both Adaptive Server Anywhere version 6 and version 7.0 on
your machine, you must pay attention to your system path when using
command-line tools. Setup adds the version 7.0 executable directory to the
end of your system path. If your Adaptive Server Anywhere Version 6
executable directory is ahead of it in your path and you enter a dbinit
command, for example, you will use the Version 6 tool, and consequently
create a Version 6 database.
21
Upgrade issues
22
C H A P T E R 2
About this chapter This chapter provides an overview to the new features and behavior changes
introduced in Adaptive Server Anywhere 6.0.3.
Contents
Topic Page
New features 24
Behavior changes 32
Upgrade issues 35
23
New features
New features
In addition to bug fixes, Adaptive Server Anywhere version 6.0.3 includes
new features in both the software and the documentation.
♦ SQL Remote enhancements For a list of SQL Remote enhancements
in this release, see "New features in version 6.0.3" on page 218 of the
book Replication and Synchronization Guide.
♦ UltraLite enhancements For a list of UltraLite enhancements in this
release, see "What’s new in 6.0.3" on page 18 of the book UltraLite
Developer’s Guide.
♦ Combined stored procedure and Java debugger The Java debugger
that was provided in previous releases has been upgraded. The new
version of the debugger is able to debug not only Java classes within the
database, but also SQL stored procedures and triggers.
$ For information on how to use the debugger, see "Debugging
Logic in the Database" on page 607 of the book ASA User’s Guide.
♦ Cache size changes The default initial cache size for the database
server is now computed from the database file sizes and the machine
physical memory. A specific initial cache size can be specified as a
percentage of the physical memory of the machine rather than as an
absolute amount, for easier deployment to a variety of environments. On
Windows NT, and Windows 95/98, the cache grows if it is exhausted or
if Java requires more memory, or if an internal algorithm suggests a
performance benefit. Previously, the server would give a Fatal Error:
dynamic memory exhausted error if cache was exhausted.
$ For more information, see "Cache size" on page 17 of the book
ASA Reference.
♦ Read-only databases You can designate a database as read only
when you start a database server. This feature makes deployment of
databases on read-only media, such as CD-ROMs, more straightforward.
The ReadOnly database property returns ON for read-only databases,
and OFF for databases that are not being run in read-only mode.
$ For more information on read-only databases, see "–r command-
line option" on page 33 of the book ASA Reference.
♦ Computed column extensions New flexibility has been added to
computed columns. You can now add computed columns to non-empty
tables, and change the expression associated with a computed column.
Computed columns are recalculated in a number of circumstances to
ensure that the values are reliable.
24
Chapter 2 Adaptive Server Anywhere 6.0.3
25
New features
26
Chapter 2 Adaptive Server Anywhere 6.0.3
27
New features
28
Chapter 2 Adaptive Server Anywhere 6.0.3
♦ File access from Java Support has been added for all the classes in
the package java.io, including those that enable file access from
classes in the database. For security reasons, a new option has been
introduced, which must be set by the DBA to enable this feature.
This feature is supported on Windows NT only.
$ For more information see "JAVA_INPUT_OUTPUT option" on
page 182 of the book ASA Reference.
♦ CONVERT function extensions The date and time styles supported
by the CONVERT function have been extended.
$ For more information, see "CONVERT function" on page 310 of
the book ASA Reference.
♦ Database server startup dialog On 32-bit Windows operating
systems, if you start a database server with no arguments, a window
appears where you can specify a database file and additional command-
line parameters.
$ For more information, see "Starting the server" on page 7 of the
book ASA User’s Guide.
♦ Console utility enhancements The Console utility has been enhanced
to provide more information concerning connections and server
performance.
$ For more information, see "The Console utility" on page 83 of the
book ASA Reference.
♦ dbtran utility enhancements The dbtran command-line utility
permits filtering of the transaction log operations to isolate subsets of
operations.
$ For more information, see "The dbtran command-line utility" on
page 109 of the book ASA Reference.
♦ dblog utility enhancements The dblog utility now displays additional
summary information, including offset information.
$ For more information, see "The dblog command-line utility" on
page 120 of the book ASA Reference.
♦ dbspawn utility enhancements The dbspawn utility has a -f
command-line switch to force a server to start even if one is already
running. This switch uses a ForceStart connection parameter, used only
by the db_start_engine Embedded SQL function.
$ For more information, see "The Spawn utility" on page 117 of the
book ASA Reference, and "db_start_engine function" on page 59 of the
book ASA Programming Interfaces Guide.
29
New features
30
Chapter 2 Adaptive Server Anywhere 6.0.3
31
Behavior changes
Behavior changes
The following are behavior changes from previous versions of the software.
♦ SQL Remote behavior changes For a list of SQL Remote behavior
changes, see "Behavior changes" on page 219 of the book Replication
and Synchronization Guide.
♦ UltraLite behavior changes For a list of UltraLite behavior changes,
see "Behavior changes for 6.0.3" on page 19 of the book UltraLite
Developer’s Guide.
♦ Debugger replaced The Java debugger included in previous versions
of this software has been replaced with a more comprehensive and
powerful stored procedure and Java debugger.
♦ Cache sizing New cache sizing options on the database server
command line introduce behavior changes on existing database server
command lines.
For database server command lines with no -c option, the default cache
size is now chosen based on database file sizes and machine capabilities,
instead of being a fixed value.
For database server command lines with a -c option, the cache size on
Windows NT and Windows 95/98 may increase depending on the load
on the server and the physical memory of the machine.
♦ Adding columns with default values When an added column has a
default value, the entire column is populated with the default. In
previous releases, the column was populated with NULL.
♦ Permissions of referential integrity actions When changes are made
to a primary table, referential integrity actions such as cascading deletes
or updates can take place on a secondary table. These actions are
implemented using system triggers. The triggers now execute with the
permissions of the owner of the secondary table. Previously, they
executed with permissions of the owner of the primary table. The new
behavior means that cascaded operations can take place between tables
with different owners, without additional permissions having to be
granted.
♦ datediff, MONTHS, and YEARS functions The number of months
between two dates is now calculated as the number of first-of-the-
months between the dates. For example, the difference between January
25 and February 2 is 1; the difference between January 1 and January 31
is 0. The number of years is now calculated as the number of first-of-
the-years between the dates.
32
Chapter 2 Adaptive Server Anywhere 6.0.3
33
Behavior changes
34
Chapter 2 Adaptive Server Anywhere 6.0.3
Upgrade issues
Version 6.0.3 software works with older databases. There is no need to
upgrade your database in order to continue working with existing
applications. There is no need to upgrade your database in order to use many
of the new features, including new SQL statements and statement extensions.
If you wish to use new database options, you must upgrade your database.
You can upgrade a database using the Upgrade utility or the ALTER
DATABASE statement.
Version 6.0.0, 6.0.1, and 6.0.2 database servers do not support connections
from Version 6.0.3 clients that set the new UseUDP communication
parameter to OFF (ON is the default). Otherwise, Version 6.0.0, 6.0.1, and
6.0.2 database servers support connections from Version 6.0.3 clients.
Version 6.0.3 database servers support connections from version 6.0.0,
6.0.1, or 6.0.2 client applications.
$ For more information, see "The Upgrade utility" on page 133 of the
book ASA Reference, and "ALTER DATABASE statement" on page 371 of
the book ASA Reference.
$ For information on SQL Remote upgrade issues, see "New features in
version 6.0.3" on page 218 of the book Replication and Synchronization
Guide. For information on UltraLite upgrade issues, see "Upgrade issues for
6.0.3" on page 19 of the book UltraLite Developer’s Guide.
35
Upgrade issues
36
C H A P T E R 3
About this chapter This chapter provides an overview to the new features and behavior changes
introduced in Adaptive Server Anywhere 6.0.2.
Contents
Topic Page
New features 38
Behavior changes 41
37
New features
New features
In addition to bug fixes, Adaptive Server Anywhere version 6.0.2 includes
new features in both the software and the documentation.
Cross references
The printed documentation is not necessarily updated with each
maintenance release. Cross references in this section may not be valid in
the printed documents. For current information, see the online
documentation.
38
Chapter 3 Adaptive Server Anywhere 6.0.2
39
New features
40
Chapter 3 Adaptive Server Anywhere 6.0.2
Behavior changes
The following are behavior changes from previous versions of the software.
♦ Permissions required to debug Java In order to use the Java
debugger, you must now either have DBA authority, or be granted
membership in the SA_DEBUG group. The SA_DEBUG group does not
exist in databases created prior to 6.0.2, and in these older databases any
user can use the Java debugger. The SA_DEBUG group was added to
close a potential security hole.
$ For more information, see "Requirements for using the debugger"
on page 609 of the book ASA User’s Guide.
♦ Default packet size change The default packets size for client/server
communications has been changed from 512 bytes to 1000 bytes. This
change improves performance for multi-row fetches and fetches of large
rows. It also increases the memory requirements.
$ For more information on packet size, see "CommBufferSize
connection parameter" on page 48 of the book ASA Reference, and "–p
command-line option" on page 33 of the book ASA Reference.
41
Behavior changes
42
C H A P T E R 4
About this chapter This chapter provides an overview to the new features introduced in
Adaptive Server Anywhere 6.0.1
Contents
Topic Page
Adaptive Server Anywhere for Windows CE 44
Remote data access 47
Character set translation 48
New Java features 49
Additional new features 50
New features in SQL Remote 52
Behavior changes 53
43
Adaptive Server Anywhere for Windows CE
44
Chapter 4 New Features in Adaptive Server Anywhere 6.0.1
♦ You can use Interactive SQL on your desktop to load and unload data,
and carry out queries.
♦ You can use InfoMaker to produce reports.
The Windows CE database server does not start the TCP/IP network link
unless it is explicitly requested:
dbsrv6 -x tcpip ...
45
Adaptive Server Anywhere for Windows CE
46
Chapter 4 New Features in Adaptive Server Anywhere 6.0.1
Remote data There are several aspects to the remote data access features:
access capabilities
♦ Carry out queries that join tables in external data sources to tables in the
local data source, or to other external data sources.
♦ Insert, update, and delete data in external data sources.
♦ Send statements to a remote server in its native SQL syntax.
♦ Migrate data from one server to another.
$ For information about remote data access, see the chapter "Accessing
Remote Data" on page 867 of the book ASA User’s Guide and the chapter
"Server Classes for Remote Data Access" on page 899 of the book ASA
User’s Guide. These chapters contain pointers to the relevant reference
sections.
47
Character set translation
48
Chapter 4 New Features in Adaptive Server Anywhere 6.0.1
49
Additional new features
50
Chapter 4 New Features in Adaptive Server Anywhere 6.0.1
51
New features in SQL Remote
52
Chapter 4 New Features in Adaptive Server Anywhere 6.0.1
Behavior changes
This section describes behavior changes between version 6.0.0 and 6.0.1.
Java system table changes The system tables used to record Java class
information (SYSJAR, SYSJARCOMPONENT, and SYSJAVACLASS )
had SMALLINT primary keys. These data types have been altered to use
INTEGER primary keys. This change allows more Java classes to be stored
in a database, and more changes to the Java classes in the database.
This change takes effect for new databases and databases upgraded using the
Upgrade utility from this or future releases.
53
Behavior changes
54
C H A P T E R 5
About this chapter The client/server communication protocol changed between SQL Anywhere
versions 5 and Adaptive Server Anywhere version 6. This chapter provides
upgrade instructions for those users upgrading from Version 5 to the
Adaptive Server Anywhere 7.0 release.
This chapter describes upgrade procedures for users of SQL Anywhere
Versions 5.0 and 5.5, and users of Watcom SQL 4.0.
Contents
Topic Page
Understanding upgrades 56
Review of SQL Anywhere Version 5 architecture 58
Upgrading Embedded SQL applications 61
Upgrading ODBC applications 66
Using the compatibility library 71
Capturing dbclient command-line information 77
Upgrading databases 79
Upgrading SQL Remote installations 80
55
Understanding upgrades
Understanding upgrades
A database application and DBMS consists of several components. If your
organization has a large SQL Anywhere installation, you may have many
client machines, possibly running several applications, connected to more
than one server.
When upgrading your system, you need to decide which components to
upgrade, and in which order. This chapter guides you in making those
choices and carrying out the upgrade.
56
Chapter 5 Upgrading Version 5 Applications
57
Review of SQL Anywhere Version 5 architecture
SQL Anywhere
Connection
interface library
string
(DBL50?.DLL)
5
Client
application
Embedded SQL
standalone architecture
Here, the question mark in dbl50?.dll represents a single character indicating
the operating system. The interface library is named dlb50t.dll on Windows
95 and Windows NT, dbl50w.dll on Windows 3.x, and so on.
Embedded SQL client applications make calls to the interface library. The
interface library is referenced by name, so that the name dbl50?.dll is a part
of the client application.
58
Chapter 5 Upgrading Version 5 Applications
Client
application
ODBC driver
ODBCINST.INI
manager
SQL Anywhere
SQL Anywhere
ODBC.INI interface library
ODBC driver
(DBL50?.DLL)
5
ODBC
standalone architecture
59
Review of SQL Anywhere Version 5 architecture
Embedded
SQL
Client/Server
SQL 5
Anywhere
dbclient.exe
interface
library
60
Chapter 5 Upgrading Version 5 Applications
Components The following figure illustrates the changes you need to make in your setup
upgraded in order to upgrade:
Version 5 setup
Version 5
interface
library
(dbl50?.dll)
5
Upgrade Upgrade
Version 7 setup
Version 7
Compatibility
interface
library
library
(dbl50?.dll)
(dblib7.dll)
7
61
Upgrading Embedded SQL applications
62
Chapter 5 Upgrading Version 5 Applications
♦ If you store a connection string that uses the DBF parameter to start
the default database server, then the Version 7.0 database server is
started automatically by the compatibility library, instead of the
Version 5 database server. In this case, no new connection
description is needed.
♦ If you store a connection string that uses a Start Line parameter
specifying dbeng50.exe, you must replace this with one specifying
dbeng7.exe. If your application contains a hard-coded connection
string, you need to take extra steps at this point.
$ For more information on upgrading StartLine parameters, see
"Start parameters and the compatibility library" on page 75.
♦ If the database server is started in some other way, such as by a
batch file or using a Windows NT service, you must reconfigure
this so that the Version 7.0 database server is started instead.
4 Use the new connection description With this step, you are using all
Version 7.0 software and have completed your upgrade. The database
itself does not need to be upgraded to work with existing applications.
63
Upgrading Embedded SQL applications
64
Chapter 5 Upgrading Version 5 Applications
65
Upgrading ODBC applications
StartLine parameter
If your ODBC data source contains a start line specifying the
Version 5 standalone engine (dbeng50.exe) or the SQL Anywhere
client (dbclient.exe), you cannot upgrade using the compatibility
library.
Components The following figure illustrates the changes you must make when upgrading
upgraded an ODBC standalone application.
Version 5
Version 5
ODBC Version 5
ODBC
Administrator ODBC driver
Data
Source 5
Version 7
Version 7
ODBC Version 7
ODBC
Administrator ODBC driver
Data
Source 7
Data sources The ODBC data source specifies which ODBC driver to use. When an
ODBC data source is created as an Adaptive Server Anywhere Version 7.0
data source, it uses the Version 7.0 ODBC driver.
66
Chapter 5 Upgrading Version 5 Applications
67
Upgrading ODBC applications
3 Use the new data source With this step, you are using all Version 7.0
software and have completed your upgrade. The database itself does not
need to be upgraded to work with existing applications.
Some applications may have the data source name hard wired. In this case,
you need to replace the Version 5 data source with a Version 7.0 data source
of the same name. It is recommended that you rename, rather than delete,
your Version 5 data source.
68
Chapter 5 Upgrading Version 5 Applications
69
Upgrading ODBC applications
PBDefaultExpressions=’YES’
DelimitIdentifier=’YES’
PBDateTimeInvalidInSearch=’NO’
PBTimeInvalidInSearch=’YES’
PBQualifierIsOwner=’NO’
PBSpecialDataTypes=’WATCOM_SPECIALDATATYPES’
IdentifierQuoteChar=’"’
PBSystemOwner=’sys,dbo,rs_systabgroup’
PBUseProcOwner=’YES’
SQLSrvrTSName=’YES’
SQLSrvrTSQuote=’YES’
SQLSrvrTSDelimit=’YES’
ForeignKeyDeleteRule=’Disallow if Dependent Rows
Exist (RESTRICT),Delete any Dependent Rows
(CASCADE),Set Dependent Columns to NULL (SET NULL)’
TableListType=’GLOBAL TEMPORARY’
70
Chapter 5 Upgrading Version 5 Applications
71
Using the compatibility library
72
Chapter 5 Upgrading Version 5 Applications
Compatibility
library
Adaptive Server
SQL Anywhere
Anywhere interface
interface library
library 7 5
7 5
73
Using the compatibility library
Yes
Yes No
Can engine or
server be located No Connect
using V7?
Can engine or
server be located No
using V5?
Can a V7 engine
be started using No
Yes START?
Yes
Connect Fail
74
Chapter 5 Upgrading Version 5 Applications
75
Using the compatibility library
76
Chapter 5 Upgrading Version 5 Applications
77
Capturing dbclient command-line information
How to capture the ♦ From an ODBC data source The ODBC data source upgrade captures
information the information in an ODBC data source START parameter.
♦ From a batch file or under an icon You can move the dbclient.exe
parameters into your CommLinks connection parameter. The dbcli7.exe
executable is provided for compatibility reasons only, and makes the
command-line parameters available to Version 6 interface libraries.
♦ Hard-wired connection strings Only if you have a hard-wired
connection string in your application (that is, one that cannot be edited),
you must alter the source of the application and recompile.
78
Chapter 5 Upgrading Version 5 Applications
Upgrading databases
If you wish to use the new features of Adaptive Server Anywhere Version
7.0, you need to upgrade your database to Adaptive Server Anywhere 6. The
format of the database files is the same as in SQL Anywhere Version 5, but
the system tables and available database options have changed.
Caution
Ensure that you back up your database before upgrading.
Supported versions You can upgrade your database from any of the following versions of the
software to Adaptive Server Anywhere Version 6 format:
♦ SQL Anywhere Version 5 Including versions 5.0 and 5.5, all patch
levels.
♦ Watcom SQL Version 4 All patch levels.
♦ Watcom SQL Version 3.2 Only patch level e and above.
What the upgrade The upgrade utility carries out the following tasks:
utility does
♦ Adds new system tables For example, the SYSJAR and
SYSJAVACLASS system tables are new in Version 6, and must be
present for any of the Java capabilities of Adaptive Server Anywhere to
be available.
♦ Adds new columns to existing tables For example, with the
introduction of user-defined data types in SQL Anywhere Version 5,
two system tables had a user_type column added.
♦ Adds database options Database options provide a degree of tuning
for overall database behavior or for individual user behavior. The list of
available options is kept in the system tables, and needs to be upgraded
for the options to become available.
$ For instructions on upgrading databases, see "Upgrade issues" on
page 19 on page 15.
79
Upgrading SQL Remote installations
80
Chapter 5 Upgrading Version 5 Applications
3 When all remote database servers and Message Agents are upgraded, set
the COMPRESSION database option a the consolidated site to a value
other than -1.
81
Upgrading SQL Remote installations
82
P A R T TW O
Database Concepts
This part introduces Adaptive Server Anywhere and describes the basic
concepts you need to understand in order to work with relational databases
and database applications.
83
84
C H A P T E R 6
About this chapter This chapter introduces basic database concepts. It describes what a
relational database is, and what it is used for. It describes how databases and
database applications work together.
Other parts of the documentation set assume that you are familiar with the
concepts introduced in this chapter.
Contents
Topic Page
Relational database concepts 86
SQL and database computing 91
The pieces of a database system 94
How the pieces fit together 97
85
Relational database concepts
Database tables
In a relational database, all data is held in tables, which are made up of rows
and columns.
Each table has one or more columns, and each column is assigned a specific
data type, such as an integer, a sequence of characters (for text), or a date.
Each row in the table has a single value for each column.
For example, a table containing employee information may look as follows:
86
Chapter 6 Databases and Applications
♦ All values for a given column have the same data type.
The following table lists some of the formal and informal relational database
terms describing tables and their contents, together with their equivalent in
nonrelational databases. This manual uses the informal terms.
What do you keep When you are designing your database, you should make sure that each table
in each table? in the database holds information about a specific thing, such as employees,
products, or customers.
By designing a database this way you can set up a structure that eliminates
redundancy and the possible inconsistencies caused by redundancy. For
example, both the sales and accounts payable departments might enter and
look up information about customers. In a relational database, the
information about customers is entered only once, in a table that both
departments can access.
$ For more information about database design, see "Designing Your
Database" on page 321 of the book ASA User’s Guide.
$ For instructions on how to create a table, see "Lesson 3: Design and
create a table" on page 131.
87
Relational database concepts
88
Chapter 6 Databases and Applications
89
Relational database concepts
90
Chapter 6 Databases and Applications
Example This SQL statement creates a table called food that lists types of food and the
amount in stock in the employee cafeteria:
CREATE TABLE food (
food_id integer primary key,
food_type char(20)
quantity integer
)
Queries
The "Q" in "SQL" stands for query. You query (or retrieve) data from a
database with the SELECT statement. The basic query operations in a
relational system are projection, restriction, and join. The SELECT statement
implements all of them.
91
SQL and database computing
Projections and A projection is a subset of the columns in a table. A restriction (also called
restrictions selection) is a subset of the rows in a table, based on some conditions.
For example, the following SELECT statement retrieves the names and
prices of all products that cost more than $15:
SELECT name, unit_price
FROM product
WHERE unit_price > 15
92
Chapter 6 Databases and Applications
System tables contain information about the database. You never alter the
system tables directly in the way that you can alter other tables. The system
tables hold information about the tables in a database, the users of a database,
the columns in each table, and so on. This information is data about data, or
metadata.
93
The pieces of a database system
94
Chapter 6 Databases and Applications
API
95
The pieces of a database system
96
Chapter 6 Databases and Applications
Interface
97
How the pieces fit together
In this case the database server is the Adaptive Server Anywhere network
database server, which supports network communications. The database is
also called a multi-user database.
No changes are needed to a client application for it to work in a client/server
environment, except to identify the server to which it should connect.
98
C H A P T E R 7
About this chapter This chapter introduces the Adaptive Server Anywhere relational database
system. It describes the uses and features of Adaptive Server Anywhere.
Contents
Topic Page
Introduction to Adaptive Server Anywhere 100
Adaptive Server Anywhere intended uses 101
Adaptive Server Anywhere hallmarks 102
Adaptive Server Anywhere system requirements 103
The Adaptive Server Anywhere database server 105
Adaptive Server Anywhere applications 106
99
Introduction to Adaptive Server Anywhere
100
Chapter 7 Introduction to Adaptive Server Anywhere
101
Adaptive Server Anywhere hallmarks
102
Chapter 7 Introduction to Adaptive Server Anywhere
103
Adaptive Server Anywhere system requirements
104
Chapter 7 Introduction to Adaptive Server Anywhere
Same SQL The request-processing engine is identical in the two versions of the server.
features in each They support exactly the same SQL language, and exactly the same database
version features. The personal server does not support communications across a
network, more than ten concurrent connections, or the use of more than two
CPUs. Applications developed against a personal server work unchanged
against a network server.
105
Adaptive Server Anywhere applications
Sybase Central
Sybase Central provides a graphical user interface for creating and
modifying databases and database objects, for inspecting the structure of
databases, and for database server administration.
Sybase Central lets you perform such tasks as creating a new database,
adding a table, or adding a column to a table.
$ For information on using Sybase Central, see "Lesson 2: Connect to
your database" on page 130.
106
Chapter 7 Introduction to Adaptive Server Anywhere
Interactive SQL
Interactive SQL is an application for typing and sending SQL statements to a
database. Interactive SQL allows you to query and alter data in your database
as well as modify the structure of your database.
Everything that can be done in Sybase Central can be done in Interactive
SQL, but administration tasks are easier in Sybase Central. For this reason,
this book uses Sybase Central whenever possible, but when a task is
important, or is simple to accomplish in Interactive SQL, the Interactive SQL
instructions are also included.
$ For information on working with Interactive SQL, see "Using
Interactive SQL" on page 145.
Each Interactive SQL window is divided into three sections: the SQL
Statements pane at the top; the Messages pane in the middle; and the Results
pane at the bottom.
The Interactive ♦ The SQL Statements pane This is where you type SQL statements to
SQL windows access and modify your data.
♦ The Messages pane This information displays information from the
database server, such as how much time was required to process the
request, how many rows were examined in the process, and how many
rows appear in the result set.
♦ The Results pane This is where the result sets of your data appear.
For example, if you enter a query asking how many customers ordered
five or more different types of products, that number appears in the Data
window.
Command-line utilities
A set of command-line utilities is provided for carrying out administration
tasks such as backing up a database. Command-line utilities are useful for
including in batch files for repeated use.
$ For more information about administration utilities, see "Database
Administration Utilities" on page 71 of the book ASA Reference.
Availability of components
What components you have installed depends on which operating system
you are using, what choices you made when installing the software, and
whether you received the Adaptive Server Anywhere product or installed
Adaptive Server Anywhere as part of another product.
107
Adaptive Server Anywhere applications
108
C H A P T E R 8
About this chapter This chapter describes how database applications communicate with the
Adaptive Server Anywhere database server, and provides a glimpse into the
architecture of Adaptive Server Anywhere.
Contents
Topic Page
Application programming interfaces 110
Inside Adaptive Server Anywhere 115
109
Application programming interfaces
Client
Application
Application
Programming Open Client JDBC Embedded SQL ODBC OLE DB
Interface
Driver or Open Embedded
jConnect ODBC OLE DB
interface library Client SQL
Database
Server
ASA
Database
The applications supplied with SQL Anywhere Studio use several of these
interfaces:
110
Chapter 8 The Architecture of Database Applications
ODBC
DB Tools
ISQL
ASA
Sybase Central
Communications protocols
Each interface library communicates with the database server using a
communication protocol. Adaptive Server Anywhere supports two
communication protocols, Tabular Data Stream (TDS) and Command
Sequence. These protocols are internal, and for most purposes it does not
matter which one you are using. Your choice of development environment
will be governed by your available tools.
The major differences you will see are upon connecting to the database. The
Command Sequence applications and TDS applications use different
methods to identify a database and database server, and so connection
dialogs are different.
111
Application programming interfaces
ODBC applications
You can develop ODBC applications using a variety of development tools
and programming languages, as displayed below.
VB PowerBuilder Java
JDBC/ODBC
ODBC Bridge
Delphi
C/C++
112
Chapter 8 The Architecture of Database Applications
C/C++ DB Tools
ESQL
C/C++ OmniConnect
Open
Client
113
Application programming interfaces
JDBC applications
You can develop applications that use JDBC to connect to Adaptive Server
Anywhere using Java. Several of the applications supplied with
SQL Anywhere Studio use JDBC: the stored procedure debugger, Sybase
Central, and Interactive SQL.
jConnect
JDBC
ISQL Debugger
Java and JDBC are also important programming languages for developing
UltraLite applications.
OLE DB applications
Adaptive Server Anywhere includes an OLE DB driver. You can develop
applications using Microsoft’s OLE DB interface directly, or using the
ActiveX Data Objects (ADO) interface. The ADO interface is included in
Visual Basic and other Microsoft programming tools.
114
Chapter 8 The Architecture of Database Applications
115
Inside Adaptive Server Anywhere
Communications
Parser
Java VM
Optimizer
ASA
Data Access
116
Chapter 8 The Architecture of Database Applications
117
Inside Adaptive Server Anywhere
118
P A R T T H R E E
The first chapter of this part takes you on a tour of the Adaptive Server
Anywhere sample database to illustrate how databases are put together. It
then describes how to design and create your own database.
The remaining chapters introduce SQL, the language for accessing and
manipulating data. It also describes how to incorporate SQL into database
applications.
119
120
C H A P T E R 9
About this chapter This chapter introduces some principles of database design, and describes
how to create a database using Sybase Central. It uses the Adaptive Server
Anywhere sample database to illustrate the principles involved.
Contents
Topic Page
Introduction 122
The sample database 124
Tutorial: design and build a simple database 129
121
Introduction
Introduction
It is worth spending some time designing even the simplest database: what
tables you will have, the keys that relate these tables, and so on.
Designing a database is not a difficult task for small and medium sized
databases, but it is an important one. Bad database design can lead to an
inefficient and possibly unreliable database system. Database applications
are built to work on specific parts of a database, and rely on the database
design, so a bad design can be difficult to revise at a later date.
Designing a large database is a complex task. There are formal approaches,
such as conceptual data modeling, that help you to create efficient designs.
Powerful tools such as Sybase PowerDesigner and DataArchitect enable you
to apply these techniques to design and maintain large database designs.
This chapter does not attempt to tackle design issues for large databases. For
an elementary look at the principles of database design, see "Designing Your
Database" on page 321 of the book ASA User’s Guide. For more advanced
treatments, see the Sybase PowerDesigner documentation or a book devoted
to database design.
Instead, this chapter helps you decide the kind of information you group
together in a single table, and the way in which to think about and classify
relationships between tables.
This chapter assumes that you are familiar with the concepts of database
tables, primary keys, and foreign keys. For information, see "Databases and
Applications" on page 85.
122
Chapter 9 Designing and Building Your Database
123
The sample database
asademo.db
product
employee
id <pk> integer sales_order_items
emp_id <pk> integer
name char(15) id <pk,fk> integer
manager_id integer
description char(30) line_id <pk> smallint
emp_fname char(20)
size char(18) id = prod_id prod_id <fk> integer
emp_lname char(20)
color char(6) quantity integer
dept_id <fk> integer
quantity integer ship_date date
street char(40)
unit_price numeric(15,2)
city char(20)
state char(4)
id = id
emp_id = sales_rep zip_code char(9)
phone char(10)
status char(1)
customer
ss_number char(11)
id <pk> integer sales_order salary numeric(20,3)
fname char(15) id <pk> integer start_date date
lname char(20) cust_id <fk> integer termination_date date
address char(35) order_date date birth_date date
city char(20) id = cust_id fin_code_id <fk> char(2) bene_health_ins char(1)
state char(2) region char(7) bene_life_ins char(1)
zip char(10) sales_rep <fk> integer bene_day_care char(1)
phone char(12)
sex char(1)
company_name char(35) code = fin_code_id
fin_code
code <pk> char(2)
contact dept_id = dept_id
type char(10)
id <pk> integer description char(50) emp_id = dept_head_id
last_name char(15)
first_name char(15)
title char(2) code = code
street char(30)
city char(20) fin_data
state char(2) year <pk> char(4) department
zip char(5) quarter <pk> char(2) dept_id <pk> integer
phone char(10) code <pk,fk> char(2) dept_name char(40)
fax char(10) amount numeric(9) dept_head_id <fk> integer
124
Chapter 9 Designing and Building Your Database
125
The sample database
3 Select the ODBC Data Source Name option and click Browse. In the
resulting list, choose ASA 7.0 Sample.
4 Click OK to establish the connection.
126
Chapter 9 Designing and Building Your Database
Notes Each table has a creator, or owner, which is listed in the right pane. If you
see more tables than are shown in the figure, right click the asademo
database, and choose Filter Objects By Owner from the popup menu. Check
DBA, and uncheck the other user IDs in the list. Click OK to restrict the
objects shown to those owned by DBA.
127
The sample database
128
Chapter 9 Designing and Building Your Database
129
Tutorial: design and build a simple database
2 In the left pane, open the Adaptive Server Anywhere container. Then
open the Utilities folder. In the right pane, double-click Create
Database.
3 On the Choose a Connection page, choose Connection Created By a
Local Engine, and click Next.
A personal database server starts, with the name SybCentral. This server
will create the database file.
4 Choose a location and name for your database file.
On the Create an Adaptive Server Anywhere Database page, enter a
filename of c:\temp\mysample. If your temporary directory is
somewhere other than c:\temp, specify a path of your own choice.
5 Click Finish to create the database.
Other options are available when creating a database, which you can
view by clicking Next, but the default choices are good for many
purposes.
The Create Database Message Console displays the progress of the task,
and disappears when the file is created.
130
Chapter 9 Designing and Building Your Database
Click the Database tab. Enter the full path of your database file in the
Database File field. For example, if you followed the suggestion in the
previous lesson, you should enter the following:
c:\temp\mysample.db
5 Connect to the database.
Click OK. The SybCentral database server loads your sample database.
Open the SybCentral container in the left pane to see mysample.
For now, ignore the utility_db databases that you may see under the
SybCentral database server.
In the product table from the sample database, above, each product is an item
of sports clothing.
Exercise Create a simplified version of the product table, containing only the identifier
(id) and name columns.
131
Tutorial: design and build a simple database
132
Chapter 9 Designing and Building Your Database
$ For more information, see "Tables have a primary key" on page 88.
Concepts The primary key is a special column or columns used to uniquely identify a
row in a table. In the product table, the id column uniquely identifies each
product.
Each row has a unique value for the id column, and the values in the other
columns pertain only to that one product. Two products might have the same
name or the same size, but not the same id number. In the diagram, the id
column is underlined to show that it is a primary key.
Creating a column specifically to hold an identifier, which has no other
meaning, is common practice in database design. You will know from any
bank, utility, or credit card statements you get that each account has a unique
identifier.
Using an You can make entering primary keys simple by assigning a primary key
autoincrement column a default value of AUTOINCREMENT. The value for this column is
primary key entered automatically each time a new row is added, and its value is one
more than the field’s value for the last row added.
133
Tutorial: design and build a simple database
134
Chapter 9 Designing and Building Your Database
Exercise This lesson and the last lesson have introduced the basic concepts you need
to know in order to create database tables. You can put these to work by
adding some more tables to your database. These tables will be used in the
subsequent lessons in this chapter.
Using the Sybase Central Table Editor, add the following tables to your
database:
♦ customer Add a table named customer, with the following columns:
♦ id An identification number for each customer. This column has
integer data type, and is the primary key.
♦ company_name The company name. This column is a character
data type, with a maximum length of 35 characters.
♦ sales_order Add a table named sales_order, with the following
columns:
♦ id An identification number for each sales order. This column has
integer data type, and is the primary key.
♦ order_date The date on which the order was placed. This column
has date data type.
135
Tutorial: design and build a simple database
136
Chapter 9 Designing and Building Your Database
employee department
emp_id integer dept_id integer
manager_id integer dept_name char(40)
emp_fname char(20) dept_head_id integer
dept_id = dept_id
emp_lname char(20)
dept_id integer
street char(40)
city char(20)
state char(4)
zip_code char(9)
phone char(10)
status char(1)
ss_number char(11)
salary numeric(20,3)
start_date date
termination_date date
birth_date date
bene_health_ins char(1)
bene_life_ins char(1)
bene_day_care char(1)
sex char(1)
Each entry in the cust_id column of the sales_order table must match
one of the entries in the id column of the customer table. The
sales_order table (which contains the foreign key in the relationship) is
called the foreign table or referencing table. The customer table
(which contains the referenced primary key) is called the primary table
or the referenced table.
♦ Many to many relationships A many-to-many relationship is
represented by an intermediate table, and there is a foreign key
relationship from the intermediate table to each of the related entities.
137
Tutorial: design and build a simple database
138
C H A P T E R 1 0
About this chapter This chapter shows you how to establish a connection from your application
to the database it is working with.
Contents
Topic Page
Introduction to connections 140
Referencing data sources 141
Creating an ODBC Data Source 142
139
Introduction to connections
Introduction to connections
Any client application that uses a database must establish a connection to
that database before any work can be done. The connection forms a channel
through which all activity from the client application takes place. For
example, your user ID determines permissions to carry out actions on the
database—and the database server has your user ID because it is part of the
request to establish a connection.
Many client applications, including application development systems, use the
Open Database Connectivity (ODBC) interface to access Adaptive Server
Anywhere. An ODBC data source is a set of connection parameters that are
stored in the registry or in a file.
You can use ODBC data sources to connect to Adaptive Server Anywhere
databases from any of the following applications:
♦ Sybase Central and Interactive SQL
♦ all the Adaptive Server Anywhere utilities
♦ PowerDynamo, PowerDesigner, and InfoMaker
♦ any application that supports ODBC, such as Visual Basic and
PowerDynamo
Adaptive Server Anywhere client applications on UNIX can use ODBC data
sources. On UNIX, the data source is stored as a file.
$ Adaptive Server Anywhere supports several programming interfaces in
addition to ODBC. For more information, see "Introduction to connections"
on page 32 of the book ASA User’s Guide.
140
Chapter 10 Connecting Your Application to its Database
The Connect dialog in Sybase Central and Interactive SQL has fields for
entering an ODBC Data Source Name or ODBC Data Source File.
141
Creating an ODBC Data Source
142
Chapter 10 Connecting Your Application to its Database
3 Select Adaptive Server Anywhere 7.0 from the list of drivers, and click
Finish.
The Adaptive Server Anywhere ODBC Configuration dialog appears.
Many of the fields in this dialog box are optional. Click the question
mark at the top right of the window and click an entry field to find more
information about that field. You probably only need to use the
following parameters:
♦ Data Source Name (ODBC tab) Type a name that will appear in
the Connect dialog. It can contain spaces, but should be short.
♦ User ID (Login tab) The database user ID you will use to connect.
If you omit the user ID, you will be prompted for it when you
attempt to connect.
143
Creating an ODBC Data Source
144
C H A P T E R 1 1
About this chapter This chapter discusses how to run and use Interactive SQL. Interactive SQL
is a utility shipped with Adaptive Server Anywhere; it lets you execute SQL
statements, build scripts, and display database data.
Contents
Topic Page
Introduction to Interactive SQL 146
Starting Interactive SQL 148
Using Interactive SQL to display data 151
Working with commands in Interactive SQL 152
Configuring Interactive SQL 159
145
Introduction to Interactive SQL
146
Chapter 11 Using Interactive SQL
147
Starting Interactive SQL
148
Chapter 11 Using Interactive SQL
Keyboard shortcuts
Interactive SQL provides the following keyboard shortcuts.
149
Starting Interactive SQL
150
Chapter 11 Using Interactive SQL
151
Working with commands in Interactive SQL
v To enter a command:
♦ In the SQL Statements pane, type the command.
Tips
You can execute only a selection of text in the SQL Statements button by
pressing F9.
Any messages about an executed statement, such as syntax errors, appear
in the Messages pane.
152
Chapter 11 Using Interactive SQL
Reported errors When an abort is detected, one of three different errors will be reported
depending upon when the abort is detected.
1 If the abort is detected when Interactive SQL is processing the request
(as opposed to the database engine), then the following message is
displayed:
ISQL command terminated by user
Interactive SQL stops processing immediately and the database
transaction is left alone.
2 If the cancel is detected by the database engine while processing a
standard data manipulation command (SELECT, INSERT, DELETE,
and UPDATE) and the engine is not running in bulk operations mode,
then the following message is displayed.
Statement interrupted by user.
The effects of the current command are undone, but the rest of the
transaction is left intact.
3 If the abort is detected while the database engine is processing a data
definition command (CREATE, DROP, ALTER, etc.), the following
message appears:
Terminated by user -- transaction rolled back
Since data definition commands all perform a COMMIT automatically
before the command starts, the effect of the ROLLBACK is to just
cancel the current command.
This message also occurs when the database engine is running in bulk
operations mode executing a command that modifies the database (INSERT,
UPDATE, and DELETE). In this case, ROLLBACK cancels not only the
current command, but everything that has been done since the last COMMIT.
In some cases, it may take a considerable amount of time for the database
engine to perform the automatic ROLLBACK.
153
Working with commands in Interactive SQL
UPDATE employee
SET dept_id = 400,
manager_id = 1576
WHERE emp_id = 467;
UPDATE employee
SET dept_id = 400,
manager_id = 1576
WHERE emp_id = 195;
SELECT *
FROM employee
WHERE emp_id IN ( 195, 467 );
2 On the toolbar, click the Execute SQL Statement button. All three
statements are executed. After execution, the commands remain in the
SQL Statements pane. If you want to clear this pane, press the ESC key.
154
Chapter 11 Using Interactive SQL
$ Results are filtered according to the search criteria entered into the look
up field. Once you type a search criteria into the look up field, the dialog will
pause, and then restrict the list to include only those items that begin with the
text you entered. The standard SQL "%" search metacharacter, meaning
"match anything" is also recognized. For example, to list only those tables
ending in "order", type "%order" into the look up field. To list all items
containing the word "java", type "%java%". Clearing the search criteria from
the look up field resets the filtering to display all the items.
Recalling commands
When you execute a command, Interactive SQL automatically saves it in a
history list that lasts for the duration of the current session. You can insert
any one of the previous commands listed into the SQL Statements pane, or
you can view the entire list in the Command History dialog:
155
Working with commands in Interactive SQL
The contents of the department database table appear in the Data window. As
you execute commands with Interactive SQL, they are saved in a command
history. To recall commands, choose Command➤Recall from the menu bar.
This activates the command recall window.
The command recall window displays the first line of all the commands that
you executed during your session. Position the cursor on the first command
that you executed, which was:
SELECT *
FROM department
and press the ENTER key. The cursor returns to the command window with
the selected command in it. You can now re-execute that command or
modify it to make a new command.
More recall keys The following keys can also be used to recall previous commands:
156
Chapter 11 Using Interactive SQL
You can also save commands in text files, so that you can use them in a
subsequent Interactive SQL session. For more information, see "Saving,
loading, and running command files" on page 157.
157
Working with commands in Interactive SQL
Logging commands
With the Interactive SQL logging feature, you can record commands as you
execute them. Interactive SQL continues to record until you stop the logging
process, or until you end the current session. The recorded commands are
stored in a log file.
Tips
You can also start and stop logging by typing in the SQL Statements pane.
To start logging, type and execute START LOGGING ’c:\filename.sql’,
where c:\filename.sql is the path, name, and extension of the log file. A
log file must have the .SQL extension. You only need to include the single
quotation marks if the path contains embedded spaces. To stop logging,
type and execute STOP LOGGING.
Once you start logging, all commands that you try to execute are logged,
including ones that do not execute properly.
Interrupting commands
158
Chapter 11 Using Interactive SQL
159
Configuring Interactive SQL
If you are using the jConnect driver, choosing to show multiple result
sets requires Interactive SQL to wait for an entire result set to be
retrieved before any rows are displayed. This may result in longer waits
for large result sets.
♦ Automatically refetch results Enables or disables the ability of
Interactive SQL to automatically regenerate the most recent result set
after you execute an INSERT, UPDATE, or DELETE statement. For
example, if you are updating a table with the Results pane showing the
rows about to be affected, this option causes Interactive SQL to
automatically refresh the Results pane to reflect the executed changes.
$ For more information, see "AUTO_REFETCH option" on
page 161 of the book ASA Reference in the ASA Reference.
160
Chapter 11 Using Interactive SQL
♦ Default import format Lets you choose the default file format for
importing. This format is automatically selected in the Files of Type
field in the Open dialog, but you can still choose other formats. The
default is also used when Interactive SQL interprets an INPUT statement
if no format is specified.
♦ ASCII options Let you specify the default symbols that are used for
the field separator, quote string and escape character when you import or
export data in the ASCII format.
$ For more information on importing and exporting see "Importing
and Exporting Data" on page 675 of the book ASA User’s Guide in the
ASA User’s Guide.
161
Configuring Interactive SQL
162
C H A P T E R 1 2
About this chapter This chapter introduces SQL queries, which retrieve data from a database.
Queries are built using the SELECT statement.
$ This chapter describes exclusively how to select data from a single
table at a time. For information about selecting data from multiple related
tables, see "Selecting Data from Multiple Tables" on page 181. In addition,
"Selecting Aggregate Data" on page 191 describes how to group your data
and perform calculations on the data in one or more columns.
Contents
Topic Page
Introduction 164
Looking at the information in a table 166
Ordering query results 168
Selecting columns from a table 170
Selecting rows from a table 171
Comparing dates in queries 172
Pattern matching in search conditions 173
Matching rows by sound 174
Compound search conditions in the WHERE clause 175
Short cuts for typing search conditions 176
Running command files 177
163
Introduction
Introduction
The SELECT statement is a versatile command. SELECT statements can
become highly complex in applications retrieving very specific information
from large databases. This tutorial uses only simple SELECT statements:
more advanced queries are described in later tutorials.
$ For more information about the full syntax of the select statement, see
"SELECT statement" on page 587 of the book ASA Reference.
This tutorial uses the Adaptive Server Anywhere 7.0 Sample database. The
sample database contains information about employees, departments, sales
orders, and so on.
Notes Ideally, you should be running the Adaptive Server Anywhere software on
your computer while you read and work through the examples in this
chapter.
164
Chapter 12 Selecting Data from Database Tables
165
Looking at the information in a table
You will also see some information in the Interactive SQL statistics window.
This information is explained later.
Case sensitivity The table name employee is shown starting with an upper case E, even
though the real table name is all lower case. Adaptive Server Anywhere
databases can be created as case-sensitive or case-insensitive in their string
comparisons, but are always case insensitive in their use of identifiers.
$ For information on creating databases, see "Creating a database" on
page 111 of the book ASA User’s Guide, or "The Initialization utility" on
page 92 of the book ASA Reference.
You can type select or Select instead of SELECT. You can enter SQL
keywords in upper case, lower case, or any combination of the two. In the
manuals, upper case letters are generally used for SQL keywords.
166
Chapter 12 Selecting Data from Database Tables
A SELECT The employee table contains a number of rows organized into columns.
statement returns Each column has a name, such as emp_lname or emp_id. There is a row for
rows of data each employee of the company, and each row has a value in each column.
For example, the employee with employee ID 102 is Fran Whitney. Her
manager has employee ID 501.
Tips
SQL keywords are case insensitive, meaning it doesn’t matter how you
capitalize them. For example, SELECT is the same as Select, which is
the same as select. Some objects in the database (such as table and
column names) may be case sensitive if the database is case sensitive,
meaning you must capitalize these objects correctly.
You can type the statements all on one line, or break them up by pressing
ENTER at the end of each line. Some SQL statements, such as the SELECT
statement, consist of several parts, called clauses. In many examples, each
clause is placed on a separate line for easier reading. You do not have to
type them this way for them to process correctly.
167
Ordering query results
Notes The order of the clauses is important. The ORDER BY clause must follow
the FROM clause and the SELECT clause.
168
Chapter 12 Selecting Data from Database Tables
2 Use the key on the id column to read only the companies with id greater
than 300. The results would then need to be sorted by company name.
If there are very few id values greater than 300, the second strategy is better
because only a few rows are scanned and quickly sorted. If most of the id
values are greater than 300, the first strategy is much better because no
sorting is necessary.
Solving the The example above could be solved by creating a two-column index on id
problem and company_name. (The order of the two columns is important.) The
server could then use this index to select rows from the table and have them
in the correct order. However, keep in mind that indexes take up space in the
database file and involve some overhead to keep up to date. Do not create
indexes indiscriminately.
169
Selecting columns from a table
v List the last name, department, and birthdate of each employee in:
♦ Type the following:
SELECT emp_lname, dept_id, birth_date
FROM employee
Rearranging The three columns appear in the order in which you typed them in the
columns SELECT statement. If you want to rearrange the columns, simply change the
order of the column names in the statement. For example, to put the
birth_date column on the left, use the following statement:
SELECT birth_date, emp_lname , dept_id
FROM employee
Ordering rows You can order rows and look at only certain columns at the same time as
follows:
SELECT birth_date, emp_lname , dept_id
FROM employee
ORDER BY emp_lname
As you might have guessed, the asterisk in
SELECT * FROM employee
is a short form for all columns in the table.
170
Chapter 12 Selecting Data from Database Tables
Notes ♦ The apostrophes (single quotes) around the name ’John’ are required.
They indicate that John is a character string. Quotation marks (double
quotes) have a different meaning. Quotation marks can be used to make
otherwise invalid strings valid for column names and other identifiers.
♦ The sample database is not case sensitive, so you would get the same
results whether you searched for ’ ’JOHN’, ’john’, or ’John’.
♦ How you order clauses is important. The FROM clause comes first,
followed by the WHERE clause, and then the ORDER BY clause. If you
type the clauses in a different order, you will get a syntax error.
♦ You do not need to split the statement into several lines. You can enter
the statement into the command window in any format. If you use more
than the number of lines that fit on the screen, the text scrolls in the
Command window.
Again, you can combine what you have learned:
SELECT emp_fname, emp_lname, birth_date
FROM employee
WHERE emp_fname = ’John’
ORDER BY birth_date
The WHERE clause uses a search condition to select rows. In this case the
search condition is emp_fname = ’John’.
171
Comparing dates in queries
emp_lname birth_date
Whitney 1958-06-05
Cobb 1960-12-04
Jordan 1951-12-13
Breault 1947-05-13
Espinoza 1939-12-14
Dill 1963-07-19
The database server knows that the birth_date column contains dates, and
automatically converts the string ’March 3, 1964’ to a date.
172
Chapter 12 Selecting Data from Database Tables
emp_lname emp_fname
Breault Robert
Braun Jane
The % in the search condition indicates that any number of other characters
may follow the letters BR.
v List all employees whose surname begins with BR, followed by zero
or more letters and a T, followed by zero or more letters:
♦ Type the following:
SELECT emp_lname, emp_fname
FROM employee
WHERE emp_lname LIKE ’BR%T%’
emp_lname emp_fname
Breault Robert
The first % sign matches the string eaul, while the second % sign matches
the empty string (no characters).
Another special character that can be used with LIKE is the _ (underscore)
character, which matches exactly one character.
The pattern BR_U% matches all names starting with BR and having U as the
fourth letter. In Braun the matches the letter A and the % matches N.
173
Matching rows by sound
emp_lname emp_fname
Braun Jane
174
Chapter 12 Selecting Data from Database Tables
v List all employees born before March 3, 1964, but exclude the
employee named Whitney:
♦ Type the following:
SELECT emp_lname, birth_date
FROM employee
WHERE birth_date < ’1964-3-3’
AND emp_lname <> ’whitney’
emp_lname birth_date
Cobb 1960-12-04
Jordan 1951-12-13
Breault 1947-05-13
Espinoza 1939-12-14
Dill 1963-07-19
Francis 1954-09-12
175
Short cuts for typing search conditions
Using the short The second short form, IN, may be used when looking for one of a number
form IN of values. The command
SELECT emp_lname, emp_id
FROM employee
WHERE emp_lname IN (’yeung’,’bucceri’,’charlton’)
means the same as:
SELECT emp_lname, emp_id
FROM employee
WHERE emp_lname = ’yeung’
OR emp_lname = ’bucceri’
OR emp_lname = ’charlton’
176
Chapter 12 Selecting Data from Database Tables
UPDATE employee
SET dept_id = 400,
manager_id = 1576
WHERE emp_id = 195;
SELECT *
FROM employee
WHERE emp_id IN ( 195, 467 )
2 Press the execute key (F9). All three statements are executed. After
execution, the commands are left in the Command window.
Outputting data to Notice that the data for each command remains in the Data window only
a file until the next command is executed. To keep a record of your data, you can
save the output of each statement to a separate file. If statement1 and
statement2 are two SELECT statements, then you can output them to file1
and file2, respectively, as follows:
Statement1; OUTPUT TO file1;
statement2; OUTPUT TO file2;
177
Running command files
What are Command files are just ASCII files containing SQL statements as you see
command files? them in the editor. You can use any editor you like to create command files.
You can include comment lines along with the SQL statements to be
executed. Command files are also commonly called scripts.
178
Chapter 12 Selecting Data from Database Tables
The Command window in Interactive SQL has a limit of 500 lines. For
command files larger than this, you should use a generic editor capable of
handling large files. The READ command has no limit on the number of
lines that can be read.
179
Running command files
180
C H A P T E R 1 3
About this chapter This chapter describes database queries that look at information in more than
one table. To do this, SQL provides the JOIN operator. There are several
different ways to join tables together in queries, and this chapter describes
some of the more important ones.
Contents
Topic Page
Viewing information from several tables 182
Joining tables with the cross product 184
Restricting a join 185
Joining tables using key joins 186
Joining tables using natural joins 188
Joining tables using outer joins 189
181
Viewing information from several tables
182
Chapter 13 Selecting Data from Multiple Tables
183
Joining tables with the cross product
184
Chapter 13 Selecting Data from Multiple Tables
Restricting a join
Consider the sales_order and employee tables. The most natural way to
make a join between these tables useful is to insist that the sales_rep in the
sales_order table be the same as the one in the employee table in every row
of the result. Then each row contains information about an order and the
sales representative responsible for it.
To do this, add an ON phrase to the previous query to show the list of
employees and their course registrations.
Example 1
v Restrict the query:
♦ Type the following in the Interactive SQL command window:
SELECT *
FROM sales_order JOIN employee
ON sales_order.sales_rep = employee.emp_id
The table name is given as a prefix to identify the columns. Although not
strictly required in this case, using the table name prefix clarifies the
statement, and is required when two tables have a column with the same
name. A table name used in this context is called a qualifier.
The results of this query contain only 648 rows (one for each row in the
sales_order table). Of the original 48,600 rows in the join, only 648 of them
have the employee number equal in the two tables.
Example 2 The following query is a modified version that fetches only some of the
columns and orders the results.
185
Joining tables using key joins
186
Chapter 13 Selecting Data from Multiple Tables
Company_name value
Able Inc. 6120
AMF Corp. 3624
Amo & Sons 3216
Amy’s Silk Screening 2028
Avco Ent 1752
… …
Note The example above uses the SUM operator, which is an example of an
aggregate function. Aggregate functions work with GROUP BY clauses to
return values for each row group. In this example, the sum of
sales_order_items.quantity * product.unit_price – that is, the
total amount of money paid per product type – is calculated for each
company_name, thereby returning each company's sales.
$ For more information on aggregate functions, see "A first look at
aggregate functions" on page 193.
187
Joining tables using natural joins
Errors using This join operator can cause problems by equating columns you may not
NATURAL JOIN intend to be equated. For example, the following query generates unwanted
results:
SELECT *
FROM sales_order
NATURAL JOIN customer
The result of this query has no rows.
The database server internally generates the following ON phrase:
FROM sales_order JOIN customer
ON sales_order.id = customer.id
The id column in the sales_order table is an ID number for the order. The
ID column in the customer table is an ID number for the customer. None of
them matched. Of course, even if a match were found, it would be a
meaningless one.
188
Chapter 13 Selecting Data from Multiple Tables
189
Joining tables using outer joins
190
C H A P T E R 1 4
About this chapter This chapter describes how to construct queries that tell you aggregate
information. Examples of aggregate information are as follows:
♦ The total of all values in a column
♦ The number of distinct entries in a column
♦ The average value of entries in a column
Contents
Topic Page
Summarizing data 192
A first look at aggregate functions 193
Using aggregate functions to obtain grouped data 194
Restricting groups 196
191
Summarizing data
Summarizing data
Sometimes it is worthwhile to examine aspects of the data in your table that
you can’t see with simple queries. For example, you may wish to find the
average amount of money that a customer pays for an order, or to see how
many employees work for each department. For these types of tasks you use
aggregate functions.
192
Chapter 14 Selecting Aggregate Data
count( * )
75
The result returned from this query is a table with only one column (with title
count( * )) and one row, which contains the number of employees.
The following command is a slightly more complicated aggregate query:
SELECT count( * ),
min( birth_date ),
max( birth_date )
FROM employee
The result set from this query has three columns and only one row. The three
columns contain the number of employees, the birthdate of the oldest
employee, and the birthdate of the youngest employee.
COUNT, MIN and MAX are called aggregate functions. Each of these
functions summarizes information for an entire table. In total, there are six
aggregate functions: MIN, MAX, COUNT, AVG, SUM, and LIST. All but
COUNT have the name of a column as a parameter. As you have seen,
COUNT has an asterisk as its parameter.
193
Using aggregate functions to obtain grouped data
sales_rep count( * )
129 57
195 50
299 114
467 56
667 54
The results of this query consist of one row for each sales rep ID number,
containing the sales rep ID, and the number of rows in the sales_order table
with that number.
Whenever GROUP BY is used, the resulting table has one row for each
different value found in the GROUP BY column or columns.
You can also view grouped data in Visual Basic.
A common error A common error with GROUP BY is to try to get information that cannot
with GROUP BY properly be put in a group. For example,
SELECT sales_rep, emp_lname, count( * )
FROM sales_order
KEY JOIN employee
GROUP BY sales_rep
gives the following error:
Function or column reference to ’emp_lname’ in the select list must also
appear in a GROUP BY
SQL does not realize that each of the result rows for an employee with a
given ID have the same value of emp_lname. An error is reported since SQL
does not know which of the names to display.
194
Chapter 14 Selecting Aggregate Data
195
Restricting groups
Restricting groups
You have already seen how to restrict rows in a query using the WHERE
clause. You can restrict GROUP BY clauses by using the HAVING
keyword.
sales_rep count( * )
129 57
299 114
467 56
1142 57
Order of clauses
GROUP BY must always appear before HAVING. In the same manner,
WHERE must appear before GROUP BY.
v To list all sales reps with more than 55 orders and an ID of more
than 1000:
♦ Type the following:
SELECT sales_rep, count( * )
FROM sales_order
KEY JOIN employee
WHERE sales_rep > 1000
GROUP BY sales_rep
HAVING count( * ) > 55
196
Chapter 14 Selecting Aggregate Data
v To list all sales reps with more than 55 orders and an ID of more
than 1000:
♦ Type the following:
SELECT sales_rep, count( * )
FROM sales_order
KEY JOIN employee
GROUP BY sales_rep
HAVING count( * ) > 55
AND sales_rep > 1000
The first statement is faster because it can eliminate making up groups for
some of the employees. The second statement builds a group for each sales
rep and then eliminates the groups with wrong employee numbers. For
example, in the first statement, the database engine would not have to make
up a group for the sales rep with employee ID 129. In the second command,
the database engine would make up a group for employee 129 and eliminate
that group with the HAVING clause.
Fortunately, Adaptive Server Anywhere detects this particular problem and
changes the second query to be the same as the first. Adaptive Server
Anywhere performs this optimization with simple conditions (nothing
involving OR or IN). For this reason, when constructing queries with both a
WHERE clause and a HAVING clause, you should be careful to put as many
of the conditions as possible in the WHERE clause.
197
Restricting groups
198
C H A P T E R 1 5
About this chapter This chapter shows how to use the results of one query as part of another
SELECT statement. This is a useful tool in building more complex and
informative queries.
Contents
Topic Page
Introducing subqueries 200
Preparing to use subqueries 201
A simple subquery 202
Comparisons using subqueries 204
Using subqueries instead of joins 206
199
Introducing subqueries
Introducing subqueries
A relational database allows you to store related data in more than one table.
The section "Selecting Data from Multiple Tables" on page 181 outlines one
way of extracting data from related tables. A second method involves
subqueries – queries that appear in another query's WHERE clause or
HAVING clause.
200
Chapter 15 Selecting Data Using Subqueries
v To list all products for which there are less than 20 items in stock:
♦ Type the following:
SELECT id, description, quantity
FROM product
WHERE quantity < 20
Id description quantity
401 Wool cap 12
This query shows that only wool caps are low in stock.
Example 2 You can list all the order items for wool caps with the following query:
201
A simple subquery
A simple subquery
In the previous sections, you had to obtain a result from one SQL statement
before you used it in another. SQL provides you with a way to use the results
of one query in another in just one step. The following query incorporates a
subquery.
Example 1
v To list order items for products low in stock:
♦ Type the following:
SELECT *
FROM sales_order_items
WHERE prod_id IN
( SELECT id
FROM product
WHERE quantity < 20 )
ORDER BY ship_date DESC
By using a subquery, the search can be carried out in just one query, instead
of using one query to find the list of low-stock products and a second to find
orders for those products.
The subquery in the statement is the phrase enclosed in parentheses:
( SELECT id
FROM product
WHERE quantity < 20 )
The subquery makes a list of all values in the id column in the product table
satisfying the WHERE clause search condition.
Example 2 Consider what would happen if an order for ten tank tops were shipped so
that the quantity column for tank tops contained the value 18. The query
using the subquery, would list all orders for both wool caps and tank tops.
On the other hand, the first statement you used would have to be changed to
the following:
202
Chapter 15 Selecting Data Using Subqueries
SELECT *
FROM sales_order_items
WHERE prod_id IN ( 401, 300 )
ORDER BY ship_date DESC
The command using the subquery is an improvement because it still works
even if data in the database is changed.
203
Comparisons using subqueries
This example has used qualifiers to clearly identify the table to which the
code column in each reference belongs. In this particular example, the
qualifiers could have been omitted.
Notes about In general, subqueries are restricted to one column name listed between
subqueries SELECT and FROM: one select-list item. The following example does not
make sense, since SQL would not know which column from fin_code to
compare to the fin_data.code column.
SELECT *
FROM fin_data
WHERE fin_data.code IN
( SELECT fin_code.code, fin_code.type
FROM fin_code
WHERE type = ’revenue’ )
Further, while subqueries used with an IN condition may return several rows,
a subquery used with a comparison operator must return only one row. For
example the following command results in an error since the subquery
returns two rows:
204
Chapter 15 Selecting Data Using Subqueries
SELECT *
FROM fin_data
WHERE fin_data.code =
( SELECT fin_code.code
FROM fin_code
WHERE type = ’revenue’ )
The IN comparison allows several rows. Two other keywords can be used as
qualifiers for operators to allow them to work with multiple rows: ANY and
ALL.
The following query is identical to the successful query above:
SELECT *
FROM fin_data
WHERE fin_data.code = ANY
( SELECT fin_code.code
FROM fin_code
WHERE type = ’revenue’ )
While the = ANY condition is identical to the IN condition, ANY can also be
used with inequalities such as, or, to give more flexible use of subqueries.
The word ALL is similar to the word ANY. For example, the following
query lists financial data that is not revenues:
SELECT *
FROM fin_data
WHERE fin_data.code <> ALL
( SELECT fin_code.code
FROM fin_code
WHERE type = ’revenue’ )
This is equivalent to the following command using NOT IN:
SELECT *
FROM fin_data
WHERE fin_data.code NOT IN
( SELECT fin_code.code
FROM fin_code
WHERE type = ’revenue’ )
205
Using subqueries instead of joins
id order_date company_name
2473 1994-01-04 Peachtree Active Wear
2474 1994-01-04 Sampson & Sons
2036 1994-01-05 Hermanns
2106 1994-01-05 Salt & Pepper’s
2475 1994-01-05 Cinnamon Rainbow’s
206
Chapter 15 Selecting Data Using Subqueries
The It’s a Hit! company placed no orders, and the subquery returns NULL
for this customer. Companies who have not placed an order are not listed
when inner joins are used.
You could also specify an outer join explicitly. In this case a GROUP BY
clause is also required.
SELECT company_name, state,
MAX( sales_order.id )
FROM customer
KEY LEFT OUTER JOIN sales_order
WHERE state = ’WA’
GROUP BY company_name, state
207
Using subqueries instead of joins
208
C H A P T E R 1 6
About this chapter This chapter describes how to make changes to the contents of your database.
It includes descriptions of how to add rows, remove rows, and change the
contents of rows, as well as how to make changes permanent or correct
changes you have made.
Contents
Topic Page
Introduction 210
Adding rows to a table 211
Modifying rows in a table 212
Transactions in SQL 213
Deleting rows 216
Integrity checking 217
209
Introduction
Introduction
To keep data current in your database, you need to know how to make
changes to it. You can add rows to your table to include new data, or you can
delete rows in your table to exclude outdated data. To update your existing
records, you can modify rows in your table. Finally, to ensure the integrity of
your database, you can check for errors.
210
Chapter 16 Updating the Database
211
Modifying rows in a table
The UPDATE and Since SQL updates all rows that satisfy the conditions of the WHERE clause,
INSERT sometimes more than one row is updated at one time. For example, if a group
commands of sales employees are transferred into marketing and have their dept_id
column updated, the following statement sets the manager_id for all
employees in the marketing department to 1576.
UPDATE employee
SET manager_id = 1576
WHERE dept_id = 400
For employees already in the marketing department, no change is made.
212
Chapter 16 Updating the Database
Transactions in SQL
Adaptive Server Anywhere expects you to group your commands into
transactions. You commit a transaction to make changes to your database
permanent. When you alter your data, your alterations are not made
permanent right away. Instead, they are stored in your transaction log and
made are permanent when you enter the COMMIT command.
Knowing which commands or actions signify the start or end of a transaction
lets you take full advantage of transactions.
Starting Transactions start with one of the following events:
transactions
♦ The first statement following a connection to a database
♦ The first statement following the end of a transaction
Options in Interactive SQL provides you with two options which let you control when
Interactive SQL and how transactions end:
♦ If you set the option AUTO_COMMIT to ON, Interactive SQL
automatically commits your results following every successful statement
and automatically perform a ROLLBACK after each failed statement.
♦ The setting of the option COMMIT_ON_EXIT controls what happens to
uncommitted changes when you exit Interactive SQL. If this option is
set to ON (the default), Interactive SQL does a COMMIT; otherwise it
undoes your uncommitted changes with a ROLLBACK statement.
213
Transactions in SQL
Canceling changes
Any uncommitted change you make can be cancelled. SQL allows you to
undo all of the changes you made since your last commit with one command:
ROLLBACK
The ROLLBACK The ROLLBACK statement undoes all changes you have made to the
statement database since the last time you made changes permanent (see "Making
changes permanent" ON PAGE 214).
214
Chapter 16 Updating the Database
215
Deleting rows
Deleting rows
Sometimes you will want to remove rows from a table. Suppose Rodrigo
Guevara (employee ID 249) leaves the company. The following statement
deletes Rodrigo Guevara from the employee table.
DELETE
FROM employee
WHERE emp_id = 249
With UPDATE and DELETE, the search condition can be as complicated as
you need. For example, if the employee table is being reorganized, the
following statement removes from the employee table all male employees
hired between March 3, 1989 and March 3, 1990.
DELETE
FROM employee
WHERE sex = ’m’
AND start_date between ’1988-03-03’
AND ’1989-03-03’
Since you have made changes to the database that you do not want to keep,
you should undo the changes as follows:
ROLLBACK
216
Chapter 16 Updating the Database
Integrity checking
Adaptive Server Anywhere automatically checks for some common errors in
your data.
217
Integrity checking
There isn’t an employee in the employee table with that ID number. This
prevents you from inserting orders without a valid sales rep ID. This kind of
validity checking is called referential integrity checking, as it maintains the
integrity of references among the tables in the database.
$ For more information on primary and foreign keys, see "Relations
between tables" on page 87.
Example: DELETE An error is reported indicating that there are other records in the database
errors that reference the R&D department, and the delete operation is not carried
out.
primary key for row in table ’department’ is referenced in another table
In order to remove the R&D department, you need to first get rid of all
employees in that department:
DELETE
FROM employee
WHERE dept_id = 100
You can now perform the deletion of the R&D department.
You should cancel these changes to the database (for future use) by entering
a ROLLBACK statement:
ROLLBACK WORK
All changes made since the last successful COMMIT WORK will be
undone. If you have not done a COMMIT, then all changes since you started
Interactive SQL will be undone.
Example: UPDATE The same error message is generated if you perform an update operation that
errors makes the database inconsistent.
For example, the following UPDATE statement causes an integrity error:
UPDATE department
218
Chapter 16 Updating the Database
219
Integrity checking
220
C H A P T E R 1 7
System Tables
About this chapter This chapter describes the system tables, several special tables found in
every Adaptive Server Anywhere database. These system tables describe all
the tables and columns in the database. The database server automatically
updates the system table as the database structure is changed.
Contents
Topic Page
The system tables 222
The SYSCATALOG table 223
The SYSCOLUMNS table 224
Other system tables 225
221
The system tables
222
Chapter 17 System Tables
223
The SYSCOLUMNS table
224
Chapter 17 System Tables
225
Other system tables
226
Index
autocommit
ODBC behavior change, 17
Autostart connection parameter
@ new features 6.0.1, 50
@@identity AVG function, 193
behavior change, 18
B
A base tables, 89
ActiveSync behavior changes
support for, 44 6.0.1, 53
Adaptive Server Anywhere 6.0.2, 41
about, 100 6.0.3, 32
system requirements, 103 ANSINULL option, 53
aggregate functions autocommit, 17
AVG, 193 CHAR_OEM_TRANSLATION, 54
COUNT, 193 CommLinks connection parameter, 53
LIST, 193 DATEDIFF function, 32
MAX, 193 dbport6.dll, 16
MIN, 193 DDE protocol, 15
SUM, 193 -gs command-line option, 53
ALL IPX, 15
conditions, 205 Java classes, 53
alphabetical order, 168 MONTHS function, 32
ALTER statement stack size, 53
automatic commit, 213 -v command-line option, 53
AND keyword, 175 version 7.0, 15
ANSINULL option -x command-line option, 53
behavior change 6.0.1, 53 YEARS function, 32
ANY BETWEEN conditions, 176
conditions, 205 bitmaps
apostrophes storing as blobs, 134
using, 171 blobs
asademo.db file about, 134
about, 124
attributes, 87
AUTO_COMMIT option
Interactive SQL, 213 C
settings, 213 cache
new features, 24
227
D–D
228
E–F
229
G–J
230
K–O
N
K network database server
key joins about, 105
about, 186 platform support, 105
keys new features
about, 87 6.0.1, 43
foreign, 87 6.0.2, 37
primary, 87 6.0.3, 23
db_string_ping_server function, 12
euro, 25
extended output redirection features, 12
L LIST function, 12
LIKE operator, 173 page size, 11
LIST function, 193 REPLACE function, 12
new feature, 12 version 7.0, 3
loading Windows CE, 44
commands in Interactive SQL, 157 NULL
logging allowing in columns, 135
commands in Interactive SQL, 158 NULL value
long commands, 171 allowed in columns, 211
looking up
columns in Interactive SQL, 154
procedures in Interactive SQL, 154
tables in Interactive SQL, 154 O
ODBC
Version 5 compability, 74
Windows CE, 46
M one-to-many relationships
many-to-many relationships definition of, 137
definition of, 137 one-to-one relationships
MAX function, 193 definition of, 136
maximum function, 193 opening multiple Interactive SQL windows, 149
messages operating systems
client side, 50 supported, 103
metadata options
system tables, 92 Interactive SQL viewer, 159
MIN function, 193 OR keyword, 176
minimum function, 193 Oracle
accessing, 47
231
P–R
232
S–U
233
V–Z
W Y
WHERE clause YEARS function
BETWEEN conditions, 176 behavior change, 32
date comparisons, 172
DELETE statement, 216
examples, 171
GROUP BY clause, 196 Z
ORDER BY clause, 171 zip files
pattern matching, 173 compressed, 49
UPDATE statement, 212
234