246
Adaptive Server Anywhere Getting Started Last modified: March 2000 Part Number: MC0056

Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Embed Size (px)

Citation preview

Page 1: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Adaptive Server™ AnywhereGetting Started

Last modified: March 2000Part Number: MC0056

Page 2: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Copyright © 2000 Sybase, Inc. All rights reserved.

Information in this manual may change without notice and does not represent a commitment on the part ofSybase, Inc. and its subsidiaries.

Sybase, Inc. provides the software described in this manual under a Sybase License Agreement. The software may beused only in accordance with the terms of the agreement.

No part of this publication may be reproduced, transmitted, or translated in any form or by any means, electronic,mechanical, manual, optical, or otherwise, without the prior written permission of Sybase, Inc.

Sybase, SYBASE (logo), ADA Workbench, Adaptable Windowing Environment, Adaptive Component Architecture,Adaptive Server, Adaptive Server Anywhere, Adaptive Server Enterprise, Adaptive Server Enterprise Monitor, AdaptiveServer Enterprise Replication, Adaptive Server Everywhere, Adaptive Server IQ, Adaptive Warehouse, AnswerBase,Anywhere Studio, Application Manager, AppModeler, APT-Build, APT-Edit, APT-Execute, APT-FORMS, APT-Library,APT-Translator, APT Workbench, ASEP, Backup Server, BayCam, Bit-Wise, Certified PowerBuilder Developer, CertifiedSYBASE Professional, Certified SYBASE Professional (logo), ClearConnect, Client Services, Client-Library, CodeBank,Cohesion, Column Design, ComponentPack, Connection Manager, CSP, Data Pipeline, Data Workbench, DataArchitect,Database Analyzer, DataExpress, DataServer, DataWindow, DB-Library, dbQueue, Developers Workbench, DirectConnect Anywhere, DirectConnect, Distribution Director, Dynamo, E-Anywhere, E-Whatever, Electronic CaseManagement, Embedded SQL, EMS, Enterprise Application Server, Enterprise Application Studio, EnterpriseClient/Server, Enterprise Connect, Enterprise Data Studio, Enterprise Manager, Enterprise SQL Server Manager, EnterpriseWork Architecture, Enterprise Work Designer, Enterprise Work Modeler, EWA, Financial Fusion, First Impression,Formula One, Gateway Manager, GeoPoint, ImpactNow, InfoMaker, Information Anywhere, Information Everywhere,InformationConnect, InstaHelp, Intellidex, InternetBuilder, iScript, Jaguar CTS, jConnect for JDBC, KnowledgeBase,Logical Memory Manager, MainframeConnect, Maintenance Express, MAP, MDI Access Server, MDI Database Gateway,media.splash, MetaWorks, MethodSet, MobiCATS, MySupport, Net-Gateway, Net-Library, NetImpact, Next GenerationLearning, Next Generation Learning Studio, O DEVICE, OASiS, OASiS (logo), ObjectConnect, ObjectCycle,OmniConnect, OmniSQL Access Module, OmniSQL Toolkit, Open Client, Open Client/Server, Open Client/ServerInterfaces, Open ClientConnect, Open Gateway, Open Server, Open ServerConnect, Open Solutions, Optima++,Partnerships that Work, PB-Gen, PC APT Execute, PC DB-Net, PC Net Library, PhysicalArchitect, Power ThroughKnowledge, Power++, power.stop, PowerAMC, PowerBuilder, PowerBuilder Foundation Class Library, PowerDesigner,PowerDimensions, PowerDynamo, PowerJ, PowerScript, PowerSite, PowerSocket, Powersoft, Powersoft Portfolio,Powersoft Professional, PowerStage, PowerStudio, PowerTips, PowerWare Desktop, PowerWare Enterprise,ProcessAnalyst, Relational Beans, Replication Agent, Replication Driver, Replication Server, Replication Server Manager,Replication Toolkit, Report Workbench, Report-Execute, Resource Manager, RW-DisplayLib, RW-Library, S-Designor,S Designor, SAFE, SAFE/PRO, SDF, Secure SQL Server, Secure SQL Toolset, Security Guardian, SKILS, smart.partners,smart.parts, smart.script, SQL Advantage, SQL Anywhere, SQL Anywhere Studio, SQL Code Checker, SQL Debug,SQL Edit, SQL Edit/TPU, SQL Everywhere, SQL Modeler, SQL Remote, SQL Server, SQL Server Manager, SQL ServerSNMP SubAgent, SQL Server/CFT, SQL Server/DBM, SQL SMART, SQL Station, SQL Toolset, SQLJ, Startup.Com,STEP, SupportNow, Sybase Central, Sybase Client/Server Interfaces, Sybase Development Framework, Sybase FinancialServer, Sybase Gateways, Sybase Learning Connection, Sybase SQL Desktop, Sybase SQL Lifecycle, Sybase SQLWorkgroup, Sybase Synergy Program, Sybase User Workbench, Sybase Virtual Server Architecture, Sybase MPP,SybaseWare, Syber Financial, SyberAssist, SyBooks, System XI (logo), System 10, System 11, SystemTools, Tabular DataStream, The Enterprise Client/Server Company, The Extensible Software Platform, The Future Is Wide Open,The Learning Connection, The Model For Client/Server Solutions, The Online Information Center, Transact-SQL,Translation Toolkit, Turning Imagination Into Reality, UltraLite, UNIBOM, Unilib, Uninull, Unisep, Unistring,URK Runtime Kit for UniCode, Viewer, Visual Components, VisualSpeller, VisualWriter, VQL, Warehouse ControlCenter, Warehouse Studio, Warehouse WORKS, WarehouseArchitect, Watcom, Watcom SQL Server, Watcom SQL,Web.PB, Web.SQL, Web Deployment Kit, WebSights, WebViewer, WorkGroup SQL Server, XA-Library, XA-Server,and XP Server are trademarks of Sybase, Inc. or its subsidiaries.

All other trademarks are property of their respective owners.

Last modified: March 2000. Part Number: MC0056.

Page 3: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

iii

Contents

About this Manual............................................................ viiUsing this book........................................................................viiiRelated books .......................................................................... ixDocumentation conventions...................................................... x

PART ONEMoving to Adaptive Server Anywhere 7.0 ....................... 1

1 Adaptive Server Anywhere Version 7.0............................ 3About version 7.0 ......................................................................4New features overview..............................................................5Behavior changes ...................................................................15Upgrade issues .......................................................................19

2 Adaptive Server Anywhere 6.0.3..................................... 23New features ...........................................................................24Behavior changes ...................................................................32Upgrade issues .......................................................................35

3 Adaptive Server Anywhere 6.0.2..................................... 37New features ...........................................................................38Behavior changes ...................................................................41

4 New Features in Adaptive Server Anywhere 6.0.1......... 43Adaptive Server Anywhere for Windows CE ..........................44Remote data access ...............................................................47Character set translation.........................................................48New Java features ..................................................................49Additional new features...........................................................50New features in SQL Remote .................................................52Behavior changes ...................................................................53

Page 4: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

iv

5 Upgrading Version 5 Applications ................................. 55Understanding upgrades......................................................... 56Review of SQL Anywhere Version 5 architecture................... 58Upgrading Embedded SQL applications................................. 61Upgrading ODBC applications................................................ 66Using the compatibility library ................................................. 71Capturing dbclient command-line information ........................ 77Upgrading databases.............................................................. 79Upgrading SQL Remote installations...................................... 80

PART TWODatabase Concepts ......................................................... 83

6 Databases and Applications........................................... 85Relational database concepts................................................. 86SQL and database computing ................................................ 91The pieces of a database system ........................................... 94How the pieces fit together ..................................................... 97

7 Introduction to Adaptive Server Anywhere ................... 99Introduction to Adaptive Server Anywhere ........................... 100Adaptive Server Anywhere intended uses............................ 101Adaptive Server Anywhere hallmarks................................... 102Adaptive Server Anywhere system requirements................. 103The Adaptive Server Anywhere database server ................. 105Adaptive Server Anywhere applications ............................... 106

8 The Architecture of Database Applications................. 109Application programming interfaces ..................................... 110Inside Adaptive Server Anywhere......................................... 115

PART THREEWorking with Databases ............................................... 119

9 Designing and Building Your Database....................... 121Introduction ........................................................................... 122The sample database ........................................................... 124Tutorial: design and build a simple database ....................... 129

Page 5: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

v

10 Connecting Your Application to its Database.............. 139Introduction to connections ...................................................140Referencing data sources .....................................................141Creating an ODBC Data Source ...........................................142

11 Using Interactive SQL.................................................... 145Introduction to Interactive SQL .............................................146Starting Interactive SQL........................................................148Using Interactive SQL to display data...................................151Working with commands in Interactive SQL .........................152Configuring Interactive SQL..................................................159

12 Selecting Data from Database Tables .......................... 163Introduction ...........................................................................164Looking at the information in a table .....................................166Ordering query results ..........................................................168Selecting columns from a table.............................................170Selecting rows from a table...................................................171Comparing dates in queries ..................................................172Pattern matching in search conditions..................................173Matching rows by sound .......................................................174Compound search conditions in the WHEREclause....................................................................................175Short cuts for typing search conditions.................................176Running command files ........................................................177

13 Selecting Data from Multiple Tables............................. 181Viewing information from several tables ...............................182Joining tables with the cross product ....................................184Restricting a join....................................................................185Joining tables using key joins ...............................................186Joining tables using natural joins ..........................................188Joining tables using outer joins.............................................189

14 Selecting Aggregate Data ............................................. 191Summarizing data .................................................................192A first look at aggregate functions.........................................193Using aggregate functions to obtain grouped data ...............194Restricting groups .................................................................196

Page 6: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

vi

15 Selecting Data Using Subqueries................................. 199Introducing subqueries.......................................................... 200Preparing to use subqueries ................................................. 201A simple subquery ................................................................ 202Comparisons using subqueries ............................................ 204Using subqueries instead of joins ......................................... 206

16 Updating the Database.................................................. 209Introduction ........................................................................... 210Adding rows to a table .......................................................... 211Modifying rows in a table ...................................................... 212Transactions in SQL ............................................................. 213Deleting rows ........................................................................ 216Integrity checking .................................................................. 217

17 System Tables ............................................................... 221The system tables................................................................. 222The SYSCATALOG table...................................................... 223The SYSCOLUMNS table..................................................... 224Other system tables .............................................................. 225

Index............................................................................... 227

Page 7: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

vii

About this Manual

This book describes how to build simple databases and database applicationsusing Adaptive Server Anywhere.

This manual is for beginning users of Adaptive Server Anywhere, and forusers of previous versions who want to find out what is new and different inAdaptive Server Anywhere version 7.0.

This manual assumes some familiarity with basic programming concepts. Italso assumes a working knowledge of the operating system on which youwill be using Adaptive Server Anywhere.

Subject

Audience

Before you begin

Page 8: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

viii

Using this book

Part I is for users of previous versions of the software. It describes newfeatures in Adaptive Server Anywhere 7.0, and information you need toknow if you are upgrading from an earlier version.

Part II introduces the Adaptive Server Anywhere relational databasemanagement system (RDBMS) and basic relational database concepts. If youare new to databases, this part provides a necessary foundation for your workand for understanding the product. If you have worked with other databasesystems, but are new to Adaptive Server Anywhere, you may want to readthis section to see some of the distinguishing features of Adaptive ServerAnywhere.

Part III describes how to design and build a database—planning thedatabase structure, creating tables, entering data, establishing relationshipsbetween tables, and creating views. Many of these tasks can be accomplishedusing our database administration utility, Sybase Central.

It also describes how to use structured query language (SQL) to access andmodify the data in your database.

This book does not exhaust the possibilities of Adaptive Server Anywhere. Itis intended for people who need only to develop simple applications, or whoare unfamiliar with Adaptive Server Anywhere.

Page 9: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

ix

Related booksThis book provides information you need to get started with Adaptive ServerAnywhere. More detailed information is available in other books in theAdaptive Server Anywhere documentation set:

♦ Adaptive Server Anywhere User’s Guide This book provides themost thorough and in-depth information on all aspects of AdaptiveServer Anywhere. It includes material on designing and buildingdatabases, using SQL, administering databases, and other aspects ofAdaptive Server Anywhere operation.

♦ Adaptive Server Anywhere Programming Interfaces Guide Someaspects of database programming are specific to the programminginterface you work with. The Programming Interfaces Guide providesmaterial on each of the programming interfaces you can use to accessAdaptive Server Anywhere databases.

This book is not required for users of Application Development toolswith built-in ODBC support, such as Sybase PowerBuilder or PowerJ.

♦ Adaptive Server Anywhere Reference Manual A complete referenceto 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 inwhich you obtained Adaptive Server Anywhere.

Online documentation is most currentOnline documentation is updated with each maintenance release, andalways contains the most current information.

Depending on which package you have purchased, you may have additionalbooks describing other components of your product.

Page 10: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

x

Documentation conventionsThe following icons are used in this documentation:

Icon Meaning

A client application.

If the icon is used to represent a particular applicationor kind of application, the name is indicated in thebottom right corner.

A database server, such as Sybase Adaptive ServerAnywhere or Adaptive Server Enterprise.

If the icon is used to represent a particular kind ofdatabase server, such as Adaptive Server Anywhere,the name is indicated in the bottom right corner.

An UltraLite application and database server.

In UltraLite, the database server and the applicationare part of the same process.

A database.

In some high-level diagrams, the icon may be used torepresent both the database and the database serverthat manages it.

Replication or synchronization middleware.

These pieces of software assist in sharing data amongdatabases. Examples are the MobiLinkSynchronization Server, the SQL Remote MessageAgent, and the Replication Agent (Log TransferManager) for use with Replication Server.

If the particular kind of middleware is not obviousfrom the context of the diagram, the name is indicatedin the bottom right hand corner.

A Sybase Replication Server.

Page 11: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

xi

Installed files

The following terms are used throughout the manual:

♦ Installation directory The directory into which you install AdaptiveServer Anywhere. The default installation directory isc:\Program Files\Sybase\SQL Anywhere 7

♦ Executable directory The executables and other files for eachoperating system are stored in a subdirectory of the installationdirectory. This subdirectory has the following name:

♦ Windows NT and Windows 95/98 win32

♦ UNIX bin

♦ NetWare and Windows CE The executables are held in theAdaptive Server Anywhere installation directory itself on theseplatforms.

Page 12: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

xii

Page 13: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

1

P A R T O N E

Moving toAdaptive Server Anywhere 7.0

This part is for users of previous versions of Adaptive Server Anywhere. Itdescribes new features, behavior changes, and upgrade issues introduced in

Adaptive Server Anywhere 7.0.

If you have not used previous versions of Adaptive Server Anywhere, you donot need to read this part.

Page 14: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

2

Page 15: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

3

C H A P T E R 1

Adaptive Server Anywhere Version 7.0

This chapter provides an overview of the new features and behavior changesintroduced in Adaptive Server Anywhere version 7.0.

Topic Page

About version 7.0 4

New features overview 5

Behavior changes 15

Upgrade issues 19

About this chapter

Contents

Page 16: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

About version 7.0

4

About version 7.0The primary format for the documentation is HTML Help. The HTML HelpHome Page gives you easy access to the new features, information abouthow to contact Sybase, and other starting points for this release.

If you do not have Internet Explorer 4.0 or HTML Help installed on yourmachine, you will install Windows Help instead of HTML Help. The contentis the same except for the HTML Help home page, which is not present inWindows Help.

If you are using Windows Help, you should look at Chapter 1 of GettingStarted with Adaptive Server Anywhere for information on Adaptive ServerAnywhere new features, and at the first chapters of the UltraLite Developer’sGuide and the Replication and Synchronization Guide for information onnew features in those technologies.

Finding out aboutthe new features

Page 17: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 1 Adaptive Server Anywhere Version 7.0

5

New features overviewThis section introduces the new features in Adaptive Server Anywhereversion 7.0. It provides an exhaustive listing of major and minor newfeatures, with cross references to locations where each feature is discussed indetail.

If you have the printed version of this book, and if you do not have thecomplete SQL Anywhere Studio documentation set, you should look in theonline documentation for the detailed description of each feature. To locatethe information in the online documentation, go to the index and enter thespecified title.

♦ Task scheduling and event handling in the database You can nowadd scheduled operations to the database. This can be useful forautomatic backups, periodic reports to fill summary tables, and othertasks.

The database server can also be instructed to execute event handlerswhen certain events occur, including disk space thresholds on the drivesholding the database file or the transaction log file, or failed connectionattempts.

Event handlers can be created and altered using Sybase Central, and canbe debugged using the Adaptive Server Anywhere debugger.

$ For more information see "Automating Tasks Using Schedules andEvents" on page 481 of the book ASA User’s Guide, and "CREATEEVENT statement" on page 423 of the book ASA Reference.

♦ Updated Sybase Central Sybase Central is now available as a Javaapplication. This provides a uniform interface to Adaptive ServerAnywhere from any supported platform.

The Windows version of Sybase Central is also included in case yourequire access to a feature not yet implemented in the new SybaseCentral. No new features are being added to the Windows version. Ifyou wish to access the C++ version, you can do so from the SybaseCentral directory, using the scview.exe executable.

♦ Updated Interactive SQL The Interactive SQL utility has beenenhanced and is now available as a Java application. The new InteractiveSQL has multiple windows, with each window opening a separatedatabase connection.

You can start Interactive SQL from the Adaptive Server Anywhereprogram group, or from Sybase Central, or by entering dbisql from acommand prompt. The following command gives a list of command-lineoptions:

Administration andease of useenhancements

Page 18: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features overview

6

dbisql /?

The Windows version of Interactive SQL is also included in case yourequire access to a feature not yet implemented in the new InteractiveSQL.

No new features are being added to the Windows version, which is nownamed dbisqlc.exe.

♦ New validation features Additional validation of databases isprovided by the new VALIDATE INDEX statement and byenhancements to the VALIDATE TABLE statement. This statement iscalled both by the Validation utility, and by the sa_validate systemprocedure. The enhancements are available through all these routes.

$ For more information, see "VALIDATE INDEX statement" onpage 627 of the book ASA Reference, and "VALIDATE TABLEstatement" on page 628 of the book ASA Reference.

♦ Lock troubleshooting A new system procedure, sa_locks, providesinformation on locks in the database. If lock issues are identified,information on the connection processes involved can be found using theAppInfo connection property.

$ For more information, see "sa_locks system procedure" onpage 941 of the book ASA Reference, and "AppInfo connectionparameter" on page 46 of the book ASA Reference.

♦ Unloading result sets The new UNLOAD SQL statement allowsquery result sets to be unloaded into a comma-delimited text file.

$ For more information, see "UNLOAD statement" on page 618 ofthe book ASA Reference.

♦ Validate backup copies of databases If you backup a database usingthe WAIT BEFORE START clause, the backup copy is created in sucha fashion that it can be started in read-only mode and validated.

$ For more information, see "BACKUP statement" on page 389 ofthe book ASA Reference.

♦ Default global autoincrement This feature provides an easy way togenerate integer keys which are unique across all databases in aSQL Remote replication environment.

♦ Distributed transactions and three-tiered computing Distributedtransactions include operations on more than one server in a singletransaction. A transaction server controls the commit and rollbackbehavior of distributed transactions.

Integration withdistributedcomputingarchitectures

Page 19: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 1 Adaptive Server Anywhere Version 7.0

7

In this release, Adaptive Server Anywhere can participate in distributedtransactions coordinated by the Microsoft Distributed TransactionCoordinator (DTC). Products such as Sybase Enterprise ApplicationServer and Microsoft Transaction Server can use DTC for transactioncoordination, so DTC support enables Adaptive Server Anywhere toparticipate in three-tiered computing with these products.

$ For more information, see "Three-tier Computing and DistributedTransactions" on page 917 of the book ASA User’s Guide.

♦ OLE DB provider OLE DB is a data access model from Microsoft. Ituses the Component Object Model (COM) interfaces and, unlike ODBC,OLE DB does not assume that the data source uses a SQL queryprocessor. While it has been possible to access Adaptive ServerAnywhere via OLE DB using an OLE DB/ODBC bridge provided byMicrosoft, this release of Adaptive Server Anywhere includes an OLEDB provider. This provider brings several benefits:

♦ OLE DB is the principal data access option for the forthcomingversion of Windows CE.

♦ Some features, such as updating through a cursor, are not availableusing the OLE DB/ODBC bridge.

♦ If you use the Adaptive Server Anywhere OLE DB provider, ODBCis not required in your deployment.

$ For more information, see "The OLE DB and ADO ProgrammingInterfaces" on page 147 of the book ASA Programming InterfacesGuide.

♦ Java connectivity improvements If you use jConnect to connect toAdaptive Server Anywhere from a Java application, you can now takeadvantage of many of the features previously available only to ODBCand Embedded SQL applications, such as autostarting of databaseservers, and detailed control over network communications usingcommunications parameters.

♦ TCP/IP connectivity Establishing a client/server connection overTCP/IP is now simpler. Clients no longer need to specify the portnumber when attempting to connect, even if the server is running on aport other than the default port number (2638). If the default portnumber is in use when a database server is started, the server aquires anunused port number from the operating system.

If you are trying to connect through a firewall (using UseUDP=NO), andif the database server is not running on port 2638, you must still specifya port number. For more information on this scenario, see "Connectingacross a firewall" on page 92 of the book ASA User’s Guide.

Integration withCOM

Connectivityenhancements

Page 20: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features overview

8

A command-line utility displays all Adaptive Server Anywhere databaseservers running TCP/IP on a network. For more information, see "TheServer Location utility" on page 116 of the book ASA Reference.

♦ SPX connectivity You can use the SPX protocol for connecting todatabases. This feature is particularly useful in Novell NetWareenvironments with IPX/SPX as the primary network protocol. SPX isrecommended over IPX.

$ For more information on SPX at the client, see "CommLinksconnection parameter" on page 50 of the book ASA Reference. Forinformation on SPX on the server, see "–x command-line option" onpage 37 of the book ASA Reference. For network communicationparameters that you can use with SPX, see "Network communicationsparameters" on page 61 of the book ASA Reference.

♦ Dynamic cache sizing On Windows NT and UNIX, the size of thedatabase server cache increases and decreases depending on the load onthe database server and the other demands on system memory. Thisfeature removes the need for choosing an explicit cache size under inmany circumstances, and can also boost performance. On Windows95/98, a less comprehensive cache resizing is implemented.

$ For more information, see "Using the cache to improveperformance" on page 785 of the book ASA User’s Guide.

♦ Indexing enhancements Additional flexibility has been added tocontrol the amount of information stored in indexes (the hash size) toimprove index selectivity. Also, the architecture of primary and foreignkey indexes has been altered.

For indexes on multiple columns, or for indexes on columns in whichthe first set of characters or digits are similar across many rows, controlover hash size provides a way of increasing the selectivity of indexes,and so improving performance.

$ For more information, see "How indexes work" on page 795 of thebook ASA User’s Guide, "CREATE INDEX statement" on page 435 ofthe book ASA Reference, and "CREATE TABLE statement" onpage 453 of the book ASA Reference.

$ For information on how to find the number of levels in an index,see "sa_index_levels system procedure" on page 940 of the book ASAReference.

Performanceenhancements

Page 21: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 1 Adaptive Server Anywhere Version 7.0

9

In previous releases, primary and foreign keys have had a single indexautomatically associated with them, which describes all primary keyvalues and all the related foreign key entries. In some situations, thisarchitecture lead to poor performance. The new index organizationseparates these indexes, which leads to improved performance in somesituations.

$ For more information on key indexes, see "Using keys to improvequery performance" on page 789 of the book ASA User’s Guide.

Your database must be unloaded and reloaded to take advantage ofvariable hash size indexes, and separate key indexes. Running theupgrade 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 beenreorganized. Long values are now stored on separate database pages.This change produces performance improvements, especially on queriesrequiring scans of tables storing long values.

Your database must be unloaded and reloaded to take advantage of thisfeature.

♦ 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, particularlyfor large databases. However, there are additional memory requirementswith large page sizes, and so they should only be used after investigationof the costs and benefits.

$ For more information, see "The dbinit command-line utility" onpage 93 of the book ASA Reference, and "CREATE DATABASEstatement" on page 415 of the book ASA Reference.

$ For information on the number of indexes per table and how itdepends on page size, see "Size and number limitations" on page 932 ofthe book ASA Reference.

♦ Optimizer tuning You can use the OPTIMIZATION_GOAL option toinstruct the optimizer to optimize for the time it takes to return the firstrow of a query, or the overall time it takes to return all rows. The defaultis to optimize for the first row. If you are using applications such asPowerBuilder DataWindow applications, which require a completeresult set, you may wish to change this option setting.

$ For more information, see "OPTIMIZATION_GOAL option" onpage 189 of the book ASA Reference.

Page 22: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features overview

10

♦ Optimizer enhancements Further enhancements to the optimizerhave been implemented to assist with performance of queries that useinternal temporary tables and that use primary and foreign key indexes.These enhancements require no user action.

♦ Larger numbers of users and other identifiers Many identifiers inthe system tables identifying database objects have been changed fromSMALLINT to UNSIGNED INTEGER. This change increases thenumber of objects that can be held in a database without violating anabsolute limit.

♦ Inserting and exporting images and documents Two new systemexternal functions allow you to read and write the contents of files.These functions allow direct inserting of images, documents, and so oninto tables from environments such as Interactive SQL.

$ For more information, see "Inserting documents and images" onpage 252 of the book ASA User’s Guide, "xp_read_file systemprocedure" on page 954 of the book ASA Reference, and "xp_write_filesystem procedure" on page 956 of the book ASA Reference.

♦ New interface for external functions Stored procedures and user-defined functions that reference external libraries now use a newinterface. The new interface provides a wider range of operating systems(including UNIX), a wider range of data types, removes the restrictionthat returned data fit into 255 bytes, and supports NULL as a valid valuefor arguments. The older interface is still supported, but should not beused for new development work.

$ For more information, see "Creating procedures and functions withexternal calls" on page 475 of the book ASA User’s Guide.

♦ START DATABASE, STOP DATABASE and STOP ENGINEstatements These statements were previously available only fromInteractive SQL. They are now available from all applications.

$ For more information, see "START DATABASE statement" onpage 604 of the book ASA Reference, "STOP DATABASE statement"on page 609 of the book ASA Reference, and "STOP ENGINEstatement" on page 610 of the book ASA Reference.

♦ FIRST and TOP clause in updates and deletes The FIRST and TOPclauses can be used to update or delete only the first one or more of anyset of rows satisfying a WHERE clause.

$ For more information, see "DELETE statement" on page 482 ofthe book ASA Reference, and "UPDATE statement" on page 621 of thebook ASA Reference.

Miscellaneousenhancements

Page 23: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 1 Adaptive Server Anywhere Version 7.0

11

♦ Explicit table locking The LOCK TABLE statement allows directcontrol over concurrency at a table level, independent of the currentisolation level.

$ For more information, see "LOCK TABLE statement" on page 551of the book ASA Reference.

♦ Expressions in Transact-SQL outer joins The *= and =* operatorsin a WHERE clause provide a way of specifying outer joins for userswho wish to use the Transact-SQL dialect. In previous releases, onlycolumn names could be used in such joins. Now as long as each side ofthe join operator refers to a single table, any expression can be used inthese joins. For example, the following query is now possible:

select *from customer, sales_orderwhere substr( customer.id, 1, 1 ) *=

substr( sales_order.cust_id, 1, 1)

♦ Cursors in stored procedures can reference variables In storedprocedures and user-defined functions, you can declare a cursor on avariable using the following syntax:

DECLARE cursor-name CURSOR USING variable-name

where variable-name is a string variable containing the SELECTstatement for the cursor.

$ For more information, see "DECLARE CURSOR statement" onpage 475 of the book ASA Reference.

♦ Additional database and server properties The following propertieshave been added:

♦ PageSize The database server uses a single page size from startupuntil it is closed down. This page size is the maximum page sizedatabase that can be mounted by the database server. You can nowobtain this page size using the PageSize server-level propertyfunction:

select property( ’PageSize’ )

♦ AppInfo This function provides identification information for aclient application. It is a connection property:

select connection_property( ’AppInfo’ )

$ For more information, see "AppInfo connection parameter" onpage 46 of the book ASA Reference.

♦ IsRuntimeServer This function returns YES if the database serveris a limited desktop runtime personal database server. Otherwise, itreturns NO.

Page 24: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features overview

12

♦ Log truncation points Properties for replication-specific logoffsets have been added. The properties LTMTrunc,RemoteTrunc, and SyncTrunc return the minimal confirmed logoffset for the Replication Agent, SQL Remote, and MobiLinkdbmlsync replication, respectively. These offsets are also known astruncation points because they indicate the point at which thetransaction log can be truncated. The property CurrentRedoPosreturns the current offset in the log file, where the next databaseoperation is to be logged.

$ For a complete list of property functions and information on howto access them, see "Database properties" on page 1060 of the book ASAReference.

♦ Referential integrity checks before commit A new system procedure(sa_check_commit) allows you to check for referential integrity conflictsbefore committing changes to a database.

$ For more information, see "sa_check_commit system procedure"on page 935 of the book ASA Reference.

♦ SQL function enhancements The following functions have beenadded or enhanced.

♦ REPLACE function This new function replaces all occurrences ofa substring with another substring.

$ For more information, see "REPLACE function" on page 348of the book ASA Reference.

♦ LIST function enhancement The LIST function now accepts anoptional second value, which is the delimiter string that separatesthe list items.

$ For more information, see "LIST function" on page 332 of thebook ASA Reference.

♦ Output redirection change The output redirection functionality inInteractive SQL has been extended to include three new Interactive SQLstatements and an Export option in the File menu.

You can now use an OUTPUT TO statement to redirect content from theResults pane to a new file. You can add an APPEND clause to appendthe content to the end of an existing file, or you can add a VERBOSEclause to include the content of the Messages pane with the output.

In earlier versions, output redirection in Interactive SQL could only bedone with the symbols >#, >>#, >&, and >>&. You can still use thesesymbols, but the new Interactive SQL statements allow for more preciseoutput and code that is easier to read.

Page 25: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 1 Adaptive Server Anywhere Version 7.0

13

$ For more information, see "Exporting query results" on page 705of the book ASA User’s Guide in the ASA User’s Guide.

♦ Embedded SQL enhancements A new function,db_string_ping_server, has been introduced to test that a databaseserver can be located with a specified current connection string.

$ For more information, see "db_string_ping_server function" onpage 59 of the book ASA Programming Interfaces Guide.

♦ New LOAD TABLE / UNLOAD TABLE format A new format has beenadded to the UNLOAD TABLE statement to allow data to be output inBCP format and to the LOAD TABLE statement to allow the import ofAdaptive Server Enterprise generated BCP out files containing blobs.

$ For more information, see "LOAD TABLE statement" on page 546of the book ASA Reference or "UNLOAD TABLE statement" onpage 619 of the book ASA Reference.

♦ Last default timestamp The new global variable @@dbts returns aTIMESTAMP value that represents the last value generated for acolumn using DEFAULT TIMESTAMP.

$ For more information, see "Global variables" on page 239 of thebook ASA Reference.

♦ Troubleshooting enhancements On starting the database server, youcan log operations executed by the server to a file using the –zrcommand-line switch. You can use the sa_server_option procedure tocontrol the same behavior while the server is running.

$ For more information, see "sa_server_option system procedure" onpage 942 of the book ASA Reference, and "–zr command-line option" onpage 40 of the book ASA Reference.

♦ Archive backup on NetWare The archive backup format is nowsupported on NetWare. Archive backups to tape require NetWare 5.

$ For more information, see "BACKUP statement" on page 389 ofthe book ASA Reference.

♦ Additional Java class The java.math.BigInteger class is now fullysupported.

$ For a list of supported Java classes, see "Java class data types" onpage 276 of the book ASA Reference.

♦ Added filtering for dbtran The command-line version of the LogTranslation utility allows further filtering of the output, using a new–isicommand-line option.

Page 26: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features overview

14

$ For more information, see "Log translation utility options" onpage 111 of the book ASA Reference.

♦ Faster table truncation The TRUNCATE TABLE statement is muchfaster for version 7.0 databases, for tables with foreign keys.

♦ Suppressing event log messages If you run the database server as aWindows NT service, you can suppress event log messages using aregistry entry.

$ For more information, see "Suppressing Windows NT event logmessages" on page 18 of the book ASA Reference.

Page 27: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 1 Adaptive Server Anywhere Version 7.0

15

Behavior changesThis section lists deprecated and unsupported features, and behavior changesfrom 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’sGuide.

This list includes features that are no longer supported and that impactexisting applications.

♦ Windows 3.x and Windows CE 2.0 no longer supported Windows3.1 and Windows 3.11 are no longer supported. Windows CE 2.0 is nolonger supported.

♦ DDE protocol no longer supported The DDE protocol was used tocommunicate from 16-bit Windows 3.x applications to a Windows 95/98database server on the same machine. It is no longer required: Windows3.x applications based on older versions of the software can use TCP/IPto communicate with the version 7.0 database server.

♦ IPX protocol deprecated Although communications using IPX arestill supported in the present release, it is highly recommended that youuse the SPX protocol instead. The communications parameters are thesame as for IPX, and performance is better. Support for IPX will bedropped in a future release.

By default, both the database server and the client software do not startthe IPX protocol unless you instruct it to do so explicitly using the –xcommand-line option or the CommLinks connection parameter. TheSPX protocol is started by default.

$ For information on using SPX from the client side, see"CommLinks connection parameter" on page 50 of the book ASAReference. For information on using SPX from the server side, see "–xcommand-line option" on page 37 of the book ASA Reference.

♦ NUMBER function deprecated Although it is supported in the currentrelease, the NUMBER function will not be supported in future versionsof Adaptive Server Anywhere.

♦ Deprecated network communication parameters The Broadcastand CommAutoStop communication parameters are still allowed, buthave no effect. They will not be supported in future versions of AdaptiveServer Anywhere.

♦ No dbclient compatibility executable In version 6, the dbcli6.execommand-line utility provided easier compatibility with version 5 clientconnection methods. There is no comparable utility in version 7.

Deprecated andunsupportedfeatures

Page 28: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Behavior changes

16

This list includes behavior changes in existing features that may impactapplications or have an impact during development or database management.

♦ Interactive SQL changes The new version of Interactive SQL hassome changes from previous versions. As it is an interactive tool, mostdo not need documentation.

The supported formats for INPUT and OUTPUT statements havechanged, 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 onedatabase server with the same name to be running on TCP/IP anywhereon the network. Previously, multiple servers with the same name wereallowed as long as they were on separate ports.

♦ No separate network ports library There is no longer a client-sidelibrary named dbport6.dll. The network communication functionality thatwas in this DLL is now included in the client libraries.

For clients using IPX, a separate DLL is still required (dbipx7.dll). Thislibrary is not required if you are using the SPX protocol, which is nowrecommended over SPX/IPX networks.

♦ Path settings If you use the command-line utilities and you haveAdaptive Server Anywhere 6.0 installed as well as Adaptive ServerAnywhere version 7.0, you must ensure that the version 7.0 directoryoccurs ahead of the Adaptive Server Anywhere 6.0 directory in yourpath. Otherwise, the Version 6 application starts, rather than theversion 7.0 application.

♦ Connection behavior change Same-machine connections use ashared-memory communication protocol. In version 7, connections overshared memory are attempted only if CommLinks is not specified in theconnection string or DSN. In previous releases, a connection stringcontaining the following parameters:

eng=myengine;links=tcpip

would attempt to find myengine over TCP/IIP, and if this failed wouldattempt a shared memory connection. In version 7, no shared memorylink is attempted.

$ For more information on the current behavior, see "CommLinksconnection parameter" on page 50 of the book ASA Reference.

Behavior changes

Page 29: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 1 Adaptive Server Anywhere Version 7.0

17

♦ Mirrored logs deleted when DELETE_OLD_LOGS is ON Previously,any mirror of an old transaction log was not deleted, although theprimary copy of the old transaction log was deleted.

♦ ODBC SQLDescribeCol behavior A SQLDescribeCol call on the@@identity field now returns SQL_BIGINT. In earlier versions, itreturned SQL_INTEGER.

♦ ODBC autocommit uses CHAINED option In previous releases, theautocommit behavior of the ODBC driver was independent of theCHAINED database option. The driver itself carried out the COMMITafter each operation.

Using autocommit behavior from ODBC now changes the CHAINEDoption for the connection.

In previous releases, if CHAINED=ON and ODBC autocommit=ON,the ODBC driver would issue a commit after the entire procedurefinished executing, but there would be no COMMIT after each statementin the procedure. Now a COMMIT is issued after each operation in aprocedure.

♦ Update constraints A new ANSI_UPDATE_CONSTRAINTS optionhas been added. Setting this option to CURSORS, or STRICT, restrictsupdates to those allowed by the ANSI standard. Setting this option toOFF, which is the historical behavior, allows a greater range of updates.

$ For more information, see "ANSI_UPDATE_CONSTRAINTSoption" on page 159 of the book ASA Reference, and "UPDATEstatement" on page 621 of the book ASA Reference.

♦ Identifier length limit Long identifiers are treated more consistentlythan in the past. Identifiers longer than 128 bytes were sometimesaccepted and sometimes not, depending on the type of database objectbeing named. Now any attempt to define identifiers longer than 128bytes reports an error.

$ For more information, see "Identifiers" on page 211 of the bookASA Reference.

♦ Windows CE installation With the dropping of support for WindowsCE 2.0, installation behavior has been changed. The Adaptive ServerAnywhere DLLs are no longer placed in the Windows directory; insteadthey are installed under the Adaptive Server Anywhere installationdirectory selected by the user.

The ASA_ prefix identifying Adaptive Server Anywhere DLLs no longerserves a purpose, and has been dropped.

Page 30: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Behavior changes

18

♦ jConnect connections If you use the REMOTEPWD field to connectvia jConnect to a named database on an Adaptive Server Anywheredatabase server, you must assign the field in a different manner forjConnect version 4.2 and above, included with this software.

$ For more information, see "Supplying a URL for the server" onpage 600 of the book ASA User’s Guide.

♦ User-defined errors Within procedures and triggers, you can declareexceptions in the range 99000 to 99999 as user-defined errors incompound statements. You can use the SIGNAL statement to handlethese errors.

$ For more information, see "BEGIN statement" on page 392 of thebook ASA Reference, and "SIGNAL statement" on page 603 of the bookASA Reference.

♦ LOAD TABLE and UNLOAD TABLE security A database servercommand-line option has been added to control the permissions requiredto execute the LOAD TABLE and UNLOAD TABLE statements.

$ For more information, see "–gl command-line option" on page 27of the book ASA Reference.

♦ @@identity in triggers If a table (T1) with an autoincrement columnhas an insert trigger which causes an insert into a second table (T2) alsohaving an autoincrement column, it was not previously possible toobtain the autoincrement value assigned for T1 after the insert hadcompleted. At that point, the value of @@identity would be the valueassigned to T2. The behavior of @@identity has been altered to make thevalue accessible.

$ For the new behavior of @@identity within triggers, see"@@identity global variable" on page 244 of the book ASA Reference.

♦ Starting the debugger The command to start the debugger from acommand prompt has changed to dbprdbg.

♦ Embedded SQL DECL_FIXCHAR In previous releases, the SQLpreprocessor converted a type DECL_FIXCHAR to an array. Forexample, DECL_FIXCHAR(12) was converted to charname_fixchar[12].

In the current release, the SQL preprocessor converts DECL_FIXCHARdeclarations to DECL_FIXCHAR(12) name_fixchar, and references are ofthe form name_fixchar.array[i].

Page 31: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 1 Adaptive Server Anywhere Version 7.0

19

Upgrade issuesAdaptive Server Anywhere includes new features affecting the databaseserver, client/server communications, administration utilities, andsynchronization setups using both SQL Remote and MobiLink.

Standard upgrade precautions

There are several precautions you should take before upgrading anyapplication, and these apply to Adaptive Server Anywhere upgrades just asto any other software.

♦ Check the behavior changes Before upgrading, you should confirmthat none of the documented behavior changes in Version 7 affect yourapplication.

♦ Test You should test your application in a Version 7 environmentthoroughly before upgrading any applications in production use.

♦ Backup You should back up your existing software and data beforeupgrading. In addition, as recovery cannot happen across a databaseupgrade, you should make a backup after upgrading to ensurerecoverability going forward.

♦ Test your upgrade procedure If you are upgrading many end users,test your upgrade procedure carefully before carrying it out.

SQL Anywhere is used in so many different configurations that no upgradeguidelines can be guaranteed for all cases.

Database server compatibility

Adaptive Server Anywhere database servers work with older databases.There is no need to upgrade your database in order to continue working withexisting applications.

New features in version 7.0 are of the following kinds:

♦ New features that require no change to your database. These are featuressuch as dynamic cache resizing that have no database options, systemtable changes, or database storage changes associated with them.

Page 32: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrade issues

20

♦ 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 canupgrade a database using the Upgrade utility or the ALTERDATABASE statement.

♦ New features that rely on a changed file format for the database. To useany 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 someoperations.

Upgrading a database adds system tables to support new features such asevent handling, and also adds new database options.

v To upgrade a database (command line):

1 Make a backup of your database.

2 Ensure that you have exclusive access to the database to be upgraded.

3 Execute the dbupgrad command-line utility against the database:

dbupgrad -c "connection-string"

The connection-string must connect to the database to be unloaded, withDBA authority.

4 Shut down the database and archive the transaction log, before using theupgraded database.

If you do not want to change the page size or other characteristics of yourdatabase, unloading and reloading can be done in a relatively straightforwardmanner.

v To unload and reload a database:

1 Make a backup of your database.

2 Ensure that you have exclusive access to the database to be unloadedand reloaded.

3 Execute the dbunload command-line utility using the -ar command-line switch to create a new database.

Upgrading adatabase

Unloading andreloading adatabase

Page 33: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 1 Adaptive Server Anywhere Version 7.0

21

dbunload -ar -c "connection-string"

The connection-string must connect to the database to be unloaded, withDBA authority. This command replaces the existing database with anupgraded database.

4 Shut down the database and archive the transaction log, before using thereloaded database.

If you want to change the characteristics of the database, the procedure ismore involved. For more information, see "Designing rebuild and extractprocedures" on page 691 of the book ASA User’s Guide.

Client/server compatibility

Version 6.0.0, 6.0.1, 6.0.2, and 6.0.3 database servers support connectionsfrom Version 7 clients. Version 7 database servers support connections fromversion 6.0.0, 6.0.1, 6.0.2, or 6.0.3 client applications.

Adaptive Server Anywhere debugger

The Adaptive Server Anywhere debugger included in this software can onlydebug databases that have been upgraded to version 7.0. Running theUpgrade utility is sufficient: there is no need to unload and reload thedatabase.

Command-line tools

If you have both Adaptive Server Anywhere version 6 and version 7.0 onyour machine, you must pay attention to your system path when usingcommand-line tools. Setup adds the version 7.0 executable directory to theend of your system path. If your Adaptive Server Anywhere Version 6executable directory is ahead of it in your path and you enter a dbinitcommand, for example, you will use the Version 6 tool, and consequentlycreate a Version 6 database.

v To use the version 7.0 command-line tools:

1 Change to the version 7.0 executable directory before executing yourcommand,orModify your system path so that the version 7.0 executable directory isahead of the Adaptive Server Anywhere Version 6 executable directory.

Page 34: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrade issues

22

Page 35: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

23

C H A P T E R 2

Adaptive Server Anywhere 6.0.3

This chapter provides an overview to the new features and behavior changesintroduced in Adaptive Server Anywhere 6.0.3.

Topic Page

New features 24

Behavior changes 32

Upgrade issues 35

About this chapter

Contents

Page 36: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features

24

New featuresIn addition to bug fixes, Adaptive Server Anywhere version 6.0.3 includesnew features in both the software and the documentation.

♦ SQL Remote enhancements For a list of SQL Remote enhancementsin this release, see "New features in version 6.0.3" on page 218 of thebook Replication and Synchronization Guide.

♦ UltraLite enhancements For a list of UltraLite enhancements in thisrelease, see "What’s new in 6.0.3" on page 18 of the book UltraLiteDeveloper’s Guide.

♦ Combined stored procedure and Java debugger The Java debuggerthat was provided in previous releases has been upgraded. The newversion of the debugger is able to debug not only Java classes within thedatabase, but also SQL stored procedures and triggers.

$ For information on how to use the debugger, see "DebuggingLogic in the Database" on page 607 of the book ASA User’s Guide.

♦ Cache size changes The default initial cache size for the databaseserver is now computed from the database file sizes and the machinephysical memory. A specific initial cache size can be specified as apercentage of the physical memory of the machine rather than as anabsolute amount, for easier deployment to a variety of environments. OnWindows NT, and Windows 95/98, the cache grows if it is exhausted orif Java requires more memory, or if an internal algorithm suggests aperformance 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 bookASA Reference.

♦ Read-only databases You can designate a database as read onlywhen you start a database server. This feature makes deployment ofdatabases 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 tocomputed columns. You can now add computed columns to non-emptytables, and change the expression associated with a computed column.Computed columns are recalculated in a number of circumstances toensure that the values are reliable.

Page 37: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 2 Adaptive Server Anywhere 6.0.3

25

$ For more information, see "Defining computed columns" onpage 572 of the book ASA User’s Guide, and "When computed columnsare recalculated" on page 574 of the book ASA User’s Guide.

$ For information on syntax, see "ALTER TABLE statement" onpage 380 of the book ASA Reference.

♦ Support for the euro Collations have been added that include the eurocurrency symbol. These collations are the 1252LATIN1 andISO9LATIN1 collations.

$ For more information, see "The 1252LATIN1 collation" onpage 297 of the book ASA User’s Guide, and "The ISO9LATIN1collation" on page 298 of the book ASA User’s Guide.

♦ Additional collations Other collations have been added to the list ofsupplied collations, including 852POL (OEM Code Page 852 (Latin 2),with Polish ordering), 1250POL (Windows Latin2 code page 1250 withPolish ordering), 1250Latin2 (Windows Latin2 Code page 1250).932JPN (Japanese), 936ZHO (similar to EUC_CHINA), and 950TAI(similar to EUC_TAIWAN).

$ For a complete list, see "Supplied collations" on page 294 of thebook ASA User’s Guide.

♦ New Windows CE platforms The SH4 and ARM processors are nowsupported under Windows CE 2.1x.

$ For a list of supported devices, chips, and operating systemversions, see "Adaptive Server Anywhere system requirements" onpage 103.

♦ ALTER TABLE extensions The ALTER TABLE statement has beenextended to provide SQL/92-compliant clauses to set and drop defaultson columns. These clauses are an alternative to the existing MODIFYclause.

ALTER column-name SET DEFAULT default-value| ALTER column-name DROP DEFAULT

$ For more information, see "ALTER TABLE statement" onpage 380 of the book ASA Reference.

♦ LOAD TABLE extensions You can now load specific columns of atable using the LOAD TABLE statement. A new CHECKCONSTRAINTS option has been introduced to address rebuild issues.

$ For more information, see "LOAD TABLE statement" on page 546of the book ASA Reference.

Page 38: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features

26

♦ Easier connections across firewalls A set of communicationsparameters has been introduced to allow easier connections acrossfirewalls.

$ For more information, see "Connecting across a firewall" onpage 92 of the book ASA User’s Guide.

♦ BACKUP statement extended The MATCH keyword has beenintroduced to allow renaming of the backup copy of the transaction logto a filename of the form YYMMDDnn.log. If you use this keyword, youcan execute the same statement multiple times without writing over data.

$ For more information, see "BACKUP statement" on page 389 ofthe book ASA Reference.

♦ Fast table truncation A faster form of the TRUNCATE TABLEstatement is provided for tables that meet certain criteria. As this fasttruncation carries out a COMMIT as a side effect, a new option has beenintroduced to disable it. By default, the option is set to ON; it should beset to OFF for maximum compatibility with older versions of thesoftware.

$ For more information, see"TRUNCATE_WITH_AUTO_COMMIT option" on page 202 of thebook ASA Reference, and "TRUNCATE TABLE statement" onpage 615 of the book ASA Reference.

♦ Easier unload and reload The dbunload utility has been enhanced (-ar command-line option) to allow a single-step unload and reload of adatabase that can be used whether or not your database is involved inreplication.

$ For more information, see "Unload utility options" on page 128 ofthe book ASA Reference, and "Designing rebuild and extract procedures"on page 691 of the book ASA User’s Guide.

♦ Temporary file location The database server checks for a newenvironment variable, ASTMP, when deciding on the location of thetemporary file. This allows you to use directories other than systemtemporary directories for the temporary file.

$ For more information, see "ASTMP environment variable" onpage 6 of the book ASA Reference.

♦ New system procedures New system procedures allow DBA users tooverride some database server command-line options(sa_server_option), and to flush the database server cache(sa_flush_cache).

$ For more information, see "System and catalog stored procedures"on page 935 of the book ASA Reference.

Page 39: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 2 Adaptive Server Anywhere 6.0.3

27

♦ Character set translation tuning You can control the applicationlocale used in character set translation for an individual connection usingthe new Charset connection parameter.

$ For more information, see "CharSet connection parameter" onpage 48 of the book ASA Reference.

♦ Re-organized Performance Monitor statistics The statistics madeavailable to the Windows NT Performance Monitor have been organizedinto areas. Some statistics have been added, and ones of little use havebeen removed.

$ For a list of available statistics, see "Monitoring database statisticsfrom the Windows NT Performance Monitor" on page 811 of the bookASA User’s Guide.

♦ Database properties from the utility database You can now executeSELECT statements, with no tables, against the utility database. This isprimarily of use for retrieving database and connection properties.

$ For more information, see "Using the utility database" on page 772of the book ASA User’s Guide.

♦ New database properties The following properties are availableusing the property function.

♦ IsNetworkServer Returns YES if connected to a networkdatabase server, and NO if connected to a personal database server.

$ For more information, see "Server-level properties" onpage 1065 of the book ASA Reference.

♦ DefaultCollation You can use the new DefaultCollation propertyto find the default collation to be used when creating a database.

$ For more information, see "Finding the default collation" onpage 310 of the book ASA User’s Guide, and "Server-levelproperties" on page 1065 of the book ASA Reference.

♦ MultiByteCharSet You can use the MultiByteCharSet databaseproperty to determine whether a database is using a multi-byte orsingle-byte collation.

$ For information on this property, see "Database-levelproperties" on page 1070 of the book ASA Reference.

♦ Support for some JDBC 2.0 functions in internal JDBC The internalserver-side JDBC driver now supports functions from the JDBC 2.0interface. Server-side Java applications can now use features such assuch as scrollable, updatable result sets and batch updates. A side effectis that you can now access result sets from Java methods fromInteractive SQL.

Page 40: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features

28

$ For more information, see "Server-side JDBC features" onpage 579 of the book ASA User’s Guide.

♦ Updating Java columns The restriction that set methods in UPDATEstatements must return a non-void data type has now been removed. Forexample, the following statement now works, even if the methodsetName() returns void.

UPDATE ProductSET JProd.setName( ’Tank Top’ )WHERE ID = 302

$ For more information, see "Updating Java objects" on page 554 ofthe book ASA User’s Guide.

♦ Using Java methods that return void as SQL expressions You canuse Java methods that return void as SQL expressions. These methodsreturn this, that is, the object itself, to the SQL calling environment.

$ For more information, see "Return value of methods returningvoid" on page 562 of the book ASA User’s Guide.

♦ Using the main method in Java classes You can now execute amain method of a Java class from SQL.

$ For more information, see "The main method" on page 561 of thebook ASA User’s Guide.

♦ User-defined functions using Java classes You can wrap a Javamethod in a SQL user-defined function.

$ For more information, see "CREATE FUNCTION statement" onpage 432 of the book ASA Reference.

♦ Extensions to stored procedures using Java methods You can useOUT and INOUT parameters in stored procedures that are wrappers forJava methods.

$ For more information, see "Returning values from Java via storedprocedures" on page 564 of the book ASA User’s Guide.

♦ Multi-threaded Java classes in the database Support has beenadded for the package java.lang.Thread.

$ For more information, see "Using threads in Java applications" onpage 561 of the book ASA User’s Guide.

$ For a list of all supported packages, see "Supported Java packages"on page 276 of the book ASA Reference.

Page 41: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 2 Adaptive Server Anywhere 6.0.3

29

♦ File access from Java Support has been added for all the classes inthe package java.io, including those that enable file access fromclasses in the database. For security reasons, a new option has beenintroduced, 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" onpage 182 of the book ASA Reference.

♦ CONVERT function extensions The date and time styles supportedby the CONVERT function have been extended.

$ For more information, see "CONVERT function" on page 310 ofthe book ASA Reference.

♦ Database server startup dialog On 32-bit Windows operatingsystems, if you start a database server with no arguments, a windowappears where you can specify a database file and additional command-line parameters.

$ For more information, see "Starting the server" on page 7 of thebook ASA User’s Guide.

♦ Console utility enhancements The Console utility has been enhancedto provide more information concerning connections and serverperformance.

$ For more information, see "The Console utility" on page 83 of thebook ASA Reference.

♦ dbtran utility enhancements The dbtran command-line utilitypermits filtering of the transaction log operations to isolate subsets ofoperations.

$ For more information, see "The dbtran command-line utility" onpage 109 of the book ASA Reference.

♦ dblog utility enhancements The dblog utility now displays additionalsummary information, including offset information.

$ For more information, see "The dblog command-line utility" onpage 120 of the book ASA Reference.

♦ dbspawn utility enhancements The dbspawn utility has a -fcommand-line switch to force a server to start even if one is alreadyrunning. This switch uses a ForceStart connection parameter, used onlyby the db_start_engine Embedded SQL function.

$ For more information, see "The Spawn utility" on page 117 of thebook ASA Reference, and "db_start_engine function" on page 59 of thebook ASA Programming Interfaces Guide.

Page 42: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features

30

♦ Replication Agent runs as a daemon On UNIX operating systems,you can run the Replication Agent as a daemon by supplying the -udcommand-line option.

$ For more information, see "The Log Transfer Manager" onpage 103 of the book ASA Reference.

♦ TCP/IP local machine connections You can now use TCP/IP toconnect from a client application to a database server running on thesame machine. This is of most use for Windows 3.x applicationsconnecting to a Windows 95/98 database server on the local machine,where TCP/IP connections are faster than the DDE protocol, which hasbeen the recommended method until now.

New documentation features

The printed documentation is not updated with each maintenance release.The online documentation is updated with each maintenance release. Theonline documentation is more current and more reliable than the printeddocumentation.

In addition to documenting the new features, several changes have beenmade to the documentation to improve it, or to provide information that waspreviously missing.

♦ HTML Help format Online documentation for Windows NT andWindows 95/98 is now available in HTML Help format. HTML Help isthe standard online documentation format with new versions ofWindows. Sybase Central documentation remains in Windows Help(WinHelp) format.

By default, the HTML Help version of the online documentation isinstalled if you have Internet Explorer version 4.0 or later installed, or ifyou have HTML Help already installed. Otherwise, WinHelp format isinstalled. The content of the online documentation is the same in eachformat.

If you prefer to use WinHelp, you can select the option to do so from theAdaptive Server Anywhere setup program.

♦ Corrections A major review of the documentation for technicalcorrectness has led to many small changes throughout the manuals.

♦ Backup and Recovery rewrite The Backup and Recovery chapter inthe User’s Guide has been rewritten.

$ See "Backup and Data Recovery" on page 627 of the book ASAUser’s Guide.

Page 43: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 2 Adaptive Server Anywhere 6.0.3

31

♦ International Languages and Character Sets rewrite Over recentreleases, many features have been added for better national languagesupport. The chapter has been rewritten with a focus on using locales tomanage language and character set issues.

$ See "International Languages and Character Sets" on page 279 ofthe book ASA User’s Guide.

♦ Additional deployment information Material describing how tocreate and use a silent install of Adaptive Server Anywhere has beenadded to the chapter on deployment.

$ See "Using a silent installation for deployment" on page 851 of thebook ASA User’s Guide.

Page 44: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Behavior changes

32

Behavior changesThe following are behavior changes from previous versions of the software.

♦ SQL Remote behavior changes For a list of SQL Remote behaviorchanges, see "Behavior changes" on page 219 of the book Replicationand 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 UltraLiteDeveloper’s Guide.

♦ Debugger replaced The Java debugger included in previous versionsof this software has been replaced with a more comprehensive andpowerful stored procedure and Java debugger.

♦ Cache sizing New cache sizing options on the database servercommand line introduce behavior changes on existing database servercommand lines.

For database server command lines with no -c option, the default cachesize 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 onWindows NT and Windows 95/98 may increase depending on the loadon the server and the physical memory of the machine.

♦ Adding columns with default values When an added column has adefault value, the entire column is populated with the default. Inprevious releases, the column was populated with NULL.

♦ Permissions of referential integrity actions When changes are madeto a primary table, referential integrity actions such as cascading deletesor updates can take place on a secondary table. These actions areimplemented using system triggers. The triggers now execute with thepermissions of the owner of the secondary table. Previously, theyexecuted with permissions of the owner of the primary table. The newbehavior means that cascaded operations can take place between tableswith different owners, without additional permissions having to begranted.

♦ datediff, MONTHS, and YEARS functions The number of monthsbetween two dates is now calculated as the number of first-of-the-months between the dates. For example, the difference between January25 and February 2 is 1; the difference between January 1 and January 31is 0. The number of years is now calculated as the number of first-of-the-years between the dates.

Page 45: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 2 Adaptive Server Anywhere 6.0.3

33

This changes the results of these functions by one number, in somecases. The change was made for compatibility with Adaptive ServerEnterprise.

For the smaller time units there are overflow values to the DATEDIFFfunction that are now imposed. Previous versions of the software gaveincorrect answers if the limit was exceeded.

$ For a full description, see "DATEDIFF function" on page 314 ofthe book ASA Reference.

♦ Starting the database server with no arguments In previousreleases, a command such as the following:

dbeng6

would display the usage text for the database server. On 32-bit Windowsoperating systems, it now displays a window where you can specify adatabase file and additional command-line parameters.

♦ Default page size The default page size for databases is now 2048bytes. This choice is a better choice for many users.

♦ Default database collation The default collation used when creatingdatabases has changed. The default depends on your operating systemsettings.

$ For information on how to find the default collation, see "Findingthe default collation" on page 310 of the book ASA User’s Guide.

♦ SQL Preprocessor default collation If no collation is explicitlyspecified, the Embedded SQL Preprocessor now uses locale informationto choose a default collation. If the locale information is unavailable,then 850LATIN1 will be used. The collation used is reported followingthe banner. Previous behavior was to use 850.

$ For information on the preprocessor, see "The SQL preprocessor"on page 79 of the book ASA Programming Interfaces Guide.

♦ Enforced server name length The server name is checked on startup,and is truncated to a maximum value of 40 characters. On NetBIOS, it istruncated to 16 characters. From the client side, the value of theEngineName parameter is also truncated to 40 characters.

$ For more information, see "EngineName connection parameter" onpage 55 of the book ASA Reference.

♦ Agent connection parameter The Agent connection parameterbehavior has been changed. The meaning of this parameter changedfrom version 5 to version 6, as the need for the dbclient executable wasremoved. The parameter meaning has changed to be more useful in aVersion 6 environment.

Page 46: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Behavior changes

34

$ For more information, see "Agent connection parameter" onpage 45 of the book ASA Reference.

Page 47: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 2 Adaptive Server Anywhere 6.0.3

35

Upgrade issuesVersion 6.0.3 software works with older databases. There is no need toupgrade your database in order to continue working with existingapplications. There is no need to upgrade your database in order to use manyof 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 ALTERDATABASE statement.

Version 6.0.0, 6.0.1, and 6.0.2 database servers do not support connectionsfrom Version 6.0.3 clients that set the new UseUDP communicationparameter to OFF (ON is the default). Otherwise, Version 6.0.0, 6.0.1, and6.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 thebook ASA Reference, and "ALTER DATABASE statement" on page 371 ofthe book ASA Reference.

$ For information on SQL Remote upgrade issues, see "New features inversion 6.0.3" on page 218 of the book Replication and SynchronizationGuide. For information on UltraLite upgrade issues, see "Upgrade issues for6.0.3" on page 19 of the book UltraLite Developer’s Guide.

Page 48: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrade issues

36

Page 49: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

37

C H A P T E R 3

Adaptive Server Anywhere 6.0.2

This chapter provides an overview to the new features and behavior changesintroduced in Adaptive Server Anywhere 6.0.2.

Topic Page

New features 38

Behavior changes 41

About this chapter

Contents

Page 50: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features

38

New featuresIn addition to bug fixes, Adaptive Server Anywhere version 6.0.2 includesnew features in both the software and the documentation.

Cross referencesThe printed documentation is not necessarily updated with eachmaintenance release. Cross references in this section may not be valid inthe printed documents. For current information, see the onlinedocumentation.

♦ UltraLite deployment option UltraLite databases for small devicessuch as the PalmPilot and Windows CE computers can be developedwith this version of the software.

$ For information, see the book UltraLite Developer’s Guide.

♦ Performance enhancements Many aspects of Adaptive ServerAnywhere performance are improved in this version of the software.

♦ Backup and Restore SQL statements Adding BACKUP andRESTORE as SQL statements provides server side backup andautomation of backups using SQL scripts.

The BACKUP statement provides direct backup to tape.

$ For more information, see "BACKUP statement" on page 389 ofthe book ASA Reference.

♦ Security features New security features have been added.

♦ Auditing Database administrators can keep track of activityperformed on a database by turning on the AUDITING option. Therecord of activities is kept in the transaction log. By turning onauditing, you increase the amount of data saved in the transactionlog to include login attempts, accurate timestamps of all events, allpermissions checks, and all actions requiring DBA authority.

$ For more information, see "Auditing database activity" onpage 756 of the book ASA User’s Guide.

♦ Minimum password length Database administrators can specifya minimum password length, to discourage easily discoveredpasswords.

$ For more information, see "MIN_PASSWORD_LENGTHoption" on page 186 of the book ASA Reference.

Page 51: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 3 Adaptive Server Anywhere 6.0.2

39

♦ Locating servers A command-line utility is provided fortroubleshooting connections.

$ For more information, see "The Ping utility" on page 114 of thebook ASA Reference.

♦ Starting databases from jConnect connections Databaseconnections over TDS, including connections from Java applicationsover jConnect, can start a database on a server.

$ For more information, see "Supplying a URL for the server" onpage 600 of the book ASA User’s Guide.

♦ getObject and setObject methods from Java client applications From Java applications, you can now retrieve objects from a table andinsert objects into a table without the explicit serialization anddeserialization required in previous releases.

$ For more information, see "Inserting and retrieving objects" onpage 596 of the book ASA User’s Guide.

♦ ODBC 3.51 The ODBC driver has been updated to ODBC 3.51. Thisversion of ODBC includes support for Unicode applications.

$ For more information, see "ODBC conformance" on page 128 ofthe book ASA Programming Interfaces Guide.

♦ Control of allowed JOIN syntax In previous releases, some multi-table queries have been allowed that have ambiguous join clauses. In thepresent release, you can set an option to disallow such queries.

$ For more information, see "EXTENDED_JOIN_SYNTAX option"on page 174 of the book ASA Reference.

♦ Administration utility enhancements Options have been added to theadministration utilities to provide additional features.

♦ dbtran If you use the new -d switch, dbtran puts each operationas it occurs in the transaction log file. This makes transaction logoutput easier to read. This has been added primarily for auditingpurposes.

$ For more information, see "The dbtran command-line utility"on page 109 of the book ASA Reference.

♦ dbtran You can run dbtran against a running database serverinstead of against a log file. This feature has been added to increasethe security of the transaction log—there is now no need to accessthe transaction log directly.

$ For more information, see "The dbtran command-line utility"on page 109 of the book ASA Reference.

Page 52: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features

40

♦ LTM logging New command-line options allow you to tunemessage logging from these utilities.

$ For more information, see "The Log Transfer Manager" onpage 103 of the book ASA Reference.

♦ New LTM options New command line options enable you toreplicate only backed up transactions (backup_only), and to shutdown as soon as all data is replicated (continuous).

$ For more information, see "The LTM configuration file" onpage 105 of the book ASA Reference.

♦ SQL Remote enhancements For a list of SQL Remote enhancementsin this release, see "New features in version 6.0.2" on page 220 of thebook Replication and Synchronization Guide.

New documentation features

In addition to documenting the new features, some additional material hasbeen added to the online documentation.

♦ Security features A chapter has been added, which collects togetherinformation on Adaptive Server Anywhere security features, includingauditing.

$ This chapter is "Keeping Your Data Secure" on page 749 of thebook ASA User’s Guide.

♦ Using subqueries A chapter has been added, which describes in moredetail how to use subqueries.

$ This chapter is "Selecting Data Using Subqueries" on page 199.

♦ Improved reference material Each function and data type has beenseparated into its own topic. This provides quicker access to thismaterial.

Online documentation more recent than printedThe printed documentation may not be updated with each maintenancerelease. The online documentation is updated with each maintenancerelease.

Page 53: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 3 Adaptive Server Anywhere 6.0.2

41

Behavior changesThe following are behavior changes from previous versions of the software.

♦ Permissions required to debug Java In order to use the Javadebugger, you must now either have DBA authority, or be grantedmembership in the SA_DEBUG group. The SA_DEBUG group does notexist in databases created prior to 6.0.2, and in these older databases anyuser can use the Java debugger. The SA_DEBUG group was added toclose 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/servercommunications has been changed from 512 bytes to 1000 bytes. Thischange improves performance for multi-row fetches and fetches of largerows. It also increases the memory requirements.

$ For more information on packet size, see "CommBufferSizeconnection parameter" on page 48 of the book ASA Reference, and "–pcommand-line option" on page 33 of the book ASA Reference.

Page 54: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Behavior changes

42

Page 55: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

43

C H A P T E R 4

New Features in Adaptive Server Anywhere6.0.1

This chapter provides an overview to the new features introduced inAdaptive Server Anywhere 6.0.1

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

About this chapter

Contents

Page 56: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Adaptive Server Anywhere for Windows CE

44

Adaptive Server Anywhere for Windows CEThe Microsoft Windows CE operating system developed for handheldcomputing devices and embedded devices custom-built to carry out aspecific task.

Starting with Version 6.0.1, Adaptive Server Anywhere is available forWindows CE. Versions 2.0 and up of the CE operating system are supported.

The Windows CE version of Adaptive Server Anywhere has the followingcharacteristics:

♦ Full-featured database All SQL features in other versions ofAdaptive Server Anywhere are available in the Windows CE version,including transaction processing, referential integrity actions, proceduresand triggers, and so on.

The Java features and the remote data access features are not available inWindows CE.

♦ Administer from your desktop When running Windows CE on adevice that can be attached to a network or directly to a PC, you canadminister your Windows CE database from a Sybase Central runningon the PC.

♦ ODBC and Embedded SQL applications You can use either of theseinterfaces to develop client applications.

♦ SQL Remote replication The SQL Remote file link is implemented tobe compatible with Windows CE ActiveSync synchronization.

Desktop management of Windows CE databases

Instead of the personal database server, the network database server(dbsrv6.exe) is the version supplied for Windows CE. The network serversupports communications over a TCP/IP network link.

The usual client/server arrangement has the database server running on amachine with more power and resources than the client applications. Clearly,this is not the case with Windows CE; instead, the less powerful machine isrunning the database server.

The advantage to supplying a network server on Windows CE is that you canrun database applications on your desktop computer to carry out tasks onyour Windows CE database. For example:

♦ You can use Sybase Central on your desktop PC to manage yourdatabase

Page 57: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 4 New Features in Adaptive Server Anywhere 6.0.1

45

♦ 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 linkunless it is explicitly requested:

dbsrv6 -x tcpip ...

Creating Windows CE databases

If you have Windows CE services installed on your Windows 95 orWindows NT desktop, you get an option to create a Windows CE databasewhen you create a database from Sybase Central (Windows Edition). SybaseCentral enforces the requirements for Windows CE databases, and optionallycopies the resulting database file to your Windows CE machine.

SQL Remote and Windows CE

If you have Windows CE services installed on your Windows 95 orWindows NT desktop, you get an option to create a Windows CE databasewhen you extract a remote database from Sybase Central (Windows Edition).Sybase Central enforces the requirements for Windows CE databases, andoptionally copies the resulting database file to your Windows CE machine.

From within the Sybase Central (Windows Edition) Utilities folder, if youhave Windows CE services installed, you have an option to set up SQLRemote for ActiveSync synchronization. This sets your folder for FILEmessage link messages to be the ActiveSync folder. When you dock yourWindows CE machine to your desktop machine, ActiveSync keeps the filesin your desktop machine’s ActiveSync folder synchronized with those in theWindows CE ActiveSynce folder.

Windows CE database features

The Windows CE version of the database software contains all the featuresfound on other operating systems except for a few features that are notappropriate for Windows CE. The excluded features include the following:

♦ Java in the Database

♦ External procedures and functions

♦ Only the network database server is supplied.

Page 58: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Adaptive Server Anywhere for Windows CE

46

The following SQL statements are not supported on Windows CE:

♦ ALTER DATABASE

♦ ALTER SERVER

♦ ALTER WRITEFILE

♦ CREATE COMPRESSED DATABASE

♦ CREATE DATABASE

♦ CREATE EXPANDED DATABASE

♦ CREATE EXTERNLOGIN

♦ CREATE EXISTING TABLE and CREATE TABLE using the ATclause.

♦ CREATE SERVER

♦ CREATE WRITEFILE

♦ DROP DATABASE

♦ DROP SERVER

♦ INSTALL JAVA

♦ REMOVE JAVA

♦ START JAVA

♦ STOP JAVA

Using ODBC with Windows CE

There is no ODBC driver manager for Windows CE. This requires changesto the use of data sources compared to other Windows operating systems.

$ For information on how to use ODBC data sources with Windows CE,see "Using ODBC data sources on Windows CE" on page 56 of the bookASA User’s Guide.

Page 59: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 4 New Features in Adaptive Server Anywhere 6.0.1

47

Remote data accessStarting with Adaptive Server Anywhere Version 6.0.1, a single connectioncan access data from external data sources, as if it were stored on the localserver. Supported external data sources include the following:

♦ Adaptive Server Anywhere databases

♦ Adaptive Server Enterprise databases

♦ Oracle databases

♦ IBM DB2 databases

♦ Microsoft SQL Server Databases

♦ Other ODBC data sources

There are several aspects to the remote data access features:

♦ Carry out queries that join tables in external data sources to tables in thelocal 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 "AccessingRemote 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 ASAUser’s Guide. These chapters contain pointers to the relevant referencesections.

Remote dataaccess capabilities

Page 60: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Character set translation

48

Character set translationCharacter set translation has been added to translate strings automaticallybetween different character sets as data is passed between client applicationsand the database server. This enables more flexibility in mixed character-setenvironments.

Character set translation can be carried out among character sets thatrepresent the same characters, but at different values. There needs to be adegree of compatibility between the character sets for this to be possible. Forexample, character set translation is possible between EUC-JIS and Shift-JIScharacter sets, but not between EUC-JIS and OEM code page 850.

To enable character-set translation, you must start the database server usingthe new -ct command-line option. For example:

dbeng6 -ct asademo.db

Most of the character set translation features occur automatically, with littleuser intervention required.

$ For a description of character set translation features, see "Starting adatabase server using character set translation" on page 314 of the book ASAUser’s Guide. For more detailed information, see "Understanding characterset translation" on page 302 of the book ASA User’s Guide.

Page 61: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 4 New Features in Adaptive Server Anywhere 6.0.1

49

New Java featuresThere are some changes made to the Java support. These include thefollowing:

♦ Updating Java fields You can now use standard UPDATE syntax toupdate a field in a column of Java data type. The following statementwas not supported before 6.0.1, but is now supported:

UPDATE ProductSET JProd>>unit_price = 16.00WHERE ID = 302

Use of the EVALUATE function is no longer required.

♦ Compressed jar files You can now install compressed jar files andzip files into the database. However, you should not use the jar utilitythat comes with the Sun JDK. Other zip utilities do produce suitablefiles.

♦ Result sets from Java procedures You can wrap Java methods in astored procedure, which can return a result set or multiple result sets tothe calling environment.

$ For information on this feature, see "Returning result sets fromJava methods" on page 563 of the book ASA User’s Guide.

♦ Default internal connection When a database connection isestablished for internal JDBC operations, it is now recommended thatyou use the following URL:

jdbc:default:connection

In version 6.0.0, an empty string was used to establish this connection.While the empty string does still work, it is deprecated. The new URLcorresponds to the SQLJ1 proposed standard.

Page 62: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Additional new features

50

Additional new featuresSeveral other features have been added to Adaptive Server Anywhere 6.0.1.These include the following:

♦ jConnect 4.0 The version of jConnect included in this product hasbeen updated to version 4.0.

♦ Autostart connection parameter This parameter prevents a personalserver from starting if no network connection is successful.

$ For a description, see "AutoStart connection parameter" onpage 47 of the book ASA Reference.

♦ MESSAGE statement Extensions to the MESSAGE statement allowmessages to be directed to the client, the server window, or a log file.

$ For a description, see "MESSAGE statement" on page 554 of thebook ASA Reference.

♦ Message callbacks Windows Embedded SQL applications canhandle messages received from the server while a request is beingprocessed by registering a message callback function.

$ For more information, see "Request management functions" onpage 67 of the book ASA Programming Interfaces Guide.

♦ More control over operating system threads A new database servercommand-line option (-gx) controls the number of operating systemthreads that are in use. The existing -gt option controls how many canbe in use at one time, effectively controlling the number of CPUs thatcan be exploited.

$ For more information, see "The database server" on page 14 of thebook ASA Reference.

♦ Connection property system procedures Two additional systemprocedures provide alternative ways of querying connection information.

$ For more information, see "sa_conn_properties_by_conn systemprocedure" on page 937 of the book ASA Reference, and"sa_conn_properties_by_name system procedure" on page 938 of thebook ASA Reference.

♦ NULLIF function This provides an abbreviated form of the CASEexpression. NULLIF compares the values of the two expressions. If thefirst expression equals the second expression, NULLIF returns NULL. Ifthe first expression does not equal the second expression, NULLIFreturns the first expression. The NULLIF function provides a short wayto write some CASE expressions.

Page 63: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 4 New Features in Adaptive Server Anywhere 6.0.1

51

$ For more information, see "Miscellaneous functions" on page 295of the book ASA Reference.

Page 64: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

New features in SQL Remote

52

New features in SQL RemoteSeveral features have been added to SQL Remote.

♦ Minimized Message Agent The Message Agent can be made to startwith a minimized window using the -q command-line switch.

♦ Message Agent request to resend messages The point at which theMessage Agent requests that a missing message be resent is now user-configurable using the -rp command-line switch.

$ For information on these options, see "The Message Agent" onpage 522 of the book Replication and Synchronization Guide and"Tuning incoming message polling" on page 460 of the bookReplication and Synchronization Guide.

♦ Cleaning the stable queue For Adaptive Server Enterprise, the new -fq command-line option on the Message Agent assists administration bycleaning confirmed messages from the stable queue.

$ For information, see "The Message Agent" on page 522 of thebook Replication and Synchronization Guide.

♦ Windows CE For information on using SQL Remote with WindowsCE, see "SQL Remote and Windows CE" on page 45

Page 65: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 4 New Features in Adaptive Server Anywhere 6.0.1

53

Behavior changesThis section describes behavior changes between version 6.0.0 and 6.0.1.

Java system table changes The system tables used to record Java classinformation (SYSJAR, SYSJARCOMPONENT, and SYSJAVACLASS )had SMALLINT primary keys. These data types have been altered to useINTEGER primary keys. This change allows more Java classes to be storedin a database, and more changes to the Java classes in the database.

This change takes effect for new databases and databases upgraded using theUpgrade utility from this or future releases.

Parentheses in -x command line In previous releases, database servercommand lines using the -x command-line option have used the bracecharacter ({) to surround options. The same applies to the string in theCommLinks connection parameter. For example:

dbsrv6 -x tcpip{Localhost=demo}

Existing command lines that use braces are still supported, but it is nowrecommended that you use parentheses to surround the options. Use ofparentheses provides support for multi-byte character set identifiers in thedatabase server command line and the CommLinks command-line parameter.

dbsrv6 -x tcpip(Localhost=demo)

ANSINULL default for Transact-SQL and jConnect connections This has been changed to ON, which matches Adaptive Server Enterprisedefault behavior.

Database server -v command-line option Prior to Version 6, thisoption produced verbose output to the transaction logs. This is obsolete, and-v is now used to supply version information.

Database server -gss command-line option The behavior of the -gsserver command-line option, used to set the stack size, was complicated. The-gs command-line option is now deprecated, and -gss provides the samefunctionality in a clearer way.

$ For more information, see "The database server" on page 14 of thebook ASA Reference.

Page 66: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Behavior changes

54

Character set conversion in Interactive SQL Formerly, when theCHAR_OEM_TRANSLATION option was set to DETECT, Interactive SQLwould fetch the collation label from the database to determine whether or notOEM to ANSI character set translation would be turned on. If the collationlabel started with a string that indicated an ANSI code page, translationwould be turned off. Otherwise it would be turned on. When the option wasset to DETECT, Interactive SQL would display a message in the statuswindow indicating the collation label of the database and the displaytranslation setting.

The new behaviour is as follows. If the option is set to DETECT, InteractiveSQL will obtain the CharacterSet connection property from the server. Thisis the character set that the server is using for sending all character strings onthis connection. If this character set indicates an ANSI code page, then OEMto ANSI translation is turned off. Otherwise it is turned on. A new messageis displayed, indicating the collation label of the database, the character setused for communication over this connection, and the display translationsetting.

Page 67: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

55

C H A P T E R 5

Upgrading Version 5 Applications

The client/server communication protocol changed between SQL Anywhereversions 5 and Adaptive Server Anywhere version 6. This chapter providesupgrade instructions for those users upgrading from Version 5 to theAdaptive Server Anywhere 7.0 release.

This chapter describes upgrade procedures for users of SQL AnywhereVersions 5.0 and 5.5, and users of Watcom SQL 4.0.

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

About this chapter

Contents

Page 68: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Understanding upgrades

56

Understanding upgradesA database application and DBMS consists of several components. If yourorganization has a large SQL Anywhere installation, you may have manyclient machines, possibly running several applications, connected to morethan one server.

When upgrading your system, you need to decide which components toupgrade, and in which order. This chapter guides you in making thosechoices and carrying out the upgrade.

SQL Anywhere Version 5In this chapter, SQL Anywhere Version 5 refers to both versions 5.0 and5.5 of SQL Anywhere.

$ In order to upgrade existing applications to Adaptive Server AnywhereVersion 7.0, it is helpful to understand how Version 6 and later connectionswork. For information, see "Connecting to a Database" on page 31 of thebook ASA User’s Guide.

The components in your system

If you are currently running SQL Anywhere Version 5, you will have someor all of the following components in your system:

♦ Application Your application, aside from the SQL Anywherecomponents.

♦ Connection parameters SQL Anywhere Version 5.0 connectionparameters. These may be assembled from an ODBC data source, or insome other way.

♦ Driver manager The ODBC driver manager, for ODBC applications.

♦ ODBC driver The SQL Anywhere Version 5 ODBC driver, for ODBCapplications. For network applications, the ODBC driver is on the clientmachine.

♦ Interface library The SQL Anywhere Version 5 interface library isused by ODBC and Embedded SQL applications. For networkapplications, the interface library is on the client machine.

Page 69: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

57

♦ SQL Anywhere client The dbclient.exe executable and its commandline, for network applications. The command line may specify the servername, and a set of network communications parameters. It may bestored in a batch file or an ODBC data source Start Line parameter. Fornetwork applications, the SQL Anywhere client is on the client machine.

♦ The database server The SQL Anywhere Version 5 database server.For network applications, this may be on a separate machine from theclient components.

♦ The database A SQL Anywhere Version 5 database. This is on thesame machine as the database server.

Database upgrades not requiredYou do not need to upgrade your database in order to use theVersion 6 or Version 7.0 database server with an existing application.

Major upgrading issues

The major issues in upgrading arise from the change in client/servercommunication protocol. This change means that the Version 5 interfacelibrary is not able to communicate with a Version 7.0 database server.

To help with this issue, Adaptive Server Anywhere Version 7.0 includes acompatibility library. This DLL allows communications to both Version 5and Version 7.0 database servers.

When to upgrade your database

There is no need to upgrade the database itself when you start using Version7.0. You need to upgrade the database only if you wish to take advantage ofVersion 7.0 features.

$ For more information on upgrading databases, see "Upgrade issues" onpage 19 on page 15.

Running more than one version of the software

The Adaptive Server Anywhere software is designed so that both separateversions can be run if you install them in separate directories. This is thedefault behavior of the Adaptive Server Anywhere installation program.

Page 70: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Review of SQL Anywhere Version 5 architecture

58

Review of SQL Anywhere Version 5 architectureThis section reviews the architecture for SQL Anywhere Version 5applications connecting to a SQL Anywhere Version 5 database.

This information helps you to understand the changes needed whenupgrading to Version 7.0. If you are familiar with SQL Anywhere Version 5architecture, you do not need to read this section.

Standalone components for Version 5 (Embedded SQL)

If you are using SQL Anywhere Version 5 as a personal server, with anEmbedded SQL client application, you are using the following componentson your machine:

♦ A SQL Anywhere Version 5 database.

♦ The SQL Anywhere Version 5 database engine (personal databaseserver).

♦ The SQL Anywhere Version 5 interface library.

♦ A SQL Anywhere Version 5.0 connection string.

The following figure illustrates how these pieces fit together.

5

SQL Anywhereinterface library(DBL50?.DLL)

Clientapplication

Connectionstring

Embedded SQLstandalone architecture

Here, the question mark in dbl50?.dll represents a single character indicatingthe operating system. The interface library is named dlb50t.dll on Windows95 and Windows NT, dbl50w.dll on Windows 3.x, and so on.

Embedded SQL client applications make calls to the interface library. Theinterface library is referenced by name, so that the name dbl50?.dll is a partof the client application.

Page 71: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

59

Standalone components for Version 5 (ODBC)

If you are using SQL Anywhere Version 5 as a personal server, with anODBC client application, you are using the following components on yourmachine:

♦ A SQL Anywhere Version 5 database.

♦ The SQL Anywhere Version 5 database engine.

♦ The SQL Anywhere Version 5 interface library.

♦ The SQL Anywhere Version 5 ODBC driver.

♦ The ODBC driver manager.

♦ A SQL Anywhere Version 5.0 connection description. This may be anODBC data source, or a connection string from an application.

The following figure illustrates how these pieces fit together. The clientapplication passes a data source name to the ODBC driver manager. TheODBC driver manager looks up the appropriate driver in ODBCINST.INI.The driver looks up the connection information in ODBC.INI and, via theinterface library, connects to the SQL Anywhere Version 5 database engine.

5

SQL Anywhereinterface library(DBL50?.DLL)

Clientapplication

Data source name

ODBCstandalone architecture

ODBC drivermanager

SQL AnywhereODBC driver

ODBCINST.INI

ODBC.INI

Page 72: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Review of SQL Anywhere Version 5 architecture

60

Client/server components for Version 5

If you are using SQL Anywhere as a network server, you have the followingcomponents on your server machine:

♦ A SQL Anywhere Version 5 database

♦ The SQL Anywhere Version 5 database server

You have the following components on your client machine:

♦ The SQL Anywhere Version 5 Client executable

♦ The SQL Anywhere Version 5 interface library.

♦ The SQL Anywhere ODBC driver, if your application uses ODBC.

♦ A SQL Anywhere Version 5.0 connection description. This may be anODBC data source, or a connection string from an application.

The data source may contain connection information in the start option,corresponding to a SQL Anywhere Client command line. You may alsohave connection strings in your application, and batch files that start aclient with particular command-line parameters.

The architecture of a Version 5 Embedded SQL client/server connection isillustrated in the figure. For ODBC applications the ODBC driver managerand ODBC driver stand between the application and the interface library.

SQLAnywhereinterface

library

dbclient.exe

EmbeddedSQL

Client/Server

5

Page 73: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

61

Upgrading Embedded SQL applicationsYou can upgrade a SQL Anywhere Version 5 standalone application to usethe Adaptive Server Anywhere Version 7.0 database server by upgrading thedatabase server and the interface library. You do not need to upgrade thedatabase or the client application itself.

The upgrade procedure uses the compatibility library. The compatibilitylibrary is a dynamic library (a DLL on PCs, shared library on UNIX) thatenables Embedded SQL applications to work with both Version 5 andVersion 7.0 database servers.

$ For a description of the compatibility library, see "Using thecompatibility library" on page 71.

StartLine connection parameterIf your application connection string uses a StartLine parameter thatexplicitly provides a dbclient.exe or dbeng50.exe command line, and thisis hard coded into your application, there are additional upgradeconsiderations.

For information on upgrading applications that use StartLine connectionparameters, see "Start parameters and the compatibility library" onpage 75.

The following figure illustrates the changes you need to make in your setupin order to upgrade:

5

Version 5interface

library(dbl50?.dll)

7

Version 7interface

library(dblib7.dll)

Upgrade Upgrade

Version 5 setup

Version 7 setup

Compatibilitylibrary

(dbl50?.dll)

$ For a description of the compatibility library, see "Using thecompatibility library" on page 71.

Componentsupgraded

Page 74: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrading Embedded SQL applications

62

Upgrade procedures for Embedded SQL applications

This section provides step-by-step procedures for different kinds ofEmbedded SQL applications:

♦ Applications using an embedded database are standalone applicationsusing the personal database server (dbeng50.exe for Version 5,dbeng7.exe for Version 7.0).

♦ Client/server applications connect across a network to the networkdatabase server. In Version 5, these applications use the dbclient.exeexecutable.

v To upgrade Embedded SQL applications that use an embeddeddatabase:

1 Install the Version 7.0 software The Version 7.0 software containscomponents that enable Version 5 applications to continue working. Youcan either install into a separate directory or over the top of yourVersion 5 software.

The installation places the Version 7.0 executable directory ahead of theVersion 5 executable directory in your system path.

2 Ensure that your application is using the compatibility DLL Ifnecessary, copy the compatibility library dbl50?.dll from your AdaptiveServer Anywhere executable directory to a place where your applicationwill locate it.

For example, you could copy the compatibility library to the samedirectory as the module of your application that loads it. The filedbl50?o.dll is installed into your Adaptive Server Anywhere executabledirectory. This directory must be in your path as this library is requiredby the compatibility library.

At this stage, your Version 5 application should continue to work asbefore. However, it will be connecting to your database through thecompatibility library rather than directly through the Version 5 interfacelibrary.

$ If you have any problems at this stage, you need to check how yourapplication locates the interface library. For information, see "Filelocations and the compatibility library" on page 74.

3 Create a new connection description If your application obtains itsconnection parameters from configuration files, batch files, or thesystem registry, you should prepare a new description that uses theVersion 7.0 database server. For example, Sybase Central storesconnection descriptions in the system registry.

Page 75: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

63

♦ If you store a connection string that uses the DBF parameter to startthe default database server, then the Version 7.0 database server isstarted automatically by the compatibility library, instead of theVersion 5 database server. In this case, no new connectiondescription is needed.

♦ If you store a connection string that uses a Start Line parameterspecifying dbeng50.exe, you must replace this with one specifyingdbeng7.exe. If your application contains a hard-coded connectionstring, 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 abatch file or using a Windows NT service, you must reconfigurethis so that the Version 7.0 database server is started instead.

4 Use the new connection description With this step, you are using allVersion 7.0 software and have completed your upgrade. The databaseitself does not need to be upgraded to work with existing applications.

v To upgrade Embedded SQL client/server applications:

1 Prepare for the upgrade This step must be carried out at each clientmachine. You prepare for the upgrade by installing the Version 7.0software.

The installation places the Version 7.0 executable directory ahead of theVersion 5 executable directory in your system path.

2 Ensure that your application is using the compatibility DLL Thisstep must be carried out at each client machine. If necessary, copy thecompatibility library dbl50?.dll from your Adaptive Server Anywhereexecutable directory to a place where your application will locate it.

For example, you could copy the compatibility library to the samedirectory as the module of your application that loads it. The filedbl50?o.dll is installed into your Adaptive Server Anywhere executabledirectory. This directory must be in your path as this library is requiredby the compatibility library.

At this stage, your Version 5 application should continue to work asbefore. However, it will be connecting to your database through thecompatibility library rather than directly through the Version 5 interfacelibrary.

$ If you have any problems at this stage, you need to check how yourapplication locates the interface library. For information, see "Filelocations and the compatibility library" on page 74.

Page 76: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrading Embedded SQL applications

64

3 Create a new connection description This step must be carried outat each client machine. If your application obtains its connectionparameters from configuration files, batch files, or the system registry,you should prepare a new description that uses the Version 7.0 databaseserver. This description is for use when the server is upgraded.

If you store a connection string that uses a StartLine connectionparameter specifying dbclient.exe, you must replace this with a new one.The new connection description should contain all the dbclientinformation as a set of parameters. 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.

$ For more information on creating connection descriptions thatcapture the dbclient command-line information, see "Capturing dbclientcommand-line information" on page 77.

4 Upgrade the database server This step must be carried out at theserver machine.

♦ As with any software upgrade, back up your database beforeupgrading.

♦ Install Adaptive Server Anywhere on the server machine.

♦ Start the Version 7.0 database server on the database.

5 Use the new connection description This step must be carried out ateach client machine. You need to use the new connection description toconnect to the Version 7.0 server. With this step, you are using allVersion 7.0 software and have completed your upgrade. The databaseitself does not need to be upgraded to work with existing applications.

Using the version 5 utilities with Adaptive Server Anywhere 7.0

For the Version 5 database utilities, connection strings are suppliedinteractively. The Version 5 database utilities such as ISQL are EmbeddedSQL applications that search for the interface library in the following order:

1 The current directory

2 The Version 5 executable directory

3 The system path

For these applications, even though the compatibility library is ahead of theVersion 5 interface library in the system path, the Version 5 compatibilitylibrary is located.

Page 77: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

65

v To use Version 5 utilities with Adaptive Server Anywhere 7.0:

1 Make a backup copy of your interface library file.

2 Copy the compatibility library from your Version 7.0 executabledirectory to your Version 5 directory. For example, on Windows 95 andWindows NT, copy the file dbl50t.dll from the win32 subdirectory ofyour Version 7.0 installation to the win32 subdirectory of your Version 5installation.

3 You can now run your Version 5 utilities against both Version 5 andVersion 7.0 database servers.

Page 78: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrading ODBC applications

66

Upgrading ODBC applicationsYou can upgrade Version 5 ODBC applications in the following ways:

♦ Replace the Version 5 ODBC data source with a Version 7.0 ODBCdata source. This approach is a complete upgrade, and is described inthis section.

♦ Use the compatibility library to connect to a Version 7.0 database server.If you choose this route, your application continues to use the Version 5ODBC driver, so this is not a complete upgrade. The procedure forupgrading in this way is the same as for Embedded SQL applications.

$ For information about upgrading in this manner, see "UpgradingEmbedded SQL applications" on page 61.

StartLine parameterIf your ODBC data source contains a start line specifying theVersion 5 standalone engine (dbeng50.exe) or the SQL Anywhereclient (dbclient.exe), you cannot upgrade using the compatibilitylibrary.

The following figure illustrates the changes you must make when upgradingan ODBC standalone application.

5

Version 5ODBCData

Source

ODBCAdministrator

Version 5ODBC driver

7

Version 7ODBCData

Source

ODBCAdministrator

Version 7ODBC driver

Upgrade Upgrade Upgrade

Version 5

Version 7

The ODBC data source specifies which ODBC driver to use. When anODBC data source is created as an Adaptive Server Anywhere Version 7.0data source, it uses the Version 7.0 ODBC driver.

Data source must be Version 6ODBC applications require a Version 6 ODBC data source to work with aVersion 7.0 ODBC driver.

Componentsupgraded

Data sources

Page 79: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

67

Upgrade procedures for ODBC applications

This section provides step-by-step procedures for different kinds of ODBCapplications:

♦ Applications using an embedded database are standalone applicationsusing the personal database server (dbeng50.exe for Version 5,dbeng7.exe for Version 7.0).

♦ Client/server applications connect across a network to the networkdatabase server. In Version 5, these applications use the dbclient.exeexecutable.

Some applications allow you to change the ODBC data source name you use.Other applications use a fixed data source name. You can upgrade either kindof application.

v To upgrade ODBC applications that use an embedded database:

1 Install the Version 7.0 software The Version 7.0 software containscomponents that enable Version 5 ODBC applications to continueworking. You can either install into a separate directory or over the topof your Version 5 software.

Your application should be unaffected by installation of the Version 7.0software.

2 Create a Version 7.0 ODBC data source The changes you makedepend on the connection parameters you use in the data source.

♦ If you start the default database server using the DBF parameter,you can use the same connection parameters in your new datasource as your old one.

♦ If you store a connection string that uses a Start Line parameterspecifying dbeng50.exe, you must replace this with one specifyingdbeng7.exe.

$ 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 abatch file or using a Windows NT service, you must reconfigurethis so that the Version 7.0 database server is started instead.

$ For information on creating Version 7.0 data sources, see"Working with ODBC data sources" on page 47 of the book ASA User’sGuide.

Page 80: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrading ODBC applications

68

3 Use the new data source With this step, you are using all Version 7.0software and have completed your upgrade. The database itself does notneed 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 sourceof the same name. It is recommended that you rename, rather than delete,your Version 5 data source.

v To upgrade ODBC client/server applications:

1 Prepare for the upgrade This step must be carried out at each clientmachine. You prepare for the upgrade by installing the Version 7.0software.

Your application should be unaffected by installation of the Version 7.0software.

2 Create a Version 7.0 ODBC data source This step must be carriedout at each client machine. The changes you make depend on theconnection parameters you use in the data source.

♦ If you start the default database server using the DBF parameter,you can use the same connection parameters in your new datasource as your old one.

♦ If you store a connection string that uses a StartLine connectionparameter specifying dbclient.exe, you must replace this with a newone. The new connection description should contain all the dbclientinformation as a set of parameters. If your application contains ahard-coded connection string, you need to take extra steps at thispoint.

$ For more information on upgrading StartLine parameters, see"Start parameters and the compatibility library" on page 75.

$ For more information on creating connection descriptions thatcapture the dbclient command-line information, see "Capturingdbclient command-line information" on page 77.

♦ If the database server is started in some other way, such as by abatch file or using a Windows NT service, you must reconfigurethis so that the Version 7.0 database server is started instead.

$ For information on creating Version 7.0 data sources, see"Working with ODBC data sources" on page 47 of the book ASA User’sGuide.

3 Upgrade the database server This step must be carried out at theserver machine.

Page 81: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

69

♦ As with any software upgrade, back up your database beforeupgrading.

♦ Install Adaptive Server Anywhere on the server machine.

♦ Start the Version 7.0 database server on the database.

4 Use the new data source This step must be carried out at each clientmachine. You need to use the new connection description to connect tothe Version 7.0 server. With this step, you are using all Version 7.0software and have completed your upgrade. The database itself does notneed to be upgraded to work with existing applications.

Upgrade notes for PowerBuilder and InfoMaker users

Users of Sybase PowerBuilder and InfoMaker should make some changes inorder to obtain full functionality with Adaptive Server Anywhere Version7.0.

PowerBuilder and InfoMaker use a file named pbodb60.ini to hold ODBCdata source information. The 60 in the file name may be different, dependingon the version you have. For each ODBC driver it provides such things asDDL syntax, default DBParm options, valid function names and specialdatatypes.

If your pbodb60.ini file does not have a Adaptive Server Anywhere section,PowerBuilder and InfoMaker default to a core syntax. This limits theoperations you can carry out using these tools. For example you cannotcreate, alter, or drop primary and foreign keys.

To obtain complete functionality with PowerBuilder and InfoMaker, youneed to upgrade your pbodb60.ini file.

v To upgrade your pbodb60.ini file:

1 Make a backup copy of your existing pbodb60.ini file.

2 Add an Adaptive Server Anywhere section to the working copy of thefile containing the same information as the existing SybaseSQL Anywhere section:

[Adaptive Server Anywhere]PBSyntax=’WATCOM50_SYNTAX’PBDateTime=’STANDARD_DATETIME’PBFunctions=’WATCOM_FUNCTIONS’PBDefaultValues=’autoincrement,current date,currenttime,current timestamp,timestamp,null,user’PBDefaultCreate=’YES’PBDefaultAlter=’YES’

The pbodb60.inifile

Upgrading yourpbodb60.ini file

Page 82: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrading ODBC applications

70

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 RowsExist (RESTRICT),Delete any Dependent Rows(CASCADE),Set Dependent Columns to NULL (SET NULL)’TableListType=’GLOBAL TEMPORARY’

Page 83: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

71

Using the compatibility libraryThe compatibility library is a dynamic library (a DLL on PCs, sharedlibrary on UNIX) that enables Embedded SQL applications to work withboth Version 5 and Version 7.0 database servers. This section describes howthe compatibility library works.

Who needs to read this section?You should read this section if you are upgrading SQL AnywhereVersion 5 to Adaptive Server Anywhere Version 7.0, and have existingEmbedded SQL applications that you need to work with the Version 7.0server.

The Version 5 Embedded SQL interface library

All client machines running SQL Anywhere Version 5 applications, whetherconnecting over a network or to a personal server, have a SQL AnywhereVersion 5 interface library.

For Windows 95 and Windows NT, this library is a DLL named dbl50t.dll.

How Version 5 client applications locate the interface library

Version 5 client applications locate the interface library in one of thefollowing ways:

♦ ODBC applications ODBC applications connect to a SQL Anywheredatabase using the SQL Anywhere ODBC driver. The SQL AnywhereVersion 5 ODBC driver calls functions in the Version 5 Embedded SQLinterface library.

♦ Embedded SQL applications Embedded SQL applications forWindows operating systems call into the interface library. In these calls,the interface library is referenced by name—dbl50t.dll for Windows 95and NT.

The SQL Anywhere Version 5 ODBC driver is an Embedded SQLapplication.

Page 84: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Using the compatibility library

72

Using the compatibility library

The compatibility library is optionally installed as part of the Version 7.0client software. It provides support for two interface libraries at the sametime. You should check your installation to confirm that it is installed.

The setup program should ensure that your application calls the compatibilitylibrary instead of the Version 5 interface library.

The setup program carries out the following steps to ensure that applicationscall the interface library.

♦ The compatibility library has the same name as the SQL AnywhereVersion 5 interface library. For example, on Windows NT, thecompatibility library is named dbl50t.dll.

♦ The compatibility library is installed into the same directory as otherVersion 7.0 software.

♦ The Version 7.0 installation directory is placed ahead of the Version 5directory in the system path. This ensures that applications locate thecompatibility library ahead of the Version 5 interface library.

♦ A Version 5 interface library is installed into the same directory as thecompatibility library, but with the name dbl50to.dll. When thecompatibility library is accessing Version 5 servers, it calls this interfacelibrary.

♦ The Version 7.0 interface library is installed into the same directory asthe compatibility library. It has the name dblib7.dll on Windows NT.When the compatibility library is accessing Version 7.0 servers, it callsthis interface library.

If you have problems using the compatibility library, you should check theorder of the directories in your path, and ensure that the Version 7.0 locationis ahead of the Version 5 location in the path.

How the compatibility library works

Using the supplied connection string, the compatibility library attempts toconnect to an Adaptive Server Anywhere database using the Adaptive ServerAnywhere Version 7.0 interface library. If this attempt fails, it attempts toconnect to a SQL Anywhere database using the SQL Anywhere Version 5library.

The following figure illustrates how the compatibility library enablescommunications to both a SQL Anywhere Version 5 and an Adaptive ServerAnywhere Version 7.0 database server. The number in the lower right handcorner of the boxes indicates the version of the software component.

Page 85: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

73

5

SQL Anywhereinterface library

5

Adaptive ServerAnywhere interface

library 7

7

Compatibilitylibrary

5

The following figure illustrates the algorithm used by the compatibilitylibrary to connect to a server:

Page 86: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Using the compatibility library

74

Can engine orserver be located

using V7?

Is ENGspecified?

Yes

Yes

Can engine orserver be located

using V5?

Connect

Yes

No

No

Is there a defaultlocal engine?

Connect

Yes

Can a V7 enginebe started using

START?

No

No

Can a V5 enginebe started using

START?

No

Yes

Yes

No

Fail

File locations and the compatibility library

The compatibility library and the Version 5 interface library have the samefile name (dbl50.dll). For your application to use the compatibility library, itmust locate it ahead of the Version 5 interface library when it searches forDLLs.

To ensure that your application locates the compatibility library ahead of theVersion 5 interface library you must understand how your applicationsearches for DLLs.

The Version 7.0 installation program places the Version 7.0 executabledirectory ahead of the Version 5 directory in the system path, so anyapplication that uses the path to searching for dbl50.dll will find thecompatibility library ahead of the Version 5 interface library. If yourapplication searches in a different manner, you must ensure that thecompatibility library is located.

Searching for DLLs

Page 87: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

75

The Version 5 ODBC driver is in the same directory as the Version 5interface library, and so locates this library instead of the Version 7.0 library.To enable Version 5 ODBC applications to connect to Version 7.0 databaseservers, you can either rename the Version 5 interface library, or copy theVersion 7.0 compatibility library along with dbl50to.dll into your Version 5directory.

You can test to see which library is located in the following ways:

♦ Attempt to connect to a Version 7.0 database server. You cannot connectusing the Version 5 interface library.

♦ Specify a database file parameter (DBF) and no start line in yourconnection string. If the Version 5 interface library is located, theSQL Anywhere Version 5 standalone database engine is started. If thecompatibility library is located, the Version 7.0 personal database serveris started.

Start parameters and the compatibility library

Applications using a connection string that includes a StartLine connectionparameter face some additional issues in upgrading.

The StartLine parameter provides explicit instructions for starting thedatabase engine or the SQL Anywhere Client executable. Sample StartLineparameters are as follows:

♦ Standalone application A sample StartLine parameter for a Version 5standalone application is as follows:

dbeng50.exe -c 8M

♦ Network client application A sample StartLine parameter for aVersion 5 network client application is as follows:

dbclient.exe -x tcpip

In Version 6, the dbeng50.exe executable is replaced by the personaldatabase server dbeng7.exe. The dbclient.exe executable is no longerrequired in Version 7.0.

v To upgrade StartLine parameters:

♦ The procedure depends on where your connection parameters are stored.

♦ If your connection parameters are stored outside the applicationitself, then you need to alter the connection parameters to use theappropriate dbeng7.exe executable name instead of dbeng50.exe.

Testing to seewhich library islocated

Page 88: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Using the compatibility library

76

All the information on the dbclient command line can be rephrasedin terms of other connection parameters. For information, see"Connection and Communication Parameters" on page 43 of thebook ASA Reference.

♦ If your connection parameters are hard-wired into your application,you must relink your application with a new connection string.

There are many possible configurations of client command lines andconnection parameters. Be sure you test any solution thoroughlybefore deploying.

Page 89: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

77

Capturing dbclient command-line informationVersion 5 client applications that connect to a database server do so via theSQL Anywhere Client, an executable named dbclient.exe. The clientexecutable command line contains information needed to locate a server,including the following:

♦ Default server name The server name on the client command line isthe default server name. When a client executable is running, theapplication does not need to supply a server name in order to connect tothe default server.

♦ Network communications parameters A listing of network protocolsto use together with a set of communications parameters specifies wherethe client executable is to look as it attempts to locate a server.

♦ Client/Server communication tuning A set of parameters allows thepacket size, buffer size, and so on to be tuned for optimum performance.

In Version 7.0, this information is held in an ODBC data source along withother connection information. As there is no longer a client executable, thereis no longer a client command line. In Version 7.0, Embedded SQLapplications can use ODBC data sources as a source of connectionparameters.

Only one Version 5 client executable can be run at a time, and it may be usedby more than one application and handle connections to more than oneserver. The command-line information is therefore global to the machine.

How to capture client command-line information

During upgrade to Version 7.0, you must ensure that Version 5 dbclientcommand-line information is captured in such a way that the Version 7.0ODBC or Embedded SQL applications can use it. You can do this in one ofthe following ways:

♦ Place the information in an ODBC data source If the informationcan be placed in a data source, you can use it with Version 7.0 ODBC orEmbedded SQL applications.

♦ Use the SQLCONNECT environment variable The SQLCONNECTenvironment variable contains a connection string. It is searched early inthe process of establishing which connection parameters to use. Youmay be able to use SQLCONNECT settings to override connectionparameters.

Client commandline scope

Page 90: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Capturing dbclient command-line information

78

The way to capture client command-line information depends on where theinformation is located.

Your existing command line information may be held in one of the followingplaces.

♦ ODBC data source The ODBC data source contains a STARTparameter that can hold a client executable command-line.

♦ As a connection string Your application may obtain clientinformation (for example from an initialization file), and supply it in aconnection string as the START parameter.

♦ A batch file You may have a batch file that includes a clientexecutable command line as part of your startup process.

♦ Under an icon You may have a client executable command line underan icon on your desktop.

♦ From an ODBC data source The ODBC data source upgrade capturesthe information in an ODBC data source START parameter.

♦ From a batch file or under an icon You can move the dbclient.exeparameters into your CommLinks connection parameter. The dbcli7.exeexecutable is provided for compatibility reasons only, and makes thecommand-line parameters available to Version 6 interface libraries.

♦ Hard-wired connection strings Only if you have a hard-wiredconnection string in your application (that is, one that cannot be edited),you must alter the source of the application and recompile.

Where command-line information islocated

How to capture theinformation

Page 91: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

79

Upgrading databasesIf you wish to use the new features of Adaptive Server Anywhere Version7.0, you need to upgrade your database to Adaptive Server Anywhere 6. Theformat of the database files is the same as in SQL Anywhere Version 5, butthe system tables and available database options have changed.

CautionEnsure that you back up your database before upgrading.

You can upgrade your database from any of the following versions of thesoftware to Adaptive Server Anywhere Version 6 format:

♦ SQL Anywhere Version 5 Including versions 5.0 and 5.5, all patchlevels.

♦ Watcom SQL Version 4 All patch levels.

♦ Watcom SQL Version 3.2 Only patch level e and above.

The upgrade utility carries out the following tasks:

♦ Adds new system tables For example, the SYSJAR andSYSJAVACLASS system tables are new in Version 6, and must bepresent for any of the Java capabilities of Adaptive Server Anywhere tobe available.

♦ Adds new columns to existing tables For example, with theintroduction 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 tuningfor overall database behavior or for individual user behavior. The list ofavailable options is kept in the system tables, and needs to be upgradedfor the options to become available.

$ For instructions on upgrading databases, see "Upgrade issues" onpage 19 on page 15.

Supported versions

What the upgradeutility does

Page 92: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrading SQL Remote installations

80

Upgrading SQL Remote installationsSQL Remote installations include a consolidated database and many remotedatabases, together with a Message Agent at each site.

At each site, the Message Agent handles the sending and receiving ofmessages. The messages take the form of SQL statements, and the databaseserver handles the actual execution of those SQL statements.

The upgrade requirements for SQL Remote are as follows:

♦ No need to upgrade databases There is no need to upgradedatabases for Version 7.0. However, if you do wish to upgrade adatabase, you can do so using the Upgrade utility at any of the sites.There is no need for all databases to be upgraded at the same time.

♦ Software upgrades can be one site at a time Version 5 MessageAgents can exchange messages with Version 7.0 Message Agents aslong as the COMPRESSION database option is set to a value of -1(minus one). There is no need to upgrade software throughout theinstallation simultaneously.

♦ Message Agent and server can be upgraded separately TheMessage Agent is an Embedded SQL application. Therefore, thedatabase server can be upgraded before the Message Agent as long asthe compatibility library is used. It is, however, recommended that youupgrade your Message Agent at the same time as the database server forperformance reasons.

The Message Agent cannot be upgraded before the database server, as aVersion 6 client application cannot work with a Version 5 server.

♦ Do not unload and reload There is no need to unload and reload adatabase when moving from Version 5 to Version 6.

Replication is based on the transaction log, and when a database isunloaded and reloaded, the old transaction log is no longer available. Forthis reason, good backup practices are especially important whenparticipating in replication.

One approach to upgrading is as follows:

1 Upgrade the consolidated database server and Message Agent. Set theCOMPRESSION database option to -1 so that all messages arecompatible with the Version 5 software at remote sites.

2 Over time, upgrade remote database servers and Message Agents. Youcan set the COMPRESSION database option to a value other than -1 totake advantage of compression and encoding on messages being sent tothe consolidated database server.

Example

Page 93: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 5 Upgrading Version 5 Applications

81

3 When all remote database servers and Message Agents are upgraded, setthe COMPRESSION database option a the consolidated site to a valueother than -1.

Page 94: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Upgrading SQL Remote installations

82

Page 95: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

83

P A R T T W O

Database Concepts

This part introduces Adaptive Server Anywhere and describes the basicconcepts you need to understand in order to work with relational databases

and database applications.

Page 96: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

84

Page 97: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

85

C H A P T E R 6

Databases and Applications

This chapter introduces basic database concepts. It describes what arelational database is, and what it is used for. It describes how databases anddatabase applications work together.

Other parts of the documentation set assume that you are familiar with theconcepts introduced in this chapter.

Topic Page

Relational database concepts 86

SQL and database computing 91

The pieces of a database system 94

How the pieces fit together 97

About this chapter

Contents

Page 98: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Relational database concepts

86

Relational database conceptsA relational database management system (RDBMS) is a system forstoring and retrieving data, in which the data is organized in tables. Arelational database consists of a collection of tables that store interrelateddata.

This section introduces some of the terms and concepts that are important intalking about relational databases.

Many of the concepts described here are illustrated in tutorial form in"Designing and Building Your Database" on page 121.

Database tables

In a relational database, all data is held in tables, which are made up of rowsand columns.

Each table has one or more columns, and each column is assigned a specificdata 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:

emp_ID emp_lname emp_fname emp_phone

10057 Huong Zhang 1096

10693 Donaldson Anne 7821

The tables of a relational database have some important characteristics:

♦ There is no significance to the order of the columns or rows.

♦ Each row contains one and only one value for each column.

Characteristics ofrelational tables

Page 99: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 6 Databases and Applications

87

♦ All values for a given column have the same data type.

The following table lists some of the formal and informal relational databaseterms describing tables and their contents, together with their equivalent innonrelational databases. This manual uses the informal terms.

Formal relationalterm

Informal relationalterm

Nonrelational term

Relation Table File

Attribute Column Field

Tuple Row Record

When you are designing your database, you should make sure that each tablein 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 eliminatesredundancy and the possible inconsistencies caused by redundancy. Forexample, both the sales and accounts payable departments might enter andlook up information about customers. In a relational database, theinformation about customers is entered only once, in a table that bothdepartments can access.

$ For more information about database design, see "Designing YourDatabase" on page 321 of the book ASA User’s Guide.

$ For instructions on how to create a table, see "Lesson 3: Design andcreate a table" on page 131.

Relations between tables

A relational database is a set of related tables. You use primary and foreignkeys to describe relationships between the information in different tables.

The tables in a relational database are, as the name suggests, related.Primary keys identify each row in a table uniquely, and foreign keys definethe relationships between rows in different tables.

If you make proper use of primary keys and foreign keys, you can userelational databases to hold information in an efficient manner, withoutredundancy.

What do you keepin each table?

Page 100: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Relational database concepts

88

Tables have a primary key

Each table in a relational database should have a primary key. The primarykey is a column, or set of columns, that uniquely identifies each row. No tworows in a table may have the same value of a primary key.

In the sample database, the employee table stores information aboutemployees. It has a primary key column named emp_id, which holds aunique ID number assigned to each employee. A single column holding anID number is a common way to assign primary keys, and has advantagesover names and other identifiers which, while commonly different, may notbe unique.

A more complex primary key can be seen in the sales_order_items table ofthe sample database, which has the following columns:

♦ id An order number, identifying the order the item is part of.

♦ line_id A line number, identifying each item on any order.

♦ prod_id A product ID, identifying the product being ordered.

♦ quantity A quantity, showing how many items were ordered.

♦ ship_date A ship date, showing when the order was shipped.

A particular sales order item is identified by the order it is part of, and by aline number on the order. These two numbers are stored in the id and line_idcolumns. Items may share a single id value (corresponding to an order formore than one item) or they may share a line_id number (all first items ondifferent orders have a line_id of 1). No two items share both values, and sothe primary key is made up of the two columns.

$ For a tutorial example, see "Lesson 4: Identify and create primary keys"on page 132.

Tables are related by foreign keys

The information in one table is related to that in other tables by foreign keys.

The sample database has one table holding employee information and onetable holding department information. The department table has thefollowing columns:

♦ dept_id An ID number for the department. This is the primary key forthe table.

♦ dept_name The name of the department.

♦ dept_head_id The employee ID for the department manager.

Examples

Example

Page 101: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 6 Databases and Applications

89

To find the name of a particular employee’s department, there is no need toput the name of the employee’s department into the employee table. Instead,the employee table contains a column holding a number that matches one ofthe dept_id values in the department column.

This employee column is called a foreign key to the department table. Aforeign key references a particular row in the table containing thecorresponding primary key.

In this example, the employee table (which contains the foreign key in therelationship) is called the foreign table or referencing table. Thedepartment table (which contains the referenced primary key) is called theprimary table or the referenced table.

$ For a tutorial example, see "Lesson 5: Design column properties" onpage 134.

Other database objects

A relational database holds more than a set of related tables. Among theother objects that make up a relational database are the following:

♦ Indexes Indexes allow quick lookup of information. Conceptually, anindex in a database is like an index in a book. In a book, the indexrelates each indexed term to the page or pages on which that wordappears. In a database, the index relates each indexed column value tothe physical location at which the row of data containing the indexedvalue is stored.

Indexes are an important design element for high performance. Their useis transparent to the user.

♦ Views Views are computed tables, or virtual tables. They look liketables to client applications, but they do not hold data. Instead, wheneverthey are accessed, the information in them is computed from theunderlying tables.

The tables that actually hold the information are sometimes called basetables to distinguish them from views. A view is defined with a SQLquery on base tables or other views.

♦ Stored procedures and triggers These are routines held in thedatabase itself that act on the information in the database.

You can create and name your own stored procedures to execute specificdatabase queries and to perform other database tasks. Stored procedurescan take parameters. For example, you might create a stored procedurethat returns the names of all customers who have spent more than theamount that you specify as a parameter in the call to the procedure.

Page 102: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Relational database concepts

90

A trigger is a special stored procedure that automatically fires whenevera user updates, deletes, or inserts data, depending on how you define thetrigger. You associate a trigger with a table or columns within a table.Triggers are useful for automatically maintaining business rules in adatabase.

♦ Users and groups Each user of a database has a user ID andpassword. You can set permissions for each user, so that confidentialinformation is kept private and users are prevented from makingunauthorized changes. Users can be assigned to groups in order to makethe administration of permissions easier.

♦ Java objects You can install Java classes into the database. Javaclasses provide a powerful way of building logic into your database, anda special class of user-defined data types for holding information.

Page 103: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 6 Databases and Applications

91

SQL and database computingWhen a client application wants to carry out a database task, such asretrieving information using a query or inserting a new row into a table, itdoes so using Structured Query Language (SQL) statements. SQL,pronounced "sequel", is a relational database language that has beenstandardized by the ANSI and ISO standards bodies.

Depending on how you develop a client application, SQL statements couldbe supplied in function calls from the programming language. Someapplication development tools provide user interfaces for building andgenerating SQL statements.

The programming interface delivers the SQL statement to the databaseserver. The database server receives the statement and executes it, returningthe required information (such as query results) back to the application.

Client/server communication protocols carry information between the clientapplication and the database server, and programming interfaces define howan application sends the information. No matter what interface you use, andwhat network protocol you use, it is SQL statements that are sent to a server,and the results of SQL statements that are returned to the client application.

This SQL statement extracts the last names of all employees from theemployee table in the sample database.

SELECT emp_lnameFROM employee

This SQL statement creates a table called food that lists types of food and theamount in stock in the employee cafeteria:

CREATE TABLE food (food_id integer primary key,food_type char(20)quantity integer

)

$ For an introduction to SQL, see the chapters beginning with "SelectingData from Database Tables" on page 163.

Queries

The "Q" in "SQL" stands for query. You query (or retrieve) data from adatabase with the SELECT statement. The basic query operations in arelational system are projection, restriction, and join. The SELECT statementimplements all of them.

Example

Example

Page 104: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

SQL and database computing

92

A projection is a subset of the columns in a table. A restriction (also calledselection) is a subset of the rows in a table, based on some conditions.

For example, the following SELECT statement retrieves the names andprices of all products that cost more than $15:

SELECT name, unit_priceFROM productWHERE unit_price > 15

This query uses both a projection (SELECT name, unit_price) and arestriction (WHERE unit_price > 15).

$ For more information, see Chapter 12, "Selecting rows from a table" onpage 171.

A join links the rows in two or more tables by comparing the values in keycolumns and returning rows that have matching values. For example, youmight want to select the order item identification numbers and product namesfor all order items that were shipped more than a dozen items:

SELECT sales_order_items.id, product.nameFROM product JOIN sales_order_itemsWHERE sales_order_items.quantity > 12

The product table and the sales_order_items table are joined together basedon the foreign key relationship between them.

$ For more information, see the chapter, "Selecting Data from MultipleTables" on page 181.

Other SQL statements

You can do more with SQL than just query. SQL includes statements thatcreate tables, views, and other database objects. It also includes statementsthat modify tables (the INSERT, UPDATE, and DELETE statements), andcommands that perform many other database tasks discussed in this manual.

The system tables

Every database contains a set of system tables. These are special tables thatthe system uses to manage data and the system. These tables are alsosometimes called the data dictionary or the system catalog.

Projections andrestrictions

Joins

Page 105: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 6 Databases and Applications

93

System tables contain information about the database. You never alter thesystem tables directly in the way that you can alter other tables. The systemtables 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, ormetadata.

Page 106: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

The pieces of a database system

94

The pieces of a database systemThis section describes how database applications and the database serverwork together to manage databases.

Any information system contains the following pieces:

♦ A database Data is stored in a database. In diagrams in thedocumentation, a database is indicated by a cylinder:

An Adaptive Server Anywhere database is a file, usually with anextension of .db. Adaptive Server Anywhere includes a sample databasefor you to work with: this is the file asademo.db in your AdaptiveServer Anywhere installation directory.

UltraLite databases are stored in a device-dependent manner. OnWindows CE, the UltraLite database is a file, but on the PalmComputing Platform it is stored in the Palm database.

$ For instructions on how to create a database, see "Designing andBuilding Your Database" on page 121

♦ A database server The database server manages the database. Noother application addresses the database file directly; they allcommunicate with the database server.

$ For instructions on starting database servers, see "Connecting YourApplication to its Database" on page 139

In diagrams in the documentation, a database server is indicated asfollows:

Adaptive Server Anywhere provides two versions of its database server:the personal database server and the network database server. Inaddition to the features of the personal server, the network serversupports client/server communications across a network. The request-processing engine is identical in the two servers.

Page 107: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 6 Databases and Applications

95

♦ A programming interface Applications communicate with thedatabase server using a programming interface. You can use ODBC,JDBC, OLE DB, Sybase Open Client, or Embedded SQL.

Many application development tools provide their own programmingenvironment that hides the details of the underlying interface. Forexample, if you develop an application using Sybase PowerBuilder younever have to make an ODBC function call. Nevertheless, behind thescenes each of these tools is using one of the programming interfaces.

The programming interface provides a library of function calls forcommunicating with the database. For ODBC and JDBC, the library iscommonly called a driver. The library is typically provided as a sharedlibrary on UNIX operating systems or a dynamic link library (DLL) onPC operating systems. The JDBC interface uses the Sybase jConnectdriver, which is a zip file of compiled Java classes.

In diagrams in the documentation, a programming interface is indicatedas follows:

API

♦ A client application Client applications use one of the programminginterfaces to communicate with the database server.

If you develop an application using a rapid application development(RAD) tool such as Sybase PowerBuilder, you may find that the toolprovides its own methods for communicating with database servers, andhides the details of the language interface. Nevertheless, all applicationsdo use one of the supported interfaces.

In diagrams in the documentation, a client application is indicated by thefollowing:

UltraLite database servers are custom-generated for each UltraLiteapplication, and are part of the application itself. An UltraLiteapplication together with its database server are indicated as follows:

Page 108: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

The pieces of a database system

96

Page 109: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 6 Databases and Applications

97

How the pieces fit togetherDatabase applications can connect to a database server located on the samemachine as the application itself, or on a different machine. In addition, withAdaptive Server Anywhere you can build distributed databases, withphysically-distinct databases on different machines sharing data.

Personal applications and embedded databases

You can use SQL Anywhere to build a complete application and database ona single computer. In the simplest arrangement, this is a standaloneapplication or personal application: it is self-contained, with no connectionto other databases. In this case, the database server, and the database, can bestarted by the client application, and it is common to refer to the database asan embedded database: as far as the end user is concerned, the database is apart of the application.

Standalone applications have the following architecture, with a clientapplication connecting through a programming interface to a database serverrunning on the same machine:

Interface

The Adaptive Server Anywhere personal database server is generally usedfor standalone applications, although you can also use applications on thesame machine as the network server. When a database server is used to runembedded databases, it is sometimes called a database engine.

Page 110: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

How the pieces fit together

98

Client/server applications and multi-user databases

You can use Adaptive Server Anywhere to build an installation with manyapplications running on different machines, connected over a network to asingle database server running on a separate machine. This is a client/serverenvironment, and has the following architecture. The interface library islocated on each client machine.

In this case the database server is the Adaptive Server Anywhere networkdatabase server, which supports network communications. The database isalso called a multi-user database.

No changes are needed to a client application for it to work in a client/serverenvironment, except to identify the server to which it should connect.

Page 111: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

99

C H A P T E R 7

Introduction to Adaptive Server Anywhere

This chapter introduces the Adaptive Server Anywhere relational databasesystem. It describes the uses and features of Adaptive Server Anywhere.

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

About this chapter

Contents

Page 112: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Introduction to Adaptive Server Anywhere

100

Introduction to Adaptive Server AnywhereThe previous chapter, "Databases and Applications" on page 85, introduceddatabases in a general manner. This chapter describes the particularhallmarks of Adaptive Server Anywhere and describes the uses to which itcan be put.

Adaptive Server Anywhere provides a series of tools for storing andmanaging data. You can use these tools to enter data into your database, tochange your database’s structure, and to alter your data.

The Adaptive Server Anywhere relational database management system isthe heart of SQL Anywhere Studio. This section describes the kinds of taskfor which Adaptive Server Anywhere is designed and describes the technicalhallmarks of the product.

Adaptive Server Anywhere is designed for tasks that require a full-featuredSQL database. It is designed to operate in varied environments. It takesadvantage of available memory and CPU resources, providing goodperformance in environments with ample resources. It also operates well inenvironments with more limited physical and database administrationresources. Restricted resource environments include mobile computingenvironments, embedded database use, and workgroup servers.

Page 113: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 7 Introduction to Adaptive Server Anywhere

101

Adaptive Server Anywhere intended usesRoles for which Adaptive Server Anywhere is ideally suited include thefollowing:

♦ An embedded database Many applications require a database"behind the scenes". Personal Information Managers, documentmanagement systems —just about any application that storesinformation. Adaptive Server Anywhere is intended to be the databasefor these applications. The UltraLite deployment option is intended forembedded environments that have very restricted resources.

♦ Mobile computing Laptop and notebook computers are now commonin many workplaces. Adaptive Server Anywhere is intended to be theSQL database for these computers. With SQL Remote replication,Adaptive Server Anywhere extends transaction-based computingthroughout the enterprise. The UltraLite deployment option andMobiLink synchronization technology provide full databasefunctionality on devices with limited resources, such as hand-heldcomputers.

♦ A workgroup server Workgroups ranging in size from a few people toa few hundred people may require a database server that they can share.Adaptive Server Anywhere is a multi-user server that can provide ahigh-performance database for workgroups, well-suited for (but notlimited to) environments where administration and hardware resourcesare limited.

Page 114: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Adaptive Server Anywhere hallmarks

102

Adaptive Server Anywhere hallmarksAdaptive Server Anywhere 7.0 builds on the technological hallmarks of theprevious version of this product:

♦ Full SQL relational database management system Adaptive ServerAnywhere is a transaction-processing relational database managementsystem (RDBMS), with full recovery capabilities, online backup,referential integrity actions, stored procedures, triggers, row-levelconcurrency control, a rich SQL language, and all the features youexpect in a full SQL RDBMS.

♦ Economical hardware requirements Adaptive Server Anywhererequires fewer memory and disk resources than other databasemanagement systems.

♦ Easy to use You can use Adaptive Server Anywhere without theextensive database administration efforts usually associated withrelational database management systems.

♦ Standalone and network use Adaptive Server Anywhere can be usedin a standalone manner, for example as an embedded database in a data-centric application, or as a network server in a multi-user client/server orthree-tier environment. As an embedded database system, it can bestarted automatically by an application when required.

♦ High performance While Adaptive Server Anywhere is designed withsimple administration and modest resource requirements in mind, it is ascalable, high-performance DBMS. Adaptive Server Anywhere can runon multiple CPUs, has an advanced query optimizer, and providesperformance monitoring and tuning tools.

♦ Industry standard interfaces Adaptive Server Anywhere provides anative ODBC 3.5 driver for high performance from ODBC applications,and an OLE DB driver for use from ActiveX Data Object (ADO)programming environments. It comes with Sybase jConnect for JDBC,and supports Embedded SQL and Sybase Open Client interfaces.

♦ A cross-platform solution Adaptive Server Anywhere can be run onmany operating systems, including Windows NT, Windows 95/98,Windows CE, Novell NetWare, Sun Solaris, Hewlett Packard HP-UX,IBM AIX, and Linux.

$ The components available on each platform may differ. Forinformation, see "Availability of components" on page 107.

Page 115: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 7 Introduction to Adaptive Server Anywhere

103

Adaptive Server Anywhere system requirementsAdaptive Server Anywhere requires the following:

♦ Operating system and CPU You must have one of the following inorder to run the Adaptive Server Anywhere database server:

♦ Windows NT Version 3.51 or later, or Windows 2000.

♦ Windows Windows 95 and Windows 98 are supported.

♦ Windows CE Version 2.11 is supported. Handheld PC (HPC),HPC Pro, and Palm-sized PC (PPC) devices using the Hitachi SH3or SH4 processor, the MIPS processor, or the ARM processor isrecommended. The OLE DB driver is available on SH3, MIPS, andARM processors.

♦ Novell NetWare Version 3.2 or later.

♦ UNIX, including Linux For a detailed list of supported UNIXoperating systems, see the SQL Anywhere Studio Read Me First forUNIX.

For PC operating systems, an Intel 486 or higher CPU, or compatibleCPU, is required.

♦ Memory Adaptive Server Anywhere can run with as little as 3 MB ofmemory. If you use Java in the database, Adaptive Server Anywhererequires 8 MB of memory. Your computer must have this much memoryin addition to the requirements for the operating system.

$ For more information on supported operating systems for componentsin SQL Anywhere Studio, see "Supported Platforms" on page 149 of thebook Introducing SQL Anywhere Studio.

Network software requirements

If you are running an Adaptive Server Anywhere network database server,you must have appropriate networking software installed and running.

The Adaptive Server Anywhere network server is available for WindowsNT, Windows 95/98, Windows CE, Novell NetWare, Linux, and UNIXoperating systems.

Adaptive Server Anywhere supports the following network protocols:

♦ TCP/IP

♦ SPX (not UNIX operating systems or Windows CE)

Page 116: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Adaptive Server Anywhere system requirements

104

♦ NetBIOS (not UNIX operating systems or Windows CE)

Page 117: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 7 Introduction to Adaptive Server Anywhere

105

The Adaptive Server Anywhere database serverThere are two versions of the Adaptive Server Anywhere database serverincluded in the product:

♦ The personal database server This server is provided for single-user,same-machine use: for example, as an embedded database server. It isalso useful for development work.

The name of the personal server executable is as follows:

♦ On UNIX operating systems, it is dbeng7.

♦ On Windows 95/98 and Windows NT, it is dbeng7.exe.

♦ The network database server In addition to the features of thepersonal server, the network server supports client/servercommunications across a network. It is provided for multi-user use.

The name of the network server executable is as follows:

♦ On UNIX operating systems, it is dbsrv7.

♦ On Windows 95/98 and Windows NT, it is dbsrv7.exe.

♦ On Novell NetWare, the server is a NetWare Loadable Module(NLM) called dbsrv7.nlm.

The request-processing engine is identical in the two versions of the server.They support exactly the same SQL language, and exactly the same databasefeatures. The personal server does not support communications across anetwork, more than ten concurrent connections, or the use of more than twoCPUs. Applications developed against a personal server work unchangedagainst a network server.

Same SQLfeatures in eachversion

Page 118: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Adaptive Server Anywhere applications

106

Adaptive Server Anywhere applicationsThis section introduces some of the database applications that are suppliedwith Adaptive Server Anywhere in the SQL Anywhere Studio product.These applications help you design, build, and administer your databases.

Sybase Central

Sybase Central provides a graphical user interface for creating andmodifying databases and database objects, for inspecting the structure ofdatabases, 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 toyour database" on page 130.

The Sybase Central window is similar to Windows Explorer. The mainwindow is split into two vertically-aligned panes. The left pane displays ahierarchical view of database objects or containers in a tree-like structure. Acontainer is a database object that can hold other database objects, includingother containers.

The right pane displays the contents of the container that has been selected inthe left pane. For example, to create a database, click the Utilities folder in theleft pane, and then double-click Create Database in the right pane.

Page 119: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 7 Introduction to Adaptive Server Anywhere

107

Interactive SQL

Interactive SQL is an application for typing and sending SQL statements to adatabase. Interactive SQL allows you to query and alter data in your databaseas well as modify the structure of your database.

Everything that can be done in Sybase Central can be done in InteractiveSQL, but administration tasks are easier in Sybase Central. For this reason,this book uses Sybase Central whenever possible, but when a task isimportant, or is simple to accomplish in Interactive SQL, the Interactive SQLinstructions are also included.

$ For information on working with Interactive SQL, see "UsingInteractive SQL" on page 145.

Each Interactive SQL window is divided into three sections: the SQLStatements pane at the top; the Messages pane in the middle; and the Resultspane at the bottom.

♦ The SQL Statements pane This is where you type SQL statements toaccess and modify your data.

♦ The Messages pane This information displays information from thedatabase server, such as how much time was required to process therequest, how many rows were examined in the process, and how manyrows 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 orderedfive or more different types of products, that number appears in the Datawindow.

Command-line utilities

A set of command-line utilities is provided for carrying out administrationtasks such as backing up a database. Command-line utilities are useful forincluding in batch files for repeated use.

$ For more information about administration utilities, see "DatabaseAdministration Utilities" on page 71 of the book ASA Reference.

Availability of components

What components you have installed depends on which operating systemyou are using, what choices you made when installing the software, andwhether you received the Adaptive Server Anywhere product or installedAdaptive Server Anywhere as part of another product.

The InteractiveSQL windows

Page 120: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Adaptive Server Anywhere applications

108

For example, if you have received Adaptive Server Anywhere as part ofanother product, you may not have both versions of the database server.

Not all components are available on all operating systems. For example,there is no personal server for NetWare, only a network server.

The SQL Anywhere program group

This section does not apply to users of UNIX operating systems. InstallingSQL Anywhere Studio under UNIX does not provide a program group.

For Windows operating systems, after the software is installed you will havea SQL Anywhere program group. You can reach the program group byclicking the Start button and choosing Programs ➤Sybase ➤SQL Anywhere7.

The program group contains some or all of the following items. The itemsyou see depend on the choices you made when installing the software.

♦ Interactive SQL Starts the Interactive SQL utility for sending SQLstatements to a database.

♦ Manage Adaptive Server Anywhere Starts Sybase Central.

♦ Network Server Sample Starts the network database server and loadsthe sample database.

♦ ODBC Administrator Starts the ODBC Administrator program forsetting up and editing ODBC data sources.

♦ Personal Server Sample Starts the personal server and loads thesample database.

♦ SQL Anywhere documentation Opens the online documentation forAdaptive Server Anywhere.

♦ Sybase Web Opens a Web page with information about Sybaseproducts.

Program groupitems

Page 121: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

109

C H A P T E R 8

The Architecture of Database Applications

This chapter describes how database applications communicate with theAdaptive Server Anywhere database server, and provides a glimpse into thearchitecture of Adaptive Server Anywhere.

Topic Page

Application programming interfaces 110

Inside Adaptive Server Anywhere 115

About this chapter

Contents

Page 122: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Application programming interfaces

110

Application programming interfacesAn overview of database application architecture was given in Chapter 6,"How the pieces fit together" on page 97. The current section describes thearchitecture in more detail.

Adaptive Server Anywhere supports a wide set of programming interfaces toprovide flexibility in the kinds of applications and application developmentenvironments you can use.

Supported interfaces and protocols

The following diagram displays the supported interfaces, and the interfacelibraries used. In most cases the interface library is the same name as theinterface itself.

ASA

ODBCjConnectEmbedded

SQL

JDBC Embedded SQL ODBC

OLE DB

OLE DB

OpenClient

Open Client

ClientApplication

Driver orinterface library

CommunicationProtocol

Tabular DataStream

CommandSequence

ApplicationProgrammingInterface

DatabaseServer

Database

The applications supplied with SQL Anywhere Studio use several of theseinterfaces:

Page 123: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 8 The Architecture of Database Applications

111

ASA

ISQL

SQL Modeler

JDBC

ODBC

Sybase Central

InfoMaker PowerDynamo

DB Tools

Embedded SQL

Communications protocols

Each interface library communicates with the database server using acommunication protocol. Adaptive Server Anywhere supports twocommunication protocols, Tabular Data Stream (TDS) and CommandSequence. These protocols are internal, and for most purposes it does notmatter which one you are using. Your choice of development environmentwill be governed by your available tools.

The major differences you will see are upon connecting to the database. TheCommand Sequence applications and TDS applications use differentmethods to identify a database and database server, and so connectiondialogs are different.

TDS This protocol is also used by Sybase Adaptive Server Enterprise,Open Client applications and Java applications that use the jConnect JDBCdriver connect using TDS.

Command Sequence This protocol is used by Adaptive ServerAnywhere, Adaptive Server IQ, and is used by Embedded SQL, ODBC, andOLE DB applications.

Page 124: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Application programming interfaces

112

ODBC applications

You can develop ODBC applications using a variety of development toolsand programming languages, as displayed below.

VB PowerBuilder

ODBC

C/C++

Java

JDBC/ODBCBridge

Delphi

For example, of the applications supplied with SQL Anywhere Studio,InfoMaker, SQL Modeler, and PowerDynamo use ODBC to connect to thedatabase.

Embedded SQL applications

You can develop C or C++ applications using the Embedded SQLprogramming interface. The command line database tools are examples ofapplications developed in this manner.

Embedded SQL is also a programming interface for UltraLite applications.

Page 125: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 8 The Architecture of Database Applications

113

C/C++ DB Tools

ESQL

Open Client applications

Open Client is an interface that is also supported by Sybase Adaptive ServerEnterprise. You can develop Open Client applications in C or C++. OtherSybase applications, such as OmniConnect or Replication Server, use OpenClient.

C/C++ OmniConnect

OpenClient

Page 126: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Application programming interfaces

114

JDBC applications

You can develop applications that use JDBC to connect to Adaptive ServerAnywhere using Java. Several of the applications supplied withSQL Anywhere Studio use JDBC: the stored procedure debugger, SybaseCentral, and Interactive SQL.

Debugger

Sybase Central Java

jConnectJDBC

ISQL

Java and JDBC are also important programming languages for developingUltraLite applications.

OLE DB applications

Adaptive Server Anywhere includes an OLE DB driver. You can developapplications using Microsoft’s OLE DB interface directly, or using theActiveX Data Objects (ADO) interface. The ADO interface is included inVisual Basic and other Microsoft programming tools.

Page 127: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 8 The Architecture of Database Applications

115

Inside Adaptive Server AnywhereWhile you never need to deal with the internals of the database server, aglimpse behind the scenes may help you understand the process better.

Inside the database server

The Adaptive Server Anywhere database server has an internal structure thatallows many requests to be handled efficiently.

♦ A communications layer handles the actual exchange of data with clientapplications. This layer receives requests from client applications, andreturns results. The timing of these actions is governed by a negotiationbetween client and server, to make sure that the network traffic is kept toa minimum, but that the data is made available as soon as possible onthe client side.

♦ The parser checks each SQL statement sent to the database server, andtransforms it into an internal form for processing.

♦ If the request is a query, or an update or delete statement, there may bemany different ways of accessing the data, which may take massivelydifferent times. The job of the optimizer is to select from among allthese possibilities the best route to getting the required data quickly.

♦ A Java Virtual Machine is built into the database server, and any Javaoperations sent by client applications, or invoked internally by thedatabase server, are handled by the Java VM.

♦ The efficient access of data is a complex task, and the lowest level of thedatabase server is concerned with reading and writing data from thedisk, caching data in memory to avoid unnecessary disk access, andbalancing the demands of different users.

Page 128: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Inside Adaptive Server Anywhere

116

ASA

Data Access

Communications

Java VMOptimizer

Parser

Inside the database

All the information in an Adaptive Server Anywhere database is stored in asingle database file, which can be copied from one machine to another. It ispossible to make databases of several files, but this is generally only requiredfor very large databases.

In addition to the database file, Adaptive Server Anywhere uses two otherfiles when it is running a database. These are the transaction log and thetemporary file.

♦ The database file Internally, the database file is composed of pages:fixed size areas of disk. The data access layer reads and writes data onepage at a time. Many pages hold the data that is in the database tables,but other pages hold index information, information about thedistribution of data within the database, and so on.

♦ The transaction log The transaction log is a separate file, whichcontains a record of all the operations performed on the database.Normally, it has the same name as the database file, except that it endswith the suffix .log instead of .db. It has three important functions.

♦ Record operations on your data to enable recovery You canrecreate your database from a backup together with the transactionlog if the database file is damaged.

♦ Enable database replication SQL Remote uses this file toreplicate the changes to your database on portable computers whichare sometimes, but not always, connected to the network.

Page 129: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 8 The Architecture of Database Applications

117

♦ Improve performance By writing information to the transactionlog, the database server can safely process your commands withoutwriting to the database file as frequently.

♦ The temporary file The temporary file is opened when the databaseserver starts, and is closed down when the server stops. As its namesuggests, the temporary file is used while the server is running to holdtemporary information. The temporary file does not hold informationthat needs to be kept between sessions.

The temporary file is stored in your temporary directory. The location ofthis directory is generally identified by your TEMP environmentvariable.

Page 130: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Inside Adaptive Server Anywhere

118

Page 131: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

119

P A R T T H R E E

Working with Databases

The first chapter of this part takes you on a tour of the Adaptive ServerAnywhere 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 andmanipulating data. It also describes how to incorporate SQL into database

applications.

Page 132: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

120

Page 133: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

121

C H A P T E R 9

Designing and Building Your Database

This chapter introduces some principles of database design, and describeshow to create a database using Sybase Central. It uses the Adaptive ServerAnywhere sample database to illustrate the principles involved.

Topic Page

Introduction 122

The sample database 124

Tutorial: design and build a simple database 129

About this chapter

Contents

Page 134: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Introduction

122

IntroductionIt is worth spending some time designing even the simplest database: whattables you will have, the keys that relate these tables, and so on.

Designing a database is not a difficult task for small and medium sizeddatabases, but it is an important one. Bad database design can lead to aninefficient and possibly unreliable database system. Database applicationsare built to work on specific parts of a database, and rely on the databasedesign, 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 youto apply these techniques to design and maintain large database designs.

This chapter does not attempt to tackle design issues for large databases. Foran elementary look at the principles of database design, see "Designing YourDatabase" on page 321 of the book ASA User’s Guide. For more advancedtreatments, see the Sybase PowerDesigner documentation or a book devotedto database design.

Instead, this chapter helps you decide the kind of information you grouptogether in a single table, and the way in which to think about and classifyrelationships between tables.

This chapter assumes that you are familiar with the concepts of databasetables, primary keys, and foreign keys. For information, see "Databases andApplications" on page 85.

About this chapter

If you want to know… Then see…

Where to find information about thesample database

"The sample database" on page 124

How to connect to the sample database "Connect to the sample database" onpage 125

How to view tables "View a list of tables in the sampledatabase" on page 126

How to view columns "View the columns of a table" onpage 128

How to create a database file "Lesson 1: Create a database file" onpage 129

Page 135: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 9 Designing and Building Your Database

123

If you want to know… Then see…

How to connect to a database "Lesson 2: Connect to your database"on page 130

How to create a table "Lesson 3: Design and create a table"on page 131

How to create a primary key "Lesson 4: Identify and createprimary keys" on page 132

How to set column properties "Lesson 5: Design columnproperties" on page 134

How to create relationships betweentables

"Lesson 6: Design and createrelationships between tables" onpage 136

Page 136: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

The sample database

124

The sample databaseThere is a sample database included with Adaptive Server Anywhere. Manyof the examples throughout the documentation use this sample database.

The sample database represents a small company that makes a limited rangeof sports clothing. It contains internal information about the company(employees, departments, and financial data) as well as product information(products), and sales information (sales orders, customers, and contacts).

The following figure shows the tables in the sample database and how theyare related to each other. The boxes represent tables, and the arrowsrepresent foreign key relationships. Primary key columns are underlined.

We will use this database to illustrate the concepts described in this chapter.

id = id

id = prod_id

code = fin_code_id

emp_id = sales_rep

id = cust_id

code = code

dept_id = dept_idemp_id = dept_head_id

contactid <pk> integerlast_name char(15)first_name char(15)title char(2)street char(30)city char(20)state char(2)zip char(5)phone char(10)fax char(10)

customerid <pk> integerfname char(15)lname char(20)address char(35)city char(20)state char(2)zip char(10)phone char(12)company_name char(35)

sales_orderid <pk> integercust_id <fk> integerorder_date datefin_code_id <fk> char(2)region char(7)sales_rep <fk> integer

fin_codecode <pk> char(2)type char(10)description char(50)

fin_datayear <pk> char(4)quarter <pk> char(2)code <pk,fk> char(2)amount numeric(9)

productid <pk> integername char(15)description char(30)size char(18)color char(6)quantity integerunit_price numeric(15,2)

sales_order_itemsid <pk,fk> integerline_id <pk> smallintprod_id <fk> integerquantity integership_date date

employeeemp_id <pk> integermanager_id integeremp_fname char(20)emp_lname char(20)dept_id <fk> integerstreet 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 datetermination_date datebirth_date datebene_health_ins char(1)bene_life_ins char(1)bene_day_care char(1)sex char(1)

departmentdept_id <pk> integerdept_name char(40)dept_head_id <fk> integer

asademo.db

Page 137: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 9 Designing and Building Your Database

125

Viewing the structure of the sample database using Sybase Central

This section describes how to use Sybase Central to view the contents of thesample database.

Connect to the sample database

You need to connect to the sample database from Sybase Central in order toview the tables and other objects in the database.

v To connect to the sample database from Sybase Central:

1 Start Sybase Central

Choose Start➤Programs➤Sybase SQL Anywhere 7➤Sybase Central4.0.

2 Open the Connect dialog

♦ Click Tools➤Connect.

♦ If you are presented with a list of plugins, choose Adaptive ServerAnywhere from the list.

The Connect dialog appears:

Page 138: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

The sample database

126

3 Select the ODBC Data Source Name option and click Browse. In theresulting list, choose ASA 7.0 Sample.

4 Click OK to establish the connection.

View a list of tables in the sample database

Once you are connected to the sample database, you can open the folders inthe left pane to view the tables and other objects that make up the database.

$ For information on connecting to a database from Sybase Central, see"Connect to the sample database" on page 125.

v To view a list of tables in the database:

1 In Sybase Central, open Adaptive Server Anywhere.

The Sybase Central left pane contains a list of plugins. Each one is usedto manage a different Sybase product. The Adaptive Server Anywhereplugin is used to manage all aspects of Adaptive Server Anywhere.

2 Open the sample database.

Page 139: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 9 Designing and Building Your Database

127

Under the Adaptive Server Anywhere plugin is a list of database serversto which you have connections. When the sample database is started, thedatabase server is named asademo.

Each database server may be running one or more databases. In thiscase, the sample database is also named asademo. The database also hasthe user name for the current connection in parentheses next to it. In thiscase, you are connected as a user named DBA.

3 Open the tables folder.

Each database contains a set of folders, describing the different types ofdatabase objects. Here, we are interested only in the tables in thedatabase. Open the tables folder to list the available tables.

Each table has a creator, or owner, which is listed in the right pane. If yousee more tables than are shown in the figure, right click the asademodatabase, and choose Filter Objects By Owner from the popup menu. CheckDBA, and uncheck the other user IDs in the list. Click OK to restrict theobjects shown to those owned by DBA.

Notes

Page 140: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

The sample database

128

View the columns of a table

Sybase Central displays tables as containers. Each table has folders forcolumns, foreign keys to and from the table, indexes, and triggers. Here, welook only at the columns of the product table in the sample database.

$ For information on viewing tables, see "View a list of tables in thesample database" on page 126.

v To view information about the columns of the product table:

1 In Sybase Central, open the product table.

2 Open the Columns folder.

The name, data type, and other information about each column isdisplayed in the right pane.

3 View the properties of the color column.

Right click the color column, and choose Properties from the popupmenu. The color property sheet is displayed. This property sheet containsa detailed description of the column. Some of the properties are usefulfor advanced users only, and are not described in this book.

You can use Sybase Central to browse other aspects of the sample database,including foreign keys and primary keys. You are encouraged to do so inorder to be familiar with the sample database for examples in the remainderof the documentation.

Page 141: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 9 Designing and Building Your Database

129

Tutorial: design and build a simple databaseWhen designing a database, you plan what items you want to storeinformation about, and what information you will keep about each. You alsodetermine how these items are related. You classify the things in yourdatabase as entities; the links between these entities are called relationships.

In this tutorial, you design and build a very simple database, modeled on theproduct, sales_order_items, sales_order, and customer tables of the sampledatabase, but simplified. The database you create is not used in other parts ofthe documentation, so going through the activities is not required. However,it is highly recommended to gain familiarity with the software and concepts.

Lesson 1: Create a database file

In this lesson, you create a database file to hold your database.

$ For more information, see "The pieces of a database system" onpage 94.

A database file, is a container, ready to hold your database. The database filecontains system tables and other system objects that are common to alldatabases, but you must add all the tables and the data they hold.

The collection of tables, indexes, and so on within the database, and all therelationships between them, make up the database schema. The schema isthe database, without the data. This tutorial describes how to design andcreate a very simple database schema.

For a conceptual introduction to some of these pieces, see Chapter 6,"Relational database concepts" on page 86.

The name of each object within the database, including tables, columns, andindexes, is an identifier. There are rules governing what you can use asidentifiers. You can use any set of letters, numbers or symbols. However,you must enclose a column name in double quotes if it contains charactersother than letters, numbers, or underscores, if it does not begin with a letter,or if it is the same as a keyword.

$ For more information about identifiers, see "Identifiers" on page 211 ofthe book ASA Reference.

v To create a new database file:

1 Start Sybase Central.

You do not need to connect to any database in this tutorial.

Concepts

Exercise

Page 142: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Tutorial: design and build a simple database

130

2 In the left pane, open the Adaptive Server Anywhere container. Thenopen the Utilities folder. In the right pane, double-click CreateDatabase.

3 On the Choose a Connection page, choose Connection Created By aLocal Engine, and click Next.

A personal database server starts, with the name SybCentral. This serverwill create the database file.

4 Choose a location and name for your database file.

On the Create an Adaptive Server Anywhere Database page, enter afilename of c:\temp\mysample. If your temporary directory issomewhere 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 canview by clicking Next, but the default choices are good for manypurposes.

The Create Database Message Console displays the progress of the task,and disappears when the file is created.

Lesson 2: Connect to your database

In this lesson, you connect to the database file you created.

$ For more information, see "How the pieces fit together" on page 97.

Once your database is created, you can connect to it in order to create tablesand other database objects.

v To connect to your database:

1 Start Sybase Central.

2 Choose Tools➤Connect to open the Connect dialog. If you havemultiple plug-ins loaded, you may need to choose a plug-in before theConnect dialog opens.

3 Specify the user ID and password.

On the first page of the Connect dialog (the Identification page), enter auser ID of DBA and a password of SQL. These are the values created fornew databases, and so grant access to your new database.

Choose None in the profile options at the bottom of the page.

4 Specify your database file.

Exercise

Page 143: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 9 Designing and Building Your Database

131

Click the Database tab. Enter the full path of your database file in theDatabase File field. For example, if you followed the suggestion in theprevious 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 theSybCentral database server.

Lesson 3: Design and create a table

In this lesson, you add a table to your database.

Each table in your database should contain information about a singlesubject. In the language of database design, you are identifying an entity. Forexample, the sample database holds information about employees in onetable, and information about products in another table: employees andproducts are entities within the database design.

$ For an introduction to tables, see "Database tables" on page 86.

Each column in a table describes a particular characteristic of the thing thatyou would like to store information about. For example, in the sampledatabase, the employee table has columns that hold an employee ID number,the first and last names, an address, and other particular information thatpertains to a particular employee.

In database diagrams, each table is depicted by a rectangular box. The nameof the table is at the top of the box, and the column names are listed insidethe box.

In the product table from the sample database, above, each product is an itemof sports clothing.

Create a simplified version of the product table, containing only the identifier(id) and name columns.

Concepts

Exercise

Page 144: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Tutorial: design and build a simple database

132

v To create the product table:

1 In Sybase Central, connect to your database.

2 Open the Tables folder in your database.

First open the server and database containers, then open the Tablesfolder.

3 Double-click Add Table in the right panel. The Table Editor appears.

The Sybase Central Table Editor is where you add tables to yourdatabase.

4 Name your table.

Type product in the Name box in the upper left corner of the table editor.

5 Create the columns.

The next lesson tells you more about columns and what to put in them.Here, we create two columns for our simplified version of the producttable.

Add an identifier column with the following properties:

♦ Name Give the column a name of id.

♦ Primary key Click the Key heading until an icon with a key andthe letter P appears, indicating that the column is a primary key.

♦ Data type Give the column the integer data type.

Add a column with the following properties:

♦ Name Give the column a name of name. This column holds theproduct name.

♦ Data type Give the column the char data type, which holdscharacter strings, and enter a maximum length of 15 in theSize/Precision column.

6 To finish, click the Save and Close button.

You have now created a table in your database. The table data is held in thedatabase file. At present, the table is empty.

The next two lessons have more to say about columns and data types.

Lesson 4: Identify and create primary keys

In this lesson, you learn more about defining primary keys for your tables.There is no exercise associated with this lesson.

Page 145: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 9 Designing and Building Your Database

133

$ For more information, see "Tables have a primary key" on page 88.

The primary key is a special column or columns used to uniquely identify arow in a table. In the product table, the id column uniquely identifies eachproduct.

Each row has a unique value for the id column, and the values in the othercolumns pertain only to that one product. Two products might have the samename or the same size, but not the same id number. In the diagram, the idcolumn is underlined to show that it is a primary key.

Creating a column specifically to hold an identifier, which has no othermeaning, is common practice in database design. You will know from anybank, utility, or credit card statements you get that each account has a uniqueidentifier.

You can make entering primary keys simple by assigning a primary keycolumn a default value of AUTOINCREMENT. The value for this column isentered automatically each time a new row is added, and its value is onemore than the field’s value for the last row added.

v To create an AUTOINCREMENT primary key:

1 Open the Sybase Central Table Editor.

2 Select the column in which you wish to have AUTOINCREMENT data.Click the Property sheet button on the toolbar to open the property sheetfor the column.

3 Choose the Default tab.

4 Click Select.

5 Click on System-Defined, and select Autoincrement from the drop-downlist.

6 To finish, click the Save and Close button.

Concepts

Using anautoincrementprimary key

Page 146: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Tutorial: design and build a simple database

134

Lesson 5: Design column properties

In this lesson, you learn more about choosing data types and other attributesfor the columns of your tables.

Each column has a data type associated with it, that defines the type ofinformation it holds. Choose a data type of the column that is appropriate forthe data in the column. For example, identifier columns may have an integerdata type; columns holding names or addresses are character data types.

Data types are organized into the following categories:

♦ Numeric data types There are several numeric data types. Some areexact (not affected by round-off errors during operations) and some areapproximate.

The data type of the column affects the maximum size of the column.For example, if you specify SMALLINT, a column can contain amaximum value of 32,767. If you specify INTEGER, the maximumvalue is 2,147,483,647.

$ For a complete list, see "Numeric data types" on page 256 of thebook ASA Reference.

♦ Character data types These are used to hold strings of text, such asnames, addresses, and so on. These data types have a length, indicatingthe maximum length of string that can be stored in them.

$ For a list, see "Character data types" on page 252 of the book ASAReference.

♦ Binary data types These can be useful to hold information that maybe meaningful to an application, but is encoded in a binary format.

$ For a list, see "Binary data types" on page 272 of the book ASAReference.

♦ Date/time data types These hold times of the day, as well as dates.

$ For a list, see "Date and time data types" on page 265 of the bookASA Reference.

♦ Long data types These are sometimes called blobs (binary largeobjects). They can be used to hold long strings of text (called memofields in some databases), or images, or other application-specificinformation.

$ For more information, see "LONG BINARY data type" onpage 272 of the book ASA Reference, and "LONG VARCHAR datatype" on page 254 of the book ASA Reference.

Concepts

Page 147: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 9 Designing and Building Your Database

135

In addition, Adaptive Server Anywhere supports user-defined data types andspecial Java data types. These are not discussed in this introductory book.

If the column value is mandatory for each row, you define the column asbeing NOT NULL. Otherwise, the column is allowed to contain NULL,which represents a missing value. The default is to allow NULL, but youshould explicitly declare columns NOT NULL unless there is a good reasonto allow NULL.

$ For a complete description of the NULL value, see "NULL value" onpage 247 of the book ASA Reference. For information on its use incomparisons, see "Search conditions" on page 226 of the book ASAReference.

v To specify a data type for a column:

1 In the Tables folder, open the table for whose column you wish tospecify a data type.

2 Open the Columns folder.

3 Select the column for which you wish to specify a data type.

4 Click on the Data Type tab.

5 Select a basic data type from the first drop-down box.

This lesson and the last lesson have introduced the basic concepts you needto know in order to create database tables. You can put these to work byadding some more tables to your database. These tables will be used in thesubsequent lessons in this chapter.

Using the Sybase Central Table Editor, add the following tables to yourdatabase:

♦ customer Add a table named customer, with the following columns:

♦ id An identification number for each customer. This column hasinteger data type, and is the primary key.

♦ company_name The company name. This column is a characterdata type, with a maximum length of 35 characters.

♦ sales_order Add a table named sales_order, with the followingcolumns:

♦ id An identification number for each sales order. This column hasinteger data type, and is the primary key.

♦ order_date The date on which the order was placed. This columnhas date data type.

NULL andNOT NULL

Exercise

Page 148: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Tutorial: design and build a simple database

136

♦ cust_id The identification number of the customer who placed thesales order. This column has integer data type.

♦ sales_order_items Add a table named sales_order_items to hold lineitem information, with the following columns:

♦ id The identification number of the sales order of which the lineitem is a part. This column has integer data type, and should beidentified as a primary key column.

♦ line_id An identification number for each sales order. Thiscolumn has integer data type, and should be identified as a primarykey column.

♦ prod_id The identification number for the product being ordered.This column has integer data type.

You have now created four tables in your database. The tables are not yetrelated in any way. In the next lesson, you define foreign keys to relate thetables to one another.

Lesson 6: Design and create relationships between tables

In this lesson, you learn about designing and creating relationships betweentables, using foreign keys.

$ For more information, see "Tables are related by foreign keys" onpage 88.

Although each table contains information about a single subject, two or moretables may contain related information. For example, an employee is amember of a department, or a sales order is for a set of products.Relationships in a database may appear as foreign key relationships betweentables, or may appear as separate tables themselves. You will see examplesof each in this chapter.

You create relationships in your database to encode rules or practices thatgovern the data in your tables. Once a relationship is built into the structureof the database, there is no provision for exceptions.

Relationships among tables are classified according to cardinality. In thissection the different relationships are listed.

♦ One-to-one relationships Each item in one entity corresponds toeither zero or one entity in another. For example, in the sample database,one employee manages one department. There is nowhere to put asecond department manager. Duplicating the department entry wouldinvolve duplicating the department ID, which is the primary key.

Concepts

Page 149: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 9 Designing and Building Your Database

137

It is often appropriate to combine the items in a one-to-one relationshipinto a single table. There is a column in the department table for amanager, rather than having a separate table named manager.

$ For cases where it is appropriate to keep the items separate, see"Designing Your Database" on page 321 of the book ASA User’s Guide.

♦ Many-to-one relationships A many-to-one relationship becomes aforeign key relationship between tables. In a many-to-one relationship,the primary key in the one entity appears as a new foreign key column inthe many table.

For example, in the database you just created, one customer can placemany orders, but only one customer places each order. To represent theone-to-many relationship, you need a foreign key column in thesales_order table (cust_id) that maps to the primary key column in thecustomer table (id). It is often convenient to give the two columns thesame name.

dept_id = dept_id

employee

emp_id integermanager_id integeremp_fname char(20)emp_lname char(20)dept_id integerstreet 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 datetermination_date datebirth_date datebene_health_ins char(1)bene_life_ins char(1)bene_day_care char(1)sex char(1)

department

dept_id integerdept_name char(40)dept_head_id integer

Each entry in the cust_id column of the sales_order table must matchone of the entries in the id column of the customer table. Thesales_order table (which contains the foreign key in the relationship) iscalled the foreign table or referencing table. The customer table(which contains the referenced primary key) is called the primary tableor the referenced table.

♦ Many to many relationships A many-to-many relationship isrepresented by an intermediate table, and there is a foreign keyrelationship from the intermediate table to each of the related entities.

Page 150: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Tutorial: design and build a simple database

138

For example, in the sample database, there is a many-to-manyrelationship between products and sales orders. One sales order can befor many products, and one product can appear on many sales orders.

id = prod_id

id = id sales_order

id integerorder_date dateregion char(7)

product

id integername char(15)description char(30)size char(18)color char(6)quantity integerunit_price numeric(15,2)

sales_order_items

id integerline_id smallintprod_id integerquantity integership_date date

In some cases, the intermediate table (sales_order_items) containsadditional information, such as the number of items of the product thatwere ordered and the date they were shipped. In this case, theintermediate table holds no additional information.

Add foreign keys to relate the tables in your database.

Add the following foreign keys:

♦ A foreign key from the id column in sales_order_items, referencing theid column in sales_order. This key builds the many-to-one relationshipbetween sales orders and sales order items into the database.

♦ A foreign key from the prod_id column in sales_order_items,referencing the id column in product. This key builds the many-to-onerelationship between sales order items and products into the database.

♦ A foreign key from the cust_id column in sales_order, referencing the idcolumn in customer. This key builds the many-to-one relationshipbetween sales orders and customers into the database.

The first two foreign keys, taken together build the many-to-manyrelationship between sales orders and products into the database.

v To create a foreign key:

1 Click the table for which you wish to create a foreign key.

2 Open the Foreign Keys folder.

3 Double click Add Foreign Key to invoke the Foreign Key Wizard.

4 Follow the steps of the wizard.

This completes this introductory section on designing and building relationaldatabases. Remaining chapters in the book describe how to add and retrievedata from databases. These chapters use the Adaptive Server Anywheresample database, which is a bigger database than the one you have justcreated.

Exercise

Page 151: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

139

C H A P T E R 1 0

Connecting Your Application to itsDatabase

This chapter shows you how to establish a connection from your applicationto the database it is working with.

Topic Page

Introduction to connections 140

Referencing data sources 141

Creating an ODBC Data Source 142

About this chapter

Contents

Page 152: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Introduction to connections

140

Introduction to connectionsAny client application that uses a database must establish a connection tothat database before any work can be done. The connection forms a channelthrough which all activity from the client application takes place. Forexample, your user ID determines permissions to carry out actions on thedatabase—and the database server has your user ID because it is part of therequest to establish a connection.

Many client applications, including application development systems, use theOpen Database Connectivity (ODBC) interface to access Adaptive ServerAnywhere. An ODBC data source is a set of connection parameters that arestored in the registry or in a file.

You can use ODBC data sources to connect to Adaptive Server Anywheredatabases 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 andPowerDynamo

Adaptive Server Anywhere client applications on UNIX can use ODBC datasources. On UNIX, the data source is stored as a file.

$ Adaptive Server Anywhere supports several programming interfaces inaddition to ODBC. For more information, see "Introduction to connections"on page 32 of the book ASA User’s Guide.

Page 153: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 10 Connecting Your Application to its Database

141

Referencing data sourcesYou need an ODBC data source on the client computer for each database youwant to connect to.

The ODBC data source contains a set of connection parameters. You canstore sets of Adaptive Server Anywhere connection parameters as an ODBCdata source, in either the system registry or as files.

Once you have a data source, your connection string can simply name thedata source to use:

♦ Data source Use the DSN connection parameter to reference a datasource in the registry:

DSN=my data source

♦ File data source Use the FileDSN connection parameter to referencea data source held in a file:

FileDSN=mysource.dsn

The Connect dialog in Sybase Central and Interactive SQL has fields forentering an ODBC Data Source Name or ODBC Data Source File.

Page 154: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Creating an ODBC Data Source

142

Creating an ODBC Data SourceThis section describes how to create an ODBC data source in Windows. Theprocess is almost identical for creating system data sources and file datasources—just go to the System DSN tab or File DSN tab on the ODBC DataSource Administrator dialog (see below).

$ For information about setting up ODBC data sources on UNIX, see"Using ODBC data sources on UNIX" on page 55 of the book ASA User’sGuide.

v To create an ODBC data source:

1 From the Windows Start menu, choose Programs➤Sybase SQLAnywhere 7➤Adaptive Server Anywhere 7➤ODBC Administrator.

orFrom Sybase Central, choose Tools➤Adaptive ServerAnywhere➤ODBC Administrator.

The ODBC Data Source Administrator appears, showing a list of thedata sources you currently have installed on your computer. Forexample,

2 On the User DSN tab, click Add.

The Create New Data Source wizard appears.

Page 155: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 10 Connecting Your Application to its Database

143

3 Select Adaptive Server Anywhere 7.0 from the list of drivers, and clickFinish.

The Adaptive Server Anywhere ODBC Configuration dialog appears.

Many of the fields in this dialog box are optional. Click the questionmark at the top right of the window and click an entry field to find moreinformation about that field. You probably only need to use thefollowing parameters:

♦ Data Source Name (ODBC tab) Type a name that will appear inthe 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 youattempt to connect.

Page 156: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Creating an ODBC Data Source

144

♦ Password (Login tab) You should omit or encrypt the passwordif there are security concerns with having passwords stored on yourmachine. If you omit the password, you will be prompted for itwhen you attempt to connect.

♦ Database File (Database tab) You can select a database file bybrowsing your machine.

4 When you have specified the parameters you need, click OK to createthe data source and close the dialog box.

$ For a full description of database connections, see "Connecting to aDatabase" on page 31 of the book ASA User’s Guide.

$ For more information about ODBC data sources, see "Working withODBC data sources" on page 47 of the book ASA User’s Guide.

Page 157: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

145

C H A P T E R 1 1

Using Interactive SQL

This chapter discusses how to run and use Interactive SQL. Interactive SQLis a utility shipped with Adaptive Server Anywhere; it lets you execute SQLstatements, build scripts, and display database data.

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

About this chapter

Contents

Page 158: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Introduction to Interactive SQL

146

Introduction to Interactive SQLInteractive SQL is a utility for sending SQL statements to the databaseserver. You can use it for the following purposes:

♦ Browsing the information in a database.

♦ Trying out SQL statements that you plan to include in an application.

♦ Loading data into a database and carrying out administrative tasks.

In addition, Interactive SQL can run command files or script files. Forexample, you can build repeatable scripts to run against a database and thenuse Interactive SQL to execute these scripts in a batch fashion.

When you open an Interactive SQL window, it appears with the followingthree main panes:

♦ SQL Statements Provides a place for you to type SQL statements. Ifthe amount of code you type exceeds the size of the pane, scroll barsautomatically appear for the pane.

♦ Messages Displays information about an execution. You can specifyoptions for this pane in the Options dialog.

♦ Results Displays the results of commands that you execute. Forexample, if you use SQL statements to search for specific data in thedatabase, this pane displays the columns and rows that match the searchcriteria. If the information exceeds the size of the pane, scroll barsautomatically appear for the pane.

About this chapter

The following table lists the most common information how to run and useInteractive SQL.

Main windowdescription

Page 159: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 11 Using Interactive SQL

147

If you want to know… Then see…

How to start Interactive SQL "Starting Interactive SQL" onpage 148

How to use the Interactive SQL toolbar "Using the Interactive SQL toolbar"on page 148

How to open a new Interactive SQLwindow

"Opening multiple windows" onpage 149

Where to find information aboutkeyboard short cuts

"Keyboard shortcuts" on page 149

How to display data "Using Interactive SQL to displaydata" on page 151

How to use commands in Interactive SQL "Working with commands" onpage 152

How to set Interactive SQL vieweroptions

"Configuring Interactive SQL" onpage 159

Where to find more detailed informationon selecting data

"Selecting Data from DatabaseTables" on page 163

Page 160: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Starting Interactive SQL

148

Starting Interactive SQLYou can start Interactive SQL in two ways: from Sybase Central or on itsown. The way that you start Interactive SQL on its own depends on youroperating system.

If you start Interactive SQL on its own, the Connect dialog appears, whichlets you connect to a database just as you would in Sybase Central.

$ For detailed information on connecting to databases, see "Connectingto a Database" on page 31 of the book ASA User’s Guide.

v To start Interactive SQL from Sybase Central:

♦ To start Interactive SQL, right-click the database in Sybase Central andchoose File➤Open Interactive SQL.

or

To start Interactive SQL without a connection to a database, chooseTools➤Adaptive Server Anywhere➤Open Interactive SQL. TheConnect dialog automatically appears.

v To start Interactive SQL on its own:

♦ Select Interactive SQL from the Adaptive Server Anywhere programgroup in the Start menu. You can also type dbisql at a commandprompt.

or

♦ Type the following command at a system prompt:

dbisql

Using the Interactive SQL toolbar

The Interactive SQL toolbar (shown below) appears at the top of theInteractive SQL window. It provides you with buttons for executing commoncommands.

Page 161: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 11 Using Interactive SQL

149

With the buttons on this toolbar, you can:

♦ Recall the executed SQL statement immediately before your currentposition in the history list.

♦ View a list of up to 50 previously executed SQL statements.

♦ Recall the executed SQL statement immediately after your currentposition in the history list.

♦ Execute the SQL statement currently showing in the SQL Statementspane.

♦ Interrupt the execution of the current SQL statement.

As an easy reminder of what these buttons do, you can hold your cursor overeach button to see a popup description.

Opening multiple windows

In Interactive SQL, you can open multiple windows. Each windowcorresponds to a separate database connection. Using this feature, you canconnect simultaneously to two (or more) different databases on differentservers, or you can open concurrent connections to a single database.

v To open a new Interactive SQL window:

1 Choose File➤New Window.

2 In the resulting Connect dialog, enter connection options, and click OKto connect.

You can also connect to or disconnect from a database with the Connect andDisconnect commands in the SQL menu, or by executing a CONNECT orDISCONNECT statement.

Keyboard shortcuts

Interactive SQL provides the following keyboard shortcuts.

Page 162: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Starting Interactive SQL

150

Function key Description

F1 Help

F5 Executes all text in the SQL Statements pane

You can also perform this operation by clicking the ExecuteSQL Statement button on the toolbar

F9 Executes whatever text is selected in the SQL Statementspane

If no text is selected, all of the statements are executed.

PGUP Moves up in the current pane

PGDN Moves down in the current pane

CTRL+HOME Moves to the top of the current pane

CTRL+END Moves to the bottom of the current pane

CTRL+N Opens a new window. Each window corresponds with aseparate database connection

ESC Clears the SQL Statements pane

ALT+LEFT

CURSOR

Shows the previous SQL statement in the history list

ALT+RIGHT

CURSOR

Shows the next SQL statement in the history list

CTRL+H Shows the history of your executed SQL statements duringthe current session

F7 Displays the Lookup Table Name dialog

In this dialog, you can find and select a table and then pressENTER to insert the table name into the SQL Statements paneat the cursor position. Or, with a table selected in the list,press F7 again to show the columns in that table. You canthen select a column and press ENTER to insert the columnname into the SQL Statements pane at the cursor position.

F8 Displays the Lookup Procedure Name dialog

In this dialog, you can find and select a procedure and thenpress ENTER to insert the procedure name into the SQLStatements pane at the cursor position.

CTRL+S Saves the contents of the SQL Statements pane

ALT+F4 Exits Interactive SQL

Page 163: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 11 Using Interactive SQL

151

Using Interactive SQL to display dataOne of the principal uses of Interactive SQL is to browse the information indatabases. This section shows how to query the information in the sampledatabase.

You can display database information using the SELECT statement inInteractive SQL. The following example shows the command to type in theSQL Statements pane. Once you have typed the command, you must clickthe Execute SQL Statement button on the toolbar to carry out the command.

After you execute the statement, the data (called a result set) appears in theResults pane. You can use the scroll bars to see areas of the table that areoutside your current view of the pane.

v To list all the columns and rows of the employee table:

1 Start Interactive SQL and connect to the sample database (asademo).

2 Type the following in the SQL Statements pane:

SELECT *FROM employee

3 On the toolbar, click the Execute SQL Statement button.

Emp_id Manager_id Emp_lname emp_fname ...

102 501 Fran Whitney ...

105 501 Matthew Cobb ...

129 902 Philip Chin ...

148 1293 Julie Jordan ...

160 501 Robert Breault ...

...

$ For more information on Select statements, see "Selecting Data fromDatabase Tables" on page 163.

Page 164: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Working with commands in Interactive SQL

152

Working with commands in Interactive SQLThe following chapters describe some of the commands you can use inInteractive SQL. This section describes general tasks for working withcommands in Interactive SQL.

All SQL statements can be entered as commands in the top pane of theInteractive SQL viewer. When you are finished typing, you need to executethe statement to run it.

v To enter a command:

♦ In the SQL Statements pane, type the command.

v To execute a command, do one of the following:

♦ On the toolbar, click the Execute SQL Statement button.

or

Choose SQL➤Execute.

or

Press F5.

v To clear the SQL Statements pane:

♦ Choose Edit➤Clear SQL.

TipsYou can execute only a selection of text in the SQL Statements button bypressing F9.

Any messages about an executed statement, such as syntax errors, appearin the Messages pane.

Canceling an Interactive SQL command

The STOP button cancels a command.

A Stop operation stops current processing and prompts for the nextcommand. If a command file was being processed, you are prompted for anaction to take (Stop command file, Continue, or Exit Interactive SQL). Theseactions can be controlled with the Interactive SQL ON_ERROR option (see"ON_ERROR option" on page 188 of the book ASA Reference).

Page 165: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 11 Using Interactive SQL

153

When an abort is detected, one of three different errors will be reporteddepending 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 isdisplayed:

ISQL command terminated by user

Interactive SQL stops processing immediately and the databasetransaction is left alone.

2 If the cancel is detected by the database engine while processing astandard 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 thetransaction is left intact.

3 If the abort is detected while the database engine is processing a datadefinition command (CREATE, DROP, ALTER, etc.), the followingmessage appears:

Terminated by user -- transaction rolled back

Since data definition commands all perform a COMMIT automaticallybefore the command starts, the effect of the ROLLBACK is to justcancel the current command.

This message also occurs when the database engine is running in bulkoperations mode executing a command that modifies the database (INSERT,UPDATE, and DELETE). In this case, ROLLBACK cancels not only thecurrent command, but everything that has been done since the last COMMIT.In some cases, it may take a considerable amount of time for the databaseengine to perform the automatic ROLLBACK.

Combining multiple statements

The Interactive SQL environment allows multiple statements to be entered atthe same time. This can be done by ending each statement with a semi-colon(;).

v To enter multiple statements in SQL Statements pane:

1 Try entering the following three commands into the SQL Statementspane.

Reported errors

Page 166: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Working with commands in Interactive SQL

154

UPDATE employeeSET dept_id = 400, manager_id = 1576WHERE emp_id = 467;

UPDATE employeeSET dept_id = 400, manager_id = 1576WHERE emp_id = 195;

SELECT *FROM employeeWHERE emp_id IN ( 195, 467 );

2 On the toolbar, click the Execute SQL Statement button. All threestatements are executed. After execution, the commands remain in theSQL Statements pane. If you want to clear this pane, press the ESC key.

Looking up tables, columns, and procedures

While you are entering commands in Interactive SQL, you can look up thenames of tables, columns, or procedures stored in the current database andinsert them at your cursor position.

v To look up the names of tables in the database:

1 Choose Tools➤Lookup Table Name.

2 Find and select the table.

3 Click OK to insert the table name into the SQL Statements pane.

v To look up column names in the database:

1 Choose Tools➤Lookup Table Name.

2 Find and select the table containing the column.

3 Click Show Columns.

4 Select the column and click OK to insert the column name into the SQLStatements pane.

v To look up the names of procedures in the database:

1 Choose Tools➤Lookup Procedure Name.

2 Find and select the procedure.

3 Click OK to insert the procedure name into the SQL Statements pane.

Page 167: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 11 Using Interactive SQL

155

$ Results are filtered according to the search criteria entered into the lookup field. Once you type a search criteria into the look up field, the dialog willpause, and then restrict the list to include only those items that begin with thetext you entered. The standard SQL "%" search metacharacter, meaning"match anything" is also recognized. For example, to list only those tablesending in "order", type "%order" into the look up field. To list all itemscontaining the word "java", type "%java%". Clearing the search criteria fromthe look up field resets the filtering to display all the items.

Recalling commands

When you execute a command, Interactive SQL automatically saves it in ahistory list that lasts for the duration of the current session. You can insertany one of the previous commands listed into the SQL Statements pane, oryou can view the entire list in the Command History dialog:

Interactive SQL maintains a record of up to 50 of the most recent commandsyou have entered throughout your session so that you may easily re-enterthem.

The most recent commands appear at the bottom of the list. You canhighlight a command and click OK to insert it into the SQL Statements paneat your current cursor position. Interactive SQL stores up to 50 commands.

1 Type the following in the command window:

SELECT * FROM department

2 Press F9.

Page 168: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Working with commands in Interactive SQL

156

The contents of the department database table appear in the Data window. Asyou execute commands with Interactive SQL, they are saved in a commandhistory. 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 thatyou executed during your session. Position the cursor on the first commandthat you executed, which was:

SELECT *FROM department

and press the ENTER key. The cursor returns to the command window withthe selected command in it. You can now re-execute that command ormodify it to make a new command.

v To insert the previous command:

♦ On the toolbar, click the Recall previous SQL statement button.

or

Choose SQL➤Previous SQL.

v To insert the next command in the history list:

♦ On the toolbar, click the Recall next SQL statement button.

or

Choose SQL➤Next SQL.

v To view the entire command history, do one of the following:

♦ Click the Open a list of past SQL statements button on the toolbar.

or

Choose SQL➤History.

The following keys can also be used to recall previous commands:

Key sequence Description

CTRL+R Opens the command recall window

CTRL+P Cycles backwards through previously executedcommands. Retrieved commands are placed into thecommand window.

CTRL+N Cycles forward through previously executed commands

More recall keys

Page 169: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 11 Using Interactive SQL

157

You can also save commands in text files, so that you can use them in asubsequent Interactive SQL session. For more information, see "Saving,loading, and running command files" on page 157.

Saving, loading, and running command files

You can save the commands currently present in the SQL Statements pane sothat they are available for future Interactive SQL sessions. The file in whichyou save them is called a command file (also known as a script).

When you begin a new session, you can load the contents of a command fileinto the SQL Statements pane, or you can run the contents immediately.

v To save the commands in the SQL Statements pane:

1 Choose File➤Save As.

2 In the Save dialog, specify a location, name and format for the file. ClickSave when finished.

v To load commands from a file into the SQL Statements pane:

1 Choose File➤Open.

2 In the Open dialog, find and select the file. Click Open when finished.

v To run a command file immediately:

1 Choose File➤Run Script.

2 In the Open dialog, find and select the file. Click Open when finished.

You can supply a command file as a command line argument for InteractiveSQL.

The Run Script menu item is the functional equivalent of a READ statement.For example, in the SQL Statements pane, you can also run a command fileby typing:

READ ’c:\filename.sql’

where c:\filename.sql is the path, name, and extension of the file. You canenclose the string in single quotation marks (as shown) if you want, but theyare only required if the path contains embedded spaces

Page 170: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Working with commands in Interactive SQL

158

Logging commands

With the Interactive SQL logging feature, you can record commands as youexecute them. Interactive SQL continues to record until you stop the loggingprocess, or until you end the current session. The recorded commands arestored in a log file.

v To begin logging Interactive SQL commands:

1 Choose SQL➤Start Logging.

2 In the Save dialog, specify a location and name for the log file.

3 Click Save when finished.

v To stop logging Interactive SQL commands:

♦ Choose SQL➤Stop Logging.

TipsYou 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. Alog file must have the .SQL extension. You only need to include the singlequotation 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

v To interrupt an Interactive SQL command:

♦ On the toolbar, click the Interrupt the SQL statement button.

or

Choose SQL➤Stop.

This operation stops current processing and prompts for the next command.If a command file was being processed, you are prompted for an action totake.

Page 171: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 11 Using Interactive SQL

159

Configuring Interactive SQLYou can configure different Interactive SQL viewer options in the Optionsdialog. This dialog provides settings for commands, viewer appearance,import/export features and messages.

Each option can be set from the interface, or using the SET OPTIONstatement.

v To access the Options dialog:

♦ Choose Tools➤Options.

The tabs of the Options dialog are described in the following sections.

Commands dialog tab

The Commands tab of the Options dialog has the following components.

♦ Commit options Lets you choose when transactions are committed.You can choose to commit automatically after each transaction isexecuted or only when you exit your Interactive SQL session. You canalso commit manually by entering an explicit COMMIT commandwhenever appropriate.

$ For more information, see "AUTO_COMMIT option" on page 161of the book ASA Reference in the ASA Reference.

♦ When an error occurs Lets you configure how Interactive SQLresponds to errors.

$ For more information, see "ON_ERROR option" on page 188 ofthe book ASA Reference in the ASA Reference.

♦ Echo Command Files To Log option When you start logging, thisoption causes SQL statements executed from script files (or commandfiles) to be copied to the log along with the SQL statements enteredinteractively. If this option is disabled, only SQL statements enteredinteractively are copied to the log when you start logging.

$ For more information, see "ECHO option" on page 174 of the bookASA Reference in the ASA Reference.

♦ Show multiple result sets Enables or disables the display of multipleresult sets. For example, you can use this feature when you create aprocedure containing multiple SELECT statements. If this option isenabled, you can see each result set when you call the procedure.

Page 172: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Configuring Interactive SQL

160

If you are using the jConnect driver, choosing to show multiple resultsets requires Interactive SQL to wait for an entire result set to beretrieved before any rows are displayed. This may result in longer waitsfor large result sets.

♦ Automatically refetch results Enables or disables the ability ofInteractive SQL to automatically regenerate the most recent result setafter you execute an INSERT, UPDATE, or DELETE statement. Forexample, if you are updating a table with the Results pane showing therows about to be affected, this option causes Interactive SQL toautomatically refresh the Results pane to reflect the executed changes.

$ For more information, see "AUTO_REFETCH option" onpage 161 of the book ASA Reference in the ASA Reference.

Appearance dialog tab

The Appearance tab of the Options dialog has the following components.

♦ Display null values as Lets you specify how you want nulls displayedin the table columns when you browse data.

$ For more information, see "NULLS option" on page 188 of thebook ASA Reference in the ASA Reference.

♦ Maximum number of rows to display Lets you limit the number ofrows displayed.

♦ Application look and feel Lets you choose the viewer appearance.You have three options:

♦ Metal provides the standard Java look

♦ CDE/Motif provides the standard Motif look

♦ Windows provides the standard Windows look

Import/Export dialog tab

The Import/Export tab of the Options dialog has the following components.

♦ Default export format Lets you choose the default file format forexporting. This format is automatically selected in the Files of Typefield in the Save dialog, but you can still choose other formats. Thedefault is also used when Interactive SQL interprets an OUTPUTstatement if no format is specified.

Page 173: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 11 Using Interactive SQL

161

♦ Default import format Lets you choose the default file format forimporting. This format is automatically selected in the Files of Typefield in the Open dialog, but you can still choose other formats. Thedefault is also used when Interactive SQL interprets an INPUT statementif no format is specified.

♦ ASCII options Let you specify the default symbols that are used forthe field separator, quote string and escape character when you import orexport data in the ASCII format.

$ For more information on importing and exporting see "Importingand Exporting Data" on page 675 of the book ASA User’s Guide in theASA User’s Guide.

Messages dialog tab

The Messages tab of the Options dialog has the following components.

♦ Execution plan options Lets you determine the level of detail givenabout the way your query is optimized. You have the following options:

♦ None No information about an execution appears in the Messagespane.

♦ Short plan Basic information about an execution appears in oneline in the Messages pane. This line can show the table(s) accessedand whether the rows are to be read sequentially or accessedthrough an index. This plan is the default.

♦ Long plan Detailed information about an execution appears inmultiple lines in the Messages pane.

♦ Measure execution time for SQL statements Enables or disables theability of Interactive SQL to measure the time it takes for a statement toexecute. When this option is enabled, the time appears in the Messagespane.

♦ Default number of lines in Messages pane Lets you specify theinitial height (in lines) of the Messages pane. The default is 7 lines.

$ For more information, see "Reading access plans" on page 817 ofthe book ASA User’s Guide in the ASA User’s Guide.

Page 174: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Configuring Interactive SQL

162

Page 175: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

163

C H A P T E R 1 2

Selecting Data from Database Tables

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 singletable at a time. For information about selecting data from multiple relatedtables, see "Selecting Data from Multiple Tables" on page 181. In addition,"Selecting Aggregate Data" on page 191 describes how to group your dataand perform calculations on the data in one or more columns.

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

About this chapter

Contents

Page 176: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Introduction

164

IntroductionThe SELECT statement is a versatile command. SELECT statements canbecome highly complex in applications retrieving very specific informationfrom 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. Thesample database contains information about employees, departments, salesorders, and so on.

About this chapter

If you want to know… Then see…

How to view information in a table withInteractive SQL

"Viewing information in a table withInteractive SQL" on page 166

How to enter query results "Ordering query results" on page 168

How to select columns from a table "Selecting columns from a table" onpage 170

How to select rows from a table "Selecting rows from a table" onpage 171

How to compare dates in queries "Comparing dates in queries" onpage 172

How to use Pattern matching "Pattern matching in searchconditions" on page 173

How to match rows by sound "Matching rows by sound" onpage 174

How to use compound search conditions "Compound search conditions in theWHERE clause" on page 175

Where to find information about shortcuts for search conditions

"Short cuts for typing searchconditions" on page 176

Where to find information aboutcommand files

"Running command files" onpage 177

Ideally, you should be running the Adaptive Server Anywhere software onyour computer while you read and work through the examples in thischapter.

Notes

Page 177: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 12 Selecting Data from Database Tables

165

v To start Interactive SQL from Sybase Central:

♦ To start Interactive SQL, right-click the database in Sybase Central andchoose File➤Open Interactive SQL.

or

To start Interactive SQL without a connection to a database, chooseTools➤Adaptive Server Anywhere➤Open Interactive SQL. TheConnect dialog automatically appears.

v To start Interactive SQL on its own:

♦ Select Interactive SQL from the Adaptive Server Anywhere programgroup in the Start menu. You can also type dbisql at a commandprompt.

or

♦ Type the following command at a system prompt:

dbisql

v To connect to the sample database from Sybase Central:

1 Start Sybase Central

Choose Start➤Programs➤Sybase SQL Anywhere 7➤Sybase Central4.0.

2 Open the Connect dialog.

♦ Click Tools➤Connect.

♦ If you are presented with a list of plugins, choose Adaptive ServerAnywhere from the list.

The Connect dialog appears:

3 Select the ODBC Data Source Name option and click Browse. In theresulting list, choose ASA 7.0 Sample.

4 Click OK to establish the connection.

Each example instructs you to type commands into Interactive SQL anddescribes what you will see on your computer screen. If you cannot run thesoftware as you read the tutorials, you will still be able to learn about SQLbut you will not have the opportunity to experiment on your own.

Page 178: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Looking at the information in a table

166

Looking at the information in a tableTo view the information in a database’s tables, you use commands. You canenter multiple commands by separating them with semicolons.

Viewing information in a table with Interactive SQL

You use the SELECT statement to view data from one or more tables. In thislesson, you look at one of the tables in the database. The command used willlook at everything in a table called employee.

v To view the employee table:

♦ Type the following in the Interactive SQL command window:

SELECT * FROM Employee

The SELECT statement retrieves all the rows and columns of the employeetable, and the Interactive SQL Data window lists those that will fit:

Emp_id Manager_id Emp_fname emp_lname dept_id

102 501 Fran Whitney 100

105 501 Matthew Cobb 100

129 902 Philip Chin 200

148 1293 Julie Jordan 300

160 501 Robert Breault 100

You will also see some information in the Interactive SQL statistics window.This information is explained later.

The table name employee is shown starting with an upper case E, eventhough the real table name is all lower case. Adaptive Server Anywheredatabases can be created as case-sensitive or case-insensitive in their stringcomparisons, but are always case insensitive in their use of identifiers.

$ For information on creating databases, see "Creating a database" onpage 111 of the book ASA User’s Guide, or "The Initialization utility" onpage 92 of the book ASA Reference.

You can type select or Select instead of SELECT. You can enter SQLkeywords in upper case, lower case, or any combination of the two. In themanuals, upper case letters are generally used for SQL keywords.

Case sensitivity

Page 179: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 12 Selecting Data from Database Tables

167

The employee table contains a number of rows organized into columns.Each column has a name, such as emp_lname or emp_id. There is a row foreach employee of the company, and each row has a value in each column.For example, the employee with employee ID 102 is Fran Whitney. Hermanager has employee ID 501.

TipsSQL keywords are case insensitive, meaning it doesn’t matter how youcapitalize them. For example, SELECT is the same as Select, which isthe same as select. Some objects in the database (such as table andcolumn 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 pressingENTER at the end of each line. Some SQL statements, such as the SELECTstatement, consist of several parts, called clauses. In many examples, eachclause is placed on a separate line for easier reading. You do not have totype them this way for them to process correctly.

A SELECTstatement returnsrows of data

Page 180: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Ordering query results

168

Ordering query resultsUnless otherwise requested, the database server returns the rows of a table inan order that has no meaning. Often it is useful to look at the rows in a tablein a more meaningful sequence. For example, you might like to seeemployees in alphabetical order.

The following example shows how adding an ORDER BY clause to theSELECT statement causes the results to be retrieved in alphabetical order.

v List the employees in alphabetical order:

♦ Type the following in the Interactive SQL command window:

SELECT * FROM employee ORDER BY emp_lname

Emp_id manager_id emp_fname emp_lname dept_id

1751 1576 Alex Ahmed 400

1013 703 Joseph Barker 500

591 1576 Irene Barletta 400

191 703 Jeannette Bertrand 500

1336 1293 Janet Bigelow 300

The order of the clauses is important. The ORDER BY clause must followthe FROM clause and the SELECT clause.

Ordering query results to improve performance

Sometimes there is more than one possible way for Adaptive ServerAnywhere to execute a query with an ORDER BY clause. You can useindexes to enable the database server to search the tables more efficiently.

An example of a query that can be executed in more than one possible way isone that has both a WHERE clause and an ORDER BY clause.

SELECT *FROM customerWHERE id > 300ORDER BY company_name

In this example, the server must decide between two strategies:

1 Go through the entire customer table in order by company name,checking each row to see if the customer id is greater than 300.

Notes

Queries with WHEREand ORDER BYclauses

Page 181: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 12 Selecting Data from Database Tables

169

2 Use the key on the id column to read only the companies with id greaterthan 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 betterbecause only a few rows are scanned and quickly sorted. If most of the idvalues are greater than 300, the first strategy is much better because nosorting is necessary.

The example above could be solved by creating a two-column index on idand company_name. (The order of the two columns is important.) Theserver could then use this index to select rows from the table and have themin the correct order. However, keep in mind that indexes take up space in thedatabase file and involve some overhead to keep up to date. Do not createindexes indiscriminately.

Solving theproblem

Page 182: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Selecting columns from a table

170

Selecting columns from a tableOften, you are only interested in some of the columns in a table. Forexample, to make up birthday cards for employees you might want to see theemp_lname, dept_id, and birth_date columns.

v List the last name, department, and birthdate of each employee in:

♦ Type the following:

SELECT emp_lname, dept_id, birth_dateFROM employee

emp_lname dept_id birth_date

Whitney 100 1958-06-05

Cobb 100 1960-12-04

Chin 200 1966-10-30

Jordan 300 1951-12-13

Breault 100 1947-05-13

The three columns appear in the order in which you typed them in theSELECT statement. If you want to rearrange the columns, simply change theorder of the column names in the statement. For example, to put thebirth_date column on the left, use the following statement:

SELECT birth_date, emp_lname , dept_idFROM employee

You can order rows and look at only certain columns at the same time asfollows:

SELECT birth_date, emp_lname , dept_idFROM employeeORDER BY emp_lname

As you might have guessed, the asterisk in

SELECT * FROM employee

is a short form for all columns in the table.

Rearrangingcolumns

Ordering rows

Page 183: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 12 Selecting Data from Database Tables

171

Selecting rows from a tableSometimes you will not want to see information on all the employees in theemployee table. Adding a WHERE clause to the SELECT statement allowsonly some rows to be selected from a table.

For example, suppose you would like to look at the employees with firstname John.

v List all employees named John:

♦ Type the following:

SELECT *FROM employeeWHERE emp_fname = ’John’

emp_id manager_id emp_fname emp_lname dept_id

318 1576 John Crow 400

862 501 John Sheffield 100

1483 1293 John Letiecq 300

♦ The apostrophes (single quotes) around the name ’John’ are required.They indicate that John is a character string. Quotation marks (doublequotes) have a different meaning. Quotation marks can be used to makeotherwise invalid strings valid for column names and other identifiers.

♦ The sample database is not case sensitive, so you would get the sameresults 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 youtype 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 enterthe statement into the command window in any format. If you use morethan the number of lines that fit on the screen, the text scrolls in theCommand window.

Again, you can combine what you have learned:

SELECT emp_fname, emp_lname, birth_dateFROM employeeWHERE emp_fname = ’John’ORDER BY birth_date

The WHERE clause uses a search condition to select rows. In this case thesearch condition is emp_fname = ’John’.

Notes

Page 184: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Comparing dates in queries

172

Comparing dates in queriesSometimes, you will not know exactly what value you are looking for, or youwould like to see a set of values. You can use comparisons, other thanequals, in the WHERE clause to select a set of rows that satisfy the searchcondition. The following example shows the use of a date inequality searchcondition.

v List all employees born before March 3, 1964:

♦ Type the following:

SELECT emp_lname, birth_dateFROM employeeWHERE birth_date < ’March 3, 1964’

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, andautomatically converts the string ’March 3, 1964’ to a date.

Page 185: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 12 Selecting Data from Database Tables

173

Pattern matching in search conditionsAnother useful type of search condition is a pattern match. In SQL, the wordLIKE is used to search for patterns. The use of LIKE can be explained byexample.

v List all employees whose last name begins with BR:

♦ Type the following:

SELECT emp_lname, emp_fnameFROM employeeWHERE emp_lname LIKE ’br%’

emp_lname emp_fname

Breault Robert

Braun Jane

The % in the search condition indicates that any number of other charactersmay follow the letters BR.

v List all employees whose surname begins with BR, followed by zeroor more letters and a T, followed by zero or more letters:

♦ Type the following:

SELECT emp_lname, emp_fnameFROM employeeWHERE emp_lname LIKE ’BR%T%’

emp_lname emp_fname

Breault Robert

The first % sign matches the string eaul, while the second % sign matchesthe 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 thefourth letter. In Braun the matches the letter A and the % matches N.

Page 186: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Matching rows by sound

174

Matching rows by soundWith the SOUNDEX function, you can match rows by sound, as well as byspelling. For example, suppose a phone message was left for a name thatsounded like "Ms. Brown". Which employees in the company have namesthat sound like Brown?

v List employees with surnames that sound like Brown:

♦ Type the following:

SELECT emp_lname, emp_fnameFROM employeeWHERE SOUNDEX( emp_lname ) = SOUNDEX( ’Brown’ )

emp_lname emp_fname

Braun Jane

Jane Braun is the only employee matching the search condition.

Page 187: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 12 Selecting Data from Database Tables

175

Compound search conditions in the WHEREclause

We have seen how equal (=) and less than (<) work as comparison operators.Adaptive Server Anywhere also supports other comparison operators, suchas greater than (>), greater than or equal (>=), less than or equal (<=), andnot equal (<>), as well as the functions LIKE and SOUNDEX.

These conditions can be combined using AND and OR to make morecomplicated search conditions.

v List all employees born before March 3, 1964, but exclude theemployee named Whitney:

♦ Type the following:

SELECT emp_lname, birth_dateFROM employeeWHERE 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

Page 188: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Short cuts for typing search conditions

176

Short cuts for typing search conditionsSQL has two short forms for typing in search conditions. The first,BETWEEN, is used when you are looking for a range of values. For examplethe following query:

SELECT emp_lname, birth_dateFROM employeeWHERE birth_date BETWEEN ’1963-1-1’AND ’1965-3-31’

is equivalent to the following:

SELECT emp_lname, birth_dateFROM employeeWHERE birth_date >= ’1963-1-1’AND birth_date <= ’1965-3-31’

The second short form, IN, may be used when looking for one of a numberof values. The command

SELECT emp_lname, emp_idFROM employeeWHERE emp_lname IN (’yeung’,’bucceri’,’charlton’)

means the same as:

SELECT emp_lname, emp_idFROM employeeWHERE emp_lname = ’yeung’OR emp_lname = ’bucceri’OR emp_lname = ’charlton’

Using theshortformBETWEEN

Using the shortform IN

Page 189: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 12 Selecting Data from Database Tables

177

Running command filesThis section describes how to use the Interactive SQL command window toenter multiple commands at a time and how to process files consisting of aset of commands.

Entering multiple statements

SQL statements can get quite large. You have already seen how to use theeditor to enter statements on several lines. The Interactive SQL environmentalso allows multiple commands to be entered at the same time. This is doneby ending each statement with a semi-colon (;).

v To enter multiple statement in the Interactive SQL Commandwindow

1 Try entering the following three commands into the Command window.

UPDATE employeeSET dept_id = 400, manager_id = 1576WHERE emp_id = 467;

UPDATE employeeSET dept_id = 400, manager_id = 1576WHERE emp_id = 195;

SELECT *FROM employeeWHERE emp_id IN ( 195, 467 )

2 Press the execute key (F9). All three statements are executed. Afterexecution, the commands are left in the Command window.

Notice that the data for each command remains in the Data window onlyuntil the next command is executed. To keep a record of your data, you cansave the output of each statement to a separate file. If statement1 andstatement2 are two SELECT statements, then you can output them to file1and file2, respectively, as follows:

Statement1; OUTPUT TO file1;statement2; OUTPUT TO file2;

Example: enteringmultiple statements

Outputting data toa file

Page 190: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Running command files

178

Saving statements as command files

You can save commands you enter in Interactive SQL to a command file.This keeps a permanent record of the SQL commands so they can be usedlater if you wish.

v To save statements as a command file:

1 Choose File ➤Save As from the menu bar. You are then prompted for afilename.

2 Type a file name (for example, transfer.sql) and press ENTER.

3 The command file can be run using the Interactive SQL READcommand, but you should rollback the changes first. Press the ESCAPE

key to clear the editor and then execute the ROLLBACK WORKcommand.

4 Now enter the following command:

READ transfer.sql

This command executes the command file transfer.sql which containsthe three commands that we saved previously. As each command isexecuted, it flashes up in the Command window.

Command files are just ASCII files containing SQL statements as you seethem 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 beexecuted. Command files are also commonly called scripts.

Executing command files

You can execute command files in the following ways:

♦ You can use the Interactive SQL READ command to execute commandfiles.

The following statement executes the file temp.sql:

READ temp.sql

♦ You can load a command file into the Interactive SQL Commandwindow and execute it directly from there.

You load command files back into the Command window by choosingFile ➤Open. Enter transfer.sql when prompted for the file name.

♦ You can supply a command file as a command line argument forInteractive SQL.

What arecommand files?

Page 191: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 12 Selecting Data from Database Tables

179

The Command window in Interactive SQL has a limit of 500 lines. Forcommand files larger than this, you should use a generic editor capable ofhandling large files. The READ command has no limit on the number oflines that can be read.

Page 192: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Running command files

180

Page 193: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

181

C H A P T E R 1 3

Selecting Data from Multiple Tables

This chapter describes database queries that look at information in more thanone table. To do this, SQL provides the JOIN operator. There are severaldifferent ways to join tables together in queries, and this chapter describessome of the more important ones.

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

About this chapter

Contents

Page 194: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Viewing information from several tables

182

Viewing information from several tablesSometimes it is necessary to view data from multiple related tables. To dothis, you use a join to view the data in a useful and meaningful way.

About this chapter

If you want to know… Then see…

How to display a list of tables "Displaying a list of tables" onpage 182

How to display all combinations of datafrom two tables

"Joining tables with the crossproduct" on page 184

How to make a join useful "Restricting a join" on page 185

How to join two tables in which the join’sforeign keys have the same name

"Joining tables using key joins" onpage 186

How to join tables on columns with thesame names

"Joining tables using natural joins" onpage 188

Displaying a list of tables

In Interactive SQL, you can display a list of tables by pressing the F7 key.The tables for the database are prefixed with dba (the owner of the tables).

Page 195: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 13 Selecting Data from Multiple Tables

183

Positioning the highlight on a particular table and pressing the Columnsbutton displays the list of columns for that table. The ESCAPE key takes youback to the table list and pressing it again will take you back to the commandwindow. Pressing ENTER instead of ESCAPE copies the highlighted table orcolumn name into the command window at the current cursor position.

Press ESCAPE to leave the list.

Page 196: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Joining tables with the cross product

184

Joining tables with the cross productOne of the tables in the sample database is sales_order, which lists theorders placed to the company. Each order has a sales_rep column,containing the employee ID of the sales representative responsible for theorder. There are 648 rows in the sales_order table.

You can get information from two tables at the same time by listing bothtables in the FROM clause of a SELECT query.

The following example lists all the data in the employee table and thesales_order table:

SELECT *FROM sales_orderCROSS JOIN employee

The results of this query, displayed in the Interactive SQL data window,match every row in the employee table with every row in the sales_ordertable. Since there are 75 rows in the employee table and 648 rows in thesales_order table, there are 75 × 648 = 48,600 rows in the result of the join.Each row consists of all columns from the sales_order table followed by allcolumns from the employee table. This join is called a full cross product.

The cross product join is a simple starting point for understanding joins, butnot very useful in itself.

Example

Page 197: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 13 Selecting Data from Multiple Tables

185

Restricting a joinConsider the sales_order and employee tables. The most natural way tomake a join between these tables useful is to insist that the sales_rep in thesales_order table be the same as the one in the employee table in every rowof the result. Then each row contains information about an order and thesales representative responsible for it.

To do this, add an ON phrase to the previous query to show the list ofemployees and their course registrations.

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 notstrictly required in this case, using the table name prefix clarifies thestatement, and is required when two tables have a column with the samename. 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 thesales_order table). Of the original 48,600 rows in the join, only 648 of themhave the employee number equal in the two tables.

The following query is a modified version that fetches only some of thecolumns and orders the results.

v Modify the query:

♦ Type the following in the Interactive SQL command window:

SELECT employee.emp_lname, sales_order.id,sales_order.order_date

FROM sales_order JOIN employeeON sales_order.sales_rep = employee.emp_idORDER BY employee.emp_lname

You can also create joins in Visual Basic. In this example, you will create aform to display all of the sales orders, grouped by the employee who dealtwith them.

Example 1

Example 2

Page 198: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Joining tables using key joins

186

Joining tables using key joinsMany common joins are between two tables related by a foreign key. Themost common join restricts foreign key values to be equal to primary keyvalues. The example you have already seen restricts foreign key values in thesales_order table to be equal to the primary key values in the employeetable.

SELECT emp_lname, id, order_dateFROM sales_order JOIN employee

ON sales_order.sales_rep = employee.emp_id

The query can be more simply expressed using a KEY JOIN:

SELECT emp_lname, id, order_dateFROM sales_order

KEY JOIN employee

The join operator KEY JOIN is just a short cut for typing the ON phrase; thetwo queries are identical.

If you look at the diagram of the employee database, foreign keys arerepresented by lines between tables. You can use the KEY JOIN operatoranywhere two tables are joined by a line in the diagram.

$ To view the employee database diagram, see "The sample database" onpage 124.

Two or more tables can be joined using join operators. The following queryuses four tables to list the total value of the orders placed by each customer.It connects the four tables customer, sales_order, sales_order_items andproduct using the single foreign-key relationships between each pair ofthese tables.

SELECT company_name,SUM(sales_order_items.quantity *

product.unit_price) AS valueFROM customer

KEY JOIN sales_orderKEY JOIN sales_order_itemsKEY JOIN product

GROUP BY company_name

Joining more thantwo tables

Page 199: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 13 Selecting Data from Multiple Tables

187

Company_name value

Able Inc. 6120

AMF Corp. 3624

Amo & Sons 3216

Amy’s Silk Screening 2028

Avco Ent 1752

… …

The example above uses the SUM operator, which is an example of anaggregate function. Aggregate functions work with GROUP BY clauses toreturn values for each row group. In this example, the sum ofsales_order_items.quantity * product.unit_price – that is, thetotal amount of money paid per product type – is calculated for eachcompany_name, thereby returning each company's sales.

$ For more information on aggregate functions, see "A first look ataggregate functions" on page 193.

Note

Page 200: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Joining tables using natural joins

188

Joining tables using natural joinsThe NATURAL JOIN operator joins two tables based on common columnnames. In other words, Adaptive Server Anywhere generates a ON phrasethat equates the common columns from each table.

For example, for the following query:

SELECT emp_lname, dept_nameFROM employee

NATURAL JOIN department

the database server looks at the two tables and determines that the onlycolumn name they have in common is dept_id. The following ON phrase isinternally generated and used to perform the join:

FROM employee JOIN departmentON employee.dept_id = department.dept_id

This join operator can cause problems by equating columns you may notintend to be equated. For example, the following query generates unwantedresults:

SELECT *FROM sales_orderNATURAL JOIN customer

The result of this query has no rows.

The database server internally generates the following ON phrase:

FROM sales_order JOIN customerON sales_order.id = customer.id

The id column in the sales_order table is an ID number for the order. TheID column in the customer table is an ID number for the customer. None ofthem matched. Of course, even if a match were found, it would be ameaningless one.

Example

Errors usingNATURAL JOIN

Page 201: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 13 Selecting Data from Multiple Tables

189

Joining tables using outer joinsIn the previous examples, you created joins to display all data from two ormore tables with matching key values. These joins are called inner joins.Sometimes, you may wish to display all data from a table containing aprimary key, as well as the data from a second table whose foreign keyvalues match the primary key values of the first table. To do this, you use anouter join.

This SQL statement displays all of the rows of the customer table, along withall of the rows from the sales_order table where the customer ID fieldagrees:

Select *from customer, sales_orderleft outer join sales_orderon customer_id = sales_order.cust_id

The result set of this SQL statement will be all of the rows from the customertable, and whenever a customer has placed one or more orders, then thatcustomer’s orders from the sales_order table will be displayed alongside hispersonal information from the customer table.

Creating outer joins on three or more tables

You can create multiple outer joins in a SQL statement. However, outer joinscan sometimes be ambiguous. For instance, consider a SELECT statement ofthe following form:

Select *from tableA, tableB, tableCleft outer join tableAon tableA.colA = tableB.colBleft outer join tableBon tableB.colB = tableC.colC

In this case, it is unclear how the user wants SQL to evaluate this statement.If the first outer join is performed first, then all of the rows of tableA will beextracted, as well as those of tableB which match rows in tableA, and thosein tableC which match rows in tableB. If, however, the second outer join isperformed first, the all of the rows of tableB will be extracted, along those intableC and tableA that match tableB’s rows. You can remove this ambiguityby using parentheses to instruct SQL how to evaluate the statements.

This example illustrates some of the complexity that you can build intoqueries. For more information on joins, see "Joins: Retrieving Data fromSeveral Tables" on page 189 of the book ASA User’s Guide in the ASA User’sGuide.

Example

Page 202: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Joining tables using outer joins

190

Page 203: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

191

C H A P T E R 1 4

Selecting Aggregate Data

This chapter describes how to construct queries that tell you aggregateinformation. 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

Topic Page

Summarizing data 192

A first look at aggregate functions 193

Using aggregate functions to obtain grouped data 194

Restricting groups 196

About this chapter

Contents

Page 204: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Summarizing data

192

Summarizing dataSometimes it is worthwhile to examine aspects of the data in your table thatyou can’t see with simple queries. For example, you may wish to find theaverage amount of money that a customer pays for an order, or to see howmany employees work for each department. For these types of tasks you useaggregate functions.

About this chapter

If you want to know… Then see…

How to view summary information aboutan entire table

"A first look at aggregate functions"on page 193

How to view summary information aboutgroups in a table

"Using aggregate functions to obtaingrouped data" on page 194

How to view summary data about arestricted set of groups in a table

"Restricting groups" on page 196

Page 205: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 14 Selecting Aggregate Data

193

A first look at aggregate functionsSuppose you want to know how many employees there are. The followingstatement retrieves the number of rows in the employee table:

SELECT count( * )FROM employee

count( * )

75

The result returned from this query is a table with only one column (with titlecount( * )) 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

count( * ) min( birth_date ) max( birth_date )

75 1936-01-02 1973-01-18

The result set from this query has three columns and only one row. The threecolumns contain the number of employees, the birthdate of the oldestemployee, and the birthdate of the youngest employee.

COUNT, MIN and MAX are called aggregate functions. Each of thesefunctions summarizes information for an entire table. In total, there are sixaggregate functions: MIN, MAX, COUNT, AVG, SUM, and LIST. All butCOUNT have the name of a column as a parameter. As you have seen,COUNT has an asterisk as its parameter.

Page 206: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Using aggregate functions to obtain grouped data

194

Using aggregate functions to obtain groupeddata

In addition to providing information about an entire table, aggregatefunctions can be used on groups of rows.

v To list the number of orders each sales representative isresponsible for:

♦ Type the following:

SELECT sales_rep, count( * )FROM sales_orderGROUP BY sales_rep

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 tablewith that number.

Whenever GROUP BY is used, the resulting table has one row for eachdifferent value found in the GROUP BY column or columns.

You can also view grouped data in Visual Basic.

A common error with GROUP BY is to try to get information that cannotproperly be put in a group. For example,

SELECT sales_rep, emp_lname, count( * )FROM sales_order

KEY JOIN employeeGROUP BY sales_rep

gives the following error:

Function or column reference to ’emp_lname’ in the select list must alsoappear in a GROUP BY

SQL does not realize that each of the result rows for an employee with agiven ID have the same value of emp_lname. An error is reported since SQLdoes not know which of the names to display.

A common errorwith GROUP BY

Page 207: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 14 Selecting Aggregate Data

195

However, the following is valid:

SELECT sales_rep, max( emp_lname ), count( * )FROM sales_order

KEY JOIN employeeGROUP BY sales_rep

The max function chooses the maximum (last alphabetically) surname fromthe detail rows for each group. The surname is the same on every detail rowwithin a group so the max is just a trick to bypass a limitation of SQL.

These examples both use joins. Joins are a way of displaying data frommultiple tables in a meaningful way. For more information on joins, see"Selecting Data from Multiple Tables" on page 181.

Note

Page 208: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Restricting groups

196

Restricting groupsYou have already seen how to restrict rows in a query using the WHEREclause. You can restrict GROUP BY clauses by using the HAVINGkeyword.

v To list all sales reps with more than 55 orders:

♦ Type the following:

SELECT sales_rep, count( * )FROM sales_orderKEY JOIN employeeGROUP BY sales_repHAVING count( * ) > 55

sales_rep count( * )

129 57

299 114

467 56

1142 57

Order of clausesGROUP BY must always appear before HAVING. In the same manner,WHERE must appear before GROUP BY.

HAVING clauses and WHERE clauses can be combined. When combiningthese clauses, the efficiency of the query can depend on whether criteria areplaced in the HAVING clause or in the WHERE clause. Criteria in theHAVING clause restrict the rows of the result only after the groups havebeen constructed. Criteria in the WHERE clause are evaluated before thegroups are constructed, and save time.

v To list all sales reps with more than 55 orders and an ID of morethan 1000:

♦ Type the following:

SELECT sales_rep, count( * )FROM sales_orderKEY JOIN employeeWHERE sales_rep > 1000GROUP BY sales_repHAVING count( * ) > 55

Page 209: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 14 Selecting Aggregate Data

197

The following statement produces the same results.

v To list all sales reps with more than 55 orders and an ID of morethan 1000:

♦ Type the following:

SELECT sales_rep, count( * )FROM sales_orderKEY JOIN employeeGROUP BY sales_repHAVING count( * ) > 55AND sales_rep > 1000

The first statement is faster because it can eliminate making up groups forsome of the employees. The second statement builds a group for each salesrep and then eliminates the groups with wrong employee numbers. Forexample, in the first statement, the database engine would not have to makeup 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 eliminatethat group with the HAVING clause.

Fortunately, Adaptive Server Anywhere detects this particular problem andchanges the second query to be the same as the first. Adaptive ServerAnywhere performs this optimization with simple conditions (nothinginvolving OR or IN). For this reason, when constructing queries with both aWHERE clause and a HAVING clause, you should be careful to put as manyof the conditions as possible in the WHERE clause.

Page 210: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Restricting groups

198

Page 211: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

199

C H A P T E R 1 5

Selecting Data Using Subqueries

This chapter shows how to use the results of one query as part of anotherSELECT statement. This is a useful tool in building more complex andinformative queries.

Topic Page

Introducing subqueries 200

Preparing to use subqueries 201

A simple subquery 202

Comparisons using subqueries 204

Using subqueries instead of joins 206

About this chapter

Contents

Page 212: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Introducing subqueries

200

Introducing subqueriesA relational database allows you to store related data in more than one table.The section "Selecting Data from Multiple Tables" on page 181 outlines oneway of extracting data from related tables. A second method involvessubqueries – queries that appear in another query's WHERE clause orHAVING clause.

About this chapter

If you want to know… Then see…

When subqueries are used "Preparing to use subqueries" onpage 201

An example of a simple subquery "A simple subquery" on page 202

How to compare column values to asingle value returned by a subquery

"Comparisons using subqueries" onpage 204

How to use a subquery instead of a join "Using subqueries instead of joins"on page 206

Page 213: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 15 Selecting Data Using Subqueries

201

Preparing to use subqueriesSometimes it is useful to use the results of one statement as part of anotherstatement.

For example, suppose that you need a list of order items for products that arelow in stock.

You can look up the products for which there are less than 20 items in stockin the product table.

v To list all products for which there are less than 20 items in stock:

♦ Type the following:

SELECT id, description, quantityFROM productWHERE quantity < 20

Id description quantity

401 Wool cap 12

This query shows that only wool caps are low in stock.

You can list all the order items for wool caps with the following query:

v To list all orders for wool caps, most recent first:

♦ Type the following:

SELECT *FROM sales_order_itemsWHERE prod_id = 401ORDER BY ship_date DESC

Id line_id prod_id quantity ship_date

2082 1 401 48 1994-07-09

2053 1 401 60 1994-06-30

2125 2 401 36 1994-06-28

2027 1 401 12 1994-06-17

2062 1 401 36 1994-06-17

This two-step process of identifying items low in stock and identifyingorders for those items can be combined into a single query using subqueries.

Example 1

Example 2

Page 214: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

A simple subquery

202

A simple subqueryIn the previous sections, you had to obtain a result from one SQL statementbefore you used it in another. SQL provides you with a way to use the resultsof one query in another in just one step. The following query incorporates asubquery.

v To list order items for products low in stock:

♦ Type the following:

SELECT *FROM sales_order_itemsWHERE prod_id IN

( SELECT idFROM productWHERE quantity < 20 )

ORDER BY ship_date DESC

id line_id prod_id quantity ship_date

2082 1 401 48 1994-07-09

2053 1 401 60 1994-06-30

2125 2 401 36 1994-06-28

2027 1 401 12 1994-06-17

2062 1 401 36 1994-06-17

By using a subquery, the search can be carried out in just one query, insteadof using one query to find the list of low-stock products and a second to findorders for those products.

The subquery in the statement is the phrase enclosed in parentheses:

( SELECT idFROM productWHERE quantity < 20 )

The subquery makes a list of all values in the id column in the product tablesatisfying the WHERE clause search condition.

Consider what would happen if an order for ten tank tops were shipped sothat the quantity column for tank tops contained the value 18. The queryusing 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 tothe following:

Example 1

Example 2

Page 215: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 15 Selecting Data Using Subqueries

203

SELECT *FROM sales_order_itemsWHERE prod_id IN ( 401, 300 )ORDER BY ship_date DESC

The command using the subquery is an improvement because it still workseven if data in the database is changed.

Page 216: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Comparisons using subqueries

204

Comparisons using subqueriesTwo tables in the sample database are concerned with financial results. Thefin_code table is a small table holding the different codes for financial dataand their meanings:

v To list the revenue items from the fin_data table:

♦ Type the following:

SELECT *FROM fin_dataWHERE fin_data.code IN

( SELECT fin_code.codeFROM fin_codeWHERE type = ’revenue’ )

year quarter code amount

1992 Q1 r1 1023

1992 Q2 r1 2033

1992 Q3 r1 2998

1992 Q4 r1 3014

1993 Q1 r1 3114

This example has used qualifiers to clearly identify the table to which thecode column in each reference belongs. In this particular example, thequalifiers could have been omitted.

In general, subqueries are restricted to one column name listed betweenSELECT and FROM: one select-list item. The following example does notmake sense, since SQL would not know which column from fin_code tocompare to the fin_data.code column.

SELECT *FROM fin_dataWHERE fin_data.code IN

( SELECT fin_code.code, fin_code.typeFROM fin_codeWHERE 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. Forexample the following command results in an error since the subqueryreturns two rows:

Notes aboutsubqueries

Page 217: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 15 Selecting Data Using Subqueries

205

SELECT *FROM fin_dataWHERE fin_data.code =

( SELECT fin_code.codeFROM fin_codeWHERE type = ’revenue’ )

The IN comparison allows several rows. Two other keywords can be used asqualifiers for operators to allow them to work with multiple rows: ANY andALL.

The following query is identical to the successful query above:

SELECT *FROM fin_dataWHERE fin_data.code = ANY

( SELECT fin_code.codeFROM fin_codeWHERE type = ’revenue’ )

While the = ANY condition is identical to the IN condition, ANY can also beused with inequalities such as, or, to give more flexible use of subqueries.

The word ALL is similar to the word ANY. For example, the followingquery lists financial data that is not revenues:

SELECT *FROM fin_dataWHERE fin_data.code <> ALL

( SELECT fin_code.codeFROM fin_codeWHERE type = ’revenue’ )

This is equivalent to the following command using NOT IN:

SELECT *FROM fin_dataWHERE fin_data.code NOT IN

( SELECT fin_code.codeFROM fin_codeWHERE type = ’revenue’ )

Page 218: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Using subqueries instead of joins

206

Using subqueries instead of joinsSuppose you need a chronological list of orders and the company that placedthem, but would like the company name instead of their customer ID. Youcan get this result using a join as follows:

v To list the order id, date, and company name for each order sincethe beginning of 1994:

♦ Type the following:

SELECT sales_order.id,sales_order.order_date,customer.company_name

FROM sales_orderKEY JOIN customer

WHERE order_date > ’1994/01/01’ORDER BY order_date

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

$ For more on joins, see "Selecting Data from Multiple Tables" onpage 181.

The following statement obtains the same results using a subquery instead ofa join:

SELECT sales_order.id,sales_order.order_date,( SELECT company_name FROM customer

WHERE customer.id = sales_order.cust_id )FROM sales_orderWHERE order_date > ’1994/01/01’ORDER BY order_date

The subquery refers to the cust_id column in the sales_order table eventhough the sales_order table is not part of the subquery. Instead, thesales_order.cust_id column refers to the sales_order table in the main bodyof the statement. This is called an outer reference. Any subquery thatcontains an outer reference is called a correlated subquery.

Using a join

Using a subquery

Page 219: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 15 Selecting Data Using Subqueries

207

A subquery can be used instead of a join whenever only one column isrequired from the other table. (Recall that subqueries can only return onecolumn.) In this example, you only needed the company_name column sothe join could be changed into a subquery.

If the subquery might have no result, this method is called an outer join. Thejoin in previous sections of the tutorial is more fully called an inner join.

v To list all customers in Washington state together with their mostrecent order ID:

♦ Type the following:

SELECT company_name, state,( SELECT MAX( id )

FROM sales_orderWHERE sales_order.cust_id = customer.id )

FROM customerWHERE state = ’WA’

company_name state MAX(id)

Custom Designs WA 2547

It’s a Hit! WA (NULL)

The It’s a Hit! company placed no orders, and the subquery returns NULLfor this customer. Companies who have not placed an order are not listedwhen inner joins are used.

You could also specify an outer join explicitly. In this case a GROUP BYclause is also required.

SELECT company_name, state,MAX( sales_order.id )

FROM customerKEY LEFT OUTER JOIN sales_order

WHERE state = ’WA’GROUP BY company_name, state

Using an outer join

Page 220: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Using subqueries instead of joins

208

Page 221: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

209

C H A P T E R 1 6

Updating the Database

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 thecontents of rows, as well as how to make changes permanent or correctchanges you have made.

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

About this chapter

Contents

Page 222: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Introduction

210

IntroductionTo keep data current in your database, you need to know how to makechanges to it. You can add rows to your table to include new data, or you candelete rows in your table to exclude outdated data. To update your existingrecords, you can modify rows in your table. Finally, to ensure the integrity ofyour database, you can check for errors.

About this chapter

If you want to know… Then see…

How to add rows to your table "Adding rows to a table" on page 211

How to update rows in your table "Modifying rows in a table" onpage 212

How to impliment transactions "Transactions in SQL" on page 213

How to delete rows in your table "Deleting rows" on page 216

How to check for errors in your data "Integrity checking" on page 217

Page 223: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 16 Updating the Database

211

Adding rows to a tableSuppose that the company decides to sell a new product, a brown acrylicvest. This action requires you to add data to the product table of the sampledatabase.

v To add a brown acrylic vest to the product table in Interactive SQL:

♦ You can add this information to the database using the followingINSERT statement:

INSERTINTO product ( id, name, description, size, color,quantity, unit_price )VALUES ( 800, ’Vest’, ’Acrylic Vest’, ’Extra Large’,’Brown’, 42, 20.00 )

If you make a mistake and forget to specify one of the columns,Adaptive Server Anywhere reports an error.

The NULL value is a special value used to indicate that something is eithernot known or not applicable. Some columns are allowed to contain theNULL value, and others are not.

NULL values incolumns

Page 224: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Modifying rows in a table

212

Modifying rows in a tableIn most databases, you need to update records that are already stored in thedatabase. For example, the manager ID should change when employees aretransferred between departments, as well as the department ID.

v To transfer employee #195 to department 400 in Interactive SQL:

♦ The following statement carries out both updates at the same time foremployee Marc Dill (employee ID 195):

UPDATE employeeSET dept_id = 400, manager_id = 1576WHERE emp_id = 195

Since SQL updates all rows that satisfy the conditions of the WHERE clause,sometimes more than one row is updated at one time. For example, if a groupof sales employees are transferred into marketing and have their dept_idcolumn updated, the following statement sets the manager_id for allemployees in the marketing department to 1576.

UPDATE employeeSET manager_id = 1576WHERE dept_id = 400

For employees already in the marketing department, no change is made.

The UPDATE andINSERTcommands

Page 225: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 16 Updating the Database

213

Transactions in SQLAdaptive Server Anywhere expects you to group your commands intotransactions. You commit a transaction to make changes to your databasepermanent. When you alter your data, your alterations are not madepermanent right away. Instead, they are stored in your transaction log andmade are permanent when you enter the COMMIT command.

Knowing which commands or actions signify the start or end of a transactionlets you take full advantage of transactions.

Transactions start with one of the following events:

♦ The first statement following a connection to a database

♦ The first statement following the end of a transaction

Transactions complete with one of the following events:

♦ A COMMIT statement makes the changes to the database permanent.

♦ A ROLLBACK statement undoes all the changes made by thetransaction.

♦ A statement with a side effect of an automatic commit is executed:Database definition commands, such as ALTER, CREATE,COMMENT, and DROP all have the side effect of an automaticcommit.

♦ A disconnection from a database performs an implicit rollback.

Interactive SQL provides you with two options which let you control whenand how transactions end:

♦ If you set the option AUTO_COMMIT to ON, Interactive SQLautomatically commits your results following every successful statementand automatically perform a ROLLBACK after each failed statement.

♦ The setting of the option COMMIT_ON_EXIT controls what happens touncommitted changes when you exit Interactive SQL. If this option isset to ON (the default), Interactive SQL does a COMMIT; otherwise itundoes your uncommitted changes with a ROLLBACK statement.

If you are using a data sourceBy default, ODBC operates in autocommit mode. Even if you have set theAUTO_COMMIT option to OFF in Interactive SQL, ODBC’s setting willoverride Interactive SQL’s. You can change ODBC’s setting by using theSQL_ATTR_AUTOCOMMIT connection attribute. ODBC autocommit isindependent of the CHAINED option.

Startingtransactions

Completingtransactions

Options inInteractive SQL

Page 226: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Transactions in SQL

214

$ Adaptive Server Anywhere also supports Transact-SQL commands,such as BEGIN TRANSACTION, for compatibility with SybaseAdaptive Server Enterprise. For further information, see "An overviewof Transact-SQL support" on page 932 of the book ASA User’s Guidein the ASA User’s Guide.

Making changes permanent

The SQL statement

COMMIT

makes all changes permanent.

You should use the COMMIT command after groups of statements that makesense together. For example, if you want to transfer money from onecustomer’s account to another, you should add money to one customer’saccount, then delete it from the other’s, and then commit, since in this case itdoes not make sense to leave your database with less or more money than itstarted with.

You can instruct Adaptive Server Anywhere to commit your changesautomatically by setting the AUTOCOMMIT option to ON. WhenAUTOCOMMIT is set to ON, Adaptive Server Anywhere must update thedatabase after every insert, update, and delete statement you make to it. Thiscan slow down performace considerably, especially if your database is large.Therefore, it is a good idea to leave the AUTOCOMMIT option set to OFF.

Use COMMIT with careWhen trying the examples in this tutorial, be careful not to COMMIT anychanges until you are sure that you want to change the databasepermanently.

$ For more information on Interactive SQL options, see "Interactive SQLoptions" on page 155 of the book ASA Reference.

Canceling changes

Any uncommitted change you make can be cancelled. SQL allows you toundo all of the changes you made since your last commit with one command:

ROLLBACK

The ROLLBACK statement undoes all changes you have made to thedatabase since the last time you made changes permanent (see "Makingchanges permanent" ON PAGE 214).

The ROLLBACKstatement

Page 227: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 16 Updating the Database

215

$ For more information on Interactive SQL options, see "Interactive SQLoptions" on page 155 of the book ASA Reference.

Transactions and data recovery

Suppose that a system failure or power outage suddenly takes your databaseengine down. Adaptive Server Anywhere is carefully designed to protect theintegrity of your database in such circumstances. It provides you with anumber of independent means of restoring your database. For example, itprovides you with a log file which you may store on a separate drive so thatshould the system failure damage one drive, you still have a means ofrestoring your data. In addition, when you use a log file, Adaptive ServerAnywhere does not have to update your database between COMMITstatements, which improves your database’s performance.

Transaction processing allows the database server to identify states in whichyour data is in a consistent state. Transaction processing ensures that if, forany reason, a transaction is not successfully completed, then the entiretransaction is undone, or rolled back. The database is left entirely unaffectedby failed transactions.

Adaptive Server Anywhere’s transaction processing ensures that the contentsof a transaction are processed securely, even in the event of a system failurein the middle of a transaction.

$ For a detailed description of data recovery mechanisms, see "Backupand Data Recovery" on page 627 of the book ASA User’s Guide in the ASAUser’s Guide.

Page 228: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Deleting rows

216

Deleting rowsSometimes you will want to remove rows from a table. Suppose RodrigoGuevara (employee ID 249) leaves the company. The following statementdeletes Rodrigo Guevara from the employee table.

DELETEFROM employeeWHERE emp_id = 249

With UPDATE and DELETE, the search condition can be as complicated asyou need. For example, if the employee table is being reorganized, thefollowing statement removes from the employee table all male employeeshired between March 3, 1989 and March 3, 1990.

DELETEFROM employeeWHERE 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

Page 229: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 16 Updating the Database

217

Integrity checkingAdaptive Server Anywhere automatically checks for some common errors inyour data.

Inserting duplicate data

For example, suppose you attempt to create a department but supply adept_id value that is already in use:

To do this, enter the command:

INSERTINTO department ( dept_id, dept_name, dept_head_id )VALUES ( 200, ’Eastern Sales’, 902 )

The INSERT is rejected, as it would make the primary key for the table notunique. Since dept_id field is a primary key duplicate values are notpermitted.

Inserting incorrect values

Another mistake is to type an incorrect value. The following statementinserts a new row in the sales_order table, but incorrectly supplies asales_rep ID that does not exist in the employee table.

INSERTINTO sales_order ( id, cust_id, order_date,

sales_rep)VALUES ( 2700, 186, ’1995-10-19’, 284 )

There is a one-to-many relationship between the employee table and thesales_order table, with a join between the sales_rep field of the sales_ordertable and the emp_id field of the employee table. Only after a record in thetable containing the primary key for the join (the employee table) has beenentered can a corresponding record on table containing the foreign key (thesales_order table) be inserted.

The primary key for the employee table is the employee ID number. Thesales rep ID number in the sales_rep table is a foreign key for the employeetable, meaning that each sales rep number in the sales_order table mustmatch the employee ID number for some employee in the employee table.

When you try to add an order for sales rep 284 you get an error message:

No primary key value for foreign key ’ky_so_employee_id’ in table’sales_order’

Foreign key

Page 230: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Integrity checking

218

There isn’t an employee in the employee table with that ID number. Thisprevents you from inserting orders without a valid sales rep ID. This kind ofvalidity checking is called referential integrity checking, as it maintains theintegrity of references among the tables in the database.

$ For more information on primary and foreign keys, see "Relationsbetween tables" on page 87.

Errors on DELETE or UPDATE

Foreign key errors can also arise when doing update or delete operations. Forexample, suppose you try to remove the R&D department from thedepartment table. The dept_id field, being the primary key of the departmenttable, constitutes the ONE side of a one-to-many relationship (the dept_idfield of the employee table is the corresponding foreign key, and henceforms the MANY side). A record on the "one" side of a relationship may notbe deleted until all corresponding records on the MANY side are deleted.

DELETEFROM departmentWHERE dept_id = 100

An error is reported indicating that there are other records in the databasethat reference the R&D department, and the delete operation is not carriedout.

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 allemployees in that department:

DELETEFROM employeeWHERE 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 enteringa ROLLBACK statement:

ROLLBACK WORK

All changes made since the last successful COMMIT WORK will beundone. If you have not done a COMMIT, then all changes since you startedInteractive SQL will be undone.

The same error message is generated if you perform an update operation thatmakes the database inconsistent.

For example, the following UPDATE statement causes an integrity error:

UPDATE department

Example: DELETEerrors

Example: UPDATEerrors

Page 231: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 16 Updating the Database

219

SET dept_id = 600WHERE dept_id = 100

In all of the above examples, the integrity of the database was checked aseach command was executed. Any operation that would result in aninconsistent database is not performed.

It is possible to configure the database so that the integrity is not checkeduntil the COMMIT WORK is done. This is important if you want to changethe value of a referenced primary key; for example, changing the R&Ddepartment’s ID from 100 to 600 in the department and employee tables. Inorder to make these changes, the database has to be inconsistent in betweenthe changes. In this case, you must configure the database to check only oncommits.

$ For more information, see "WAIT_FOR_COMMIT option" onpage 205 of the book ASA Reference.

You can also define foreign keys in such a way that they are automaticallyfixed. In the above example, if the foreign key from employee todepartment were defined with ON UPDATE CASCADE, then updating thedepartment ID would automatically update the employee table.

In the above cases, there is no way to have an inconsistent databasecommitted as permanent. Adaptive Server Anywhere also supportsalternative actions if changes would render the database inconsistent.

$ For more information, see the chapter "Ensuring Data Integrity" onpage 345.

Example: checkingthe integrity afterthe COMMITWORK is complete

Page 232: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Integrity checking

220

Page 233: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

221

C H A P T E R 1 7

System Tables

This chapter describes the system tables, several special tables found inevery Adaptive Server Anywhere database. These system tables describe allthe tables and columns in the database. The database server automaticallyupdates the system table as the database structure is changed.

Topic Page

The system tables 222

The SYSCATALOG table 223

The SYSCOLUMNS table 224

Other system tables 225

About this chapter

Contents

Page 234: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

The system tables

222

The system tablesAdaptive Server Anywhere stores important information about your databasein system tables. The data from tables can be viewed in the same way thatthe data from other tables can be viewed, but you can not update data fromthe system tables.

About this chapter

If you want to know… Then see…

Where to find a listing of all the tables inthe database

"The SYSCATALOG table" onpage 223

Where to find information about thecolumns in a table

"The SYSCOLUMNS table" onpage 224

How to find other information about thetables in your database

"Other system tables" on page 225

Page 235: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 17 System Tables

223

The SYSCATALOG tableThe first system table, syscatalog, lists all the tables in the database. You canview the data from the syscatalog table in the same way that you view thedata from any other table in your database. For more information on viewingdata, see "Looking at the information in a table" on page 166.

Alternately, you can display a lit of all the tables in the database by pressingthe F7 key. This shows a list of the database’s tables, each with a prefix ofDBA, representing the owner of the tables. To leave the list, press ESCAPE.

The owner of the system tables is the special user ID, SYS and the owner ofthe company tables is dba. In addition, there is a set of views owned by thespecial user ID DBO, which provide an emulation of the Sybase SQL Serversystem catalog; these tables are not discussed in this section.

Recall that dba is the user ID you used when connecting to the databasefrom Interactive SQL. So far, you have simply typed the table namesemployee and department; SQL looked in SYSCATALOG for tables withthose names created by dba. In this example, by typingSYS.SYSCATALOG you specified that SYSCATALOG was created bythe user ID SYS. Note the similarity to the way column names are qualified,such as employee.emp_id.

The other columns in this table contain other important information. Forexample, the column named Ncols is the number of columns in each table,and the column named tabletype identifies the table as a permanent table(also called a base table) or a view.

The owner of thesystem tables

Other columns inthe system table

Page 236: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

The SYSCOLUMNS table

224

The SYSCOLUMNS tableAnother important system table is called SYSCOLUMNS describing all thecolumns in all the tables in the database. To see the contents of a table, typethe command, in which tablename represents the name of the table whosecolumns you wish to list:

SELECT *FROM sys.syscolumnsWHERE tname = tablename

This command lists all the columns in the employee table. If you look at thecolumns to the right, you can see from the Coltype column that somecolumns in the employee table contain character information; others containinteger and date information.

Alternately, you may view a table’s columns as follows:

1 Invoke the list of tables by pressing F7.

2 Select the table whose columns you wish to view.

3 Click on the columns button.

Page 237: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Chapter 17 System Tables

225

Other system tablesThere are several other system tables in the database that will not bedescribed in the tutorial. You can find out their names by examiningSYS.SYSCATALOG and look at them if you want.

$ For a full description of each of the system tables, see "System Tables"on page 961 of the book ASA Reference.

Page 238: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

Other system tables

226

Page 239: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

227

Index

@@@identity

behavior change, 18

AActiveSync

support for, 44Adaptive Server Anywhere

about, 100system requirements, 103

aggregate functionsAVG, 193COUNT, 193LIST, 193MAX, 193MIN, 193SUM, 193

ALLconditions, 205

alphabetical order, 168ALTER statement

automatic commit, 213AND keyword, 175ANSINULL option

behavior change 6.0.1, 53ANY

conditions, 205apostrophes

using, 171asademo.db file

about, 124attributes, 87AUTO_COMMIT option

Interactive SQL, 213settings, 213

autocommitODBC behavior change, 17

Autostart connection parameternew features 6.0.1, 50

AVG function, 193

Bbase tables, 89behavior changes

6.0.1, 536.0.2, 416.0.3, 32ANSINULL option, 53autocommit, 17CHAR_OEM_TRANSLATION, 54CommLinks connection parameter, 53DATEDIFF function, 32dbport6.dll, 16DDE protocol, 15-gs command-line option, 53IPX, 15Java classes, 53MONTHS function, 32stack size, 53-v command-line option, 53version 7.0, 15-x command-line option, 53YEARS function, 32

BETWEEN conditions, 176bitmaps

storing as blobs, 134blobs

about, 134

Ccache

new features, 24

Page 240: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

D–D

228

cardinalityrelationships and, 136

cascading deletespermissions, 32

cascading updatespermissions, 32

case sensitivity, 166, 171CHAR_OEM_TRANSLATION option

behavior change 6.0.1, 54character data types, 224character set translation

Interactive SQL, 54character sets

euro, 25translation, 48

clearing Interactive SQL commands, 152collations

behavior change, 33default, 33new features, 25, 27

columnsabout, 86, 131, 167allowing NULL, 135data types, 134looking up in Interactive SQL, 154ordering, 170selecting from a table, 170

command filesbuilding, 153, 177Command window, 177executing, 178overview, 153, 177recording, 178SQL Statements pane, 153

Command windowInteractive SQL, 166

command-linebehavior change for -x, 53

command-line toolsupgrading, 21version 7.0, 21

commandsediting in Interactive SQL, 155executing in Interactive SQL, 152, 166getting in Interactive SQL, 166Interactive SQL, 152interrupting in Interactive SQL, 152, 158loading in Interactive SQL, 157, 166logging in Interactive SQL, 158previous, 155recalling in Interactive SQL, 155

saving in Interactive SQL, 157, 166stopping in Interactive SQL, 152

COMMENT statementautomatic commit, 213

COMMIT statementabout, 214and transactions, 213

CommLinks connection parameterbehavior change 6.0.1, 53

comparisonsabout, 171, 172using subqueries, 204

compatibilityissues, 19version 7.0, 19

compatibility libraryinstallation, 72introduction, 57locating, 74ODBC applications, 74upgrades, 71

completing transactions, 213compound search conditions, 175conceptual database models

definition of, 129conditions, 173

GROUP BY clause, 196search, 171, 172, 176

configuringInteractive SQL viewer, 159

connectionssample database, 130

conventionsdocumentation, x

correlated subqueriesdefined, 206

correlation namesdefined, 206

COUNT function, 193, 194CREATE statement

automatic commit, 213creating

databases, 129cross product

joins, 184

Ddata recovery

and transactions, 215

Page 241: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

E–F

229

data typesabout, 86choosing, 134

database administration utilitiesVersion 5, 64

database fileintroduction, 116

database serverconnecting to, 139-gx option, 50running, 139stack size, 53Windows CE, 45

databasesclient application, 94components, 94connecting, 130creating, 129creating for Windows CE, 45design concepts, 129designing, 121files, 116language interface, 94objects, 89queries, 91relational, 86server, 94sql, 91system tables, 92upgrading, 57, 79

DATEDIFF functionbehavior change, 32

dates, 172, 176, 224combining, 175compound, 175

db_string_ping_server functionnew feature, 12

DB2accessing, 47

dbclientupgrading, 77

dbisql.exeInteractive SQL, 5

dbisqlc.exeInteractive SQL, 5

dbl50t.dllllocating, 74

DDE protocolbehavior change, 15

debuggingbehavior changes, 32, 41upgrade issues, 21version 7 databases required, 21

default collationbehavior change, 33new features, 27sqlpp, 33

DefaultCollation propertynew features, 27

DELETE statementabout, 216errors, 218examples, 218

designing databasesabout, 121concepts, 129

directoriesexecutable, xiinstallation, xi

documentationabout, 30, 40conventions, xversion, 30, 40

DROP statementautomatic commit, 213

Eediting commands, 171ending transactions, 213entering Interactive SQL commands, 152euro

new feature, 25executable directory

about, xiexecuting Interactive SQL commands, 152external data sources

access, 47external procedures

Windows CE, 45

Ffinishing transactions, 213firewalls

new features, 26

Page 242: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

G–J

230

foreign keysabout, 88defined, 87inserts, 217

FROM clausejoins, 185

functionsaggregate, 193SOUNDEX function, 174

Ggetting started, viiiGROUP BY clause, 194grouped data, 193-gs command-line option

behavior change 6.0.1, 53

HHAVING clause

and GROUP BY clause, 196HPC

Windows CE support, 103HPC Pro

Windows CE support, 103HTML Help

new features, 30

Iicons

used in manuals, xidentifier

defined, 129IN conditions, 176inequality, testing for, 172InfoMaker

using with Adaptive Server Anywhere, 69inner joins

using, 207INSERT statement

examples, 211, 217installation directory

about, xiinteger data types, 224

Interactive SQLabout, 145AUTO_COMMIT option, 213clearing commands, 152Command window, 166commands overview, 152COMMIT_ON_EXIT option, 213displaying a list of tables, 182effect of exiting, 213entering commands, 152executing commands, 152, 166executing/running commands, 152function keys, 149getting commands, 166interrupting commands, 152, 158introduction, 107loading commands, 157, 166logging commands, 158lookup, 154main window description, 146opening multiple windows, 149overview, 146recalling commands, 155reported errors, 152, 153running scripts, 157saving commands, 157, 166setting options, 159starting, 148toolbar description, 148Version 5, 64

IPXbehavior change, 15

ISQL, 145

Jjar files

compressed, 49jar utility

not supported, 49Java

new features 6.0.1, 49updating fields, 49Windows CE support, 45

Java classesbehavior change 6.0.1, 53

Java proceduresresult sets, 49

Page 243: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

K–O

231

jConnectnew features 6.0.1, 50version number, 50

joinscross product, 184errors, 188inner joins, 207natural, 188or subqueries, 206outer joins, 207

Kkey joins

about, 186keys

about, 87foreign, 87primary, 87

LLIKE operator, 173LIST function, 193

new feature, 12loading

commands in Interactive SQL, 157logging

commands in Interactive SQL, 158long commands, 171looking up

columns in Interactive SQL, 154procedures in Interactive SQL, 154tables in Interactive SQL, 154

Mmany-to-many relationships

definition of, 137MAX function, 193maximum function, 193messages

client side, 50metadata

system tables, 92MIN function, 193minimum function, 193

MIPS chipWindows CE support, 103

MONTHS functionbehavior change, 32

multi-byte character setsproperty function, 27

MultiByteCharSet propertynew features, 27

multiple Interactive SQL windows, 149

Nnetwork database server

about, 105platform support, 105

new features6.0.1, 436.0.2, 376.0.3, 23db_string_ping_server function, 12euro, 25extended output redirection features, 12LIST function, 12page size, 11REPLACE function, 12version 7.0, 3Windows CE, 44

NULLallowing in columns, 135

NULL valueallowed in columns, 211

OODBC

Version 5 compability, 74Windows CE, 46

one-to-many relationshipsdefinition of, 137

one-to-one relationshipsdefinition of, 136

opening multiple Interactive SQL windows, 149operating systems

supported, 103options

Interactive SQL viewer, 159OR keyword, 176Oracle

accessing, 47

Page 244: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

P–R

232

ORDER BY clause, 171examples, 168

outer joinsusing, 207

outer referencesdefined, 206

Ppage size

new feature, 11parameters

to functions, 193passwords

using, 130path

setting, 15pattern matching, 173performance

improving, 197permissions, 225

referential integrity actions, 32personal database server

about, 105platform support, 105

platformssupported, 103

PowerBuilderusing with Adaptive Server Anywhere, 69

PPCWindows CE support, 103

preferencesInteractive SQL, 159

primary keys, 87procedures

looking up in Interactive SQL, 154program group

Adaptive Server Anywhere, 108projection

defined, 92

Qqueries

Interactive SQL, 152query

defined, 91quotation marks

using, 171

Rrange, 172RDBMS

defined, 86recalling

commands in Interactive SQL, 155referential integrity actions

permissions, 32relational database management system

defined, 86relational databases

about, 87concepts, 86terminology, 87

relationsentities, 87

relationshipsabout, 136cardinality of, 136many-to-many, 137one-to-many, 137one-to-one, 136

remote data accessabout, 47

REPLACE functionnew feature, 12

requirements, 103restriction

defined, 92restrictions. See WHERE clauseresult sets

Java procedures, 49retrieving

commands in Interactive SQL, 155ROLLBACK statement

about, 214and transactions, 213examples, 216

rolling back transactions, 213rows

about, 86, 167adding, 211selecting, 171

running Interactive SQL commands, 152running scripts in Interactive SQL, 157

Page 245: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

S–U

233

Ssample database

about, 124connecting to, 130

savingcommands in Interactive SQL, 157

saving transaction results, 213schema

defined, 129scripts

running in Interactive SQL, 157search conditions

AND keyword pattern matching, 173date comparisons, 172GROUP BY clause, 196introduction to, 171short cuts for, 176subqueries, 201

SELECT statementabout, 201Interactive SQL, 151

selectiondefined, 92

SH3 chipWindows CE support, 103

SH4 chipWindows CE support, 103

sortingquery results, 168

SOUNDEX function, 174SQL

about, 91SQL Remote

new features 6.0.1, 52Windows CE, 45

SQL Serveraccessing, 47

sqlppcollations, 33

stack sizebehavior change 6.0.1, 53

Start menuAdaptive Server Anywhere, 108

starting Interactive SQL, 148starting transactions, 213subqueries

comparisons, 204correlated subqueries, 206or joins, 206using, 201

SUM function, 193supported platforms

Adaptive Server Anywhere, 103system failures

and transactions, 215system requirements

Adaptive Server Anywhere, 103system tables

defined, 92SYSCOLUMNS, 224SYSTABLE, 225

Ttables

about, 86, 131characteristics, 86columns, 131foreign keys, 88looking up in Interactive SQL, 154primary keys, 131

temporary fileintroduction, 116

threadingnew features 6.0.1, 50

toolbarInteractive SQL, 148

transaction logintroduction, 116

transaction processingand data recovery, 215

transactionsand data recovery, 215completing, 213starting, 213

tuples, 87

UUPDATE statement

examples, 212Java, 49

upgradescompatibility library, 71databases, 57, 79dbclient, 77overview, 56SQL Remote, 80standalone applications, 61

Page 246: Adaptive Server Anywhere Getting Startedjinggoy.globalonerealtycorp.com/files/liguori/SQL Anywhere 7/pdf... · Adaptive Server™ Anywhere Getting Started ... InformationConnect,

V–Z

234

upgradingcomponents, 56issues, 19, 35precautions, 19version 6.0.3, 35version 7.0, 19

user IDusing, 130

user IDsabout, 130system tables, 223

V-v command-line option

behavior change 6.0.1, 53validity checking, 217version 7.0

behavior changes, 15

WWHERE clause

BETWEEN conditions, 176date comparisons, 172DELETE statement, 216examples, 171GROUP BY clause, 196ORDER BY clause, 171pattern matching, 173UPDATE statement, 212

window descriptionsInteractive SQL, 146

WindowsCE, 44supported versions, 103

Windows 2000supported platform, 103

Windows 95supported operating systems, 103

Windows 98supported operating systems, 103

Windows CEdesktop management, 44features, 44ODBC, 46SQL Remote, 45supported devices, 103supported versions, 103

Windows NTsupported versions, 103

YYEARS function

behavior change, 32

Zzip files

compressed, 49