Você está na página 1de 1140

Adaptive Server Anywhere

Reference

Last modified: March 2000


Part Number: MC0058
Copyright © 2000 Sybase, Inc. All rights reserved.
Information in this manual may change without notice and does not represent a commitment on the part of
Sybase, Inc. and its subsidiaries.
Sybase, Inc. provides the software described in this manual under a Sybase License Agreement. The software may be
used 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, Adaptive
Server 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, Certified
SYBASE 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, Direct
Connect Anywhere, DirectConnect, Distribution Director, Dynamo, E-Anywhere, E-Whatever, Electronic Case
Management, Embedded SQL, EMS, Enterprise Application Server, Enterprise Application Studio, Enterprise
Client/Server, Enterprise Connect, Enterprise Data Studio, Enterprise Manager, Enterprise SQL Server Manager, Enterprise
Work 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 Generation
Learning, Next Generation Learning Studio, O DEVICE, OASiS, OASiS (logo), ObjectConnect, ObjectCycle,
OmniConnect, OmniSQL Access Module, OmniSQL Toolkit, Open Client, Open Client/Server, Open Client/Server
Interfaces, 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 Through
Knowledge, 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 Server
SNMP 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 Financial
Server, Sybase Gateways, Sybase Learning Connection, Sybase SQL Desktop, Sybase SQL Lifecycle, Sybase SQL
Workgroup, 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 Data
Stream, 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 Control
Center, 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: MC0058.
Contents

About This Manual............................................................ xi


Related documentation ............................................................xii
Documentation conventions....................................................xiii
The sample database..............................................................xvi

1 File Locations and Installation Settings........................... 1


Installation directory structure ................................................... 2
How Adaptive Server Anywhere locates files ........................... 4
Environment variables .............................................................. 6
Registry entries and INI files ................................................... 10

2 The Database Server ....................................................... 13


The database server ............................................................... 14

3 Connection and Communication Parameters................ 43


Connection parameters........................................................... 44
Network communications parameters .................................... 61

4 Database Administration Utilities ................................... 71


Administration utilities overview .............................................. 73
The Backup utility.................................................................... 74
The Collation utility.................................................................. 78
The Compression utility........................................................... 81
The Console utility................................................................... 83
The Data Source utility............................................................ 84
The Erase utility ...................................................................... 88
The Information utility.............................................................. 90
The Initialization utility............................................................. 92
The Interactive SQL utility....................................................... 99
The License utility ................................................................. 101
The Log Transfer Manager ................................................... 103
The Log Translation utility..................................................... 109
The Ping utility....................................................................... 114
The REBUILD utility .............................................................. 115

iii
The Server Location utility .................................................... 116
The Spawn utility................................................................... 117
The Stop utility ...................................................................... 118
The Transaction Log utility.................................................... 120
The Uncompression utility..................................................... 124
The Unload utility .................................................................. 126
The Upgrade utility................................................................ 133
The Validation utility.............................................................. 136
The Write File utility .............................................................. 139

5 Database Options .......................................................... 143


Introduction to database options........................................... 144
General database options..................................................... 149
Transact-SQL and SQL/92 compatibility options.................. 151
Replication options................................................................ 154
Interactive SQL options......................................................... 155
Alphabetical list of options .................................................... 157

6 SQL Language Elements .............................................. 207


Keywords .............................................................................. 208
Identifiers............................................................................... 211
Strings ................................................................................... 212
Operators .............................................................................. 213
Expressions........................................................................... 218
Search conditions ................................................................. 226
Special values ....................................................................... 234
Variables ............................................................................... 237
Comments............................................................................. 246
NULL value ........................................................................... 247

7 SQL Data Types ............................................................. 251


Character data types............................................................. 252
Numeric data types ............................................................... 256
Money data types.................................................................. 263
Bit data type .......................................................................... 264
Date and time data types ...................................................... 265
Binary data types .................................................................. 272
Domains ................................................................................ 274
Java class data types............................................................ 276
Data type conversions .......................................................... 281
Java / SQL data type conversion .......................................... 282
Year 2000 compliance .......................................................... 285

iv
8 SQL Functions ............................................................... 291
Function types....................................................................... 292
Alphabetical list of functions.................................................. 301

9 SQL Statements ............................................................. 365


Using the SQL statement reference...................................... 366
ALLOCATE DESCRIPTOR statement [ESQL] ..................... 369
ALTER DATABASE statement ............................................. 371
ALTER DBSPACE statement ............................................... 373
ALTER EVENT statement..................................................... 375
ALTER PROCEDURE statement.......................................... 377
ALTER SERVER statement.................................................. 378
ALTER TABLE statement ..................................................... 380
ALTER TRIGGER statement ................................................ 386
ALTER VIEW statement ....................................................... 387
ALTER WRITEFILE statement ............................................. 388
BACKUP statement .............................................................. 389
BEGIN statement .................................................................. 392
BEGIN TRANSACTION statement ....................................... 395
CALL statement .................................................................... 398
CASE statement.................................................................... 400
CHECKPOINT statement...................................................... 402
CLEAR statement [Interactive SQL] ..................................... 403
CLOSE statement [ESQL] [SP]............................................. 404
COMMENT statement........................................................... 406
COMMIT statement............................................................... 408
CONFIGURE statement [Interactive SQL]............................ 410
CONNECT statement [ESQL] [Interactive SQL]................... 411
CREATE COMPRESSED DATABASE statement................ 414
CREATE DATABASE statement .......................................... 415
CREATE DBSPACE statement ............................................ 419
CREATE DOMAIN statement ............................................... 421
CREATE EVENT statement.................................................. 423
CREATE EXISTING TABLE statement ................................ 428
CREATE EXTERNLOGIN statement.................................... 430
CREATE FUNCTION statement ........................................... 432
CREATE INDEX statement................................................... 435
CREATE MESSAGE statement [T-SQL] .............................. 439
CREATE PROCEDURE statement....................................... 440
CREATE PROCEDURE statement [T-SQL]......................... 447
CREATE SCHEMA statement .............................................. 449
CREATE SERVER statement............................................... 451
CREATE TABLE statement .................................................. 453
CREATE TRIGGER statement ............................................. 464
CREATE TRIGGER statement [T-SQL] ............................... 467

v
CREATE VARIABLE statement............................................ 468
CREATE VIEW statement .................................................... 469
CREATE WRITEFILE statement .......................................... 471
DEALLOCATE DESCRIPTOR statement [ESQL] ................ 472
Declaration section [ESQL]................................................... 473
DECLARE statement ............................................................ 474
DECLARE CURSOR statement [ESQL] [SP] ....................... 475
DECLARE CURSOR statement [T-SQL].............................. 480
DECLARE LOCAL TEMPORARY TABLE
statement .............................................................................. 481
DELETE statement ............................................................... 482
DELETE (positioned) statement [ESQL] [SP]....................... 484
DESCRIBE statement [ESQL] .............................................. 486
DISCONNECT statement
[ESQL][Interactive SQL]........................................................ 490
DROP statement................................................................... 491
DROP DATABASE statement............................................... 493
DROP CONNECTION statement ......................................... 494
DROP EXTERNLOGIN statement........................................ 495
DROP OPTIMIZER STATISTICS statement ........................ 496
DROP SERVER statement ................................................... 497
DROP STATEMENT statement [ESQL] ............................... 498
DROP VARIABLE statement ................................................ 499
EXECUTE statement [ESQL]................................................ 500
EXECUTE statement [T-SQL]............................................... 502
EXECUTE IMMEDIATE statement [SP] ............................... 504
EXIT statement [Interactive SQL] ......................................... 506
EXPLAIN statement [ESQL] ................................................. 507
FETCH statement [ESQL] [SP]............................................. 509
FOR statement...................................................................... 514
FORWARD TO statement..................................................... 516
FROM clause ........................................................................ 518
GET DATA statement [ESQL]............................................... 521
GET DESCRIPTOR statement [ESQL] ................................ 523
GET OPTION statement [ESQL] .......................................... 524
GOTO statement [T-SQL] ..................................................... 525
GRANT statement................................................................. 526
HELP statement [Interactive SQL]........................................ 530
IF statement .......................................................................... 531
IF statement [T-SQL] ............................................................ 533
INCLUDE statement [ESQL]................................................. 535
INPUT statement [Interactive SQL] ...................................... 536
INSERT statement ................................................................ 540
INSTALL statement............................................................... 542
LEAVE statement.................................................................. 544
LOAD TABLE statement ....................................................... 546

vi
LOCK TABLE statement ....................................................... 551
LOOP statement ................................................................... 553
MESSAGE statement ........................................................... 554
OPEN statement [ESQL] [SP]............................................... 556
OUTPUT statement [Interactive SQL]................................... 559
PARAMETERS statement [Interactive SQL] ........................ 563
PREPARE statement [ESQL] ............................................... 564
PREPARE TO COMMIT statement ...................................... 566
PRINT statement [T-SQL]..................................................... 567
PUT statement [ESQL] ......................................................... 568
RAISERROR statement [T-SQL] .......................................... 570
READ statement [Interactive SQL] ....................................... 572
READTEXT statement [T-SQL] ............................................ 573
RELEASE SAVEPOINT statement ....................................... 574
REMOVE statement.............................................................. 575
RESIGNAL statement ........................................................... 576
RESTORE statement............................................................ 577
RESUME statement .............................................................. 578
RETURN statement .............................................................. 579
REVOKE statement .............................................................. 581
ROLLBACK statement .......................................................... 583
ROLLBACK TO SAVEPOINT statement .............................. 584
ROLLBACK TRIGGER statement......................................... 585
SAVEPOINT statement......................................................... 586
SELECT statement ............................................................... 587
SET statement ...................................................................... 591
SET statement [T-SQL]......................................................... 593
SET CONNECTION statement
[Interactive SQL][ESQL]........................................................ 594
SET DESCRIPTOR statement [ESQL] ................................. 595
SET OPTION statement ....................................................... 596
SET OPTION statement [Interactive SQL] ........................... 599
SET SQLCA statement [ESQL] ............................................ 600
SETUSER statement ............................................................ 601
SIGNAL statement ................................................................ 603
START DATABASE statement ............................................. 604
START ENGINE statement [Interactive SQL]....................... 606
START JAVA statement ....................................................... 607
START LOGGING statement [Interactive SQL].................... 608
STOP DATABASE statement ............................................... 609
STOP ENGINE statement..................................................... 610
STOP JAVA statement ......................................................... 611
STOP LOGGING statement [Interactive SQL]...................... 612
SYSTEM statement [Interactive SQL]................................... 613
TRIGGER EVENT statement................................................ 614
TRUNCATE TABLE statement ............................................. 615

vii
UNION operation .................................................................. 617
UNLOAD statement .............................................................. 618
UNLOAD TABLE statement.................................................. 619
UPDATE statement............................................................... 621
UPDATE (positioned) statement........................................... 625
VALIDATE INDEX statement................................................ 627
VALIDATE TABLE statement ............................................... 628
WHENEVER statement [ESQL]............................................ 630
WHILE statement [T-SQL] .................................................... 631
WRITETEXT statement [T-SQL]........................................... 632

10 Database Error Messages............................................. 633


Error messages indexed by Adaptive Server
Anywhere SQLCODE ........................................................... 634
Error messages indexed by SQLSTATE .............................. 652
Error messages indexed by Sybase error code.................... 670
Alphabetic list of error messages.......................................... 693
Internal errors (assertion failed) ............................................ 904

11 SQL Preprocessor Error Messages.............................. 905


SQL Preprocessor error messages indexed by
error message value ............................................................. 906
SQLPP errors........................................................................ 910

12 Differences from Other SQL Dialects........................... 927


Adaptive Server Anywhere SQL features ............................. 928

13 Physical Limitations...................................................... 931


Size and number limitations.................................................. 932

14 System Procedures and Functions .............................. 933


System procedure overview.................................................. 934
System and catalog stored procedures ................................ 935
System extended stored procedures .................................... 950
Adaptive Server Enterprise system and catalog
procedures ............................................................................ 957

15 System Tables ............................................................... 961


System tables diagram ......................................................... 963
System table descriptions ..................................................... 965
DUMMY system table ........................................................... 966
SYSARTICLE system table .................................................. 967

viii
SYSARTICLECOL system table ........................................... 968
SYSCAPABILITY system table............................................. 969
SYSCAPABILITYNAME system table .................................. 970
SYSCOLLATION system table ............................................. 971
SYSCOLLATIONMAPPINGS system table .......................... 972
SYSCOLPERM system table................................................ 973
SYSCOLUMN system table .................................................. 974
SYSDOMAIN system table ................................................... 976
SYSEXTENT system table ................................................... 977
SYSEXTERNLOGINS system table ..................................... 978
SYSFILE system table .......................................................... 979
SYSFKCOL system table...................................................... 980
SYSFOREIGNKEY system table .......................................... 981
SYSGROUP system table .................................................... 983
SYSINDEX system table....................................................... 984
SYSINFO system table ......................................................... 986
SYSIXCOL system table....................................................... 988
SYSJAR system table ........................................................... 989
SYSJARCOMPONENT system table ................................... 990
SYSJAVACLASS system table............................................. 991
SYSLOGIN system table ...................................................... 993
SYSOPTION system table.................................................... 994
SYSPROCEDURE system table........................................... 995
SYSPROCPARM system table............................................. 996
SYSPROCPERM system table............................................. 998
SYSPUBLICATION system table.......................................... 999
SYSREMOTEOPTION system table .................................. 1000
SYSREMOTEOPTIONTYPE system table ......................... 1001
SYSREMOTETYPE system table....................................... 1002
SYSREMOTEUSER system table ...................................... 1003
SYSSERVERS system table .............................................. 1005
SYSSQLSERVERTYPE system table ................................ 1006
SYSSUBSCRIPTION system table..................................... 1007
SYSTABLE system table .................................................... 1008
SYSTABLEPERM system table.......................................... 1010
SYSTRIGGER system table ............................................... 1012
SYSTYPEMAP system table .............................................. 1014
SYSUSERMESSAGES system table ................................. 1015
SYSUSERPERM system table ........................................... 1016
SYSUSERTYPE system table ............................................ 1018

16 System Views............................................................... 1021


SYSARTICLECOLS system view ....................................... 1023
SYSARTICLES system view............................................... 1024
SYSCAPABILITIES system view ........................................ 1025

ix
SYSCATALOG system view ............................................... 1026
SYSCOLAUTH system view ............................................... 1027
SYSCOLUMNS system view .............................................. 1028
SYSFOREIGNKEYS system view ...................................... 1029
SYSGROUPS system view................................................. 1030
SYSINDEXES system view ................................................ 1031
SYSOPTIONS system view ................................................ 1032
SYSPROCAUTH system view ............................................ 1033
SYSPROCPARMS system view......................................... 1034
SYSPUBLICATIONS system view...................................... 1035
SYSREMOTEOPTIONS system view ................................ 1036
SYSREMOTETYPES system views ................................... 1037
SYSREMOTEUSERS system view .................................... 1038
SYSSUBSCRIPTIONS system view................................... 1039
SYSTABAUTH system view ............................................... 1040
SYSTRIGGERS system view ............................................. 1041
SYSUSERAUTH system view ............................................ 1042
SYSUSERLIST system view............................................... 1043
SYSUSEROPTIONS system view...................................... 1044
SYSUSERPERMS system view ......................................... 1045
SYSVIEWS system view..................................................... 1046
Views for Transact-SQL Compatibility ................................ 1047

A Database Performance and Connection Properties...1051


Database performance statistics ........................................ 1052
Database properties............................................................ 1060

Index..............................................................................1073

x
About This Manual

Subject
This manual provides reference material for all aspects of Adaptive Server
Anywhere, including SQL statements, administration utilities, error
messages, system tables, and so on.
While other manuals provide more motivation and context for how to carry
out particular tasks, this manual is the place to look for complete listings of
available syntax, utility command-line options, and so on.

Audience
This manual is for all users of Adaptive Server Anywhere. It is to be used in
conjunction with other manuals in the documentation set.
Contents
Topic Page
Related documentation xii
Documentation conventions xiii
The sample database xvi

xi
Related documentation
Adaptive Server Anywhere is a part of SQL Anywhere Studio. For an
overview of the different components of SQL Anywhere Studio, see
Introducing SQL Anywhere Studio.
The Adaptive Server Anywhere documentation consists of the following
books:
♦ Getting Started Intended for all users of Adaptive Server Anywhere,
this book describes the following:
♦ New features in Adaptive Server Anywhere
♦ Behavior changes from previous releases
♦ Upgrade procedures
♦ Introductory material for beginning users.
♦ Programming Interfaces Guide Intended for application developers
writing programs that directly access the ODBC, Embedded SQL, or
Open Client interfaces, this book describes how to develop applications
for Adaptive Server Anywhere.
This book is not required for users of Application Development tools
with built-in ODBC support, such as Sybase PowerBuilder.
♦ User’s Guide A comprehensive guide to using SQL, administering
databases, and using Adaptive Server Anywhere features.
♦ Quick Reference A handy printed booklet with complete SQL syntax
and other key reference material in a concise format.
♦ Read Me First (UNIX only) A separate booklet is provided with UNIX
versions of Adaptive Server Anywhere, describing installation and
adding some UNIX-specific notes.
The format of these books (printed or online) may depend on the product in
which you obtained Adaptive Server Anywhere. Depending on which
package you have purchased, you may have additional books describing
other components of your product.

xii
Documentation conventions
This section lists the typographic and graphical conventions used in this
documentation.

Syntax conventions
The following conventions are used in the SQL syntax descriptions:
♦ Keywords All SQL keywords are shown in UPPER CASE. However,
SQL keywords are case insensitive, so you can enter keywords in any
case you wish; SELECT is the same as Select is the same as select.
♦ Placeholders Items that must be replaced with appropriate identifiers
or expressions are shown in italics.
♦ Continuation Lines beginning with ... are a continuation of the
statements from the previous line.
♦ Repeating items Lists of repeating items appear with an element of
the list followed by an ellipsis (three dots). One or more list elements are
allowed. If you specify more than one, they must be separated by
commas.
♦ Optional portions Optional portions of a statement are enclosed by
square brackets. For example,
RELEASE SAVEPOINT [ savepoint-name ]
indicates that the savepoint-name is optional. Do not type the square
brackets.
♦ Options When none or only one of a list of items must be chosen, the
items are separated by vertical bars and the list enclosed in square
brackets. For example,
[ ASC | DESC ]
indicates that you can choose one of ASC, DESC, or neither. The square
brackets should not be typed.
♦ Alternatives When precisely one of the options must be chosen, the
alternatives are enclosed in curly braces. For example,
QUOTES { ON | OFF }
indicates that exactly one of ON or OFF must be provided. Do not type
the braces.

xiii
Graphic icons
The following icons are used in this documentation:

Icon Meaning

A client application.
If the icon is used to represent a particular application
or kind of application, the name is indicated in the
bottom right corner.

A database server, such as Sybase Adaptive Server


Anywhere or Adaptive Server Enterprise.
If the icon is used to represent a particular kind of
database 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 application
are part of the same process.

A database.
In some high-level diagrams, the icon may be used to
represent both the database and the database server
that manages it.

Replication or synchronization middleware.


These pieces of software assist in sharing data among
databases. Examples include the MobiLink
Synchronization Server, the SQL Remote Message
Agent, and the Replication Agent (Log Transfer
Manager) for use with Replication Server.
If the particular kind of middleware is not obvious
from the context of the diagram, the name is indicated
in the bottom right hand corner.
A Sybase Replication Server.

xiv
Installed files
The following terms are used throughout the manual:
♦ Installation directory The directory into which you install Adaptive
Server Anywhere.
♦ Executable directory The executables and other files for each
operating system are held in an executable subdirectory of the
installation directory. This subdirectory has the following name:
♦ Windows NT and Windows 95/98 win32
♦ UNIX bin
♦ Windows 3.x win
♦ NetWare and Windows CE The executables are held in the
Adaptive Server Anywhere installation directory itself on these
platforms.

xv
The sample database
There is a sample database included with Adaptive Server Anywhere. Many
of the examples throughout the documentation use this sample database.
The sample database represents a small company. It contains internal
information about the company (employees, departments, and financial data)
as well as product information (products), sales information (sales orders,
customers, and contacts), and financial information (fin_code, fin_data).
The following figure shows the tables in the sample database and how they
are related to each other.

asademo.db

product employee
id <pk> integer sales_order_items
emp_id <pk> integer
name char(15) id <pk,fk> integer
manager_id integer
description char(30) line_id <pk> smallint
emp_fname char(20)
size char(18) id = prod_id prod_id <fk> integer
emp_lname char(20)
color char(6) quantity integer
dept_id <fk> integer
quantity integer ship_date date
street char(40)
unit_price numeric(15,2)
city char(20)
state char(4)
id = id
emp_id = sales_rep zip_code char(9)
phone char(10)
customer status char(1)
ss_number char(11)
id <pk> integer sales_order
salary numeric(20,3)
fname char(15) id <pk> integer start_date date
lname char(20) cust_id <fk> integer termination_date date
address char(35) order_date date birth_date date
city char(20) id = cust_id fin_code_id <fk> char(2) bene_health_ins char(1)
state char(2) region char(7) bene_life_ins char(1)
zip char(10) sales_rep <fk> integer bene_day_care char(1)
phone char(12)
sex char(1)
company_name char(35) code = fin_code_id

fin_code
code <pk> char(2)
contact dept_id = dept_id
type char(10)
id <pk> integer description char(50) emp_id = dept_head_id
last_name char(15)
first_name char(15)
title char(2) code = code
street char(30)
city char(20) fin_data
state char(2) year <pk> char(4) department
zip char(5) quarter <pk> char(2) dept_id <pk> integer
phone char(10) code <pk,fk> char(2) dept_name char(40)
fax char(10) amount numeric(9) dept_head_id <fk> integer

The sample database is held in a file named asademo.db, and is located in


your installation directory.

xvi
C H A P T E R 1

File Locations and Installation Settings

About this chapter This chapter describes the installation and operating system settings used by
Adaptive Server Anywhere. Depending on the operating system, these
settings may be stored as environment variables, initialization file entries, or
registry entries.
Contents
Topic Page
Installation directory structure 2
How Adaptive Server Anywhere locates files 4
Environment variables 6
Registry entries and INI files 10

1
Installation directory structure

Installation directory structure


When you install Adaptive Server Anywhere, several directories may be
created. Some of the files in these directories are essential, and others are
not. This section describes the directory structure.
Adaptive Server Anywhere software, whether you receive it as a product or
bundled as part of another product, is installed under a single installation
directory. The tools provided with the Adaptive Server Anywhere product,
however, are installed in other directories. This section describes only the
installation directory structure for Adaptive Server Anywhere itself.
The Adaptive The Adaptive Server Anywhere installation directory itself holds several
Server Anywhere items, including the following:
installation
♦ The sample database The sample database is held in the file
directory
asademo.db.
♦ Read Me First A Read Me First file named readme.txt holds late-
breaking information.
For platforms other than Novell NetWare and Windows CE, there are several
directories under the installation directory:
♦ Executable directories There is a separate directory for each
operating system, which holds executables, dynamic link libraries, and
help files.
If you are using Windows 95/98, or NT, these files are installed in the
win32 directory. If you are using UNIX, they are installed in the bin
directory. On NetWare, the executables are stored in the installation
directory itself.
You will not have all these directories on your machine; you will have
only the ones required for the operating system version you installed.
♦ Java directory Java base classes are stored in this directory.
♦ ProcDebug directory The stored procedure debugger is stored in this
directory.
♦ Scripts directory The scripts directory contains SQL scripts that are
used by the database administration utilities and as examples. With the
exception of specific scripts (custom.sql, custmap.sql), do not edit these
scripts. If the scripts directory is not present, the administration utilities
will not work.
♦ Examples directories There are separate directories for C (cxmp) and
Java (jxmp) examples.

2
Chapter 1 File Locations and Installation Settings

♦ h directory The h directory contains header files for ESQL and ODBC
database development.
Novell NetWare file On Novell NetWare, all files are installed to a single directory on the server.
locations Throughout this documentation, when reference is made to files in
subdirectories of the installation directory, the file on NetWare is in the
installation directory itself.
Windows CE file On Windows CE, all files are installed to the installation directory, and no
locations subdirectories are created. The exception is that all DLLs are installed into
the \Windows directory. To make identification easy, the DLL names all have
the prefix ASA_.

3
How Adaptive Server Anywhere locates files

How Adaptive Server Anywhere locates files


The client library and the database server need to locate files for two main
purposes:
♦ DLLs and initialization files are required to run Adaptive Server
Anywhere. If an incorrect DLL is located, there is the possibility of
version mismatch errors.
♦ Some files are specified in SQL statements and need to be located at run
time, such as INSTALL or LOAD TABLE.
Examples of SQL statements that use file names include the following:
♦ INSTALL statement The name of the file that holds Java classes.
♦ LOAD TABLE and UNLOAD TABLE statements The name of the file
from which data should be loaded or to which the data should be
unloaded.
♦ CREATE DATABASE statement A file name is needed for this
statement and similar statements that can create files (such as CREATE
WRITEFILE).
In some cases, Adaptive Server Anywhere uses a simple algorithm to locate
files. In other cases, a more extensive search is carried out.
Simple file In many SQL statements (such as LOAD TABLE, or CREATE
searching DATABASE), the file name is interpreted as relative to the current working
directory of the database server.
Also, when a database server is started and a database file name (DBF
parameter) is supplied, the path is interpreted as relative to the current
working directory.
Extensive file Adaptive Server Anywhere programs, including the database server and
searching administration utilities, carry out a more extensive search for required files,
such as DLLs or shared libraries. In these cases, Adaptive Server Anywhere
programs look for files in the following order:
1 Executable directory Holds the program executable file.
2 Related directories Holds directories with the following paths relative
to the program executable directory:
♦ Parent of the executable directory
♦ A child of the parent directory named scripts. The UNIX server
does not search in this location.

4
Chapter 1 File Locations and Installation Settings

3 Current working directory When a program is started, it has a


current working directory (the directory from which it is started). This
directory is searched for required files.
4 Location registry entry On installation onto Windows 95/98, and NT,
Adaptive Server Anywhere adds a LOCATION registry entry. The
indicated directory is searched, followed by:
♦ A child named scripts
♦ A child with the operating system name (win32, win, and so on)
5 System specific directories This includes directories where common
operating system files are held, such as the Windows directory and the
Windows\system directory on Windows and Windows NT operating
systems.
6 CLASSPATH directories For Java files, directories listed in the
CLASSPATH environment variable are searched to locate files.
7 PATH directories Directories in the system path and the user’s path
are searched to locate files.

5
Environment variables

Environment variables
Adaptive Server Anywhere uses a set of environment variables to store
various types of information. Not all variables need to be set in all
circumstances. These environment variables are listed in this section.

Setting environment variables


The way you set an environment variable depends on the operating system
you are using.

v To set an environment variable (Windows NT):


1 Right click on My Computer and select Properties from the popup menu.
2 Click the Environment tab. If the environment variable does not already
exist, type variable and its value in the spaces provided, and click Set.
If the variable does exist, select it from the list of System Variables or
User Variables, and make any modifications in the Value field. Click Set
to make the setting.

v To set an environment variable (UNIX):


♦ In one of your startup files (.cshrc, .shrc, .login), add a line that sets the
variable.
In some shells (such as sh, bash, ksh) the line is as follows:
export VARIABLE=value
In other shells (such as csh, tsch) the line is as follows:
setenv VARIABLE value

ASTMP environment variable


Syntax ASTMP= directory-name
Default None.
Description The database server checks the value of the ASTMP environment variable to
determine where to hold the temporary file. If the ASTMP environment
variable does not exist, then the first of the TMP, TMPDIR, and TEMP
environment variables to exist is used.

6
Chapter 1 File Locations and Installation Settings

In many circumstances, ASTMP is not needed. It can be of use in security-


conscious environments when running the database server as a service, to
enable you to hold the temporary file in a directory that cannot be accessed
by other programs.

LD_LIBRARY_PATH environment variable [UNIX]


Syntax LD_LIBRARY_PATH= installation_path/lib
Description The LD_LIBRARY_PATH environment variable is used on UNIX only. It is
modified by the installation program to include the directories where
Adaptive Server Anywhere libraries are located.
The executables are located in the lib subdirectory of the installation
directory (for example, /opt/SYBSasa7/lib ).

PATH environment variable


Syntax PATH= installation_path
Description The PATH environment variable is modified by the installation program to
include the directories where Adaptive Server Anywhere executables are
located.
The executables are located in a subdirectory of the installation directory.
In addition, if you are using other Sybase applications, the SYBASE\bin and
SYBASE\dll directories are added to your path.
On UNIX, each user must have the directory holding the executables
(/opt/SYBSasa7/bin ) added to their path.

SATMP environment variable


Syntax SATMP= temp_directory
Description The SATMP environment variable is used by UNIX versions of Adaptive
Server Anywhere to indicate a directory where temporary files are kept.
If more than one database server is running on a machine, each user needs
their own temporary directory. Typically, this is set to /tmp/.userid, so that
each user has their own directory and conflicts are avoided.

7
Environment variables

SQLCONNECT environment variable


Syntax SQLCONNECT=parameter#value ; ...
Description The SQLCONNECT environment variable is optional, and is not set by the
installation program.
SQLCONNECT specifies connection parameters that are used by several of
the database administration utilities when connecting to a database server.
This string is a list of parameter settings, of the form parameter=value,
delimited by semicolons.
The number sign "#" is an alternative to the equals sign, and should be used
if you are setting the connection parameters string in the SQLCONNECT
environment variable. Using "=" inside an environment variable setting is a
syntax error. The = sign is allowed only in Windows NT.
$ For a description of the connection parameters, see "Connection
parameters" on page 60 of the book ASA User’s Guide.

SQLLOCALE environment variable


Syntax SQLLOCALE= Charset=cslabel;Language=langlabel;CollationLabel=colabel
See also "Setting the SQLLOCALE environment variable" on page 293 of the book
ASA User’s Guide
Description The SQLLOCALE environment variable is not set by the installation
program, and is required only in multi-character-set environments.
The SQLLOCALE environment variable is a single string that consists of
three semi-colon-separated assignments. The assignments set out the
character set, language, and collation of the environment.
$ For a list of supported character set labels, see "Setting the
SQLLOCALE environment variable" on page 293 of the book ASA User’s
Guide.

SQLPATH environment variable


Syntax SQLPATH=path;...
Description The SQLPATH environment variable is optional, and is not set by the
installation program.
Interactive SQL searches along SQLPATH for command files and Help files
before searching the system path.

8
Chapter 1 File Locations and Installation Settings

SQLREMOTE environment variable


Syntax SQLREMOTE=path
Description The SQLREMOTE environment variable is optional, and is not set by the
installation program.
Addresses for the FILE message link in SQL Remote are subdirectories of
the SQLREMOTE environment variable. This variable should point to a
shared directory.
On 32-bit Windows, an alternative to setting the SQLREMOTE environment
variable is to set the SQL Remote\Directory registry entry to the proper root
directory.

SYBASE environment variable


Syntax SYBASE=path
Description The SYBASE variable marks the home directory for installation of some
Sybase applications, including Adaptive Server Enterprise and utilities such
as dsedit. You need this variable only if you are using Adaptive Server
Anywhere together with other members of the Adaptive Server family.

TEMP environment variable


Syntax TMP=path
TMPDIR=path
TEMP=path
Description The database server creates a temporary file for various operations such as
sorting and performing unions. Temporary files are placed in the directory
specified by the TMP, TMPDIR, or TEMP environment variable. Adaptive
Server Anywhere takes the first one of the three that it finds.
If none of the environment variables is defined, temporary files are placed in
the current working directory of the server.
On UNIX, the SATMP variable is used instead of the TEMP environment
variable.

9
Registry entries and INI files

Registry entries and INI files


On Windows 95/98 and Windows NT operating systems, Adaptive Server
Anywhere uses several registry settings. On Windows 3.x, UNIX, and
Netware 3.11, these settings are held in initialization files instead.
These settings are made for you by the software, and in general operation
you should not need to access the registry. The settings are provided here for
those people who make modifications to their operating environment.

Current user and local machine settings


Some operating systems, such as Windows NT, hold two levels of system
settings. Some settings are specific to an individual user, and are used only
when that user is logged on; these settings are called current user settings.
Some settings are global to the machine, and are available no matter which
user is logged on; these are called local machine settings. You must have
administrator permissions on your machine to make local machine settings.
Adaptive Server Anywhere permits both current user and local machine
settings. For Windows NT, these are held in the HKEY_CURRENT_USER
registry and HKEY_LOCAL_MACHINE registry, respectively.
Current user takes If a setting is made in both current user and local machine registries, the
precedence current user setting takes precedence over the local machine setting.
When local If you are running an Adaptive Server Anywhere program as a service under
machine settings Windows NT, you should ensure that the settings are made at the local
are needed machine level.
Services can continue to run under a special account when you log off a
machine, as long as you do not shut the machine down entirely. They can be
made independent of individual accounts, and therefore need access to local
machine settings.
In addition to Adaptive Server Anywhere programs, some Web servers run
as services. You must set local machine settings in order for PowerDynamo
to work with such a Web server.
In general, the use of local machine settings is recommended.

10
Chapter 1 File Locations and Installation Settings

Registry structure
On Windows 95/98 and Windows NT, you can access the registry directly
with the registry editor. The Adaptive Server Anywhere registry entries are
held in either the HKEY_CURRENT_USER or
HKEY_LOCAL_MACHINE registries, in the following location:
Software
Sybase
Adaptive Server Anywhere
7.0
Sybase Central
4.0
Profiles
Providers

Registry settings on installation


The installation program makes the following registry settings in the Sybase
registry:
♦ Location In the Adaptive Server Anywhere\7.0 registry, this entry
holds the installation directory location. For example:
Location "c:\sybase\asa7"
♦ Language In the Adaptive Server Anywhere\7.0 registry, this entry
holds a two-letter code indicating the current language for messages and
errors. For example:
Language "EN"
The default setting is English (EN). The installation program sets this
entry only if the software is installed for a language other than English.
♦ Providers In the Sybase Central\Providers registry, this entry stores
the file names of installed plug-ins for Sybase Central. Adaptive Server
Anywhere has its own Sybase Central plug-in:
Adaptive Server Anywhere 7.0
"c:\sybase\asa7\win32\scasany7.dll"

11
Registry entries and INI files

12
C H A P T E R 2

The Database Server

About this chapter This chapter describes the command-line options for the Adaptive Server
Anywhere database server.
It also contains information for the command-line options of the client
executable (provided for compatibility with Version 5 software).
Contents
Topic Page
The database server 14

13
The database server

The database server


Function Start a personal database server or network database server.
Syntax { dbeng7 | dbsrv7 }
[ server-switches ] [ database-file [ database-switches ] ]*
NetWare syntax load dbsrv7 [ server-switches ] [ database-file [ database-switches ] ]*

Switch Description
@filename Read in switches from a configuration file. See "@filename
command-line option" on page 19.
@environment- Read in switches from an environment variable. See
variable "@environment-variable command-line option" on page 19.
-? Display usage information. See "–? command-line option" on
page 20.
-b Run in bulk operations mode. See "–b command-line option" on
page 20.
-c size Set initial cache size. See "–c command-line option" on page 21.
-ca 0 Disable dynamic cache sizing [Windows NT, Windows 95/98].
See "–ca command-line option" on page 22.
-ch size Set the cache size upper limit [Windows NT, Windows 95/98].
See "–ch command-line option" on page 22.
-cl Set the cache size lower limit [Windows NT].
-cs Display cache usage in database server window. For more
information, see "–cs command-line option" on page 23.
-ct Enable character-set translation [Not NetWare or Windows CE].
See "–ct command-line option" on page 23.
-d Disable asynchronous I/O [Windows NT, NetWare]. See "–d
command-line option" on page 24.
-e Enable packet encryption [network server]. See "–e command-
line option" on page 24.
-ga Automatically unload the database after the last connection
closed. In addition, shut down after the last database is closed
[Not NetWare]. See "–ga command-line option" on page 24.
-gb level Set database process priority class to level [Windows NT]. See "–
gb command-line option" on page 25.
-gc minutes Set maximum checkpoint timeout period to num minutes. See "–
gc command-line option" on page 25.
-gd level Set database starting permission. See "–gd command-line option"
on page 25.

14
Chapter 2 The Database Server

Switch Description
-ge size Set the stack size for threads that run external functions [not
UNIX]. See "–ge command-line option" on page 26.
-gf Disable firing of triggers. See "–gf command-line option" on
page 27.
-gl level Set the permission required to load or unload data. See "–gl
command-line option" on page 27.
-gk level Set the permission required to stop the server. See "–gk
command-line option" on page 27.
-gm num Limit the maximum number of connections. See "–gm command-
line option" on page 28.
-gn num Set the number of threads. See "–gn command-line option" on
page 28.
-gp size Set the maximum page size to size bytes. See "–gp command-line
option" on page 28.
-gr minutes Set the maximum recovery time to num minutes. See "–gr
command-line option" on page 29.
-gss size Set the thread stack size to size bytes. See "–gss command-line
option" on page 29.
-gt num Set the number of CPUs for request processing. See "–gt
command-line option" on page 29.
-gu level Set the permission level for utility commands: utility_db, all,
none, dba. See "–gu command-line option" on page 30.
-gw Set the interval (in milliseconds) for background processing. See
"–gw command-line option" on page 30.
-gx Modify operating system threading [Windows 95/98 and
Windows NT]. See "–gx command-line option" on page 30.
-m Truncate the transaction log after each checkpoint, for all
databases. See "–m command-line option" on page 31.
-n name Use name as the name of the database server. See "–n command-
line option" on page 31.
-o filename Output messages to the specified file. See "–o command-line
option" on page 32.
-os size Limit the size of the log file for messages. See "–os command-
line option" on page 32.
-p packet-size Set the maximum network packet size [network server]. See "–p
command-line option" on page 33.
-q Quiet mode—suppress output. See "–q command-line option" on
page 33.

15
The database server

Switch Description
-r Opens database in read-only mode. See "–r command-line
option" on page 33.
-s Set the syslog facility ID [UNIX]. See "–s command-line option"
on page 34.
-sc Disable the shared memory port, and enable Named Pipes.
[Windows NT]. See "–sc command-line option" on page 34.
-ti minutes Client idle time before shutdown—default 240 minutes [network
server]. See "–ti command-line option" on page 34.
-tl seconds Default liveness timeout for clients in seconds—default 120
seconds [network server]. See "–tl command-line option" on
page 35.
-tmf Force transaction manager recovery for distributed transactions.
See "–tmf command-line option" on page 35.
-tmt Set the reenlistment timeout for distributed transactions. See "–
millisecondst tmt command-line option" on page 35.
-tq time Set quitting time [network server]. See "–tq time command-line
option" on page 36.
-u Use buffered disk I/O. See "–u command-line option" on
page 36.
-ud Run as a daemon [UNIX]. See "–ud command-line option" on
page 36.
-ut minutes Touch temporary files every min minutes [UNIX]. See "–ut
command-line option" on page 37.
-v Display database server version and stop. See "–v command-line
option" on page 37.
-x list Comma-separated list of communication links to try. See "–x
command-line option" on page 37.
-y Run as a Windows 95/98 service [Windows 95/98]. See "–y
command-line option" on page 39.
-z Provide diagnostic information on communication links [network
server]. See "–z command-line option" on page 39.
-zo filename Redirect request-level logging information to a separate file. See
"–zo command-line option" on page 39.
-zr { all | SQL | Turn on logging of SQL operations. The default is NONE. See "–
none } zr command-line option" on page 40.
-zs size Limit the size of the log file used for request-level logging. See
"–zs command-line option" on page 40.

16
Chapter 2 The Database Server

Recovery Switch Description


- filename Apply the named transaction log file. See "–a command-line
option" on page 40.
-f Force the database to start without a transaction log. See "–f
command-line option" on page 41.

Database Switch Description


-m Truncate (delete) the transaction log after each checkpoint. See "–
m command-line option" on page 41.
-n name Name the database. See "–n command-line option" on page 42.

See also
"Running the Database Server" on page 3 of the book ASA User’s Guide
"Network communications parameters" on page 61
Description The dbeng7 command starts a personal database server. The dbsrv7
command starts a network database server.
Cache size The amount of cache memory available to the database server can be a key
factor in affecting performance. The database server takes an initial amount
of cache memory that is either specified by the -c command-line option or is
a default value. For information on the default cache size, see "–c command-
line option" on page 21.
On Windows NT, Windows 95/98, and UNIX the database server
automatically takes more memory for use in the cache as needed, determined
by a heuristic algorithm
$ For more information, see "Using the cache to improve performance"
on page 785 of the book ASA User’s Guide.
You can use database command-line options to configure the upper limit: see
"–ch command-line option" on page 22. You can force the cache to remain at
its initial amount: see "–ca command-line option" on page 22.
Server differences The personal database server has a maximum of ten concurrent connections,
uses at most two CPUs for request processing, and does not support network
client/server connections.
In addition, there are other minor differences, such as the default permission
level that is required to start new databases, or the permissions required to
execute the CHECKPOINT statement.
Platform availability Both personal and network database servers are supplied for each supported
operating system, with the following exceptions:

17
The database server

♦ Novell NetWare Only the network server is supplied.


♦ Windows CE Only the network server is supplied. The support for
TCP/IP in the network server enables you to carry out tasks from your
desktop machine, including database management with Sybase Central.
NetWare notes In NetWare, the database file and the transaction log file must be on a
NetWare volume, and the paths must be fully specified. NetWare allows you
to have volumes that span two or more hard disks.
Adaptive Server Anywhere uses the Direct File System to maintain database
files. The Direct File System is built into NetWare 4.0 and 4.1, but not in
NetWare 3.12. Novell has provided a loadable module that contains the
DIRECTFS functions for version 3.12. directfs.nlm comes with Adaptive
Server Anywhere, and is installed during the installation if it is not found on
your NetWare server. The DIRECTFS module is automatically loaded if
necessary when you load dbsrv7.
Novell has also provided an updated clib.nlm for NetWare 3.11. This update
contains bug fixes that are necessary for Adaptive Server Anywhere to work
properly. It is installed during the installation of Adaptive Server Anywhere
if it is not already on your NetWare server.

Database file The database-file specifies the database filename. If


database-file is specified without a file extension, Adaptive Server
Anywhere looks first for database-file with extension .wrt (a write file)
followed by database-file with extension .db.
If you use a relative path, it is read relative to the current working directory.
You can supply a full path. Also, you can supply a path that conforms to the
Universal Naming Convention (UNC) format:
\\server\volume\path\file.ext
In addition, users of Novell NetWare version 4 and later can use NetWare
Directory Services (NDS) volumes, which have the following format:
\\treename\volume.org_unit.org\path\file.ext
where volume.org_unit.org is the name of an NDS volume object.

Caution
The database file must be on the same machine as the database server.
Managing a database file that is located on a network drive can lead to
file corruption.

Suppressing If you run the database server as a Windows NT service, you can suppress
Windows NT event NT event log entries by setting a registry entry. The registry entry is
log messages
Software\Sybase\Adaptive Server Anywhere\7.0

18
Chapter 2 The Database Server

To control event log entries, set the EventLogMask key, which is of type
REG_DWORD. The value is a bit mask containing the internal bit values for
the different types of event messages:
errors EVENTLOG_ERROR_TYPE 0x0001
warnings EVENTLOG_WARNING_TYPE 0x0002
information EVENTLOG_INFORMATION_TYPE 0x0004
For example, if the EventLogMask is set to zero, no messages appear at all.
A better setting would be 1, so that informational and warning messages do
not appear, but errors do. The default setting (no entry present) is for all
message types to appear.

Database server switches


These switches apply to the server as a whole, not just to an individual
database.

@filename command-line option


Function Read in command-line switches from the supplied file.
Syntax [ dbsrv7 | dbeng7 ] @filename ...
Applies to All operating systems and servers.
Description The command-line file may contain line breaks, and may contain any set of
command line switches. For example, the following command file holds a set
of command line switches for a server named myserver that starts with a
cache size of 4Mb and loads the sample database:
-c 4096
-n myserver
c:\asa6\asademo.db
If this configuration file is saved as c:\config.txt, it can be used in a command
line as follows:
dbsrv7 @c:\config.txt

@environment-variable command-line option


Function Read in command-line switches from the supplied environment variable.
Syntax [ dbsrv7 | dbeng7 ] @env-var ...
Applies to All operating systems and servers.

19
The database server

Description The environment variable may contain any set of command line switches.
For example, the first statement sets an environment variable that holds
command line switches for a database server that starts with a cache size of
4Mb and loads the sample database. The second statement starts the database
server:
set envvar=-c 4096 c:\asa6\asademo.db
dbsrv7 @envvar

Environment variable given priority


If you have both a file and an environment variable with the value of your
@ command-line switch, the environment variable is used.

–? command-line option
Function Display usage information.
Syntax [ dbsrv7 | dbeng7 ] -?
Applies to All operating systems and servers.
Description Display a short description of each command-line option. The database does
not carry out any other task.

–b command-line option
Function Use bulk operation mode.
Syntax [ dbsrv7 | dbeng7 ] -b ...
Applies to All operating systems and servers.
Description This is useful for using the Interactive SQL INPUT command to load large
quantities of data into a database.
The -b option should not be used if you are using LOAD TABLE to bulk
load data.
When you use this option, the database server allows only one connection by
one application. It does not keep a rollback log or a transaction log, and the
multi-user locking mechanism is turned off.
When you first start the database server after loading data with the -b
switch, you should use a new log file.
Bulk operation mode does not disable the firing of triggers.

20
Chapter 2 The Database Server

–c command-line option
Function Set the initial memory reserved for caching database pages and other server
information.
Syntax [ dbsrv7 | dbeng7 ] -c [integer | integerK | integerM | integerP ] ...
Applies to All operating systems and servers.
Description The amount of memory available for use as a database server cache is one of
the key factors controlling performance. You can set the initial amount of
cache memory using the -c command-line option
The more cache memory that can be given the server, the better will be its
performance.
The units K and M can be either lower case or upper case. If K or M is not
supplied, any integer less than 10000 is assumed to be in kilobytes, and any
integer 10000 or greater is assumed to be in bytes. For example, -c 4096
means 4096KB or 4 194 304 bytes. Whereas, -c 200 000 means (an
unreasonably small) cache of 200 000 bytes.
The unit P is a percentage of the physical system memory, and if you use
this, the argument is a percentage. You can use % as an alternative to P, but
as most non-UNIX operating systems use % as an environment variable
escape character, you must escape the % character. To use 50 percent of the
physical system memory, you would use the following:
dbeng7 -c 50%% ...

If no -c option is provided, the database server computes the initial cache


allocation as follows:
1 It uses the following operating-system-specific default cache sizes:
♦ Windows CE 600K
♦ Windows NT, Windows 95/98, NetWare 2 Mb
♦ UNIX 8 Mb
2 It computes a runtime-specific minimum default cache size, which is the
lesser of the following items:
♦ 25% of the machine’s physical memory
♦ The sum of the sizes of the main database files specified on the
command line. Additional dbspaces apart from the main database
files are not included in the calculation. If no files are specified, this
value is zero.
3 It allocates the greater of the two values computed.

21
The database server

NetWare database server


There is a trade off between memory for the database server and memory
for the NetWare file system buffers. A larger database server cache will
improve database server performance at the expense of NetWare file
system performance. If the database server cache is too big, NetWare will
report an error that there is insufficient memory for cache buffers.
NetWare memory requirements increase with every new directory and file
on the file server. To track memory usage on the NetWare server, load
monitor.nlm (if it is not already loaded) and select "Resource Utilization".
Extra memory for your NetWare server computer could improve database
performance and/or file server performance dramatically.

See also "–ch command-line option" on page 22

–ca command-line option


Function When used as -ca 0, enforces a static cache size. The zero argument is
required.
Syntax [ dbsrv7 | dbeng7 ] -ca 0 ...
Applies to Windows NT, Windows 95/98
Description Without setting -ca to 0, the database server automatically takes additional
cache as needed. You can disable automatic cache increase due to high
server load by using -ca 0 on the command line. The cache size still increases
if the database server would otherwise run into the error Fatal Error: dynamic
memory exhausted, or if the Java VM requires memory that would lead to a
fatal error.
This command-line option should be used only in the form -ca 0. If -ca is
omitted, automatic cache growth is enabled.
See also "–c command-line option" on page 21
"–ch command-line option" on page 22

–ch command-line option


Function Sets a maximum cache size, as a limit to automatic cache growth.
Syntax [ dbsrv7 | dbeng7 ] -ch [integer | integerK | integerM | integerP ] ...
Applies to Windows NT, Windows 95/98

22
Chapter 2 The Database Server

Description This option limits the cache that the database server can take during
automatic cache growth. By default the upper limit is approximately the
lower of 256 Mb and 90% of the physical memory of the machine.
$ For the meaning and usage of the cache size arguments and the K, M,
and P characters, see "–c command-line option" on page 21.
See also "–c command-line option" on page 21
"–ca command-line option" on page 22
"–cl command-line option" on page 23

–cl command-line option


Function Sets a minimum cache size, as a lower limit to automatic cache resizing.
Syntax [ dbsrv7 | dbeng7 ] -cl [integer | integerK | integerM | integerP ] ...
Applies to Windows NT
Description This option sets a lower limits to the cache. The default minimum cache size
is the initial cache size.
$ For the meaning and usage of the cache size arguments and the K, M,
and P characters, see "–c command-line option" on page 21.
See also "–c command-line option" on page 21
"–ca command-line option" on page 22
"–ch command-line option" on page 22

–cs command-line option


Function Display cache size changes in the database server window.
Syntax [ dbsrv7 | dbeng7 ] -cs...
Applies to All platforms with dynamic cache sizing.
Description For troubleshooting purposes, display cache information in the database
server window whenever the cache size changes.

–ct command-line option


Function Enable character set translation.
Syntax [ dbsrv7 | dbeng7 ] -ct ...
Applies to All operating systems except NetWare and Windows CE.

23
The database server

Description Character set translation converting strings between character sets that
represent the same characters, but at different values. This is useful when the
client machine and the database use different character sets.
$ For more information, see "Starting a database server using character
set translation" on page 314 of the book ASA User’s Guide.

–d command-line option
Function Disable asynchronous I/O.
Syntax [ dbsrv7 | dbeng7 ] -d ...
Applies to Windows NT, NetWare
Description Use synchronous I/O rather than asynchronous I/O. Asynchronous I/O is
generally the preferred option.

This option applies only to Windows NT and NetWare systems, which use
asynchronous I/O by default.

–e command-line option
Function Encrypt all packets transmitted to and from all clients.
Syntax [ dbsrv7 | dbeng7 ] -e...
Applies to All operating systems and servers.
Description By default, communication packets are not encrypted, thus posing a potential
security risk. If you are concerned about the security of network packets, use
the -e switch. Encryption does marginally affect performance.

–ga command-line option


Function Unload database after last connection dropped.
Syntax [ dbsrv7 | dbeng7 ] -ga ...
Applies to All operating systems except NetWare.
Description The meaning of this switch depends on whether you are running a personal
server or a network server.
♦ Network server Specifying this switch on the network server causes
each database to be unloaded after the last connection to it is dropped.
The database server itself does not shut down.

24
Chapter 2 The Database Server

♦ Personal server In addition to unloading each database after the last


connection is dropped, the personal server shuts down when the last
database is stopped.

–gb command-line option


Function Set the database process priority class.
Syntax [ dbsrv7 | dbeng7 ] -gb [ idle | normal | high | maximum ] ...
Applies to Windows NT
Description Set the database process priority class. The value idle is provided for
completeness, and maximum may interfere with the running of your
computer. Normal and high are the commonly used settings.

–gc command-line option


Function Set maximum desired interval between checkpoints.
Syntax [ dbsrv7 | dbeng7 ] -gc integer...
Applies to All operating systems and servers.
Description Set the maximum desired length of time in minutes that the database server
runs without doing a checkpoint on each database.

The default value is 60 minutes.

When a database server is running with multiple databases, the checkpoint


time specified by the first database started is used unless overridden by this
switch. If a value of 0 is entered, the default value of 60 minutes is used.
Checkpoints generally occur more frequently than the specified time. For
more information, see "How the database server decides when to checkpoint"
on page 653 of the book ASA User’s Guide.
See also "CHECKPOINT_TIME option" on page 165.
"Checkpoints and the checkpoint log" on page 650 of the book ASA User’s
Guide

–gd command-line option


Function Set permissions required to start a database.
Syntax [ dbsrv7 | dbeng7 ] -gd [ dba | all | none ] ...
Applies to All operating systems and servers.

25
The database server

Description This is the permission required for a user to cause a new database file to be
loaded by the server. The level can be one of the following:
♦ dba Only users with DBA authority can start new databases.
♦ all All users can start new databases.
♦ none Starting new databases is not allowed.

The default setting is ALL for the personal database server and DBA for the
network database server. Both uppercase and lowercase syntax is acceptable.
Example The following set of steps illustrates how to use the –gd option for the
network database server.
1 Enter a password in the util_db.ini file in your SQL Anywhere win32
directory:
[UTILITY_DB]
pwd=mypwd
2 Start the network database server:
dbsrv7 -x tcpip -n myserver -gd dba
3 Connect to the utility database from Interactive SQL.
The following command assumes that myserver is the default database
server:
dbisql -c "uid=dba;pwd=mypwd;dbn=utility_db "
4 Start a database:
start database asademo
on myserver;
5 Connect to the database you have started:
connect
to myserver
database asademo
user DBA identified by SQL

–ge command-line option


Function Set stack size for external functions.
Syntax [ dbsrv7 | dbeng7 ] -ge integer ...
Applies to Windows 95/98, Windows NT, NetWare
Description Sets the stack size for threads running external functions, in bytes. The
default is 16384 (16K).

26
Chapter 2 The Database Server

–gf command-line option


Function Disable firing of triggers by the server.
Syntax [ dbsrv7 | dbeng7 ] -gf...
Applies to All operating systems and servers.

–gk command-line option


Function Set the permission required to stop the database server using dbstop.
Syntax [ dbsrv7 | dbeng7 ] -gk [ dba | all | none ] ...
Applies to All operating systems and servers.
Description ♦ dba Only users with DBA authority can use dbstop to stop the server
(the default).
♦ all All users can use dbstop to stop the server.
♦ none The server cannot be stopped using dbstop.
Both uppercase and lower case syntax is acceptable.

–gl command-line option


Function Set the permission required to load data using LOAD TABLE, and to unload
data using UNLOAD or UNLOAD TABLE.
Syntax [ dbsrv7 | dbeng7 ] -gl [ dba | all | none ] ...
Applies to All operating systems and servers.
Description Using the UNLOAD TABLE or UNLOAD statements places data in files on
the database server machine, and the LOAD TABLE statement reads files
from the database server machine.
To control access to the file system using these statements, the –gl
command-line option allows you to control the level of database permission
that is required to use these statements.
The allowed values are as follows:
♦ dba Only users with DBA authority can load or unload data from the
database.
♦ all All users can load or unload data from the database.
♦ none Data cannot be unloaded or loaded.
Both uppercase and lower case syntax is acceptable.

27
The database server

The default settings are all for personal database servers on non-Unix
operating systems, and dba for the network database server and the Unix
personal server. These settings reflect the fact that, on non-UNIX platforms,
the personal database server is running on the current machine, and so the
user already has access to the file system.

–gm command-line option


Function Limit the number of concurrent connections to the server.
Syntax [ dbsrv7 | dbeng7 ] -gm integer...
Applies to All operating systems and servers.
Description If this number is greater than the number that is allowed under licensing and
memory constraints, it has no effect.

–gn command-line option


Function Set the number of execution threads.
Syntax [ dbsrv7 | dbeng7 ] -gn integer...
Applies to All operating systems and servers.
Description Set the number of execution threads to be used in the database server. Each
connection uses a thread for each request, and when the request is completed
the thread is returned to the pool for use by other connections. As no
connection can have more than one request in progress at one time, no
connection uses more than one thread at a time.
An exception to this rule is if a Java application uses threads. Each thread in
the Java application is a database server execution thread.
The default is 20 threads for the network database server, and 10 threads for
the personal database server. The number of threads cannot be greater than
the number of server connections, so the maximum number of threads for the
personal database server is also 10.

–gp command-line option


Function Set the maximum allowed database page size.
Syntax [ dbsrv7 | dbeng7 ] -gp [ 1024 | 2048 | 4096 ] ...
Applies to All operating systems and servers.
Description Database files with a page size larger than the page size of the server cannot
be loaded. This switch explicitly sets the page size of the server, in bytes.
28
Chapter 2 The Database Server

If you do not use this switch, then the page size of the first database on the
command line is used.
The minimum page size on all UNIX platforms is 2048 bytes. You can still
use databases with smaller page sizes, but cache memory is used very
inefficiently. If you do not use this switch and start a server with no
databases loaded, the default value is 2048.
On all other platforms, if you do not use this switch and start a server with no
databases loaded, the default value is 1024.

–gr command-line option


Function Set the maximum length of time (in minutes) for recovery from system
failure.
Syntax [ dbsrv7 | dbeng7 ] -gm integer...
Applies to All operating systems and servers.
Description When a database server is running with multiple databases, the recovery time
that is specified by the first database started is used unless overridden by this
switch.
$ For more information, see "RECOVERY_TIME option" on page 195.

–gss command-line option


Function Set the stack size per internal execution thread in the server.
Syntax [ dbsrv7 | dbeng7 ] -gss [ integer | integerK | integerM ] ...
Applies to This option has no effect on Windows operating systems.
Description The number of internal execution threads is controlled by the -gn option, and
has a default value of 20. The default stack size per internal execution thread
is 16KB. The -gss option allows you to lower the memory usage of the
database server in environments with limited memory.

–gt command-line option


Function Set the number of CPUs to use for request processing.
Syntax [ dbsrv7 | dbeng7 ] -gt integer ...
Applies to All operating systems and servers except NetWare.

29
The database server

Description By default, on Windows operating systems and NetWare, the network


database server uses all CPUs available on the machine, the personal
database server is limited to two processors, and the runtime database server
uses a single processor. On UNIX, all database servers use all available
processors by default.

–gu command-line option


Function Set permission levels for utility commands.
Syntax [ dbsrv7 | dbeng7 ] -gu [ all | none | dba | utility_db ] ...
Applies to All operating systems and servers.
Description Sets permission levels for utility commands such as CREATE DATABASE
and DROP DATABASE. The level can be set to one of the following:
utility_db, all, none, dba.

The utility_db level restricts the use of these commands to only those users
who can connect to the utility database. The all, none, and dba levels permit
all users , no users, or users with dba authority to execute utility commands.

–gw command-line option


Function Set the interval for background processing.
Syntax [ dbsrv7 | dbeng7 ] -gw milliseconds...
Applies to All operating systems and servers.
Description Sets the interval for background processing, in milliseconds. At each
interval, the server carries out one I/O operation. The default setting is 500
(half a second).

–gx command-line option


Function Set the number of execution threads.
Syntax [ dbsrv7 | dbeng7 ] -gx integer ...
Applies to Windows 95/98, Windows NT
Description By default, this is set to one more than the number of CPUs on the machine.
You may want to use a larger number of threads if you wish to use remote
data access and use a large number of tables.

30
Chapter 2 The Database Server

On UNIX, each task is executed in its own thread, so that the number of
tasks (-gn) also determines the number of threads.

–m command-line option
Function Delete the transaction log when a checkpoint is done.
Syntax [ dbsrv7 | dbeng7 ] -m ...
Applies to All operating systems and servers.
Description This option deletes the transaction log when a checkpoint is done, either at
shutdown or as a result of a checkpoint scheduled by the server.

Caution
When this option is selected, there is no protection against media failure
on the device that contains the database files.

This provides a way to automatically limit the growth of the transaction log.
Checkpoint frequency is still controlled by the CHECKPOINT_TIME and
RECOVERY_TIME options (which you can also set on the command line).

This option is useful where high volume transactions that require fast
response times are being processed, and the contents of the transaction log
are not being relied upon for recovery or replication.

To avoid database file fragmentation, it is recommended that where this


option is used, the transaction log be placed on a separate device or partition
from the database itself.

Replicated databases
Do not use the -m option with databases that are being replicated.
Replication inherently relies on transaction log information.

–n command-line option
Function Set the name of the database server.
Syntax [ dbsrv7 | dbeng7 ] -n string ...
Applies to All operating systems and servers.
See also "Identifiers" on page 211
"EngineName connection parameter" on page 55

31
The database server

Description By default, the database server receives the name of the database file with
the path and extension removed. For example, if the server is started on the
file c:\sybase\asa6\asademo.db and no -n switch is specified, the name of
the server is asademo.
The server name is interpreted according to the character set of the machine,
as no database collation exists at startup time. It must be a valid identifier,
and long engine names are truncated to 40 characters. On NetBIOS, 16
characters is the maximum length.

The server name specifies the name to be used in the EngineName parameter
of client application connection strings or profiles. In all environments, there
is a default database server that will be used if no server name is specified,
provided at least one database server is running on the computer.

There are two n switches


The -n switch is positional. If it appears after a database file name, it has
a different meaning.
$ For more information, see "–n command-line option" on page 42.

–o command-line option
Function Print all server window output to a file.
Syntax [ dbsrv7 | dbeng7 ] -o filename ...
Applies to All operating systems and servers.
Description Print all server message window output to a file.

–os command-line option


Function Limit the file size for the server window output.
Syntax [ dbsrv7 | dbeng7 ] -os size...
Applies to All operating systems and servers.
Description Limit the size of the log file used by the –o switch. The default is no limit,
and the value is in bytes.
See also "–o command-line option" on page 32

32
Chapter 2 The Database Server

–p command-line option
Function Set the maximum size of communication packets.
Syntax [ dbsrv7 | dbeng7 ] -p integer...
Applies to All operating systems and servers.
Description The default is 512 bytes. The minimum value is 280 bytes and the maximum
is 16000.

–q command-line option
Function Do not display the server screen or its output.
Syntax [ dbsrv7 | dbeng7 ] -q...
Applies to All operating systems and servers, except NetWare.

–r command-line option
Function Opens a database in read-only mode. No changes to the database are
allowed. The database file and transaction log files are not modified by the
server.
Syntax [ dbsrv7 | dbeng7 ] -r ...
Applies to All operating systems and servers.
Description Opens all database files as read-only with the exception of the temporary file.
You can make changes on temporary tables, but ROLLBACK has no effect,
since the transaction and rollback logs are disabled.
Databases distributed on CD-ROM devices, and compressed databases are
examples of database files that cannot be modified. You can either create a
write file to allow changes to the database outside the database file, or run in
read-only mode.
If you attempt to modify the database, for example with an INSERT or
DELETE statement, a SQLSTATE_READ_ONLY_DATABASE error is
returned.
Databases that require recovery cannot be started in read-only mode. For
example, database files created using an online backup cannot be started in
read-only mode if there were any open transactions when the backup was
started, since these transactions would require recovery when the backup
copy is started.

33
The database server

–s command-line option
Function Set the user ID for syslog messages.
Syntax [ dbsrv7 | dbeng7 ] -s { none | user | login-id...}
Applies to UNIX
Description Sets the system user ID used in messages to the syslog facility. The default
is user, which uses the user ID for the database server process. A value of
none prevents any syslog messages from being logged.

–sc command-line option


Function Disable the shared memory communications protocol and use Named Pipes.
Syntax [ dbsrv7 | dbeng7 ] -sc...
Applies to Windows NT.
Description This option disables the shared memory communications protocol that is
used for same-machine communications, and starts the NamedPipes
protocol.
This option is implemented as part of an initiative to obtain C2 security
certification. It is likely to be of general use only for customers wanting to
run in a C2-certified environment.

–ti command-line option


Function Disconnect inactive connections.
Syntax [ dbsrv7 | dbeng7 ] -ti minutes ...
Applies to All operating systems and servers.
See also "sa_server_option system procedure" on page 942
Description Disconnect connections that have not submitted a request for minutes. The
default is 240 (4 hours). A client machine in the middle of a database
transaction holds locks until the transaction is ended or the connection is
terminated. The -ti option is provided to disconnect inactive connections,
freeing their locks.
The -ti option does not disconnect clients that use the shared memory
communications link.
Setting the value to zero disables checking of inactive connections, so that no
connections are disconnected.

34
Chapter 2 The Database Server

–tl command-line option


Function Set the period at which to send liveness packets.
Syntax [ dbsrv7 | dbeng7 ] -tl seconds ...
Applies to Network database servers using TCP/IP or SPX.
See also "sa_server_option system procedure" on page 942
Description A liveness packet is sent periodically across a client/server TCP/IP or SPX
communications protocol to confirm that a connection is intact. If the server
runs for a liveness timeout period (default 2 minutes) without detecting a
liveness packet, the communication is severed. The server drops any
connections associated with that client. UNIX non-threaded clients and TDS
connections do not do liveness checking.

The -tl switch on the server sets the liveness timeout for all clients that do
not specify a liveness period.

Liveness packets are sent at an interval of the (liveness timeout)/4.

–tmt command-line option


Function To set a reenlistment timeout for participation in distributed transactions.
Syntax [ dbsrv7 | dbeng7 ] -tmt [ milliseconds ]...
Applies to Windows NT only.
Description Used during recovery of distributed transactions. The value specifies how
long the database server should wait to be reenlisted. By default there is no
timout (the database server waits indefinitely).

–tmf command-line option


Function For recovery from distributed transactions in unusual circumstances.
Syntax [ dbsrv7 | dbeng7 ] -tmf ...
Applies to Windows NT only.
Description Used during recovery of distributed transactions when the distributed
transaction coordinator is not available. It could also be used if starting a
database with distributed transactions in the transaction log, on a platform
where the distributed transaction coordinator is not available.

35
The database server

Caution
If you use this option, distributed transactions are not recovered properly.
It is not for routine use.

–tq time command-line option


Function Shut down the server at a specified time.
Syntax [ dbsrv7 | dbeng7 ] -tq [ datetime | time ]...
Applies to All operating systems and servers.
See also "sa_server_option system procedure" on page 942
Description This is useful for setting up automatic off-line backup procedures (see
"Backup and Data Recovery" on page 627 of the book ASA User’s Guide).
The format for the time is in hh:mm (24 hour clock), and can be preceded by
an optional date. If a date is specified, the date and time must be enclosed in
double quotes and be in the format YYYY/MM/DD HH:MM.

–u command-line option
Function Open files using the operating system disk cache.
Syntax [ dbsrv7 | dbeng7 ] -u ...
Applies to Windows NT, Windows 95/98, UNIX
Description Files are opened using the operating system disk cache in addition to the
database cache.

While the operating system disk cache may improve performance in some
cases, in general better performance is obtained without this switch, using the
database cache only.

If the server is running on a dedicated machine, you should not use the -u
option, as the database cache itself is generally more efficient. You may want
to use the -u option if the server is running on a machine with several other
applications (so that a large database cache may interfere with other
applications) and yet IO-intensive tasks are run intermittently on the server
(so that a large cache will improve performance).

–ud command-line option


Function Run as a daemon.

36
Chapter 2 The Database Server

Syntax [ dbsrv7 | dbeng7 ] -ud ...


Applies to UNIX
Description Using this option lets you run the server so that it continues running after the
current operating system session ends.

–ut command-line option


Function Touch temporary files.
Syntax [ dbsrv7 | dbeng7 ] -ut minutes ...
Applies to UNIX
Description This switch causes the server to touch temporary files at specified intervals.

–v command-line option
Function Display the software version.
Syntax [ dbsrv7 | dbeng7 ] -v
Applies to All operating systems and servers.
Description Supplies the database server version in a message box, and then stops.

–x command-line option
Function Specify communications links.
Syntax [ dbsrv7 | dbeng7 ] -x {
all
| none
| { [ipx | namedpipes | netbios | spx | tcpip ] parmlist,... }
} ...
parmlist:
{ keyword=value;...}
Applies to All operating systems and servers.
See also "CommLinks connection parameter" on page 50
Description For example,
-x tcpip,spx

allows only TCP/IP and SPX communications.

37
The database server

A shared-memory protocol is provided for same-machine communications.


It is always made available for both network server and personal server.

The default set of communications links is to try all settings that are
supported by the database server that you are running on your operating
system, with the following exceptions:
♦ On Windows CE; the TCP/IP protocol is not started unless it is
explicitly requested.
♦ The IPX protocols is not started unless they are explicitly requested. It is
recommended that you use SPX instead of IPX.

The list is a comma-separated list of settings taken from the following case-
insensitive list:
♦ ALL Start all communications links that are supported on this platform
by the server that you are starting. This is the default.
♦ IPX Supported by NetWare, Windows NT, and Windows 95/98
network servers. This protocol is deprecated, and is not started by
default, as SPX provides a faster and more robust solution for IPX/SPX
communications.
♦ NamedPipes (NP) Supported on Windows NT, as an alternative
means of same-machine communication.
♦ NetBIOS Supported by Windows NT and Windows 95/98 network
database servers.
♦ NONE Do not start any communications links except for the shared
memory link.
♦ SPX Supported by NetWare, Windows NT, and Windows 95/98
network servers.
♦ TCPIP (TCP) Supported by the network server on all operating
systems. This communications link is also supported by the personal
database server for same-machine communications.
The database server always listens on port 2638, even if you specify a
different port using a network communication parameter. Hence,
applications can connect to the database server without specifying a port
number. For information, see "ServerPort parameter" on page 66.
An exception is the HP-UX operating system, on which the server does
not listen on port 2638 if it is started on another port.

For some protocols, additional parameters may be provided, in the format


-x tcpip(PARM1=value1;PARM2=value2;...)

38
Chapter 2 The Database Server

For UNIX, quotation marks are required if more than one parameter is
supplied:
-x "tcpip(PARM1=value1;PARM2=value2;...)"
$ For a description of available parameters, see "Network
communications parameters" on page 61.

–y command-line option
Function Run as a Windows 95/98 service.
Syntax [ dbsrv7 | dbeng7 ] -y ...
Applies to Windows 95/98
Description If the server registered as a Windows 95/98 service, it continues to operate
whether users log on or off, and shutdown commands are ignored.

–z command-line option
Function Display communications operations on startup for troubleshooting purposes.
Syntax [ dbsrv7 | dbeng7 ] -z ...
Applies to All operating systems and servers.
Description This should only be used when tracking problems. The information is
displayed in the database server window.

–zo command-line option


Function Redirect request-level logging information to a file separate from the regular
log file.
Syntax [ dbsrv7 | dbeng7 ] -z ...
Applies to All operating systems and servers.
See also "–zr command-line option" on page 40
"–zs command-line option" on page 40
Description Request-level logging is turned on using the –zr switch. You can direct the
output from this file to a separate file from that specified on a –o switch.
This switch also prevents request-level logging from being displayed in the
console.

39
The database server

–zr command-line option


Function Enable request-level logging of operations.
Syntax [ dbsrv7 | dbeng7 ] -zr { all | sql | none }...
Applies to All operating systems and servers.
See also "sa_server_option system procedure" on page 942
Description This should only be used when tracking problems. The information is
displayed in the database server window or sent to the logging file.

–zs command-line option


Function Limit the size of the request-level logging file.
Syntax [ dbsrv7 | dbeng7 ] -zs size...
Applies to All operating systems and servers.
See also "–zo command-line option" on page 39
"–zr command-line option" on page 40
Description Request-level logging is turned on using the –zr switch, and redirected to a
separate file using the –zo switch.. You can limit the size of the file using the
–zs switch.
By default there is no limit. The value is in bytes.

Recovery switches
These switches are for use in recovery situations only.

–a command-line option
Function Apply the named transaction log.
Syntax [ dbsrv7 | dbeng7 ] -a log-filename...
Applies to All operating systems and servers.
Description This is used to recover from media failure on the database file. When this
option is specified, the database server applies the log and then terminates—
it will not continue to run.
$ For information on recovery, see "Backup and Data Recovery" on
page 627 of the book ASA User’s Guide.

40
Chapter 2 The Database Server

–f command-line option
Function Force the database server to start after the transaction log has been lost.
Syntax [ dbsrv7 | dbeng7 ] -f ...
Applies to All operating systems and servers.
Description If there is no transaction log, the database server carries out a checkpoint
recovery of the database and then terminates—it does not continue to run.
You can then restart the database server without the -f option for normal
operation.

If there is a transaction log in the same directory as the database, the database
server carries out a checkpoint recovery, and a recovery using the transaction
log, and then terminates—it does not continue to run. You can then restart
the database server without the -f option for normal operation.
$ For more information see "Backup and Data Recovery" on page 627 of
the book ASA User’s Guide.

Database switches
These switches are entered after the database name, and apply only to that
database.

–m command-line option
Function Truncate the transaction log when a checkpoint is done.
Syntax [ dbsrv7 | dbeng7 ] [ server-switches ]. database-file -m ..
Applies to All operating systems and servers.
Description Truncate (delete) the transaction log when a checkpoint is done, either at
shutdown or as a result of a checkpoint scheduled by the server. This
provides a way to automatically limit the growth of the transaction log.
Checkpoint frequency is still controlled by the CHECKPOINT_TIME and
RECOVERY_TIME options (which you can also define on the command
line).

The -m option is useful where high volume transactions requiring fast


response times are being processed, and the contents of the transaction log
are not being relied upon for recovery or replication. When this option is
selected, there is no protection against media failure on the device that
contains the database files.

41
The database server

To avoid database file fragmentation, it is recommended that where this


option is used, the transaction log be placed on a separate device or partition
from the database itself.
This switch is the same as the -m server switch, but applies only to the
current database or the database identified by the database-file command-
line variable.

Replicated databases
Do not use the -m option with databases that are being replicated.
Replication inherently relies on transaction log information.

–n command-line option
Function Set the name of the database.
Syntax [ dbsrv7 | dbeng7 ] [ server-switches ]. database-file -n string ..
Applies to All operating systems and servers.
Description Both database servers and databases can be named. Since a database server
can load several databases, the database name is used to distinguish the
different databases.

By default, the database receives the name of the database file with the path
and extension removed. For example, if the database is started on
c:\asa7\asademo.db and no -n switch is specified, the name of the database
is asademo.

42
C H A P T E R 3

Connection and Communication


Parameters

About this chapter This chapter provides a reference for the parameters that establish and
describe connections from client applications to a database.
Contents
Topic Page
Connection parameters 44
Network communications parameters 61

43
Connection parameters

Connection parameters
This section describes each connection parameter. Connection parameters are
included in connection strings. They can be entered in the following places:
♦ In an application’s connection string. For more information, see
"Assembling a list of connection parameters" on page 65 of the book
ASA User’s Guide.
♦ In an ODBC data source. For more information, see "Working with
ODBC data sources" on page 47 of the book ASA User’s Guide.
♦ In the Adaptive Server Anywhere connection window. For more
information, see "Connecting from Adaptive Server Anywhere utilities"
on page 46 of the book ASA User’s Guide.
The ODBC configuration dialog and the Adaptive Server Anywhere
connection window for Windows operating systems share a common format.
Some of the parameters correspond to checkboxes and fields in these
windows, others can be entered in the text box at the end of the Advanced
tab.
Notes ♦ Connection parameters are case-insensitive.
♦ The Usage for each connection parameter describes the circumstances
under which the parameter is to be used. Common usage entries include
the following:
♦ Embedded databases When Adaptive Server Anywhere is used
as an embedded database, the connection starts a personal server
and loads the database. When the application disconnects from the
database, the database is unloaded and the server stops.
♦ Running local databases This refers to the case where an
Adaptive Server Anywhere personal server is already running, and
the database is already loaded on the server.
♦ Network servers When Adaptive Server Anywhere is used as a
network server, the client application must locate a server already
running somewhere on the network and connect to a database.
♦ You can use the dbping utility to test connection strings. For example, if
the database file MyDB.db is not currently running, the following string
returns the message Ping database successful:
dbping -d -c "dbf=c:\Databases\MyDB.db;astart=yes"
The following command, however, returns the message Ping database
failed – Database server not running, because Adaptive Server
Anywhere is unable to find a server for MyDB.db:

44
Chapter 3 Connection and Communication Parameters

dbping -d -c "dbf=c:\Databases\MyDB.db;astart=no"
$ For more information, see "The Ping utility" on page 114.

Agent connection parameter [Agent]


Function To restrict the type of connections attempted by the client.
Usage Anywhere
Values String. Must be one of the following:
♦ any
♦ engine or personal server.
♦ server or client
See also "CommLinks connection parameter" on page 50
Default No value
Description If you set the AGENT connection parameter to engine or personal server,
the application attempts to connect only to a database server running on the
same machine as the client. It attempts the following connections:
♦ Shared memory connection
♦ Named Pipes connection, for Adaptive Server Anywhere version 6
Windows 3.x applications running on Windows NT.
♦ TCP/IP connection to a database server running on the local machine.
This is useful only for Adaptive Server Anywhere version 6 Windows
3.x applications running on Windows 95/98.
For the application to attempt a Named Pipes or TCP/IP connection, these
links must be specified in a CommLinks connection parameter. If a shared
memory link is available, it is always attempted first, even if CommLinks is
specified.
If you set the AGENT connection parameter to server or client, the client
attempts the following connection types:
♦ TCP/IP
♦ IPX
♦ NetBIOS
♦ SPX

45
Connection parameters

The database server may be running on the same machine, or on a different


machine. The client does not attempt to connect using shared memory,
Named Pipes, or DDE. The CommLinks connection parameter must specify
the appropriate protocol for it to be used.

AppInfo connection parameter [App]


Function To assist administrators in identifying the origin of particular client
connections from a database server.
Usage Anywhere
Default Empty string
Description This connection parameter is sent to the database server from
Embedded SQL, ODBC, or OLE DB clients, as well as Interactive SQL and
Sybase Central. It is not available from Open Client or jConnect applications
such as Interactive SQL or Sybase Central.
It consists of a generated string that holds information about the client
process, such as the IP address of the client machine, the operating system it
is running on, and so on. The string is associated in the database server with
the connection, and you can retrieve it using the following statement:
select connection_property( ’appinfo’ )

Clients can also specify their own string, which is appended to the generated
string. The AppInfo property string is a sequence of semi-colon-delimited
key=value pairs. The valid keys are as follows:
♦ IP The IP address of the client machine (Unix and NetWare only)
♦ HOST The host name of the client machine
♦ OS The operating system name and version number (for example,
Windows NT 4.0, NetWare 3.12)
♦ PID The process ID of the client (Windows and Unix only)
♦ THREAD The thread ID of the client (Windows and Unix only)
♦ EXE The name of the client executable (Windows and NetWare only)
♦ VERSION The version of the connection protocol in use, including
major and minor values, and a build number (for example 7.0.00.3642)
♦ APPINFO If you specified APPINFO in the connection string, the
string entered
Examples ♦ Connect to the default database from the C++ version of
Interactive SQL:

46
Chapter 3 Connection and Communication Parameters

dbisqlc -c uid=dba;pwd=sql
View the application information:
select connection_property(’appinfo’)
The result is as follows (in a single string):
HOST=machine-name;
OS=Windows NT 4.0;
PID=0x11b;
THREAD=0x102;
VERSION=7.0.00.3642
♦ Connect to the default database from the C++ version of
Interactive SQL, appending your own information to the AppInfo
property:
dbisqlc -c "uid=dba;pwd=sql;app=ISQL connection"
View the application information:
select connection_property(’appinfo’)
The result is as follows (in a single string):
HOST=machine-name;
OS=Windows NT 4.0;
PID=0x10e;
THREAD=0xe1;
VERSION=7.0.00.3642;
APPINFO=ISQL connection

AutoStart connection parameter [Astart]


Function To prevent a local database server from being started if no connection is
found.
Usage Anywhere
Default Yes
Description By default, if no server is found during a connection attempt, and a database
file is specified, then a database server is started on the same machine. You
can turn this behavior off by setting the AutoStart parameter to No or OFF in
the connection string.

AutoStop connection parameter [Astop]


Function To prevent a database from being stopped as soon as there are no more open
connections.

47
Connection parameters

Usage Embedded databases


Default Yes
Description By default, any server that is started from a connection string is stopped
when there are no more connections to it. Also, any database that is loaded
from a connection string is unloaded as soon as there are no more
connections to it. This behavior is equivalent to Autostop=Yes.
If you supply Autostop=No, any database that you start in that connection
remains running when there are no more connections to it. As a consequence,
the database server remains operational as well.
The AutoStop parameter is used only if you are connecting to a database that
is not currently running. It is ignored if the database is already started.

CharSet connection parameter [CS]


Function To specify the character set to be used on this connection.
Usage Anywhere
Default The local character set. For information on how this is determined, see
"Determining locale information" on page 311 of the book ASA User’s
Guide.
Description If you supply a value for CharSet, the specified character set is used for the
current connection.
$ For a list of valid character set values, see "Character set labels" on
page 291 of the book ASA User’s Guide.

CommBufferSize connection parameter [CBSize]


Function To set the maximum size of communication packets, in bytes.
Usage Anywhere
Values Integer
Default 1024
Description The CommBufferSize parameter specifies the size of communications
packets, in bytes. The minimum value of CommBufferSize is 300, and the
maximum is 16000. If the specified packet size is larger than that of the
database server, the server’s packet size is used.

48
Chapter 3 Connection and Communication Parameters

The maximum size of a packet on a network is set by the protocol stack. If


you set CommBufferSize to be larger than that permitted by your network,
the largest buffers are broken up by the network software. You should set the
buffer size to be somewhat smaller than that allowed by your network,
because the network software may add information to each buffer before
sending it over the network.
A larger packet size improves performance for multi-row fetches and fetches
of larger rows. As each connection has its own pool of buffers, a large buffer
size increases the memory usage. The application side uses four default-sized
buffers per connection, and on the server side, there are two.
This corresponds to the SQL Anywhere Version 5 dbclient –p command-line
switch.
The value is a global setting: the value is set on the first connection attempt
for a session, and that value is used for all connections until the client library
is closed down.
Examples ♦ To set the buffer size to 400 bytes:
...
CommBuffSize=400
...
Alternatively, you can set this parameter by entering its value in the Buffer
size text box of the Network tab of the connection window.

CommBufferSpace connection parameter [CBSpace]


Function To specify the amount of space to allocate on startup for communication
buffers, in kilobytes.
Usage Anywhere
Values Integer
Default 10
Description Specify amount of space to allocate on startup for communication buffers, in
kilobytes. The value is a global setting: the value is set on the first
connection attempt for a session, and that value is used for all connections
until the client library is closed down.
Examples The following connection string fragment instructs the network library to
allocate 200 kb for network buffers on startup.
CBSpace=200

49
Connection parameters

You can set this parameter by entering its value in the Buffer space text box
of the Network tab of the connection window.

CommLinks connection parameter [Links]


Function To specify network communications links.
Usage Anywhere
Default Use only the shared memory communications link to connect.
See also "Network communications parameters" on page 61
"Client/Server Communications" on page 81 of the book ASA User’s Guide
"–x command-line option" on page 37
Description If no CommLinks parameter is specified in a connection string, no search is
made for a server other than on the current machine, and only a shared
memory connection is attempted. This behavior is equivalent to
CommLinks=None.

The shared memory protocol is used for communication between a client and
server running under the same operating system on the same machine, as is
typical for applications connecting to the personal database server.

If a CommLinks parameter is supplied, the named communication links are


started and used when searching for a database server. The CommLinks
parameter is required for connections to a network server.
Available values of the CommLinks parameter are case insensitive, and are
as follows:
♦ ALL Start all available communications links except IPX and
NamedPipes.
♦ IPX Start the IPX communications link. The IPX protocol is currently
supported for Windows and NetWare clients. In a future version, IPX of
this software, IPX support will be dropped. It is recommended that you
use SPX instead.
♦ NamedPipes (NP) For C2 security purposes, connect from a
Windows NT client to a database server on the same machine that was
started with the –sc command-line option.
♦ NetBIOS Start the NetBIOS communications link. NetBIOS is
supported on Windows operating systems.
♦ NONE Start no communications links.

50
Chapter 3 Connection and Communication Parameters

♦ SharedMemory (ShMem) Start the shared memory link for same-


machine communication.
♦ SPX Start the SPX communications link. The SPX protocol is
supported for Windows and NetWare clients.
♦ TCPIP (TCP) Start the TCP/IP communications link. TCP/IP is
supported on all operating systems.
Each of these values can have additional network communications
parameters supplied.
$ For a list of parameters, see "Network communications parameters" on
page 61.
You may wish to use a specific protocol, as opposed to ALL, for the
following reasons:
♦ The network library starts slightly faster if unnecessary network links
are not started.
♦ Connecting to the database may be faster.
♦ If you wish to tune the broadcast behavior of a particular protocol by
providing additional network communications parameters, you must
specify the link explicitly.
Additional network communications parameters may be provided for each
link, to tune the broadcast behavior of the link.
The CommLinks parameter corresponds to the database server –x
command-line switch. The default behavior of the network server is
equivalent to -x ALL.
Examples ♦ The following connection string fragment starts the TCP/IP protocol
only:
CommLinks=tcpip
♦ The following connection string fragment starts the TCP/IP and IPX
protocols, searching for the host kangaroo in addition to servers on the
immediate TCP/IP network:
CommLinks=ipx,tcpip(HOST=kangaroo)

ConnectionName connection parameter [CON]


Function Names a connection, to make switching to it easier in multi-connection
applications.
Usage Not available for ODBC.

51
Connection parameters

Default No connection name.


Description An optional parameter, providing a name for the particular connection you
are making. You may leave this unspecified unless you are going to establish
more than one connection, and switch between them.
The connection name is not the same as the data source name.
Examples ♦ Connect, naming the connection FirstCon:
CON=First Con

DatabaseFile connection parameter [DBF]


Function The database file to which you want to connect.
Usage Embedded databases
Default There is no default setting.
Description To load and connect to a specific database file.
♦ If a database is loaded with a name that is the same as the DatabaseFile
parameter, but without the .db extension, the connection is made to that
database instead.
♦ If the filename does not include an extension, a file of name .db is
looked for.
♦ The path of the file is relative to the working directory of the database
server. If you start the server from the command prompt, the working
directory is the directory that you are in when entering the command. If
you start the server from an icon or shortcut, it is the working directory
that the icon or shortcut specifies.
You can also use UNC filenames and Novell NetWare Directory Services
file names. For information, see "The database server" on page 14.

Caution
The database file must be on the same machine as the database server.
Managing a database file that is located on a network drive can lead to
file corruption.

Example ♦ To load and connect to the sample database, installed in directory


c:\asa6, use the following DBF parameter:
DBF=c:\asa7\asademo.db

52
Chapter 3 Connection and Communication Parameters

DatabaseName connection parameter [DBN]


Function Identifies a loaded database to which a connection needs to be made.
Usage Running local databases or network servers.
Default There is no default setting.
Description Whenever a database is started on a server, it is assigned a database name.
The default database name is the name of the database file with the extension
and path removed.
Examples ♦ Connect to a running database named Kitchener:
DBN=Kitchener

DatabaseSwitches connection parameter [DBS]


Function To provide database-specific switches when starting a database.
Usage Connecting to a running server when the database is not loaded.
Default No switches
See also "The database server" on page 14
"StartLine connection parameter" on page 59
Description You should supply DatabaseSwitches only if you are connecting to a
database that is not currently running. When the server starts the database
specified by DatabaseFile, the server uses the supplied DatabaseSwitches
as command line options to determine startup options for the database.
Only database switches can be supplied using this parameter. Server
switches must be supplied using the START connection parameter.
Examples ♦ The following command, entered all on one line at the command
prompt, connects to the default database server, loads the database file
asademo.db (DBF parameter), names it as my_db (DBS parameter) and
connects to the database of that name (DBN parameter).
dbcollat -c
"uid=dba;pwd=sql;dbf=asademo.db;dbn=my_db;dbs=-n
my_db" e:\temp\temp.col

DataSourceName connection parameter [DSN]


Function Tells the ODBC driver manager or Embedded SQL library where to look in
the odbc.ini file or registry to find ODBC data source information.

53
Connection parameters

Usage Anywhere
Default There is no default data source name.
See also "FileDataSourceName connection parameter" on page 56
Description It is common practice for ODBC applications to send only a data source
name to ODBC. The ODBC driver manager and ODBC driver locate the data
source, which contains the remainder of the connection parameters.
In Adaptive Server Anywhere, Embedded SQL applications can also use
ODBC data sources to store connection parameters.
Examples ♦ The following parameter uses a data source name:
DSN=Dynamo Demo

Debug connection parameter [DBG]


Function To provide diagnostic information on communications links on startup.
Usage Anywhere
Default No diagnostic information
See also "Logfile connection parameter" on page 58
Description If you are having trouble establishing a connection to a network server, set
the Debug connection parameter to Yes and the Logfile parameter to a log
file name. Diagnostic information is then placed in the log file.
Examples ♦ The following data source fragment says to use the Debug switch, with
output to a file named error.log.
...
DBG=Yes;
Log=ERROR.LOG
...

DisableMultiRowFetch connection parameter [DMRF]


Function To turn off multi-row fetches across the network
Usage Anywhere
Default No

54
Chapter 3 Connection and Communication Parameters

Description By default, when the database server gets a simple fetch request, the
application asks for extra rows. You can disable this behavior by setting this
parameter to ON.
$ For more information, see "Using cursors in procedures and triggers"
on page 458 of the book ASA User’s Guide.
$ Setting the DisableMultiRowFetch parameter to ON is equivalent to
setting the PREFETCH option to OFF. For more information, see
"Prefetching rows" on page 272 of the book ASA User’s Guide.
Examples ♦ The following connection string fragment prevents prefetching:
DMRF=Yes

EngineName connection parameter [ENG]


Function Synonym for ServerName. The name of a running database server to which
you want to connect.
Usage Network servers or running personal servers.
Default The default local database server.
See also "Identifiers" on page 211
"–n command-line option" on page 31
Description EngineName is not needed if you wish to connect to the default local
database server.
You need to supply an EngineName only if more than one local database
server is running, or you wish to connect to a network server.
In the Sybase Central and Interactive SQL Connect dialog box, and in the
ODBC Administrator, this is the Server Name field.
The server name is interpreted according to the character set of the client
machine. It must be a valid identifier, and long engine names are truncated to
40 characters. On NetBIOS, 16 characters is the maximum length.
Examples ♦ Connect to a server named Guelph:
ENG=Guelph

EncryptedPassword connection parameter [ENP]


Function To provide a password, stored in an encrypted fashion in a data source.

55
Connection parameters

Usage Anywhere
Default None
Description Data sources are stored on disk as a file or in the registry. Storing passwords
on disk may present a security problem. For this reason, when you enter a
password into a data source, it is stored in an encrypted form.
If both Password and EncryptedPassword are specified, Password takes
precedence.

Encryption connection parameter [ENC]


Function To encrypt packets sent between the client application and the server.
Usage Anywhere
Values Boolean
Default No encryption
Description You can use this parameter if you are concerned about the security of
network packets. Encryption does affect performance marginally.
This parameter corresponds to the SQL Anywhere Version 5 dbclient –e
command-line switch.

Using the -e switch on the dbsrv7 command line encrypts packets for all
clients regardless of whether the Encryption parameter is used at the client.
Similarly, if the client asks for encryption, the server will encrypt.

FileDataSourceName connection parameter [FileDSN]


Function The FileDataSourceName parameter tells the client library that there is an
ODBC file data source holding information about the database to which you
want to connect.
Both ODBC and Embedded SQL applications can use File data sources
Usage Anywhere
Default There is no default name.
See also "DataSourceName connection parameter" on page 53
Description File data sources hold the same information as ODBC data sources stored in
the registry. File data sources can be easily distributed to end users, so that
connection information does not have to be reconstructed on each machine.

56
Chapter 3 Connection and Communication Parameters

Integrated connection parameter [INT]


Function To use the integrated login facility.
Usage Anywhere
Default No
See also "LOGIN_MODE option" on page 183
Description The Integrated parameter has the following settings:
♦ Yes An integrated login is attempted. If the connection attempt fails
and the LOGIN_MODE option is set to Mixed, a standard login is
attempted.
♦ No This is the default setting. No integrated login is attempted.
For a client application to use an integrated login, the server must be running
with the LOGIN_MODE database option set to Mixed or Integrated.
Examples ♦ The following data source fragment uses an integrated login:
INT=yes

LivenessTimeout connection parameter [LTO]


Function To control the termination of connections when they are no longer intact.
Usage Network server only
Windows 95/98 and NT, NetWare and multi-threaded UNIX applications
only.
Values Integer
Default If no LivenessTimeout value is set, the liveness timeout is controlled by the
setting on the server, which defaults to 120 seconds.
Description A liveness packet is sent periodically across a client/server TCP/IP, SPX,
IPX, or NetBIOS communications protocol to confirm that a connection is
intact. If the client runs for the liveness timeout period without detecting a
liveness packet, the communication is severed.

Liveness packets are sent at an interval of one quarter of the


LivenessTimeout value when the connection is idle; that is, there have been
no request or response packets sent back and forth for at least one quarter of
the LivenessTimeout value.
Examples ♦ The following sets a Liveness timeout value of 60 seconds

57
Connection parameters

LTO=60
Alternatively, you can set this parameter by entering its value in the Liveness
timeout text box of the Network tab of the connection window.

Logfile connection parameter [LOG]


Function To send client error messages and debugging messages to a file.
Usage Anywhere
Default No log file
See also "Debug connection parameter" on page 54
Description If you want to save client error messages and debugging messages in a file,
use the Logfile parameter.
If the file name includes a path, it is relative to the current working directory
of the client application.

Password connection parameter [PWD]


Function To provide a password for the connection.
Usage Anywhere
Default No password provided.
See also "EncryptedPassword connection parameter" on page 55
Description Every user of a database has a password. The password must be supplied for
the user to be allowed to connect to the database.
The password parameter is not encrypted. If you are storing passwords in a
data source, you should use the EncryptedPassword parameter. Sybase
Central and the Adaptive Server Anywhere ODBC configuration tool both
use encrypted parameters.
If both Password and EncryptedPassword are specified, Password takes
precedence.
Examples ♦ The following connection string fragment supplies the user ID DBA and
password SQL.
uid=DBA;pwd=SQL
Alternatively, you can set these parameters in the User ID and Password
text boxes in the connection window.

58
Chapter 3 Connection and Communication Parameters

ServerName connection parameter [ENG]


Synonym for "EngineName connection parameter" on page 55.
$ For more information, see "EngineName connection parameter" on
page 55.

StartLine connection parameter [START]


Function To start a database server running from an application.
Usage Embedded databases
Default No StartLine parameter
Description You should supply a StartLine parameter only if you are connecting to a
database server that is not currently running. The StartLine parameter is a
command line to start a personal database server.
$ For a detailed description of available command line switches, see "The
database server" on page 14.
Examples ♦ The following data source fragment starts a personal database server
with a cache of 8 Mb.
StartLine=dbeng7 -c 8M asademo.db

Unconditional connection parameter [UNC]


Function To stop a server using dbstop even when there are connections to the server.
Usage Anywhere
Default No
See also "The dbstop command-line utility" on page 118
Description The dbstop command-line utility shuts down a database server. If you
specify unc=Yes in the connection string, the server is shut down even if
there are active connections. If Unconditional is not set to Yes, then the
server is shut down only if there are no active connections.
Examples ♦ The following command line shuts down the server unconditionally:
dbstop -c "uid=dba;pwd=sql;eng=server-name;unc=yes"

59
Connection parameters

Userid connection parameter [UID]


Function The user ID with which you log on to the database.
Usage Anywhere
Default None
Description You must always supply a user ID when connecting to a database
Examples ♦ The following connection string fragment supplies the user ID DBA and
password SQL:
uid=DBA;pwd=SQL

60
Chapter 3 Connection and Communication Parameters

Network communications parameters


If you experience problems with client/server network communications,
there are a number of command line parameters for both the client and the
server. These parameters enable you to work around peculiarities of different
network protocol implementations.
You can supply the network communication parameters on the server
command line as in the following example:
dbsrv7 -x tcpip(PARM1=value1;PARM2=value2;. . .),IPX
From the client side, the communications parameters are entered as the
CommLinks communication parameter:
CommLinks=tcpip(PARM1=value1;PARM2=value2;. . .),IPX
If there are spaces in a parameter, the network communication parameters
must be enclosed in quotation marks to be parsed properly by the system
command interpreter:
dbsrv7 -x "tcpip(PARM1=value 1;PARM2=value 2;...),IPX"
CommLinks="tcpip(PARM1=value 1;PARM2=value 2;...),IPX"
The quotation marks are required under UNIX if more than one parameter is
given, because UNIX interprets the semicolon as a command separator.
Boolean parameters are turned on with YES, ON, TRUE, or 1, and are turned
off with any of NO, OFF, FALSE, and 0. The parameters are case-
insensitive.
The examples provided should all be entered on a single line; you can also
include them in a configuration file and use the @ server command-line
switch to invoke the configuration file.
The parameters currently available are as follows.

ClientPort parameter [CPort]


Usage TCP/IP. Client side only.
Default Assigned dynamically per-connection by the networking implementation. If
you do not have firewall restrictions, it is recommended that you do not use
this parameter.
See also "Host parameter" on page 64
"DoBroadcast parameter" on page 62
"UseUDP parameter" on page 69
"Connecting across a firewall" on page 92 of the book ASA User’s Guide

61
Network communications parameters

This option is provided for connections across firewalls, as firewall software


Description
filters according to TCP/UDP port. It is recommended that you do not use
this parameter unless you need to for firewall reasons.
The ClientPort option designates the port number on which the client
application communicates using TCP/IP. You may specify a single port
number, or a combination of individual port numbers and ranges of port
numbers.
It is best to specify a list or a range of port numbers if you wish to make
multiple connections using a given Data Source or given connect string. If
you specify a single port number, then your application will be able to
maintain only one connection at a time. In fact, even after closing the one
connection, there is a short timeout period during which no new connection
can be made using the specified port. When you specify a list and/or range of
port numbers, the application keeps trying port numbers until it finds one to
which it can successfully bind.
Examples
♦ The following string makes a connection from an application using port
6000 to a server named my_server using port 5000:
CommLinks=tcpip{ClientPort=6000;ServerPort=5000};
ServerName=my_server
♦ The following string makes a connection from an application that can
use ports 5050 through 5060, as well as ports 5040 and 5070 for
communicating with a server named my_server using the default server
port:
CommLinks=tcpip{ClientPort=5040,5050-
5060,5070};ServerName=my_server

DoBroadcast parameter
Usage TCP/IP, IPX, SPX (Windows 95/98 and NT only)
Description On the client side, with DOBROADCAST=YES, a broadcast is performed to
search for a server if the server is not found in the bindery.
With DOBROADCAST=NO, 0, or OFF, no broadcast is performed to search
for a database server. In this case, you must specify the server host with the
HOST option.
For IPX only, you can also supply an address for the DOBROADCAST
argument. The address serves as a mask for the HOST parameter, and allows
you to specify a non-zero network number. This is intended for use when
broadcasting over a router. The network number is assigned by the network
administrator.

62
Chapter 3 Connection and Communication Parameters

In IPX, a node address consists of six numbers (up to 255 each) and the
network address consists of four digits, separated by colons.
Default Yes
Example ♦ The following command starts a client without broadcasting to search
for a database server. Instead, the server is looked for only on the
computer named silver.
CommLinks=tcpip(DOBROADCAST=NO;HOST=silver) asademo
♦ On an IPX network, the following parameter specifies a broadcast over
network 2:
CommLinks=ipx(dobroadcast=255:255:255:255:255:255/0:
0:0:2)

DLL parameter
Usage TCP/IP, SPX (Windows 95/98, Windows NT)
Description To support untested TCP/IP protocol stacks where the required networking
interface functions are in DLLs that differ from the default protocol stack.
The client or server looks for its required functionality in the named DLLs.
Default ♦ On Windows NT, the default is ws2_32.dll (Winsock 2.0).
♦ On Windows 95/98 the default is wsock32.dll (Winsock 1.1).
Example ♦ The following command starts a server using Winsock 1.1:
dbsrv7 -x tcpip(dll=wsock32.dll) asademo

ExtendedName parameter
Usage IPX (platforms other than Windows 95/98 or NT)
Description According to the Novell standard for legal SAP names, the following
characters are not allowed:
\ / : ; , * ? + -
If you start a server named "asademo-1", the default behavior is to strip out
the - and try to start a server asademo1. By turning on ExtendedName, the
name is left untouched.

63
Network communications parameters

Caution
Users should be wary of using this option as it is contrary to the SAP
standard.

Default No.
Example ♦ The following command starts a NetWare server with name asademo-1.
load dbsrv7.nlm -x ipx(ExtendedName=Yes) asademo-1

Host parameter [IP]


Usage TCP/IP, SPX, IPX (all platforms)
Where Server and client sides
See also "Debug connection parameter" on page 54
"UseUDP parameter" on page 69
Description HOST specifies additional machines outside the immediate network to be
searched by the client library. On the server, the search is carried out to avoid
starting a server with a duplicate name.
For TCP/IP, the hostname or a dot-separated IP address may be used. For
SPX and IPX, an address of the form a:b:c:d:e:f/g:h:i:j is used, where
a:b:c:d:e:f is the node number (Ethernet card address) of the server, and
g:h:i:j is the network number. The server prints this addressing information
during startup if the -Z switch is used. In addition, the application writes this
information to its logfile if Debug is set to TRUE and LogFile is specified.
You can use a semicolon-separated list of addresses to search for more than
one machine. Also, you can append a port number to an IP address, using a
colon as separator. Alternatively, you can specify the host and server ports
explicitly, as in Host=a:b:c:d:e:f;ServerPort=k.
IP is a synonym for HOST.
Default No additional machines.
Example ♦ The following connection string fragment instructs the client to look on
the machines "kangaroo" and 197.75.209.222 (port 2369) to find a
database server:
Links=tcpip(IP=kangaroo;IP=197.75.209.222:2369)

MaxLANA parameter
Usage NetBIOS
64
Chapter 3 Connection and Communication Parameters

Description Each path through a NetBIOS protocol stack is assigned a LAN adapter
number. By default, the server looks through all possible numbers up to 255.
To speed up server startup, you can truncate the search for valid LAN
adapters at a specified value using the MAXLANA parameter.
Default 255
Example ♦ The following command line looks only at LAN adapters with numbers
less than 10 to identify active protocol stacks:
dbsrv7 -x netbios(MaxLANA=10) asademo

MyIP parameter
Usage TCP/IP
Description The MyIP parameter is provided for machines with more than one network
adapter.
Each adapter has an IP address. By default, the database server uses the first
network card it finds. If you wish your database server to use more than one
network card, specify the address of each card in the MyIP parameter.
If the keyword NONE is supplied as the IP number, no attempt is made to
determine the addressing information. The NONE keyword is intended for
clients on machines where this operation is expensive, such as machines with
multiple network cards or remote access (RAS) software and a network card.
It is not intended for use on the server.
Under Windows 95/98 or Windows NT, this option can be used multiple
times for machines with multiple IP addresses.
You can optionally append a port number to the IP address, separated by a
colon.
Example ♦ The following command line (entered all on one line) instructs the
server to use two network cards, one with a specified port number.
dbsrv7 -x
tcpip(MyIP=192.75.209.12:2367,192.75.209.32)
c:\asa7\asademo.db
♦ The following connection string fragment instructs the client to make no
attempt to determine addressing information.
Links= tcpip(MyIP=NONE)

65
Network communications parameters

ReceiveBufferSize parameter
Usage TCP/IP
Description Sets the size for a buffer used by the TCP/IP protocol stack. You may want
to increase the value if blob performance over the network is important.
Default Machine-dependent.

RegisterBindery parameter [REGBIN]


Usage IPX, SPX (Windows 95/98 and NT only). Server side only.
Description The database server attempts to register its name with any active binderies on
the network when loading the IPX link. To disable this name registration, set
RegisterBindery to NO, FALSE or 0. In this case, the client library must be
able to locate the database server over IPX by broadcasting packets.
Default TRUE

SearchBindery parameter [BINSEARCH]


Usage IPX, SPX (Windows 95/98 and NT only)
Description With SEARCHBINDERY=NO, 0, or OFF no NetWare bindery is searched
for a database server.
Default Yes

SendBufferSize parameter
Usage TCP/IP
Description Sets the size for a buffer used by the TCP/IP protocol stack. You may want
to increase the value if blob performance over the network is important.
Default Machine-dependent.

ServerPort parameter [PORT]


Usage TCP/IP (all platforms)

66
Chapter 3 Connection and Communication Parameters

Description The Internet Assigned Numbers Authority has assigned the Adaptive Server
Anywhere database server port number 2638 to use for TCP/IP
communications. However, applications are not disallowed from using this
reserved port, and this may result in an addressing collision between the
database server and another application.
In the case of the database server, the ServerPort option designates the port
number on which to communicate using TCP/IP.
In a data source, the ServerPort option informs the client of the port or ports
on which database servers are listening for TCP/IP communication. The
client broadcasts to every port that is specified on the ServerPort parameter
to find the server.
The database server always listens on port 2638, even if you specify a
different port using a network communication parameter. Hence,
applications can connect to the database server without specifying a port
number. An exception is the HP-UX operating system, on which the server
does not listen on port 2638 if it is started on another port.
Default 2638
Example 1 Start a network database server:
dbsrv7 -x tcpip -n server1
Port number 2638 is now taken.
2 Attempt to start another database server:
dbsrv7 -x tcpip -n server2
The default port is currently allocated, and so the server starts on another
port.

Sessions parameter
Usage NetBIOS. Server side only.
Description Sets the maximum number of clients that can communicate with the server at
one time through a single LAN adapter. The default setting is operating-
system specific. The value is an integer, with maximum value 254.
NetBIOS network software has a limit to the number of commands allowed
per machine. Adaptive Server Anywhere uses these NetBIOS commands,
and disallows further connections if the system has no more commands
available, even if this is less than the value of the Sessions parameter.
Default Operating system specific. On Windows NT, the default is 16.

67
Network communications parameters

Example ♦ The following statement starts a server with a database named asademo,
allowing 200 NetBIOS connections.
dbsrv7 -x netbios(sessions=200) asademo.db

TDS parameter
Usage TCP/IP, NamedPipes. Server side only.
Description To disallow TDS connections to a database server, set TDS to NO. If you
want to ensure that only encrypted connections are made to your server,
these port options are the only way to disallow TDS connections.
Default YES
Example ♦ The following command starts a database server using the TCP/IP
protocol, but disallowing connections from Open Client or jConnect
applications.
dbsrv7 -x tcpip(TDS=NO) ...

Threads parameter
Usage IPX (Windows 95/98 and Windows NT)
Description THREADS specifies the number of threads that are used for reading network
communications. Integers from one to ten are allowed. It has been found that
two threads produces good performance, but the option is provided as a
performance parameter that you can tune.
Default 2
Example ♦ The following command starts a database server to use the IPX protocol
only, using three threads.
dbsrv7 -x ipx(threads=3) c:\asa7\asademo.db

ThreadStats parameter [STATS]


Usage IPX (Windows 95/98 and Windows NT only)
Description This option creates a file into which IPX thread statistics are written.
Currently, the only statistic written to the file is the number of packets
received by each executing IPX thread.
Default NULL

68
Chapter 3 Connection and Communication Parameters

Example ♦ The following statement places the statistics in the file ipxstat.txt in the
current directory.
dbsrv7 -x ipx(threadstats=ipxstat.txt)
c:\asa7\asademo.db

Timeout parameter [TO]


Usage TCP/IP, IPX, SPX (all platforms)
Description TIMEOUT specifies the length of time, in seconds, to wait for a response
when establishing communications. You may wish to try longer times if you
are having trouble establishing TCP/IP communications.
Default 5 seconds.
Example ♦ The following data source fragment starts a TCP/IP communications
link only, with a timeout period of twenty seconds.
...
CommLinks=tcpip(TO=20)
...

UseUDP parameter [UDP]


Usage TCP/IP, Client side only.
Allowed values ON, OFF
The Host option must also be used to specify the hosts.
Default ON
See also "ClientPort parameter" on page 61
"Host parameter" on page 64
"DoBroadcast parameter" on page 62
"Connecting across a firewall" on page 92 of the book ASA User’s Guide
Description This option controls whether or not UDP packets are used to locate a server
via the TCP/IP communications link.
UDP packets are refused by firewalls. It is recommended that you do not use
this parameter unless you need to for firewall reasons. You can set the
UseUDP option to OFF to assist in connecting across a firewall.
By default, and if UseUDP is ON, Adaptive Server Anywhere uses UDP to
locate database servers on the TCP/IP communications link. All subsequent
communications use TCP/IP, not UDP.

69
Network communications parameters

On the server side, you can avoid the use of UDP by specifying
DoBroadcast=NO, since the only UDP packets the server uses are to
broadcast to check for other servers with the same name.
Setting UDP=NO also implicitly sets DoBroadcast to NO, since UDP
packets are used for broadcasting.
When specifying UDP=NO, you must specify one or more IP addresses
where the server may be located, using the HOST parameter and the PORT
parameter. Each possible combination of host:port is attempted one at a time
until the requested server name is found.
When using UseUDP in conjunction with the ClientPort option, it is
recommended that multiple ports be supplied to the ClientPort option, for
example:
Examples Restrict the client application to ports 5050 through 5060, disable UDP
packets, and connect to the server named myeng running on the machine at
address myhost using the server port 2020.
Links=tcpip{UDP=no;ClientPort=5050-5060;Host=myhost;Port=2020;Eng=myeng}

The following example fails because no Host parameter is specified, and


broadcasting is implicitly turned off, so there is no way to find the server.
eng=engine_name;links=tcpip{udp=no}
The following example uses TCP connections to try host_1:2638 and
host_2:2638 until one of the addresses is running the server servername.
eng=servername;links=tcpip{udp=no;host=host_1, host_2}
The following example tries try myhost:1234, then myhost:5678
eng=myeng;links=tcpip{udp=no;host=myhost;port=1234,5678}
The following example fails, because setting UDP=no prevents a broadcast.
eng=my_eng;links=tcpip{udp=no;dobroadcast=yes}

70
C H A P T E R 4

Database Administration Utilities

About this chapter Adaptive Server Anywhere includes a set of utility programs for backing up
databases and performing other database administration tasks. This chapter
provides reference information for each of the database administration
utilities.
Contents
Topic Page
Administration utilities overview 73
The Backup utility 74
The Collation utility 78
The Compression utility 81
The Console utility 83
The Data Source utility 84
The Erase utility 88
The Information utility 90
The Initialization utility 92
The Interactive SQL utility 99
The License utility 101
The Log Transfer Manager 103
The Log Translation utility 109
The Ping utility 114
The REBUILD utility 115
The Server Location utility 116
The Spawn utility 117
The Stop utility 118
The Transaction Log utility 120
The Uncompression utility 124
The Unload utility 126

71
Administration utilities overview

The Upgrade utility 133


The Validation utility 136
The Write File utility 139

72
Chapter 4 Database Administration Utilities

Administration utilities overview


This chapter presents reference information on the programs and database
administration utilities that are part of Adaptive Server Anywhere. The
utilities can be accessed from Sybase Central, from Interactive SQL, or as
command-line programs.
$ For comprehensive documentation on Sybase Central, see the Sybase
Central online Help. For an introduction to the Sybase Central database
administration tool, see "Managing Databases with Sybase Central" on
page 35 of the book Introducing SQL Anywhere Studio.
The administration utilities use a set of system environment variables. These
variables are described in "Environment variables" on page 6.
Database file A set of SQL statements are available that carry out some of the tasks that
administration the administration utilities carry out. These statements are listed in "SQL
statements Statements" on page 365.

73
The Backup utility

The Backup utility


With the Backup utility, you can back up running databases, database files,
transaction logs, and write files.
You can access the Backup utility in the following ways:
♦ From Sybase Central
♦ From the system command line, using the dbbackup utility. This is
useful for incorporating backup procedures into batch or command files.
The Backup utility makes a backup copy of all the files for a single database.
A simple database consists of two files: the main database file and the
transaction log. More complicated databases can store tables in multiple
files, with each file as a separate dbspace. All backup filenames are the same
as the database filenames.
Running the Backup utility on a running database is equivalent to copying
the database files when the database is not running. Thus, you can back up
the database while other applications or users are using it.
$ For a description of suggested backup procedures, see "Backup and
Data Recovery" on page 627 of the book ASA User’s Guide.
$ For more information about the backup utility, see "BACKUP
statement" on page 389.

Backing up a database from Sybase Central

v To back up a running database:


1 Connect to the database.
2 Right-click the database and choose Backup in the popup menu. The
Backup wizard appears.
3 Follow the instructions in the wizard.

v To back up a database file or a running database:


1 Open the Utilities folder in the left panel.
2 Double-click Backup Database in the right panel.
3 Follow the instructions in the wizard.

74
Chapter 4 Database Administration Utilities

$ For full information on backing up a database from Sybase Central, see


"Backup and Data Recovery" on page 627 of the book ASA User’s Guide.
For more information about options, see "Backup utility options" on page 75

The dbbackup command-line utility


Syntax dbbackup [ switches ] directory

Switch Description
–c "keyword=value; ..." Supply database connection parameters
–d Only back up the main database file
–l file Live backup of the transaction log to a file
–n Change the naming convention for the backup
transaction log
–o filename Log output messages to a file
–q Quiet mode—do not print messages
–r Rename and start a new transaction log
–t Only back up the transaction log
–w Only back up the write file
–x Delete and restart the transaction log
–xo Delete and restart the transaction log without
making a backup
–y Replace files without confirmation

Description If none of the switches -d, -t, or -w are used, all database files are backed
up.
$ For more information about the command-line switches, see "Backup
utility options" on page 75.

Backup utility options


Directory The directory to which the backup files are copied. If the
directory does not exist, it is created. However, the parent directory must
exist.

75
The Backup utility

Connection parameters (–c) For a description of the connection


parameters, see "Connection parameters" on page 60 of the book ASA User’s
Guide. If the connection parameters are not specified, connection parameters
from the SQLCONNECT environment variable are used, if set. The user ID
must have DBA authority or REMOTE DBA authority.
For example, the following command backs up the asademo database
running on the server sample_server, connecting as user ID DBA with
password SQL, into the asabackup directory:
dbbackup -c "eng=sample_server;dbn=asademo;uid=DBA;pwd=SQL" asabackup

Backup main database only (–d) Back up the main database files only,
without backing up the transaction log file or a write file, if one exists.

Live backup (–l lower-case L) This option is provided to enable a


secondary system to be brought up rapidly in the event of a server crash. A
live backup does not terminate, but continues running while the server runs.
It runs until the primary server crashes. At that point, it is shut down, but the
backed up log file is intact and can be used to bring a secondary system up
quickly.

Change backup transaction log naming convention (–n) This option


is used in conjunction with -r. It changes the naming convention of the
backup transaction log file to yymmddnn.log, where nn is a number from 00
to 99 and yymmdd represents the current year, month and day.
The backup copy of the transaction log file is stored in the directory specified
on the command line, and with the yymmddnn.log naming convention. This
allows backups of multiple versions of the transaction log file to be kep in
the same backup directory.
The two-digit year notation does not cause any year 2000 problems. The
names are used solely for identification, not for ordering.

Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

Rename and start new transaction log (–r) This option forces a
checkpoint and the following three steps to occur:
♦ Step 1 The current working transaction log file is copied and saved to
the directory specified in the command line.

76
Chapter 4 Database Administration Utilities

♦ Step 2 The current transaction log remains in its current directory, but
is renamed using the format yymmddxx.log, where xx is a number from
00 to 99 and yymmdd represents the current year, month and day. This
file is then no longer the current transaction log.
♦ Step 3 A new transaction log file is generated that contains no
transactions. It is given the name of the file that was previously
considered the current transaction log, and is used by the database server
as the current transaction log.

Back up the transaction log file only (–t) This can be used as an
incremental backup since the transaction log can be applied to the most
recently backed up copy of the database file(s).

Back up the database write file only (–w) For a description of database
write files, see "The Write File utility" on page 139.

Delete and restart the transaction log (–x) Back up the existing
transaction log, then delete the original log and start a new transaction log.
This option causes the backup to wait for a point when all transactions from
all connections are committed.

Delete and restart the transaction log without a backup (–xo) Delete
the current transaction log and start a new one. This operation does not carry
out a backup; its purpose is to free up disk space in non-replication
environments.

Operate without confirming actions (–y) Choosing this option creates


the backup directory or the replacement of a previous backup file in the
directory without confirmation.

77
The Collation utility

The Collation utility


With the Collation utility, you can extract a collation (sorting sequence) into
a file suitable for creating a database using a custom collation.
The file that is produced can be modified and used with Sybase Central or
the -z option of dbinit to create a new database with a custom collation.
You must change the label on the following line in the collation file. If you
do not, the custom collation will conflict with the original collation on which
it is based.
Collation label (name)
$ For more information on custom collating sequences, see "Creating a
database with a custom collation" on page 317 of the book ASA User’s
Guide.
You can access the Collation utility in the following ways:
♦ From Sybase Central
♦ From the system command line, using the dbcollat command-line utility

Extracting a collation using Sybase Central

v To use the Collation utility from Sybase Central:


1 Open the Utilities folder in the left panel.
2 Double-click Create a Custom Collation in the right panel. The Custom
Collation wizard appears.
3 Follow the instructions in the wizard.

Tip
You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Create a Custom Collation.

The dbcollat command-line utility


Syntax dbcollat [ switches ] output-file

78
Chapter 4 Database Administration Utilities

Switch Description
–c "keyword=value; ..." Supply database connection parameters
–d mapping-file Convert the definition file to INSERT statements
with collation mapping placed in mapping-file
–e Include empty mappings
–o filename Log output messages to a file
–q Quiet mode — do not print messages
–x Use hex for extended characters (7F-FF)
–y Replace the file without confirmation
–z col-seq Specify a collating sequence label

$ For more information about the command-line switches, see "Collation


utility options" on page 79.

Collation utility options


Connection parameters (–c) For a description of the connection
parameters, see "Connection parameters" on page 60 of the book ASA User’s
Guide. If the connection parameters are not specified, connection parameters
from the SQLCONNECT environment variable are used, if set.
For example, the following command extracts a collation file from the
asademo database that is running on the sample_server server, and connects
as user ID DBA with password SQL:
dbcollat -c "eng=sample_server;dbn=asademo;uid=DBA;pwd=SQL" c:\sample\col

Convert the definition file to an INSERT statement (–d) When a


database is created, the collation is inserted into the SYS.SYSCOLLATION
system table. This collation is selected from the set of collations specified in
the scripts subdirectory of your Adaptive Server Anywhere installation
directory. Custom collations are added to the custom.sql script. The -d
switch converts the collation file that you edited into an INSERT statement
that can be copied into custom.sql.
From the dbcollat command-line utility you can use this option as follows:
dbcollat -d coll-defn-file cust-map-file custom-file

The coll-defn-file is read and parsed as a collation definition. Output is


written to cust-map-file and custom-file. The cust-map-file contents should
be added to custmap.sql, and custom-file contents to custom.sql.

79
The Collation utility

Include empty mappings (–e) Normally, collations don’t specify the


actual value that a character is to sort to. Instead, each line of the collation
sorts to one position higher than the previous line. However, older collations
have gaps between some sort positions. Normally, the Collation utility skips
the gaps and writes the next line with an explicit sort-position. This option
causes the Collation utility to write empty mappings (consisting of just a
colon (:)) for each line in the gap.

Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

Use hexadecimal for extended characters [ 7F to FF ] (–x) Extended


single-byte characters (whose value is greater than hex 7F) may or may not
appear correctly on your screen, depending on whether the code page on
your computer is the same as the code page of the collation that you are
extracting. This option causes the Collation utility to write any character to
hex 7F or above as a two-digit hexadecimal number, in the form \xdd. For
example:
\x80, \xFE

Without the –x option, only characters from \x00 to \x1F, \x7F and \xFF are
written in hexadecimal form.

Operate without confirming actions (–y) Choosing this option


automatically replaces an existing collation file without prompting for
confirmation.

Specify a collating sequence label (–z) Specify the label of the


collation to be extracted. The names of the available collation sequences can
be found by executing the following command:
dbinit -l

If this option is specified with one of the available collation labels, then
dbcollat does not connect to a database. Otherwise, it connects to a database
and extracts the collation of that database. If the collation label does not
match the collation label of the database, an error is returned.

80
Chapter 4 Database Administration Utilities

The Compression utility


With the Compression utility you can compress a database file. The
Compression utility reads the given database file and creates a compressed
database file. Compressed databases are usually 40 to 60 per cent of their
original size. The database server cannot update compressed database files:
they must be used as read-only files, in conjunction with write files.
The Compression utility does not compress files other than the main database
file. The database to be compressed must not be running.
You can access the Compression utility in the following ways:
♦ From Sybase Central
♦ From the system command line, using the dbshrink command-line
utility. This is useful for incorporating into batch or command files.

Compressing a database in Sybase Central

v To compress a database file:


1 Open the Utilities folder in the left panel.
2 Double-click Compress Database in the right panel. The Compress
Database wizard appears.
3 Follow the instructions in the wizard.

Tip
You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Compress Database.

The dbshrink command-line utility


Syntax dbshrink [ switches ] database-file [ compressed-database-file ]

Switch Description
–o filename Log output messages to a file
–q Quiet mode—do not print messages
–y Replace an existing output file without confirmation

81
The Compression utility

Description The dbshrink utility reads database-file and creates a compressed database
file. The compressed filename defaults to the same name as the original
database file, but with an extension of .cdb. The output filename (with
extension) must not be same as the input filename (with extension).
$ For more information about the command-line switches, see
"Compression utility options" on page 82.

Compression utility options


Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

Operate without confirming actions (–y) Choosing this option


automatically replaces existing compressed database file(s) without
requesting confirmation.

82
Chapter 4 Database Administration Utilities

The Console utility


The Console utility provides administration and monitoring facilities for
database server connections.
Syntax dbconsol [ switches ]
UNIX Syntax dbconsole [ switches ]

Switch Description
–c "keyword=value; ..." Supply database connection parameters

Description Start the server console utility.


The server console utility allows you to monitor the server from a client
machine. You can use it to track who is logged on to a database server
elsewhere on your network. You can also display both the server and the
client statistics on your local client screen, disconnect users and configure
the database server.

v To disconnect a user from a database:


1 Connect to the database from the Console utility.
2 Double-click the connection to display the Connection Detail window.
3 Click Disconnect to disconnect the specified connection from the
database.
Switches –c "keyword=value; ..." Specify connection parameters.
$ For a description of connection parameters, see "Connection
parameters" on page 60 of the book ASA User’s Guide.

83
The Data Source utility

The Data Source utility


Syntax dbdsn [ modifier-witches ]
{ –l | –d dsn | –g dsn | –w dsn [details-switch;…] | –cl }
Parameters Major switch Description
–l List defined data sources
–d dsn Delete the named data source
–g dsn List (get) details of the named data source
–w dsn [ details-switch ] Create (write) a data source definition
–cl List available connection parameters

Modifier switch Description


–b Brief. Print connection string for the data source
–q Quiet. Do not print banner
–v Verbose. Print connection parameters in tabular form
–y Delete or overwrite data source without confirmation

Details-switch Description
–c "keyword=value;…" Supply database connection parameters
–e Encrypt all network packets
–o filename Write client message to filename
–p size Set maximum network packet size
–r Disable multiple record fetching
–s size Set network buffer size
–t1 seconds Client liveness timeout period
–x list List network drivers to run
–z Display debugging information
server-name Connect to named database server

See also "Working with ODBC data sources" on page 47 of the book ASA User’s
Guide
"Using ODBC data sources on UNIX" on page 55 of the book ASA User’s
Guide

84
Chapter 4 Database Administration Utilities

Description The Data Source utility is a cross-platform alternative to the ODBC


Administrator for creating, changing, and deleting Adaptive Server
Anywhere ODBC data sources. On Windows operating systems, the data
sources are held in the registry. On UNIX operating systems, the data
sources are held in the .odbc.ini file. The utility is useful for batch operations.
The modifier switches can occur before or after the major switch
specification. The order makes a difference only when a connection
parameter value is specified more than once. In such a case, the last value
specified is used.
Major switches List defined data sources (–l )Lists the available Adaptive Server
Anywhere ODBC data sources. You can modify the list format using the –b
or –v switches.

Delete the named data source (–d ) Deletes the named data source.
You are prompted for confirmation unless you modify the instruction with –
y.

List (get) details of the named data source (–g ) List the definition of
the named data source. You can modify the format of the output using the –b
or –v switches.

Create (write) a data source definition (–w) Creates a new data source,
or overwrites one if one of the same name exists. If you supply –y, any
existing data source is overwritten without confirmation.

List available connection parameters (–cl) This convenience switch


lists the connection parameters supported by the dbdsn utility. You can
modify the list format using the –b or –v switches.
Modifier switches Print connection string for the data source (–b) Format the output of
the list as a single line connection string.

Do not print banner (–q) Suppress the informational banner.

Print connection parameters in tabular form (–v) Format the output of


the list over several lines, as a table.

Delete or overwrite data source without confirmation (–y) Choosing


this option automatically deletes each file without prompting you for
confirmation.
Details switches Connection parameters (–c) Specify connection parameters as a
connection string.
$ For more information, see "Connection parameters" on page 60 of the
book ASA User’s Guide.

85
The Data Source utility

The remainder of the details switches are supplied for users familiar with the
dbcli6.exe utility shipped with Adaptive Server Anywhere version 6.

Encrypt network packets (–e) Encrypt packets sent between the client
application and the server.
$ For more information, see "Encryption connection parameter" on
page 56.

Log output messages to file (–o) Write output messages to the named
file. By default, messages are written to the console.
$ For more information, see "Logfile connection parameter" on page 58.
Operate quietly (–q) Do not display output messages. This option is
available only from the command-line utility.

Operate without confirming actions (–y) Automatically carries out the


operation without prompting for confirmation.

Set maximum network packet size (–p) The maximum packet size for
network communications, in bytes. The value must be greater than 300, and
less than 16000. The default setting is 1024.
$ For more information, see "CommBufferSize connection parameter" on
page 48.

Disable multiple-record fetching (–r) By default, when the database


server gets a simple fetch request, the application asks for extra rows. You
can disable this behavior by using this switch.
$ For more information, see "DisableMultiRowFetch connection
parameter" on page 54.

Set network buffer size (–s) Sets the memory for network
communications buffers in kb. The value must be at least 10 and no more
than 1000. The default is 100.
$ For more information, see "CommBufferSpace connection parameter"
on page 49.
Set client liveness timeout (–tl) Terminates connections when they are
no longer intact. The value is in seconds.

The default is server setting, which in turn has a default of 120 seconds.
$ For more information, see "LivenessTimeout connection parameter" on
page 57.

Set communications links (–x) A comma separated list of network


drivers to run.

86
Chapter 4 Database Administration Utilities

$ For more information, see "CommLinks connection parameter" on


page 50.

Display debugging information (–z) Provide diagnostic information on


communications links on startup.
$ For more information, see "Debug connection parameter" on page 54.
Server name Connect to the named server. Only the first 40 characters are
used.
$ For more information, see "The database server" on page 14.
Examples Write a definition of the data source newdsn. Do not prompt for
confirmation if the data source already exists.
dbdsn -y -x tcpip -w newdsn -c "uid=dba;pwd=sql" -v
or, with a different switch order,
dbdsn -w newdsn -c "uid=dba;pwd=sql" -x tcpip -y

List all known data sources, one data source name per line:
dbdsn -l

List all data sources along with their associated connection string:
dbdsn -l -b

Report the connection string for data source ASA 7.0 Sample:
dbdsn -g "ASA 7.0 Sample"

Delete the data source BadDSN, but first list the connection parameters for
BadDSN and prompt for confirmation:
dbdsn -d foo -v
Delete the data source BadDSN without prompting for confirmation.
dbdsn -d foo -y
Create a data source named NewDSN for the database server MyServer:
dbdsn -w foo -c "uid=dba;pwd=sql;eng=bar"
If a NewDSN already exists, the previous definition is overwritten.
The following example connects to the sample database server. The server
name sample overrides the previous specified value of MyServer:
dbdsn -w foo -c "uid=dba;pwd=sql;eng=MyServer" sample
List all connection parameter names and their aliases:
dbdsn -cl

87
The Erase utility

The Erase utility


With the Erase utility, you can erase a database file or write file and its
associated transaction log, or you can erase a transaction log file or
transaction log mirror file. All database files, write files, and transaction log
files are marked read-only to prevent accidental damage to the database and
accidental deletion of the database files.
Deleting a database file that references other dbspaces does not automatically
delete the dbspace files. If you want to delete the dbspace files on your own,
change the files from read-only to writable, and then delete the files
individually. As an alternative, you can use the DROP DATABASE
statement to erase a database and its associated dbspace files.
If you erase a database file or write file, the associated transaction log and
transaction log mirror are also deleted. If you erase a transaction log for a
database that also maintains a transaction log mirror, the mirror is not
deleted.
The database to be erased must not be running when this utility is used.
You can access the Erase utility in the following ways:
♦ From Sybase Central
♦ From the system command line, using the dberase command-line utility.
This is useful for incorporating into batch or command files.
$ For more information, see the "DROP DATABASE statement" on
page 493.

Erasing a database from Sybase Central

v To erase a database file:


1 Open the Utilities folder in the left panel.
2 Double-click Erase Database in the right panel. The Erase a Database
wizard appears.
3 Follow the instructions in the wizard.

Tip
You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Erase Database.

88
Chapter 4 Database Administration Utilities

$ For full information on erasing a database from Sybase Central, see


"Erasing a database" on page 114 of the book ASA User’s Guide.

The dberase command-line utility


Syntax dberase [ switches ] database-file

Switch Description
–o filename Log output messages to a file
–q Operate quietly—do not print messages
–y Erase files without confirmation

Description The database-file may be a database file, write file, or transaction log file.
The full filename must be specified, including extension. If a database file or
write file is specified, the associated transaction log file (and mirror, if one is
maintained) is also erased.
$ For more information about the command-line switches, see "Erase
utility options" on page 89.

Erase utility options


Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

Operate without confirming actions (–y) Choosing this option


automatically deletes each file without prompting you for confirmation.

89
The Information utility

The Information utility


With the Information utility, you can display information about a database.
The utility indicates when the database was created, the name of any
transaction log file or log mirror that is maintained, the page size, and other
information. Optionally, it can also provide table usage statistics and details.
The Information is available as the dbinfo command-line utility.

The dbinfo command-line utility


Syntax dbinfo [ switches ]

Switch Description
–c "keyword=value; ..." Database connection parameters
–o filename Log output messages to a file
–q Operate quietly
–u Output page usage statistics

Description The dbinfo command-line utility allows you to display information about a
database. It reports the time when the database was created, the name of any
transaction log file or log mirror, the page size, and other information.
Optionally, it can also provide table usage statistics and details.
$ For more information about the command-line switches, see
"Information utility options" on page 90.

Information utility options


Connection parameters (–c) Specify connection parameters. See
"Connection parameters" on page 60 of the book ASA User’s Guide for a
description of the connection parameters.
Any valid user ID can run the Information utility, but to obtain page usage
statistics you need DBA authority.

Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

90
Chapter 4 Database Administration Utilities

Page usage statistics (–u) Display information about the usage and size
of all tables, including system and user-defined tables.
You can only request page usage statistics if no other users are connected to
the database.

91
The Initialization utility

The Initialization utility


With the Initialization utility, you can initialize (create) a database. A
number of database attributes are specified at initialization and cannot be
changed later except by unloading, reinitializing, and rebuilding the entire
database:
♦ Case sensitivity or insensitivity
♦ Storage as an encrypted file
♦ Treatment of trailing blanks in comparisons
♦ Page size
♦ Collation sequence
In addition, the choice of whether to use a transaction log and a transaction
log mirror is made at initialization. This choice can be changed later using
the transaction log utility.
You can access the Initialization utility in the following ways:
♦ From Sybase Central, for interactive use under Windows 95/98,NT, or
Java versions on non-win32 platforms.
♦ From the system command line, using the dbinit command-line utility.
This is useful for incorporating into batch or command files.
$ For more information about creating a database, see the "CREATE
DATABASE statement" on page 415.

Creating a database in Sybase Central

v To create a database:
1 Open the Utilities folder in the left panel.
2 Double-click Create Database in the right panel. The Database Creation
wizard appears.
3 Follow the instructions in the wizard.

Tip
You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Create Database.

92
Chapter 4 Database Administration Utilities

$ For full information on creating a database in Sybase Central, see


"Creating a database" on page 111 of the book ASA User’s Guide.

The dbinit command-line utility


Syntax dbinit [ switches ] new-database-file

Switch Description
–b Blank padding of strings for comparisons and fetching
–c Case sensitivity for all string comparisons
–e Encrypt the database
–i Do not install Sybase jConnect support
–j Do not install Sybase runtime Java classes
–k Omit Watcom SQL compatibility views SYS.SYSCOLUMNS
and SYS.SYSINDEXES
–l List the available collating sequences
–m file-name Use a transaction log mirror (default is no mirror)
–n No transaction log
–o filename Log output messages to a file
–p page-size Set page size
–q Quiet mode—do not print messages
–t log-name Transaction log filename (default is the database name with .log
extension)
–z col-seq Collation sequence used for comparisons

Description For example, the database test.db can be created with 1024 byte pages as
follows:
dbinit -p 1024 test.db

$ For more information about the command-line switches, see


"Initialization utility options" on page 93.

Initialization utility options


Blank padding (–b) Ignore trailing blanks for comparison purposes and
pad strings that are fetched into character arrays. For example, the two
strings

93
The Initialization utility

’Smith’
’Smith ’
would be treated as equal in a database created with blank-padding.
This option is provided for compatibility with the ISO/ANSI SQL standard,
which is to ignore trailing blanks in comparisons. The default is that blanks
are significant for comparisons.
$ For related information, see "ANSINULL option" on page 160.
Case sensitivity for all string comparisons (–c) For databases created
with this option, all values are considered to be case sensitive in comparisons
and string operations. Identifiers in the database are case insensitive, even in
case sensitive databases.
This option is provided for compatibility with the ISO/ANSI SQL standard.
The default is that all comparisons are case insensitive.

User ID and password


All databases are created with at least one user ID, DBA, with password
SQL. If you create a case-sensitive database, all passwords are case
sensitive. User IDs, like other identifiers, are case insensitive even in case
sensitive databases.

Encrypt the database (–e) Encryption makes it more difficult for


someone to decipher the data in your database by using a disk utility to look
at the file. File compaction utilities cannot compress encrypted database files
as much as unencrypted ones.
The encryption used is intended only to keep data hidden in the event of
casual direct access of the database file.

Do not install Sybase jConnect support (–i) If you wish to use the
Sybase jConnect JDBC driver to access system catalog information, you
need to install jConnect support. Use this switch if you wish to exclude the
jConnect system objects. You can still use JDBC, as long as you do not
access system information. If you want, you can add Sybase jConnect
support at a later time using Sybase Central.

Do not install Sybase runtime Java classes (–j) If you wish to use
Java in your database, you must install the Sybase runtime Java classes. By
default, these classes are installed. The runtime classes add several
megabytes to the size of a database, so if you do not intend to use Java
classes, you can specify the -j switch to avoid installing them. If you want,
you can add Sybase runtime Java classes at a later time using Sybase Central.

94
Chapter 4 Database Administration Utilities

Omit Watcom SQL compatibility views (–k) By default, database


creation generates the views SYS.SYSCOLUMNS and SYS.SYSINDEXES
for compatibility with system tables that were available in Watcom SQL
(versions 4 and earlier of this software). These views will conflict with the
Sybase Adaptive Server Enterprise compatibility views dbo.syscolumns and
dbo.sysindexes unless the -c case sensitivity command-line switch is used.

List the available collating sequences (–l) dbinit lists the available
collating sequences and then stops. No database is created. The list of
available collating sequences is automatically presented in Sybase Central
Create Database wizard.

Use a transaction log mirror (–m) A transaction log mirror is an


identical copy of a transaction log, usually maintained on a separate device,
for greater protection of your data. By default, Adaptive Server Anywhere
does not use a mirrored transaction log.

Do not use a transaction log (–n) Creating a database without a


transaction log saves disk space. The transaction log is required for data
replication and provides extra security for database information in case of
media failure or system failure. Databases that do not use transaction logs
typically run slower than databases that use transaction logs.

Log output messages to file (–o) Write output messages to the named
file.

Page size (–p) The page size for a database can be (in bytes) 1024, 2048,
4096, 8192, 16384, or 32768, with 2048 being the default. Any other value
for the size will be changed to the next larger size.
Large databases usually benefit from a larger page size. For example, the
number of I/O operations required to scan a table is generally lower, as a
whole page is read in at a time. Also, the number of levels in an index may
be reduced as more entries can be stored on each page.
However, there are additional memory requirements for large page sizes.
Also, the maximum number of rows stored on a page is 255, so that tables
with small rows will not fill each page. For example, with 8 kb pages the
average row size must be at least 32 bytes to fully use each page. You should
only use page sizes of 16 kb or 32 kb in productions systems when you can
be sure that a large database server cache is always available, and when you
have investigated the memory and disk space costs and the performance
benefits.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

95
The Initialization utility

Set the transaction log filename (–t) The transaction log is a file where
the database server logs all changes, made by all users, no matter what
application system is being used. The transaction log plays a key role in
backup and recovery (see "The transaction log" on page 633 of the book ASA
User’s Guide), and in data replication. If the filename has no path, it is placed
in the same directory as the database file. If you run dbinit without specifying
-t or -n, a transaction log is created with the same filename as the database
file, but with extension .log.
Collating sequence (–z) The collation sequence is used for all string
comparisons in the database.
If you want to create a custom collation, use the Collation utility to create a
file containing the collation. Once you have modified the collation and
inserted it into the appropriate scripts, you use the Initialization utility to
create the database and specify the new collation.
You must change the collation label in the custom collation file. Otherwise,
the Initialization utility prevents the insertion of the new collation, since it
conflicts with an existing collation.
$ For more information on custom collating sequences, see "International
Languages and Character Sets" on page 279 of the book ASA User’s Guide.
For information on the Collation utility, see "The Collation utility" on
page 78.
In order to change the collation that an existing database uses, it is necessary
to unload the database, create a new database using the appropriate collation,
then reload the database. It may be necessary to translate the data as well.
If -z is not specified, the default collation is used. Normal ASCII (binary)
ordering is used for the lower 128 characters, subject to the case sensitivity
setting (-c). For the upper 128 characters (also called the extended
characters), any character that is an accented form of a letter in the lower 128
are sorted to the same position as the unaccented form. The determination of
whether or not an extended character is an accented letter is based upon code
page 850 (multilingual code page).
The following table identifies the available collating sequence labels.

Collation label Type Description


437LATIN1 OEM Code Page 437, Latin 1
437ESP OEM Code Page 437, Spanish
437SVE OEM Code Page 437, Swedish/Finnish
819CYR ANSI Code Page 819, Cyrillic
819DAN ANSI Code Page 819, Danish
819ELL ANSI Code Page 819, Greek

96
Chapter 4 Database Administration Utilities

Collation label Type Description


819ESP ANSI Code Page 819, Spanish
819ISL ANSI Code Page 819, Icelandic
819LATIN1 ANSI Code Page 819, Latin 1
819LATIN2 ANSI Code Page 819, Latin 2
819NOR ANSI Code Page 819, Norwegian
819RUS ANSI Code Page 819, Russian
819SVE ANSI Code Page 819, Swedish/Finnish
819TRK ANSI Code Page 819, Turkish
850CYR OEM Code Page 850, Cyrillic
850DAN OEM Code Page 850, Danish
850ELL OEM Code Page 850, Greek
850ESP OEM Code Page 850, Spanish
850ISL OEM Code Page 850, Icelandic
850LATIN1 OEM Code Page 850, Latin 1
850LATIN2 OEM Code Page 850, Latin 2
850NOR OEM Code Page 850, Norwegian
850RUS OEM Code Page 850, Russian
850SVE OEM Code Page 850, Swedish/Finnish
850TRK OEM Code Page 850, Turkish
852LATIN2 OEM Code Page 852, Latin 2
852CYR OEM Code Page 852, Cyrillic
852POL OEM Code Page 852, Polish
855CYR OEM Code Page 855, Cyrillic
856HEB OEM Code Page 856, Hebrew
857TRK OEM Code Page 857, Turkish
860LATIN1 OEM Code Page 860, Latin 1
861ISL OEM Code Page 861, Icelandic
862HEB OEM Code Page 862, Hebrew
863LATIN1 OEM Code Page 863, Latin 1
865NOR OEM Code Page 865, Norwegian
866RUS OEM Code Page 866, Russian

97
The Initialization utility

Collation label Type Description


869ELL OEM Code Page 869, Greek
920TRK ANSI Code Page 920, Turkish
932JPN Multibyte Code Page 932, Japanese Shift-JIS
encoding
936ZHO Multibyte Code Page 936, Simplified Chinese, GB
2312-80 8-bit encoding
949KOR Multibyte Code Page 949, Korean KS C 5601-1987
encoding, Wansung
950TWN Multibyte Code Page 950, Traditional Chinese, Big
5 Encoding
1250LATIN2 ANSI Code Page 1250, Windows Latin 2,
Central/Eastern European
1250POl ANSI Code Page 1250, Windows Latin 2,
Polish
1252LATIN1 ANSI Code Page 1252, Windows Latin 1,
Western
SJIS Multibyte Japanese Shift-JIS Encoding
SJIS2 Multibyte Japanese Shift-JIS Encoding, Sybase
Adaptive Server Enterprise-compatible
EUC_JAPAN Multibyte Japanese EUC JIS X 0208-1990 and JIS
X 0212-1990 Encoding
EUC_CHINA Multibyte Chinese GB 2312-80 Encoding
EUC_TAIWAN Multibyte Taiwanese Big 5 Encoding
EUC_KOREA Multibyte Korean KS C 5601-1992 Encoding
ISO_1 ANSI ISO8859-1, Latin 1
ISO_BINENG ANSI Binary ordering, English ISO/ASCII
7-bit letter case mappings
ISO1LATIN1 ANSI ISO8859-1, ISO Latin 1, Western, Latin
1 Ordering
ISO9LATIN1 ANSI ISO8859-15, ISO Latin 9, Western, Latin
1 Ordering
WIN_LATIN1 ANSI Windows Latin 1, Western, ISO8859-1
with extensions
WIN_LATIN5 ANSI Windows Latin 5, Western, ISO8859-9
with extensions
UTF8 Multibyte UCS-4 Transformation Format

98
Chapter 4 Database Administration Utilities

The Interactive SQL utility


Syntax dbisql [ switches ] [ dbisql-command | command-file ]

Switch Description
–c "keyword=value; ..." Supply database connection parameters
–datasource dsn-name Specify an ODBC data source to connect to.
–host hostname Specify the hostname or IP address of the machine
running a database server.
–nogui Run in command-prompt mode.
–ODBC
–port portnumber
–q Quiet mode—no windows or messages
–x Syntax check only—no commands executed

Description Interactive SQL provides the user with an interactive environment for
database browsing and for sending SQL statements to the database server.
Interactive SQL allows you to type SQL commands, or run command files. It
also provides feedback about the number of rows affected, the time required
for each command, the execution plan of queries, and any error messages.
If dbisql-command is specified, Interactive SQL executes the command. You
can also specify a command file name. If no dbisql-command is specified,
SQL enters interactive mode, where you can type a command into a
command window.
Switches –c Specify connection parameters. See "Connection parameters" on
page 60 of the book ASA User’s Guide for a description of the connection
parameters. If Interactive SQL cannot connect, you are presented with a
dialog where you can enter the connection parameters.

–datasource Specify an ODBC data source to connect to. You do not


need to be using the JDBC/ODBC bridge to use this option.

–host Specify the hostname or IP address of the computer on which the


database server is running. You can use the name localhost to represent the
current machine.

–nogui Run Interactive SQL in a command-prompt mode, with no


windowed user interface.

–ODBC Connect using the JDBC/ODBC bridge. If you do not specify this
option, Interactive SQL connects using jConnect.
99
The Interactive SQL utility

–port Specify the port number on which the database server is running.
The default port number for Adaptive Server Anywhere is 2638.

–q Do not display output messages. This is useful only if you start


Interactive SQL with a command or command file.

–x Scan commands but do not execute them. This is useful for checking
long command files for syntax errors.
$ For or detailed descriptions of SQL statements and Interactive SQL
commands, see "SQL Language Elements" on page 207.
Examples ♦ The following command, entered at a system prompt, runs the command
file mycom.sql against the current default server, using the user ID DBA
and the password SQL.
dbisql -c "uid=DBA;pwd=SQL" mycom.sql
♦ The following command, when entered on a single line at a system
prompt, adds a user to the current default database:
dbisql -c "uid=DBA;pwd=SQL" grant connect to joe identified by passwd

Starting Interactive SQL from Sybase Central


You can start Interactive SQL from Sybase Central in the following ways:
♦ Right-click a database, and select Open Interactive SQL from the popup
menu.
♦ Right-click a table, and select View Data from the popup menu.
Interactive SQL opens with the data in the table displayed in the Data
window.
♦ Right-click a stored procedure, and select Test from the popup menu.
Interactive SQL opens with a test script in the SQL Statements pane.
♦ Click Tools➤Adaptive Server Anywhere➤Open Interactive SQL.

100
Chapter 4 Database Administration Utilities

The License utility


Syntax dblic { switches } executable-name user-name company-name

Switch Description
–l type License type. Allowed values are perseat or
concurrent
–o filename Log output messages to a file
–p operating-system Target operating system. Allowed values are
NetWare, UNIX, WIN32, WINNT
–q Operate quietly—do not print messages
–u license-number Total number of users for license

Description The dblic command-line utility adds licensed users to your network database
server. You must only use this utility in accordance with your Sybase license
agreement, to license the number of users to which you are entitled. Running
this command does not grant you license.
Repeated running of the dblic command updates the license information.
Switches License type (–l) Enter the license type that matches the licensing model
described in your software license agreement. Valid entries are perseat and
concurrent.

Log output messages to file (–o) Write output messages to the named
file.

Operating system (–p) Enter the operating system for which you are
licensed. Allowed values are as follows:
♦ NetWare Novell NetWare operating system.
♦ UNIX A UNIX operating system.
♦ WIN32 Windows 95/98 or Windows CE operating system.
♦ WINNT Windows NT operating system.

Operate quietly (–q) Do not display output messages.

License number (–u) The total number of licensed seats or concurrent


connections. If you are adding extra licenses, this is the total, not the number
of additional license.

Executable name Enter the path and file name of the network database
server executable (dbsrv6.exe) you are licensing. The path can be relative.

101
The License utility

User name A user name for the license. This name appears on the
database server window on startup. If there are spaces in the name, enclose it
in double quotes.

Company name The company name for the license. This name appears
on the database server window on startup. If there are spaces in the name,
enclose it in double quotes.
Example The following command, executed in the same directory as the database
server executable, applies a license for 50 concurrent users, in the name of
"Sys Admin", for company "My Co", to a Windows NT network database
server. The command must be entered all on one line:
dblic -l concurrent -p WINNT -u 50 dbsrv6.exe "Sys
Admin" "My Co"
The following message appears on the screen to indicate the success of the
license:
Licensed nodes: 50
User: Sys Admin
Company: My Co

102
Chapter 4 Database Administration Utilities

The Log Transfer Manager


Syntax dbltm [ switches ]
Parameters Switch Description
–A Do not filter updates
–C config_file Use the named configuration file
–I interface_file Use the named interface file
–M Recovery mode
–S LTM_name Specify an LTM name
–dl Display log messages on screen
–o filename Log output messages to a file
–os size Maximum size of output file
–ot file Truncate file, and log output messages to file
–q Run in minimized window
–s Show Log Transfer Language (LTL) commands
–ud Run as a daemon [UNIX]
–v Verbose mode

Description The Log Transfer Manager (LTM) is also known as a replication agent.
The LTM is required for any Adaptive Server Anywhere database that
participates in a Replication Server installation as a primary site. The
Adaptive Server Anywhere LTM reads a database transaction log and sends
committed changes to Replication Server. The LTM is not required at
replicate sites.
The LTM sends messages to Replication Server in a language named Log
Transfer Language (LTL).
By default, the LTM uses a log file named DBLTM.LOG to hold status and
other messages. You can use the command-line options to change the name
of this file and to change the volume and type of messages that are sent to it.
Switches Use configuration file (–C) Use the configuration file config_file to
determine the LTM settings. The default configuration file is dbltm.cfg. The
format of the configuration file is described in "The LTM configuration file"
on page 105.

103
The Log Transfer Manager

Use interface file (–I) (Upper case i.) Use the named interfaces file. The
interfaces file is the file, created by SQLEDIT (or sybinit on NetWare),
which holds the connection information for Open Servers. The default
interfaces file is sql.ini in the ini subdirectory of your Sybase directory. On
NetWare, the default interfaces file is named interfaces.

Specify LTM name (–S) Provides the server name for this LTM. The
default LTM_name is DBLTM_LTM. The LTM_name must correspond to
the Open Server name for the LTM that was entered in SQLEDIT.

Do not filter updates (–A) Do not filter updates. By default, all changes
made by the maintenance user are not replicated. If the -A switch is set, these
changes are replicated. This may be useful in non-hierarchical Replication
Server installations, where a database acts as both a replicate site and as a
primary site.

Recover mode (–M) This is used to initiate recovery actions. The LTM
starts reading logs from the earliest available position. If the offline directory
is specified in the configuration file, the LTM reads from the oldest offline
log file.

Display Log Transfer Language messages (–dl) Display Log Transfer


Language (LTL) messages in the LTM window or on the command line and
also in the log file. This should be used only to diagnose problems, and is not
recommended in a production environment. It carries a significant
performance penalty.

Log output messages to file (–o) Use a log file different from the
default (dbltm.log). Write output messages from log transfer operations to
this file.

Limit size of output file (–os) Specify the maximum size of the output
file, in bytes. The minimum value is 10000 (ten thousand). If the log file
grows to the point where it would exceed this limit, it is renamed to
yymmdd00.log, and a new file named yymmdd01.log is started. The value of
nn in yymmddnn.log is incremented for each file on a given day.

Truncate log file and use named log file (–ot) Use a log file different
from the default (dbltm.log), and truncate the log file (all existing content is
deleted) when the LTM starts. Output messages from log transfer operations
are sent to this file for later review.

Operate quietly (–q) Minimize the window when the LTM is started.
Log all LTL commands (–s) Log all LTL commands that are generated
by the LTM. This should be used only to diagnose problems, and is not
recommended in a production environment. It carries a significant
performance penalty.

104
Chapter 4 Database Administration Utilities

Run as a daemon (–ud) You can run the LTM as a daemon on UNIX
operating systems. If you run in this manner, output is logged to the log file.

Operate in verbose mode (–v) Displays messages, other than LTL


messages, for debugging purposes.

The LTM configuration file


The Adaptive Server Anywhere and Adaptive Server Enterprise LTM
configuration files are very similar. This section describes the entries in the
Adaptive Server Anywhere LTM configuration file, and the differences from
the Adaptive Server Enterprise LTM configuration file.
The configuration file that an LTM uses is specified using the -C command-
line switch.
LTM configuration The following table describes each of the configuration parameters that the
file parameters LTM recognizes. Parameters that are used by the Adaptive Server Enterprise
LTM but not by the Adaptive Server Anywhere LTM are included in this
list, and marked as either ignored (in which case they may be present in the
configuration file, but have no effect) or as unsupported (in which case they
will cause an error if present in the configuration file).

Parameter Description
APC_pw The password for the APC_user login name. This
entry is present only in Adaptive Server
Anywhere LTM configuration files.
APC_user A user ID that is used when executing
asynchronous procedures at the primary site.
This user ID must have permissions appropriate
for all asynchronous procedures at the primary
site. This entry is present only in Adaptive Server
Anywhere LTM configuration files.
backup_only By default, this is off. If set to on, the LTM will
replicate only backed-up transactions.
batch_ltl_cmds Set to on (the default) to use batch mode. Batch
mode can increase overall throughput, but may
lead to longer response times.
batch_ltl_sz The number of commands that are saved in the
buffer before being sent to Replication Server,
when batch_ltl_cmds is on. The default is 200.
batch_ltl_mem The amount of memory that the buffer can use
before its contents are sent to Replication Server,
when batch_ltl_cmds is on. The default is
256 kb.

105
The Log Transfer Manager

Parameter Description
continuous By default, this is on. When set to off, the LTM
automatically shuts down as soon as all
committed data has been replicated.
LTM_admin_pw The password for the LTM_admin_user login
name.
LTM_admin_user The system administrator LTM login name that
is used to log in to the LTM. This parameter is
required so that the LTM can check whether a
user logging on to the LTM to shut it down has
the correct login name.
LTM_charset The Open Client/Open Server character set for
the LTM to use.
LTM_language The Open Client/Open Server language for the
LTM to use.
LTM_sortorder The Open Client/Open Server sort order for the
LTM to use to compare user names. You can
specify any Adaptive Server Enterprise-
supported sort order that is compatible with the
LTM’s character set. All sort orders in your
replication system should be the same.
The default sort order is a binary sort.
maint_cmds_to_skip [ ignored ]
rep_func Set to on to use asynchronous procedure calls
(APCs). The default is off.
retry The number of seconds to wait before retrying a
failed connection to an Adaptive Server
Anywhere database server or Replication Server.
The default is 10 seconds.
RS The name of the Replication Server to which the
LTM is transferring the log.
RS_pwd The password for the RS_user login name.
RS_source_db The name of the database whose log the LTM
transfers to the Replication Server. This name
must match the name of the database as defined
within the Replication Server connection
definitions. Most configurations use the same
setting for both RS_Source_db and
SQL_database configuration options.
RS_source_ds The name of the server whose log the LTM
transfers to the Replication Server. This name
must match the name of the server as defined
within the Replication Server connection

106
Chapter 4 Database Administration Utilities

Parameter Description
definitions. Most configurations use the same
setting for both RS_Source_ds and SQL_server
configuration options.
RS_user A login name for the LTM to use to log into
Replication Server. The login name must have
been granted connect source permission in the
Replication Server.
scan_retry The number of seconds that the LTM waits
between scans of the transaction log. This
parameter is somewhat different in meaning to
that of the Adaptive Server Enterprise LTM. The
Adaptive Server Anywhere server does not
"wake up" and scan the log when records arrive
in the log. For this reason, you may wish to set
the scan_retry value to a smaller number then
that for an Adaptive Server Enterprise LTM.
skip_ltl_cmd_err [ ignored ]
SQL_database The primary site database name on the server
SQL_server to which the LTM connects. For
Adaptive Server Enterprise during recovery, this
is the temporary database whose logs the LTM
will transfer to Replication Server. The Adaptive
Server Anywhere LTM uses the SQL_log_files
parameter to locate offline transaction logs.
SQL_log_files A directory that holds off-line transaction logs.
The directory must exist when the LTM starts up.
This entry is present only in Adaptive Server
Anywhere LTM configuration files.
SQL_pw The password for the SQL_user user ID.
SQL_server The name of the primary site Adaptive Server
Anywhere server to which the LTM connects.
For Adaptive Server Enterprise during recovery,
this is a data server with a temporary database
whose logs the LTM will transfer to Replication
Server. The LTM uses the SQL_log_files
parameter to locate offline transaction logs.
SQL_user The login name that the LTM uses to connect to
the database specified by RS_source_ds and
RS_source_db.

Example ♦ The following is a sample LTM configuration file.


configuration file

107
The Log Transfer Manager

# This is a comment line


# Names are case sensitive.
SQL_user=sa
SQL_pwd=sysadmin
SQL_server=PRIMESV
SQL_database=primedb
RS_source_ds=PRIMEOS
RS_source_db=primedb
RS=MY_REPSERVER
RS_user=sa
RS_pw=sysadmin
LTM_admin_user=DBA
LTM_admin_pw=SQL
LTM_charset=cp850
scan_retry=2
SQL_log_files=e:\logs\backup
APC_user=sa
APC_pw=sysadmin

108
Chapter 4 Database Administration Utilities

The Log Translation utility


With the Log Translation utility, you can translate a transaction log into a
SQL command file.
You can access the Log Translation utility in the following ways:
♦ From Sybase Central
♦ From the system command line, using the dbtran command-line utility.
This is useful for incorporating into batch or command files.

Translating a transaction log in Sybase Central

v To translate a transaction log into a command file:


1 Open the Utilities folder in the left panel.
2 Double-click Translate Log in the right panel. The Translate Log wizard
appears.
3 Follow the instructions in the wizard.

Tip
You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Translate Log.

The dbtran command-line utility


Syntax Running against a transaction log.
dbtran [ switches ] transaction-log [ sql-file ]
Running against a database server.
dbtran [ switches ]

Switch Description
–a Include uncommitted transactions
–c "keyword=value; ..." Supply database connection parameters. Cannot be
used with a transaction log name.
–d Display output in chronological order
–f Output only since the last checkpoint

109
The Log Translation utility

Switch Description
–g Include audit records in output
–id destination,... Include only rows intended for the specified
destinations
–ir offset1,offset2 Include only the portion of the log between the two
specified offsets
–is source,... Include only rows originating from the specified
sources
–it user.table,... Include only operations on specified tables by
specifying a comma-delimited list of user.table
–j date/time Output from the last checkpoint prior to the given time
–n filename Output SQL file, when used against a database server
–o filename Log output messages to a file
–q Run quietly, do not print messages
–r Remove uncommitted transactions (default)
–rsu username,... Override default Replication Server user names
–s Produce ANSI standard SQL UPDATE transactions
–sr Generate SQL Remote comments
–t Include trigger-generated transactions in output
–u userid,... Translate transactions for listed users only
–x userid,... Exclude transactions for listed users
–y Replace file without confirmation
–z Include trigger-generated transactions as comments
only
transaction-log Log file to be translated. Cannot be used together with
–c or -n
sql-file Output file containing the translated information. For
use with transaction-log only

Description The dbtran utility takes the information in a transaction log and places it as a
set of SQL statements and comments into an output file. The utility can be
run in the following ways:
♦ Against a database server Run in this way, the utility is a standard
client application. It connects to the database server using the connection
string specified following the -c option, and places output in a file
specified with the -n option. DBA authority is required to run in this
way.

110
Chapter 4 Database Administration Utilities

The following command translates log information from the server


asademo and places the output in a file named asademo.sql.
dbtran -c "eng=asademo;dbn=asademo;uid=DBA;pwd=SQL" -n asademo.sql

♦ Against a transaction log file Run in this way, the utility acts directly
against a transaction log file. You should protect your transaction log
file from general access if you wish to prevent users from having the
capability of running this statement.
dbtran asademo.log asademo.sql

When the dbtran utility runs, it displays the earliest log offset in the
transaction log. This can be an effective method for determining the order in
which multiple log files were generated.
$ For more information about the command-line switches, see "Log
translation utility options" on page 111

Log translation utility options


Include uncommitted transactions (–a) The transaction log contains
any changes made before the most recent COMMIT by any transaction.
Changes made after the most recent commit are not present in the transaction
log.

Connection string (–c) When running the command-line utility against a


database server, this parameter specifies the connection string.
DBA authority is required to run dbtran.
$ For a description of the connection parameters, see "Connection
parameters" on page 60 of the book ASA User’s Guide.

Display output in chronological order (–d) Transactions are displayed


in order from earliest to latest. This feature is provided primarily for use
when auditing database activity: the output of this command should not be
applied against a database.

Output from last checkpoint only (–f) Only transactions that were
completed since the last checkpoint are output.

Include audit information (–g) If the AUDITING database option is


turned on, auditing information is added to the transaction log. You can
include this information as comments in the output file using this option.
$ For more information, see "AUDITING option" on page 160.

111
The Log Translation utility

Include rows for specified destinations (–id) Isolate operations on


rows that are being sent to one or more of the following destinations,
specified as a comma-separated list:
♦ All All rows. This is the default setting.
♦ SQLRemote Include only rows that are to be replicated using
SQL Remote. You can also use the short form SR.
♦ RepServer Include only rows that are to be replicated using the
Replication Agent (LTM) and Replication Server. You can also use the
short form RS.
♦ Local Include only rows that are not replicated.

Include rows from specified sources (–is) Isolate operations on rows


that have been modified by operations from one or more of the following
sources, specified as a comma-separated list:
♦ All All rows. This is the default setting.
♦ SQLRemote Include only rows that were modified using
SQL Remote. You can also use the short form SR.
♦ RepServer Include only rows that were modified using the
Replication Agent (LTM) and Replication Server. You can also use the
short form RS.
♦ Local Include only rows that are not replicated.

Include offset range (–ir) Isolate a portion of the transaction log between
two specified offsets.

Include specified tables (–it) Isolate those operations on the specified,


comma-separated list of tables. Each table should be specified as
owner.table.

Output from the last checkpoint prior to a given date (–j) Only
transactions from the most recent checkpoint prior to the given date and/or
time are translated. The user-provided argument can be a date, time or date
and time enclosed in quotes. If the time is omitted, the time is assumed to be
the beginning of the day. If the date is omitted, the current day is assumed.
The following is an acceptable format for the date and time: "YY/MMM/DD
HH:NN".

Output file (–n) When you run the dbtran command-line utility against a
database server, use this option to specify the output file that holds the SQL
statements.

Log output messages to file (–o) Write output messages to the named
file.

112
Chapter 4 Database Administration Utilities

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

Do not include uncommitted transactions (–r) Remove any


transactions that were not committed. This is the default behavior.

Override Replication Server user names (–rsu) By default, the -id


and -is switches assume the default Replication Server user names of
dbmaint and sa. You can override this assumption using the -rsu option
with a comma-separated list of user names.

Generate ANSI standard SQL UPDATE (–s) If the switch is not used,
and there is no primary key or unique index on a table, the Translation utility
generates UPDATE statements with a non-standard FIRST keyword in case
of duplicate rows. If the switch is used, the FIRST keyword is omitted for
compatibility with the SQL standard.

Generate SQL Remote comments (–sr) Place generated comments in


the output file describing how SQL Remote distributes operations to remote
sites.

Include transactions generated by triggers (–t) By default, actions


carried out by triggers are not included in the command file. If the matching
trigger is in place in the database, when the command file is run against the
database, the trigger will carry out the actions automatically. Trigger actions
should be included if the matching trigger does not exist in the database
against which the command file is to be run.

Output transactions for listed users only (–u) This switch allows you
to limit the output from the transaction log to include only specified users.

Output transactions except for listed users (–x) This switch allows
you to limit the output from the transaction log to exclude specified users.

Operate without confirming actions (–y) Choosing this option


automatically replaces existing command file(s) without prompting you for
confirmation.

Include transactions generated by triggers as comments only (–z)


Transactions that were generated by triggers will be included only as
comments in the output file.

113
The Ping utility

The Ping utility


The Ping utility is provided to assist in diagnosing connection problems.
Syntax dbping [ switches ]

Switch Description
–c "keyword=value; ..." Database connection parameters
–d Make a database connection if the server is found
–o filename Log output messages to a file
–q Operate quietly—do not print messages

Description The dbping command-line utility is provided to help debug connection


problems. It takes a full or partial connection string and returns a message
indicating whether the attempt to locate a server or database, or to connect,
was successful.
Switches Connection parameters (–c) For a description of the connection
parameters, see "Connection parameters" on page 60 of the book ASA User’s
Guide. If the connection parameters are not specified, connection parameters
from the SQLCONNECT environment variable are used, if set.

Make database connection (–d) Ping the database, not just the server.
If you do not supply the -d switch, then dbping reports success if it finds the
server specified by the -c switch. If you do supply the -d switch, then
dbping reports success only if connects to the server and also connect to a
database.
For example, if you have a server named blair running the database sample,
the following succeeds:
dbping -c "eng=blair;dbn=sample"

The following command fails, with the message Ping database failed --
specified database not found:
dbping -d -c "eng=blair;dbn=sample"

Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) If dbping fails, a message is always displayed. If


dbping succeeds, no message appears if -q is specified.

114
Chapter 4 Database Administration Utilities

The REBUILD utility


Databases can be rebuilt using the Rebuild batch file, command file, or shell
script, which invokes a series of utilities to rebuild a database, or as part of
the unload process using the Unload an Adaptive Server Anywhere Database
wizard in Sybase Central.
For more information about the Unload an Adaptive Server Anywhere
Database wizard, see "The Unload utility" on page 126.

Rebuilding a database using the rebuild batch or command file


Syntax rebuild old-database new-database [ dba-password ]
See also "The dbunload command-line utility" on page 127
"The dbinit command-line utility" on page 93
"The Interactive SQL utility" on page 99
Description This batch file, command file, or shell script uses dbunload to rebuild old-
database into new-database. This is a simple script, but it helps document
the rebuilding process, and provides a basis for customization. Both database
names should be specified without extensions. An extension of .db is
automatically added.
You can use dbunload with the -ar command-line option to carry out
unloading and reloading without using the rebuild batch file.
The dba-password must be specified if the password to the DBA user ID in
the old-database is not the initial password SQL.
REBUILD runs the dbunload, dbinit, and Interactive SQL commands with
the default command line options. If you need different options, you will
need to run the three commands separately.

115
The Server Location utility

The Server Location utility


The server location utility is provided to assist in diagnosing connection
problems by locating database servers on the immediate TCP/IP network.
Syntax dblocate [ switches ]

Switch Description
–o filename Log output messages to a file
–q Operate quietly—do not print messages

Description The dblocate command-line utility locates any Adaptive Server Anywhere
database servers running over TCP/IP on the immediate network. It prints a
list of database servers and their addresses.
Depending on your network, the utility may take several seconds before
printing its results.
Switches Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages.

116
Chapter 4 Database Administration Utilities

The Spawn utility


This utility is provided to start a database server in the background.
Syntax dbspawn [ –q ] server command line

Switch Description
–f Do not check for a running server
–q Quiet mode—do not print messages

Description The dbspawn command-line utility is provided to start a server in the


background. dbspawn starts the server in the background and returns with an
exit code of 1 (success) or 0 (failure). If the server specified in server-
command line is already running, dbspawn reports failure.
The dbspawn utility is useful for starting a server from a batch file,
especially when subsequent commands in the batch file require a server that
is accepting requests.
If you need to provide double quotes in the command line, for example if
your database file is in a directory with spaces in it, you must provide an
extra set of quotes, and escape the quotes around the database file. For
example:
dbspawn dbeng7 "\"d:\Program Files\sa7\asademo.db\""
$ For a description of the server command line, see "The database server"
on page 14.
Switches Do not check for a running server (–f) If a database server is already
running, the dbspawn command may use it. This switch forces dbspawn to
start a new database server each time it is run.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

117
The Stop utility

The Stop utility


The Stop utility stops a database server.
The Stop utility is a command-line utility only. In windowed environments,
you can stop a database server by clicking Close on the server window or
choosing Exit from the File menu on the server window.

The dbstop command-line utility


Syntax dbstop [ switches ] { name }

Switch Description
–c "keyword=value; ..." Connection parameters
–o filename Log output messages to a file
–q Quiet mode—do not print messages
–x Do not stop if there are active connections
–y Stop without prompting even if there are active
connections

Description Command-line options let you control whether a server is stopped even if
there are active connections.
$ For more information about the command-line switches, see "Stop
utility options" on page 118.

Stop utility options


Connection parameters (–c) When stopping a network server, you must
supply a connection string with a user ID that has permissions to stop the
server. By default, DBA permission is required on the network server, and all
users can shut down a personal server, but the -gk server command-line
option can be used to change this.
$ For a description of the connection parameters, see "Connection
parameters" on page 60 of the book ASA User’s Guide.
The behavior of dbstop can be controlled if there are active connections on a
server. If there are active connections, dbstop provides a prompt asking if
you wish to shut down the server. If you specify unconditional=true on the
command line, the server is shut down without prompting, even if there are
active connections.

118
Chapter 4 Database Administration Utilities

Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not print a message if the database was not
running.

Do not stop if there are active connections (–x) Do not stop the server
if there are still active connections to the server.

Stop without prompting (–y) Stop the server even if there are still active
connections to the server.
Examples To stop a database named asademo on the server myserver:
dbstop -c "uid=DBA;pwd=SQL;eng=myserver;dbn=asademo"
To stop a server myserver, regardless of the databases running:
dbstop -c "uid=DBA;pwd=SQL;eng-myserver;dbn=utility_db"

119
The Transaction Log utility

The Transaction Log utility


With the Transaction Log utility, you can display or change the name of the
transaction log or transaction log mirror associated with a database. You can
also stop a database from maintaining a transaction log or mirror, or start
maintaining a transaction log or mirror.
A transaction log mirror is a duplicate copy of a transaction log, maintained
by the database in tandem.
The name of the transaction log is first set when the database is initialized.
The Transaction Log utility works with database files or with write files. The
database server must not be running on that database when the transaction
log filename is changed (or an error message appears).
You can access the Transaction Log utility in the following ways:
♦ From Sybase Central
♦ From the system command line, using the dblog command-line utility

Changing a log file name from Sybase Central

v To change a transaction log file name:


1 Open the Utilities folder in the left panel.
2 Double-click Change Log File Information in the right panel. The
Transaction Log wizard appears.
3 Follow the instructions in the wizard.

Tip
You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Change Log File Information.

The dblog command-line utility


Syntax dblog [ switches ] database-file

120
Chapter 4 Database Administration Utilities

Switch Description
–g n Sets the LTM generation number to n
–il Ignores the LTM truncation offset stored in the
database
–ir Ignores the SQL Remote truncation offset stored
in the database
–m mirror-name Set transaction log mirror name
–n No longer use a transaction log or mirror log
–o filename Log output messages to a file
–q Quiet mode—do not print messages
–r No longer use a transaction log mirror
–t log-name Set the transaction log name
–x n Set the transaction log current relative offset to n
–z n Set the transaction log starting offset to n

Description The dblog command line utility allows you to display or change the name of
the transaction log or transaction log mirror associated with a database. You
can also stop a database from maintaining a transaction log or mirror, or start
maintaining a transaction log or mirror.
The utility displays additional information about the transaction log,
including the following:
♦ Version number
♦ Starting offset, for use in replication
♦ Ending offset, for use in replication
♦ Page size
♦ Total number of pages
♦ Number of empty pages
♦ Percentage of the log file in use
$ For more information about the command-line switches, see
"Transaction log utility options" on page 122.

121
The Transaction Log utility

Transaction log utility options


Set the generation number (–g) Use this option if you are using the Log
Transfer Manager to participate in a Replication Server installation. It can be
used after a backup is restored, to set the generation number. It performs the
same function as the following Replication Server function:
dbcc settrunc( ’ltm’, ’gen_id’, n )
$ For information on generation numbers and dbcc, see your Replication
Server documentation.
Ignore the LTM truncation offset (–il) Use this option if you are using
the Log Transfer Manager to participate in a Replication Server installation.
It performs the same function as the following Replication Server function:
dbcc settrunc( ’ltm’, ’gen_id’, n )
$ For information on dbcc, see your Replication Server documentation.
Ignore the SQL Remote truncation offset (–ir) Use this option if you
are using the Log Transfer Manager to participate in a Replication Server
installation and a SQL Remote installation. It resets the offset that is kept for
the DELETE_OLD_LOGS option, allowing transaction logs to be deleted
when they are no longer needed.

Set the name of the transaction log mirror file (–m) This option sets a
filename for a new transaction log mirror. If the database is not currently
using a transaction log mirror, it starts using one. If the database is already
using a transaction log mirror, it changes to using the new file as its
transaction log mirror.

No longer use a transaction log (–n) Stop using a transaction log, and
stop using a mirror log. Without a transaction log, the database can no longer
participate in data replication or use the transaction log in data recovery.

Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

No longer use a transaction log mirror (–r) For databases that maintain
a mirrored transaction log, this option changes their behavior to maintain
only a single transaction log.

Set the name of the transaction log file (–t) This option sets a filename
for a new transaction log. If the database is not currently using a transaction
log, it starts using one. If the database is already using a transaction log, it
changes to using the new file as its transaction log.

122
Chapter 4 Database Administration Utilities

Set the current log offset (–x) For use when reloading a SQL Remote
consolidated database. This option resets the current log offset so that the
database can take part in replication.
$ For information on how to use this option, see "Unloading and
reloading a consolidated database" on page 488 of the book Replication and
Synchronization Guide.

Set the starting log offset (–z) For use when reloading a SQL Remote
consolidated database. This option resets the starting log offset so that the
database can take part in replication.
$ For information on how to use this option, see "Unloading and
reloading a consolidated database" on page 488 of the book Replication and
Synchronization Guide.

123
The Uncompression utility

The Uncompression utility


With the Uncompression utility, you can expand a compressed database file
created by the Compression utility. The Uncompression utility reads the
compressed file and restores the database file to its uncompressed state.
You can access the Uncompression utility in the following ways:
♦ From Sybase Central
♦ From the system command line, using the dbexpand command-line
utility. This is useful for incorporating into batch or command files.

Uncompressing a database in Sybase Central

v To uncompress a compressed database file:


1 Open the Utilities folder in the left panel.
2 Double-click Uncompress Database in the right panel. The Uncompress
wizard appears.
3 Follow the instructions in the wizard.

Tip
You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Uncompress Database.

The dbexpand command-line utility


Syntax dbexpand [ switches ] compressed-database-file [ database-file ]

Switch Description
–o filename Log output messages to a file
–q Operate quietly—do not print messages
–y Erase an existing output file without confirmation

Description The input filename extension defaults to cdb. The output filename (with
extension) must not have the same name as the input filename (with
extension).

124
Chapter 4 Database Administration Utilities

$ For more information about the command-line switches, see


"Uncompression utility options" on page 125.

Uncompression utility options


Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

Operate without confirming actions (–y) Choosing this option


automatically replaces an existing database file without prompting you for
confirmation.

125
The Unload utility

The Unload utility


With the Unload utility, you can unload a database and put a set of data files
in a named directory. The Unload utility creates an Interactive SQL
command file to rebuild your database. It also unloads all of the data in each
of your tables, into files in the specified directory in comma-delimited
format. Binary data is properly represented with escape sequences.
You can also use the Unload utility to directly create a new database from an
existing one. This avoids potential security problems with the database
contents being written to ordinary disk files.
Accessing the You can access the Unload utility in the following ways:
Unload utility
♦ From Sybase Central. The Unload an Adaptive Server Anywhere
Database wizard steps you through the process of rebuilding your
database.
♦ From the system command line, using the dbunload command-line
utility. This is useful for incorporating into batch or command files.
The Unload utility should be run from a user ID with DBA authority. This is
the only way you can be sure of having the necessary privileges to unload all
the data. In addition, the reload.sql file should be run from the DBA user ID.
(Usually, it will be run on a new database where the only user ID is DBA
with password SQL.)
The database server –gl command-line option controls the permissions
required to unload data from the database. For information, see "–gl
command-line option" on page 27.
Objects owned by The dbo user ID owns a set of Adaptive Server Enterprise-compatible
dbo system objects in a database.
The Unload utility does not unload the objects that were created for the dbo
user ID during database creation. Changes made to these objects, such as
redefining a system procedure, are lost when the data is unloaded. Any
objects that were created by the dbo user ID since the initialization of the
database are unloaded by the Unload utility, and so these objects are
preserved.
Unloading and There are special considerations for unloading databases involved in
replication replication.
$ For information, see "Unloading and reloading a consolidated
database" on page 488 of the book Replication and Synchronization Guide.

126
Chapter 4 Database Administration Utilities

Unloading a database from Sybase Central

v To unload a database file or a running database:


1 Connect to the database.
2 Display the Unload an Adaptive Server Anywhere Database wizard,
either by:
♦ Right-clicking the database and then clicking Unload in the popup
menu, or by
♦ Opening the Utilities folder in the left panel, and Double-clicking
Unload Database in the right panel.
3 Follow the instructions in the wizard.

Tip
You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Unload Database.

$ For full information on unloading a database from Sybase Central, see


"Exporting a database" on page 701 of the book ASA User’s Guide.

The dbunload command-line utility


Syntax dbunload [ switches ] [ directory ]

Switch Description
–ac "keyword=value; ..." Supply connection parameters for the reload
–an database Creates a database file with the same settings as the
database being unloaded, and automatically reloads
it
–ar directory Rebuild and replace database
–c "keyword=value; ..." Supply database connection parameters for unload
–d Unload data only
–e table,... Do not unload listed tables
–ii Internal unload, internal reload (default)
–ix Internal unload, external reload
–j nnn Repeated unload of view creation statements
–n No data—schema definition only

127
The Unload utility

Switch Description
–o filename Log output messages to a file
–p char Escape character for external unloads (default "\")
–q Quiet mode—no windows or messages
–r reload-file Specify name and directory of generated reload
Interactive SQL command file (default reload.sql)
–t table,... Unload only the listed tables
–u Unordered data. Do not use indexes to unload data.
–v Verbose messages
–xi External unload, internal reload
–xx External unload, external reload
–y Replace the command file without confirmation
directory The directory where the unloaded data is to be
placed. Not needed for -an or -ac

Description In the default mode, or if -ii or -xx is used, the directory used by dbunload
to hold the data is relative to the database server, not to the current directory
of the user. For details of how to supply a filename and path in this mode,
see "UNLOAD TABLE statement" on page 619.
If the -x, -xi, or -xx is used, the directory is relative to the current directory
of the user.
The reload.sql command file is always relative to the current directory of the
user.
If no list of tables is supplied, the whole database is unloaded. If a list of
tables is supplied, only those tables are unloaded.
$ For more information about the command-line switches, see "Unload
utility options" on page 128.
$ There are special considerations for unloading databases involved in
replication. For information, see "Unloading and reloading a consolidated
database" on page 488 of the book Replication and Synchronization Guide.

Unload utility options


Connection parameters for reload database (–ac) This switch causes
the Unload utility to connect to an existing database and reload the data
directly into it. You can combine the operation of unloading a database and
reloading the results into an existing database using this option.
128
Chapter 4 Database Administration Utilities

Typically, you would create a new database using the Initialization utility,
and then reload it using this switch. This method is useful when you want to
change the initialization options, such as page size, or collation.
For example, the following command (which should be entered all on one
line) loads a copy of the asademo.db database into an existing database file
named newdemo.db:
dbunload -c "uid=dba;pwd=sql;dbf=asademo.db" -ac
"uid=dba;pwd=sql;dbf=newdemo.db"
If you use this option, no interim copy of the data is created on disk, so you
do not specify an unload directory on the command line. This provides
greater security for your data, but at some cost for performance.

Create a database for reloading (–an) You can combine the operations
of unloading a database, creating a new database, and loading the data using
this option.
Typically, you would use this switch when you do not want to change the
initialization option of your database. The options specified when you
created the source database are used to create the new database.
For example, the following command (which should be entered all on one
line) creates a new database file named asacopy.db and copies the schema
and data of asademo.db into it:
dbunload -c "uid=dba;pwd=sql;dbf=asademo.db" -an
asacopy.db
If you use this option, no interim copy of the data is created on disk, so you
do not specify an unload directory on the command line. This provides
greater security for your data, but at some cost for performance.

Rebuild and replace database (–ar) This option creates a new database
with the same settings as the old database, reloads it, and replaces the old
database. If you use this option, there can be no other connections to the
database, and the database connection must be local, not over a network.
If you specify directory, the transaction log offsets are reset for replication
purposes, and the transaction log from the old database is moved to the
specified directory. The named directory should be the directory that holds
the old transaction logs used by the Message Agent and the Replication
Agent. The transaction log management is handled only if the database is
used in replication: if there is no SQL Remote publisher or LTM check, then
the old transaction log is not needed and is deleted instead of being copied to
the specified directory.
$ For more information on transaction log management, see "Backup
methods for remote databases in replication installations" on page 642 of the
book ASA User’s Guide.

129
The Unload utility

Connection parameters for source database (–c) For a description of


the connection parameters, see "Connection parameters" on page 60 of the
book ASA User’s Guide. The user ID should have DBA authority, to ensure
that the user has permissions on all the tables in the database.
For example, the following statement unloads the asademo database running
on the sample_server server, connecting as user ID DBA with password
SQL. The data is unloaded into the c:\unload directory.
dbunload -c "eng=sample_server;dbn=asademo;uid=DBA;pwd=SQL" c:\unload

Unload data only (–d) With this option, none of the database definition
commands are generated (CREATE TABLE, CREATE INDEX, and so on);
reload.sql contains statements to reload the data only.

No data output for listed tables (–e) This switch is accessible only from
the command-line utility. If you wish to unload almost all of the tables in the
database, the -e command-line switch unloads all tables except the specified
tables.

Internal versus external unloads and reloads


The following switches offer combinations of internal and external
unloads and reloads: -ii, -ix, -xi and -xx. A significant performance
gain can be realized by using internal commands (UNLOAD/LOAD)
versus external commands (Interactive SQL’s INPUT and OUTPUT
statement). However, internal commands are executed by the server, so
file and directory paths are relative to the location of the database server.
Using external commands, file and directory paths are relative to the
current directory of the user.
In Sybase Central, you can specify whether to unload relative to the server
or client.
For more information on filenames and paths for the Unload utility, see
"UNLOAD TABLE statement" on page 619.

Use internal unload, internal reload (–ii) This switch uses the
UNLOAD statement to extract data from the database, and uses the LOAD
statement in the reload.sql file to repopulate the database with data. This is
the default.

Use internal unload, external reload (–ix) This switch uses the
UNLOAD statement to extract data from the database, and uses the
Interactive SQL INPUT statement in the reload.sql file to repopulate the
database with data.

130
Chapter 4 Database Administration Utilities

Repeated unload of view creation statements (–j) If your database


contains view definitions that are dependent on each other, you can use this
option to avoid failure when reloading the views into a database. This option
causes view creation statements to be unloaded multiple times, as specified
by the count entered. This count should be small, and should correspond to
the number of levels of view dependency.

Unload schema definition only (–n) With this option, none of the data
in the database is unloaded; reload.sql contains SQL statements to build the
structure of the database only.

Log output messages to file (–o) Write output messages to the named
file.

Escape character (–p) The default escape character (\) for external
unloads (dbunload -x switch) can be replaced by another character, using this
option. This option is available only from the command-line utility.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

Specify reload filename (–r) Modify the name and directory of the
generated reload Interactive SQL command file. The default is reload.sql in
the current directory. The directory is relative to the current directory of the
client application, not the server.

Unload only listed tables (–t) Provide a list of tables to be unloaded. By


default, all tables are unloaded. Together with the -n option, this allows you
to unload a set of table definitions only.

Output unordered data (–u) Normally, the data in each table is ordered
by the primary key. Use this option if you are unloading a database with a
corrupt index, so that the corrupt index is not used to order the data.

Enable verbose mode (–v) The table name of the table currently being
unloaded, and how many rows have been unloaded, appears. This option is
available only from the command-line utility.

Use external unloading, internal reload (–xi) This switch uses the
Interactive SQL OUTPUT statement to extract data from the database, and
uses the LOAD statement in the generated reload command file, reload.sql,
to repopulate the database with data.

Use external unloading, external reload (–xx) This switch uses the
Interactive SQL OUTPUT statement to extract data from the database, and
uses the Interactive SQL INPUT statement in the generated reload command
file, reload.sql, to repopulate the database with data.

131
The Unload utility

Operate without confirming actions (–y) Choosing this option replaces


existing command files without prompting you for confirmation.
Rebuilding a To unload a database, start the database server with your database, and run
database the Unload utility with the DBA user ID and password.
To reload a database, create a new database and then run the generated
reload.sql command file through Interactive SQL.
In Windows 95/98 and NT, and UNIX, there is a file (rebuild.bat,
rebuild.cmd, or rebuild) that automates the unload and reload process.

132
Chapter 4 Database Administration Utilities

The Upgrade utility


The Upgrade utility upgrades a database created with older versions of the
software. While Adaptive Server Anywhere does run against databases that
were created with earlier releases of the software, some of the features that
were introduced since the version that created the database are unavailable
unless the database is upgraded.
If you want to switch to the current release to use the new features, the
Upgrade utility upgrades your databases without unloading and reloading
them.
If you wish to use replication on an upgraded database, you must also
archive your transaction log and start a new one on the upgraded database.
You can access the Upgrade utility in the following ways:
♦ From Sybase Central
♦ From the system command-line, using the dbupgrad command-line
utility

Backup before upgrading


As with any software, it is recommended that you make a backup of your
database before upgrading.

Upgrading a database from Sybase Central

v To upgrade a database:
1 Open the Utilities folder in the left panel.
2 Double-click Upgrade Database in the right panel. The Upgrade
Database wizard appears.
3 Follow the instructions in the wizard.

Upgrading databases that are too old for the Upgrade utility

v To upgrade a database created with a version of Adaptive Server


Anywhere that is too old to be upgraded:
1 Unload the database using the Unload utility.

133
The Upgrade utility

2 Create a database with the name you wish to use for the upgraded
version, using the Initialization utility.
3 Connect to the new database from Interactive SQL as the DBA user ID,
and read the reload.sql command file to build the new database.
You can also use the dbunload command-line utility to directly rebuild.

The dbupgrad command-line utility


Syntax dbupgrad [ switches ]

Switch Description
–c "keyword=value; ..." Supply database connection parameters
–i Do not install Sybase jConnect support
–j Do not install Sybase runtime Java classes
–o filename Log output messages to a file
–q Quiet mode—no windows or messages

Description The dbupgrad command-line utility upgrades a database created with


Watcom SQL 3.2, Watcom SQL 4.0, or SQL Anywhere 5.0 to the Adaptive
Server Anywhere format. While Adaptive Server Anywhere does run against
databases that were created with earlier releases of the software, some of the
features that were introduced since the version that created the database are
unavailable unless the database is upgraded.
$ For more information about the command-line switches, see "Upgrade
utility options" on page 134.

Upgrade utility options


Connection parameters (–c) For a description of the connection
parameters, see "Connection parameters" on page 60 of the book ASA User’s
Guide. The user ID must have DBA authority.
For example, the following command upgrades a database called sample40
to a 7.0 format, connecting as user DBA with password SQL:
dbupgrad -c "uid=DBA;pwd=SQL;dbf=c:\wsql40\sample40.db"
The dbupgrad command-line utility must be run by a user with DBA
authority.

134
Chapter 4 Database Administration Utilities

Do not install Sybase jConnect support (–i) If you wish to use the
Sybase jConnect JDBC driver to access system catalog information, you
need to install jConnect support. Use this option if you wish to exclude the
jConnect system objects. You can still use JDBC, as long as you do not
access system information. If you want, you can add Sybase jConnect
support later using Sybase Central.

Do not install Sybase runtime Java classes (–j) If you wish to use
Java in your database, you must install the Sybase runtime Java classes. By
default, these classes are installed when a database is upgraded to Version 6.
The runtime classes add several megabytes to the size of a database. If you
do not intend to use Java classes, you can specify the -j switch to avoid
installing these classes. If you want, you can add Sybase runtime Java classes
later using Sybase Central.

Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

135
The Validation utility

The Validation utility


With the Validation utility, you can validate the indexes and keys on some or
all of the tables in the database. The Validation utility scans the entire table,
and looks up each record in every index and key defined on the table.
This utility can be used in combination with regular backups (see "Backup
and Data Recovery" on page 627 of the book ASA User’s Guide) to give you
confidence in the integrity of the data in your database.
You can access the Validation utility in the following ways:
♦ From Sybase Central
♦ From the system command line, using the dbvalid command-line utility.
This is useful for incorporating into batch or command files.
$ For more information on validating tables, see "VALIDATE TABLE
statement" on page 628.

Validating a database from Sybase Central


You can validate a database from Sybase Central, and validate individual
tables.

v To validate a database:
1 Open the Utilities folder.
2 Double-click Validate Database.
3 Follow the instructions in the wizard.

v To validate a running database:


1 Connect to the database.
2 Right-click the database and choose Validate from the popup menu.

v To validate an individual table:


1 Connect to the database.
2 Locate the table you wish to validate.
3 Right-click the table and choose Validate from the popup menu.

136
Chapter 4 Database Administration Utilities

Tip
For validating database, you can also access this wizard by clicking
Tools➤Adaptive Server Anywhere➤Validate Database.

The dbvalid command-line utility


Syntax dbvalid [ switches ] [ object-name,... ]

Switch Description
object-name The name of a table or (if -i is used) an index to
validate
–c "keyword=value; ..." Supply database connection parameters
–o filename Log output messages to a file
–f Validate tables with full check
–fd Validate tables with data check
–fi Validate tables with index check
–i Each object-name is an index
–q Quiet mode—do not print messages
–t Each object-name is a table

Description With the command line Validation utility, you can validate the indexes and
keys on some or all of the tables in the database. This utility scans the entire
table, and confirms that each row in the table exists in the appropriate
indexes. It is equivalent to running the VALIDATE TABLE statement on
each table.
$ For information on specific checks made during validation, see
"VALIDATE TABLE statement" on page 628.
$ For more information about the command-line switches, see
"Validation utility options" on page 137.

Validation utility options


Connection parameters (–c) For a description of the connection
parameters, see "Connection parameters" on page 60 of the book ASA User’s
Guide. The user ID must have DBA authority or REMOTE DBA authority.

137
The Validation utility

For example, the following validates the sample database, connecting as user
DBA with password SQL:
dbvalid -c "uid=DBA;pwd=SQL;dbf=c:\asa6\asademo.db"

Data check for each table (–fd) In addition to the default validation
checks, check that all of each LONG BINARY, LONG VARCHAR, TEXT,
or IMAGE data type can be read. This corresponds to the WITH DATA
CHECK option on the VALIDATE TABLE statement. Depending on the
contents of your database, this option may significantly extend the time
required to validate.

Full check for each table (–f) In addition to the default validation
checks, carry out both data checks (-fd) and index checks (-fi). This
corresponds to the WITH FULL CHECK option on the VALIDATE TABLE
statement. Depending on the contents of your database, this option may
significantly extend the time required to validate.

Index check for each table (–fi) In addition to the default validation
checks, validate each index on the table. This corresponds to the WITH
INDEX CHECK option on the VALIDATE TABLE statement. Depending
on the contents of your database, this option may significantly extend the
time required to validate.

Validate specified indexes (–i) Instead of validating tables, validate


indexes. In this case, for dbvalid, each of the object-name values supplied
represents an index rather than a table, and has a name of the following form:
[ [ owner.]table-name.]index-name

Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

Validate tables (–t) The list of object-name values represents a list of


tables. This is also the default behavior.

138
Chapter 4 Database Administration Utilities

The Write File utility


The Write File utility is used to manage database write files. A write file is a
file associated with a particular database. All changes are written into the
write file, leaving the database file unchanged.
Using write files for Write files can be used effectively for testing when you do not wish to
development modify the production database. They can also be used in network and
student environments where read-only access to a database is desired, or
when you distribute on CD-ROM a database that you wish users to be able to
modify.
Compressed If you are using a compressed database, you must use a write file;
databases compressed database files cannot be accessed directly. The write file name is
then used in place of the database name when connecting to the database, or
when loading a database on the database server command line.

v You can access the write file utility in the following ways:
♦ From Sybase Central
♦ From the system command line, using the dbwrite command-line utility.
This is useful for incorporating into batch or command files.
The Write File utility runs against a database file. The database must not be
running on a server when you run the Write File utility.
The database file cannot be modified after the write file is created, otherwise
the write file becomes invalid.

Creating a write file from Sybase Central

v To create a write file for a database:


1 Open the Utilities folder in the left panel.
2 Double-click Create Write File in the right panel. The Write File wizard
appears.
3 Follow the instructions in the wizard.

Tip
You can also access this wizard by clicking Tools➤Adaptive Server
Anywhere➤Create Write File.

139
The Write File utility

The dbwrite command-line utility


Syntax dbwrite [ switches ] database-file [ write-name ]

Switch Description
–c Create a new write file
–d database-file Point a write file to a different database
–f database-file Force the write file to point at a file
–m mirror-name Set the transaction log mirror name
–o filename Log output messages to a file
–q Quiet mode—do not print messages
–s Report the write file status only
–t log-name Set the transaction log name
–y Erase old files without confirmation

Description If any changes are made to the original database (not using the write file), the
write file will no longer be valid. This happens if you start the server using
the original database file, so you should create your write file from an
archived copy of a database.
If a write file becomes invalid, you can discard all of your changes and create
a new write file with the following command.
dbwrite -c db-name write-name
The log-name and mirror-name parameters are used only when creating a
new write file. The write-name parameter is used only with the -c and -d
parameters. Note that the database_file parameter must be specified before
the write-name parameter.
$ For more information about the command-line switches, see "Write file
utility options" on page 140.

Write file utility options


Create a new write file (–c) If an existing write already exists, any
information in the old write file will be lost. If no write file name is specified
on the command line, the write filename defaults to the database name with
the extension wrt. If no transaction log name is specified, the log file name
will default to the database name with the extension wlg.

140
Chapter 4 Database Administration Utilities

Change the database file to which an existing write file points (–d)
If a database file is moved to another directory, or renamed, this option
allows you to maintain the link between the write file and the database file.
This option is available only from the command-line utility.

Force a write file to point to a file (–f) This option is available only
from the command-line utility. This option is for use when a write file is
being created and the database file is held on a Novell NetWare or other
network path, for operating systems on which they cannot be entered
directly. By providing the full Novell path name for the database file (for
example: SYS:\asademo.db), you can avoid dependencies on local mappings
of the NetWare path. Unlike with the –d option, no checking is done on the
specified path.

Set mirror name (–m) Set the name of the transaction log mirror file.
This can only be used in conjunction with-c.

Log output messages to file (–o) Write output messages to the named
file.

Operate quietly (–q) Do not display output messages. This option is


available only from the command-line utility.

Report the write file status only (–s) This displays the name of the
database to which the write file points. This option is available only from the
command-line utility.

Set the transaction log filename (–t) If you are creating a new write file
(-c), you can use this switch to set the name of the transaction log file.

Operate without confirming actions (–y) Choosing this option replaces


the existing write file without prompting you for confirmation.

141
The Write File utility

142
C H A P T E R 5

Database Options

About this chapter This chapter describes the database and Interactive SQL options that can be
set to customize and modify database behavior.
Contents
Topic Page
Introduction to database options 144
General database options 149
Transact-SQL and SQL/92 compatibility options 151
Replication options 154
Interactive SQL options 155
Alphabetical list of options 157

143
Introduction to database options

Introduction to database options


Database options control many aspects of database behavior. For example,
you can use database options for the following purposes:
♦ Compatibility You can control how much like Adaptive Server
Enterprise your Adaptive Server Anywhere database operates, and
whether SQL that does not conform to SQL/92 generates errors.
♦ Error handling You can control what happens when errors such as
dividing by zero, or overflow errors, occur.
♦ Concurrency and transactions You can control the degree of
concurrency, and details of COMMIT behavior.

Setting options
You set options with the SET OPTION statement. It has the following
general syntax:
SET [ EXISTING ] [ TEMPORARY ] OPTION
... [ userid. | PUBLIC. ]option-name = [ option-value ]
Specify a user ID or group name to set the option for that user or group only.
Every user belongs to the PUBLIC group. If no user ID or group is specified,
the option change is applied to the currently logged on user ID that issued the
SET OPTION statement.
For example, the following statement applies an option change to the user
DBA, if DBA is the user that issues it:
SET OPTION login_mode = mixed
The following statement applies a change to the PUBLIC user ID, a user
group to which all users belong.
SET OPTION Public.login_mode = standard

Caution
Changing option settings while fetching rows from a cursor is not
supported, because it can lead to ill-defined behavior. For example,
changing the DATE_FORMAT setting while fetching from a cursor would
lead to different date formats among the rows in the result set. Do not
change option settings while fetching rows.

$ For more information, see "SET OPTION statement" on page 596.

144
Chapter 5 Database Options

Finding option settings


You can obtain a list of option settings, or the values of individual options, in
a variety of ways.
Getting a list of ♦ Current option settings for your connection are available as a subset of
option values connection properties. You can list all connection properties using the
sa_conn_properties system procedure.
call sa_conn_properties
To order this list, you can call sa_conn_properties_by_name.
$ For more information, see "sa_conn_properties_by_name system
procedure" on page 938, "sa_conn_properties system procedure" on
page 937.
♦ In Interactive SQL, the SET statement with no arguments lists the
current setting of options.
SET
♦ In Sybase Central, right-click on a database, and select Set Options from
the popup menu.
♦ Use the following query on the SYSOPTIONS system view:
SELECT *
FROM SYSOPTIONS
This shows all PUBLIC values, and those USER values that have been
explicitly set.
Getting individual You can obtain a single setting using the connection_property system
option values function. For example, the following statement reports the value of the
ANSI_INTEGER_OVERFLOW option:
SELECT CONNECTION_PROPERTY (’ANSI_INTEGER_OVERFLOW’)
$ For more information, see "CONNECTION_PROPERTY function "
on page 309.

Scope and duration of database options


You can set options at 3 levels of scope: public, user, and temporary.
Temporary options take precedence over user and public settings. User level
options take precedence over public settings. If you set a user level option for
the current user, the corresponding temporary option is set as well.

145
Introduction to database options

Some options (such as COMMIT behavior) are database-wide in scope.


Setting these options requires DBA permissions. Other options (such as
ISOLATION_LEVEL) can also be applied to just the current connection,
and need no special permissions.
Changes to option settings take place at different times, depending on the
option. Changing a global option such as RECOVERY_TIME takes place
the next time the server is started.
Options that affect the current connection only generally take place
immediately. You can change option settings in the middle of a transaction,
for example. One exception to this is that changing options when a cursor is
open can lead to unreliable results. For example, changing
DATE_FORMAT may not change the format for the next row when a cursor
is opened. Depending on the way the cursor is being retrieved, it may take
several rows before the change works its way to the user.
Setting temporary Adding the TEMPORARY keyword to the SET OPTION statement changes
options the duration of the change. Ordinarily an option change is permanent. It will
not change until it is explicitly changed using the Set Option statement.
When the SET TEMPORARY OPTION statement is executed, the new
option value takes effect only for the current connection, and for the duration
of the connection.
When the SET TEMPORARY OPTION is used to set a PUBLIC option, the
change is in place for as long as the database is running. When the database
is shut down, temporary options for the PUBLIC user ID revert back to their
permanent value.
Setting an option for the PUBLIC user ID temporarily offers a security
advantage. For example, when the LOGIN_MODE option is enabled the
database relies on the login security of the system on which it is running.
Enabling it temporarily means that a database relying on the security of a
Windows NT domain will not be compromised if the database is shut down
and copied to a local machine. In this case, the LOGIN_MODE option will
revert to its permanent value, which could be Standard, a mode where
integrated logins are not permitted.

Setting public options


DBA authority is required to set an option for the PUBLIC user ID.
Changing the value of an option for the PUBLIC user ID sets the value of
the option for all users who have not SET their own value. An option value
cannot be set for an individual user ID unless there is already a PUBLIC
user ID setting for that option.

146
Chapter 5 Database Options

Deleting option settings


If option-value is omitted, the specified option setting will be deleted from
the database. If it was a personal option setting, the value reverts back to the
PUBLIC setting. If a TEMPORARY option is deleted, the option setting
reverts back to the permanent setting.
For example, the following statement resets the
ANSI_INTEGER_OVERFLOW option to its default value:
SET OPTION ANSI_INTEGER_OVERFLOW =

$ For more information, see "SET OPTION statement" on page 596.

Option classification
Adaptive Server Anywhere provides many options. It is convenient to divide
them into a few general classes. The classes of options are:
♦ "General database options" on page 149
♦ "Transact-SQL and SQL/92 compatibility options" on page 151
♦ "Replication options" on page 154
♦ "Interactive SQL options" on page 155

Initial option settings


Connections to Adaptive Server Anywhere can be made through the TDS
protocol (Open Client and jConnect JDBC connections) or through the
Adaptive Server Anywhere protocol (ODBC, Embedded SQL).
If you have users who use both TDS and the Adaptive Server Anywhere-
specific protocol, you can configure their initial settings using stored
procedures. As it is shipped, Adaptive Server Anywhere uses this method to
set Open Client connections and jConnect connections to reflect default
Adaptive Server Enterprise behavior.
The initial settings are controlled using the LOGIN_PROCEDURE option.
This option names a stored procedure to run when users connect. The default
setting is to use the sp_login_environment system procedure. If you wish to
change this behavior you can do so.
In turn, sp_login_environment checks to see if the connection is being made
over TDS. If it is, it calls the sp_tsql_environment procedure, which sets
several options to new "default" values for the current connection.

147
Introduction to database options

$ For more information, see "LOGIN_PROCEDURE option" on


page 184, "sp_login_environment system procedure" on page 945, and
"sp_tsql_environment system procedure" on page 948.

148
Chapter 5 Database Options

General database options


This section lists all database options.

OPTION VALUES DEFAULT


"AUDITING option" on page 160 ON, OFF OFF
"BACKGROUND_PRIORITY option" on ON, OFF OFF
page 162
"BLOCKING option" on page 163 ON, OFF ON
"CHECKPOINT_TIME option" on Number of 60
page 165 minutes
"CIS_ROWSET_SIZE option" on page 165 Integer 50
"COOPERATIVE_COMMITS option" on ON, OFF ON
page 168
"COOPERATIVE_COMMIT_TIMEOUT Integer 250
option" on page 169
"DATE_FORMAT option" on page 169 String ’YYYY-MM-DD’
"DATE_ORDER option" on page 171 ’YMD’, ’DMY’, ’YMD’
’MDY’
"DEFAULT_TIMESTAMP_INCREMENT Integer 1
option" on page 171
"DELAYED_COMMITS option" on ON, OFF OFF
page 172
"DELAYED_COMMIT_TIMEOUT Integer 500
option" on page 172
"EXTENDED_JOIN_SYNTAX option" on ON/OFF ON
page 174
"GLOBAL_DATABASE_ID option" on Integer 0
page 176
"ISOLATION_LEVEL option" on page 181 0, 1, 2, 3 0
"JAVA_HEAP_SIZE option" on page 182 Number of bytes 1000000
"JAVA_NAMESPACE_SIZE option" on Number of bytes 4000000
page 183
"LOGIN_MODE option" on page 183 STANDARD, STANDARD
MIXED,
INTEGRATED
"LOGIN_PROCEDURE option" on String sp_login_environment
page 184

149
General database options

OPTION VALUES DEFAULT


"MAX_CURSOR_COUNT option" on Integer 50
page 184
"MAX_HASH_SIZE option" on page 185 Integer 10
"MAX_WORK_TABLE_HASH_SIZE Integer 20
option" on page 185
"MAX_STATEMENT_COUNT option" on Integer 50
page 186
"MIN_PASSWORD_LENGTH option" on Integer 0
page 186
"OPTIMIZATION_GOAL option" on first-row or all- first-row
page 189 rows
"PRECISION option" on page 193 Number of 30
digits
"PREFETCH option" on page 193 ON, OFF ON
"RECOVERY_TIME option" on page 195 Number of 2
minutes
"RETURN_JAVA_AS_STRING option" on ON, OFF OFF
page 197
"ROW_COUNTS option" on page 196 ON, OFF OFF
"SCALE option" on page 198 Number of 6
digits
"TIME_FORMAT option" on page 200 String ’HH:NN:SS.SSS’
"TIMESTAMP_FORMAT option" on String ’YYYY-MM-DD
page 201 HH:NN:SS.SSS’
"TRUNCATE_DATE_VALUES option" on ON, OFF ON (databases created
page 202 with version 7 software)
OFF (older databases)
"TRUNCATE_WITH_AUTO_COMMIT ON, OFF OFF
option" on page 202
"WAIT_FOR_COMMIT option" on ON, OFF OFF
page 205

150
Chapter 5 Database Options

Transact-SQL and SQL/92 compatibility options


The following options allow Adaptive Server Anywhere behavior to be made
compatible with Adaptive Server Enterprise, or to support both old behavior
and allow ISO SQL/92 behavior.
For further compatibility with Adaptive Server Enterprise, some of these
options can be set for the duration of the current connection using the
Transact-SQL SET statement instead of the Adaptive Server Anywhere SET
OPTION statement. For a listing, see "SET statement" on page 593.
Default settings The default setting for some of these options differs from the Adaptive
Server Enterprise default setting. For compatibility, you should explicitly set
the options to ensure compatible behavior.
When a connection is made using the Open Client or JDBC interfaces, some
option settings are explicitly set for the current connection to be compatible
with Adaptive Server Enterprise. These options are listed in the following
table.
$ For information on how the settings are made, see "System and catalog
stored procedures" on page 935.

Option Setting
ALLOW_NULLS_BY_DEFAULT OFF
ANSI_BLANKS ON
ANSINULL OFF
CHAINED OFF
CONTINUE_AFTER_RAISERROR ON
DATE_FORMAT YYYY-MM-DD
DATE_ORDER MDY
ESCAPE_CHARACTER OFF
FLOAT_AS_DOUBLE ON
ISOLATION_LEVEL 1
ON_TSQL_ERROR CONDITIONAL
QUOTED_IDENTIFIER OFF
TSQL_VARIABLES ON
TSQL_HEX_CONSTANT ON
TIME_FORMAT HH:NN:SS.SSS
TIMESTAMP_FORMAT YYYY-MM-DD HH:NN:SS.SSS

151
Transact-SQL and SQL/92 compatibility options

List of options The following table lists the compatibility options, their allowed values, and
their default settings.

OPTION VALUES DEFAULT


"ALLOW_NULLS_BY_DEFAULT ON, OFF ON
option" on page 157
"ANSI_BLANKS option" on page 157 ON, OFF OFF
"ANSI_CLOSE_CURSORS_ON_RO ON, OFF OFF
LLBACK option" on page 158
"ANSI_INTEGER_OVERFLOW ON, OFF OFF
option" on page 158
"ANSI_UPDATE_CONSTRAINTS OFF, CURSORS
option" on page 159 CURSORS,
STRICT
"ANSINULL option" on page 160 ON, OFF ON
"ANSI_PERMISSIONS option" on ON, OFF ON
page 158
"AUTOMATIC_TIMESTAMP option" ON, OFF OFF
on page 161
"CHAINED option" on page 163 ON, OFF ON
"CLOSE_ON_ENDTRANS option" on ON, OFF ON
page 165
"CONTINUE_AFTER_RAISERROR ON,OFF ON
option" on page 167
"CONVERSION_ERROR option" on ON,OFF ON
page 168
"DIVIDE_BY_ZERO_ERROR option" ON, OFF ON
on page 173
"ESCAPE_CHARACTER option" on System use OFF
page 174
"FIRE_TRIGGERS option" on ON, OFF ON
page 175
"FLOAT_AS_DOUBLE option" on ON, OFF OFF
page 175
"NEAREST_CENTURY option" on integer 50
page 187
"NON_KEYWORDS option" on comma- No keywords turned off
page 187 separated
keywords list

152
Chapter 5 Database Options

OPTION VALUES DEFAULT


"ON_TSQL_ERROR option" on STOP, CONDITIONAL
page 189 CONDITION
AL,
CONTINUE
"PERCENT_AS_COMMENT option" ON, OFF ON
on page 192
"QUERY_PLAN_ON_OPEN option" ON, OFF OFF
on page 194
"QUOTED_IDENTIFIER option" on ON, OFF ON
page 195
"RI_TRIGGER_TIME option" on BEFORE, AFTER
page 197 AFTER
"SQL_FLAGGER_ERROR_LEVEL E, I, F, W W
option" on page 198
"SQL_FLAGGER_WARNING_LEVE E, I, F, W W
L option" on page 199
"STRING_TRUNCATION option" on ON, OFF OFF
page 200
"TSQL_HEX_CONSTANT option" on ON, OFF ON
page 203
"TSQL_VARIABLES option" on ON, OFF OFF
page 204

153
Replication options

Replication options
The following options are included to provide control over replication
behavior. Some replication options are useful for SQL Remote replication,
and some are relevant for use with Sybase Replication Server.

OPTION VALUES DEFAULT


"BLOB_THRESHOLD option" Integer 256
on page 162
"COMPRESSION option" on Integer, from -1 to 9 6
page 166
"DELETE_OLD_LOGS ON, OFF OFF
option" on page 173
"QUALIFY_OWNERS option" ON, OFF ON
on page 194
"QUOTE_ALL_IDENTIFIERS ON, OFF OFF
option" on page 195
"REPLICATE_ALL option" on ON, OFF OFF
page 196
"REPLICATION_ERROR Procedure-name (no procedure)
option" on page 196
"SUBSCRIBE_BY_REMOTE ON, OFF ON
option" on page 200
"VERIFY_ALL_COLUMNS ON, OFF OFF
option" on page 204
"VERIFY_THRESHOLD integer 1000
option" on page 204

154
Chapter 5 Database Options

Interactive SQL options


Syntax 1 SET [ TEMPORARY ] OPTION
... [ userid. | PUBLIC. ]option-name = [ option-value ]
Syntax 2 SET PERMANENT
Syntax 3 SET
Parameters userid: identifier, string or host-variable
option-name: identifier, string or host-variable
option-value: host-variable (indicator allowed), string, identifier, or
number
Description SET PERMANENT (syntax 2) stores all current Interactive SQL options in
the SYSOPTIONS system table. These settings are automatically established
every time Interactive SQL is started for the current user ID.
Syntax 3 is used to display all of the current option settings. If any options
have temporary settings for Interactive SQL or the database server, these are
displayed; otherwise, the permanent option settings are displayed.

OPTION VALUES DEFAULT


"AUTO_COMMIT option" on ON, OFF OFF
page 161
"AUTO_REFETCH option" on ON, OFF ON
page 161
"BELL option" on page 162 ON, OFF ON
"CHAR_OEM_TRANSLATION ON, OFF, DETECT DETECT
option" on page 164
"COMMAND_DELIMITER option" String ’; ’
on page 166
"COMMIT_ON_EXIT option" on ON, OFF ON
page 166
"DESCRIBE_JAVA_FORMAT Varchar, binary Varchar
option" on page 173
"ECHO option" on page 174 ON, OFF ON
"HEADINGS option" on page 177 ON, OFF ON
"INPUT_FORMAT option" on ASCII DBASE ASCII
page 177 DBASEII DBASEIII
DIF FIXED FOXPRO
LOTUS WATFILE
"ISQL_COMMAND_TIMING ON, OFF, YES, NO, 1, 0 ON

155
Interactive SQL options

OPTION VALUES DEFAULT


option" on page 178
"ISQL_ESCAPE_CHARACTER Character ’\ ’
option" on page 179
"ISQL_FIELD_SEPARATOR String ’, ’
option" on page 179
"ISQL_LOG option" on page 180 File-name (empty string)
"ISQL_PLAN option" on page 180 NONE, SHORT, LONG SHORT
"ISQL_QUOTE option" on page 181 String ’
"NULLS option" on page 188 String ’(NULL)’
"ON_ERROR option" on page 188 STOP CONTINUE PROMPT
PROMPT EXIT
NOTIFY_CONTINUE
NOTIFY_STOP
NOTIFY_EXIT
"OUTPUT_FORMAT option" on TEXT ASCII FIXED ASCII
page 190 DIF DBASEII
DBASEIII FOXPRO
LOTUS SQL WATFILE
"OUTPUT_LENGTH option" on Integer 0
page 191
"OUTPUT_NULLS option" on String ’NULL’
page 192
"STATISTICS option" on page 199 0,3,4,5,6 3
"TRUNCATION_LENGTH option" Integer 30
on page 203

156
Chapter 5 Database Options

Alphabetical list of options


This section lists options alphabetically

ALLOW_NULLS_BY_DEFAULT option
Function Controls whether new columns that are created without specifying either
NULL or NOT NULL are allowed to contain NULL values.
Allowed values ON, OFF
Default ON
OFF for Open Client and JDBC connections
Description The ALLOW_NULLS_BY_DEFAULT option is included for Transact-SQL
compatibility.
$ For more information, see "Setting options for Transact-SQL
compatibility" on page 943 of the book ASA User’s Guide.

ANSI_BLANKS option
Function Controls behavior when character data is truncated at the client side.
Allowed values ON, OFF
Default OFF
ON for Open Client and JDBC connections
Description The ANSI_BLANKS option has no effect unless the database was created
with the -b command-line option. It forces a truncation error whenever a
value of data type CHAR(N) is read into a C char(M) variable for values of N
greater than or equal to M. With ANSI_BLANKS set to OFF, a truncation
error occurs only when at least one non-blank character is truncated.
For Embedded SQL, if ANSI_BLANKS is ON when you supply a value of
data type DT_STRING, you must set the sqllen field to the length of the
value, including space for the terminating null character. With
ANSI_BLANKS off, the length is determined solely by the position of the
null character.
The ANSI_BLANKS setting persists for the life of a connection. Changing it
after a connection has been established does not affect that connection.

157
Alphabetical list of options

ANSI_CLOSE_CURSORS_ON_ROLLBACK option
Function Controls whether cursors that were opened WITH HOLD are closed when a
ROLLBACK is performed.
Allowed values ON, OFF
Default OFF
Description The draft SQL/3 standard requires all cursors be closed when a transaction is
rolled back. By default, on a rollback Adaptive Server Anywhere closes only
those cursors that were opened without a WITH HOLD clause. This option
allows you to force closure of all cursors.
The CLOSE_ON_ENDTRANS option overrides the
ANSI_CLOSE_CURSORS_ON_ROLLBACK option.

ANSI_INTEGER_OVERFLOW option
Function Controls what happens when an arithmetic expression causes an integer
overflow error.
Allowed values ON, OFF
Default OFF
Description The ISO SQL/92 standard requires integer overflow should result in an
SQLSTATE = 22003 - overflow error. Adaptive Server Anywhere behavior
was previously different from this. The ANSI_INTEGER_OVERFLOW
option can be set to OFF to maintain compatibility with previous releases of
the software.

ANSI_PERMISSIONS option
Function Controls permissions checking for DELETE and UPDATE statements.
Allowed values ON, OFF
Scope Can be set for the PUBLIC group only. Takes effect immediately. DBA
authority is required to set this option.
Default ON
Description With ANSI_PERMISSIONS ON, the SQL/92 permissions requirements for
DELETE and UPDATE statements are checked. The default value is OFF in
Adaptive Server Enterprise. The following table outlines the differences.

158
Chapter 5 Database Options

SQL Statement Permissions Required Permissions Required


with ansi_permissions off with ansi_permissions
on
UPDATE UPDATE permission on the UPDATE permission on
columns where values are the columns where values
being set are being set
SELECT permission on all
columns appearing in the
WHERE clause
SELECT permission on all
columns on the right side of
the set clause
DELETE DELETE permission on the DELETE permission on the
table table
SELECT permission on all
columns appearing in the
WHERE clause

The ANSI_PERMISSIONS option can be set only for the PUBLIC group.
No private settings are allowed.

ANSI_UPDATE_CONSTRAINTS option
Function Controls the range of updates that are permitted.
Allowed values OFF, CURSORS, STRICT
Default CURSORS in new databases.
OFF in databases created before version 7.0.
Description Adaptive Server Anywhere provides several extensions that allow updates
which are not permitted by the ANSI SQL standard. These extensions
provide powerful, efficient mechanisms for performing updates. However, in
some cases, they cause behavior that is not intuitive. This behavior can
produce anomalies such as lost updates if the user application is not designed
to expect the behavior of these extensions.
The ANSI_UPDATE_CONSTRAINTS option controls whether updates are
restricted to those permitted by the SQL/92 standard.
If the option is set to STRICT, the following updates are prevented:
♦ Updates of cursors containing JOINS

159
Alphabetical list of options

♦ Updates of columns that appear in an ORDER BY clause


♦ The FROM clauses is not allowed in UPDATE statements.
If the option is set to CURSORS, these same restrictions are in place, but
only for cursors. If a cursor is not opened with FOR UPDATE or FOR
READ ONLY, the database server chooses updatability based on the SQL/92
standard. If the ANSI_UPDATE_CONSTRAINTS option is CURSORS or
STRICT, cursors containing an ORDER BY clause default to FOR READ
ONLY; otherwise, they continue to default to FOR UPDATE.
See also "UPDATE statement" on page 621

ANSINULL option
Function Controls the interpretation of = and != with NULL values.
Allowed values ON, OFF
Default ON
Description With ANSINULL ON, any comparisons with NULL using = or != are
unknown.
Also, aggregate functions on columns that contain NULL values cause the
warning ’null value eliminated in aggregate function’ (SQLSTATE=01003).
Setting ANSINULL to OFF allows comparisons with NULL to yield results
that are not unknown, for compatibility with Adaptive Server Enterprise, and
turns off the warning.

AUDITING option
Function Enables and disables auditing in the database.
Allowed values ON, OFF
Scope Can be set for the PUBLIC group only. Takes effect immediately. DBA
permissions are required to set this option.
Default OFF
Description This option switches auditing on and off.
Auditing is the recording of detailed information about many events in the
database in the transaction log. Auditing provides some security features, at
the cost of some performance.
Example ♦ Turn on auditing

160
Chapter 5 Database Options

SET OPTION PUBLIC.AUDITING = ’ON’

AUTO_COMMIT option [ISQL]


Function Controls whether a COMMIT is performed after each statement.
Allowed values ON, OFF
Default OFF
Description If AUTO_COMMIT is on, a database COMMIT is performed after each
successful statement. If the COMMIT fails, you have the option to execute
additional SQL statements and perform the COMMIT again, or execute a
ROLLBACK statement.

By default, a COMMIT or ROLLBACK is performed only when the user


issues a COMMIT or ROLLBACK statement or a SQL statement that causes
an automatic commit (such as the CREATE TABLE statement).

AUTO_REFETCH option [ISQL]


Function Controls whether query results are fetched again after deletes, updates, and
inserts.
Allowed values ON, OFF
Default ON
Description If AUTO_REFETCH is on, the current query results that are displayed in the
Data window will be refetched from the database after any INSERT,
UPDATE or DELETE statement. Depending on how complicated the query
is, this may take some time. For this reason, it can be turned off.

AUTOMATIC_TIMESTAMP option
Function Controls interpretation of new columns with the TIMESTAMP data type.
Allowed values ON, OFF
Default OFF

161
Alphabetical list of options

Description Controls whether any new columns with the TIMESTAMP data type that do
not have an explicit default value defined are given a default value of the
Transact-SQL timestamp value as a default. The
AUTOMATIC_TIMESTAMP option is included for Transact-SQL
compatibility. The default is OFF.
$ For more information, see "Setting options for Transact-SQL
compatibility" on page 943 of the book ASA User’s Guide.

BACKGROUND_PRIORITY option
Function To limit impact on the performance of connections other than the current
connection.
Allowed values ON or OFF
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
If you set this option temporarily, that setting applies to the current
connection only. Different connections under the same user ID can have
different settings for this option.
Default OFF
Description When set to ON, it requests that the current connection have minimal impact
on the performance of other connections. This option allows tasks for which
responsiveness is critical to coexist with other tasks for which performance is
not as important.

BELL option [ISQL]


Function Controls whether the bell sounds when an error occurs.
Allowed values ON, OFF
Default ON
Description Set this option according to your preference.

BLOB_THRESHOLD option
Function Controls the size of value that the Message Agent treats as a long object
(blob).

162
Chapter 5 Database Options

Allowed values Integer, in kilobytes


Default 256
Description Any value longer than the BLOB_THRESHOLD option is replicated as a
blob. That is, it is broken into pieces and replicated in chunks, before being
reconstituted by using a SQL variable and concatenating the pieces at the
recipient site.
If you set BLOB_THRESHOLD to a high value in remote Adaptive Server
Anywhere databases, blobs are not broken into pieces, and operations can be
applied to Adaptive Server Enterprise by the Message Agent. Each SQL
statement must fit within a message, so this only allows replication of small
blobs.

BLOCKING option
Function Controls the behavior in response to locking conflicts.
Allowed values ON or OFF
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default ON
Description If BLOCKING is ON, any transaction attempting to obtain a lock that
conflicts with an existing lock held by another transaction waits until every
conflicting lock is released. At that time, the write goes through. If
BLOCKING is OFF, the transaction that attempts to obtain a conflicting lock
receives an error.
$ For more information, see "Two-phase locking" on page 410 of the
book ASA User’s Guide.

CHAINED option
Function Controls transaction mode in the absence of a BEGIN TRANSACTION
statement.
Allowed values ON, OFF
Default ON
OFF for Open Client and JDBC connections

163
Alphabetical list of options

Description Controls the Transact-SQL transaction mode. In Unchained mode


(CHAINED = OFF), each statement is committed individually unless an
explicit BEGIN TRANSACTION statement is executed to start a transaction.
In chained mode (CHAINED = ON) a transaction is implicitly started before
any data retrieval or modification statement.

CHAR_OEM_TRANSLATION option [ISQL]


Function Controls whether ANSI-to-OEM code page translation is carried out.
Allowed values ON, OFF, DETECT
Default DETECT
Description Each time Interactive SQL connects to a database or uses SET
CONNECTION, it determines the setting of Char_OEM_Translation.
If the option is set to ON or OFF, translation is set accordingly. If the option
is set to DETECT (the recommended and default setting), Interactive SQL
fetches the collation label from the database and examines it. If the collation
label starts with a string that generally indicates an ANSI code page, then
Interactive SQL turns translation off.
The strings that indicate ANSI code pages are as follows:
♦ WIN_
♦ ISO_
♦ SJIS
♦ EUC_
♦ UTF
♦ EBCDIC
♦ 813
♦ 819

For all other prefixes, translation is turned on. When the option is set to
DETECT, Interactive SQL displays a message in the status window
indicating the collation label and the display translation setting.

164
Chapter 5 Database Options

CHECKPOINT_TIME option
Function Set the maximum number of minutes that the database server will run
without doing a checkpoint.
Allowed values Integer
Scope Can be set only for the PUBLIC group. DBA authority is required to set the
option. You must shut down and restart the database server for the change to
take effect.
Default 60
Description This option is used with the "RECOVERY_TIME option" on page 195 to
decide when checkpoints should be done.
$ For information on checkpoints, see "Checkpoints and the checkpoint
log" on page 650 of the book ASA User’s Guide.

CIS_ROWSET_SIZE option
Function Set the number of rows that are returned from remote servers for each fetch.
Allowed values Integer
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect when a new connection is made to a remote server.
Default 50
Description This option sets the ODBC FetchArraySize value when using ODBC to
connect to a remote database server.

CLOSE_ON_ENDTRANS option
Function Controls the closing of cursors at the end of a transaction.
Allowed values ON, OFF
Default ON
Description When CLOSE_ON_ENDTRANS is set to ON, cursors are closed whenever
a transaction is committed unless the cursor was opened WITH HOLD. The
behavior when a transaction is rolled back is governed by the
ANSI_CLOSE_CURSORS_AT_ROLLBACK option.

165
Alphabetical list of options

When CLOSE_ON_ENDTRANS is set to OFF, cursors are not closed at


either a commit or a rollback, regardless of the
ANSI_CLOSE_CURSORS_AT_ROLLBACK option setting or whether the
cursor was opened WITH HOLD or not.
Setting this to OFF provides Adaptive Server Enterprise compatible
behavior.

COMMAND_DELIMITER option [ISQL]


Function Sets the string that indicates the end of a statement in Interactive SQL.
Allowed values String
Default Semi-colon (;)
Description You can specify a command delimiter to indicate the end of a SQL
statement. This command delimiter can be any sequence of characters
(including numbers, letters, and punctuation), but it cannot contain
embedded blanks. As well, it can contain a semicolon, but only as the first
character.
If the command delimiter is set to a string beginning with a character that is
valid in identifiers, the command delimiter must be preceded by a space.
This command delimiter is case sensitive. You should enclose the new
command delimiter in single quotation marks.
Example SET OPTION COMMAND_DELIMITER=’;;’

COMMIT_ON_EXIT option [ISQL]


Function Controls behavior when Interactive SQL disconnects or terminates.
Allowed values ON, OFF
Default ON
Description Controls whether a COMMIT or ROLLBACK is done when you leave
Interactive SQL. When COMMIT_ON_EXIT is set to ON, a COMMIT is
done; otherwise a ROLLBACK is done.

COMPRESSION option
Function Set the level of compression for SQL Remote messages.
Allowed values Integer, from -1 to 9

166
Chapter 5 Database Options

Default 6
Description The values have the following meanings:
♦ -1 Send messages in Version 5 format. Message Agents (both
dbremote and ssremote) from previous versions of SQL Remote cannot
read messages sent in Version 6 format. You should ensure that
COMPRESSION is set to -1 until all Message Agents in your system are
upgraded to Version 6.
♦ 0 No compression.
♦ 1 to 9 Increasing degrees of compression. Creating messages with
high compression can take longer than creating messages with low
compression.

CONTINUE_AFTER_RAISERROR option
Function Controls behavior following a RAISERROR statement.
Allowed values ON, OFF
Default ON
Description
Deprecated option
This option is deprecated in favor of the ON_TSQL_ERROR option.
$ For more information, see "ON_TSQL_ERROR option" on
page 189.

The RAISERROR statement is used within procedures and triggers to


generate an error. When this option is set to OFF, the execution of the
procedure or trigger is stopped whenever the RAISERROR statement is
encountered.

If you set the CONTINUE_AFTER_RAISERROR switch to ON, the


RAISERROR statement no longer signals an execution-ending error. Instead,
the RAISERROR status code and message are stored and the most recent
RAISERROR is returned when the procedure completes. If the procedure
which caused the RAISERROR was called from another procedure, the
RAISERROR is not returned until the outermost calling procedure
terminates.

167
Alphabetical list of options

Intermediate RAISERROR statuses and codes are lost after the procedure
terminates. If, at return time, an error occurs along with the RAISERROR,
then the information for the new error is returned and the RAISERROR
information is lost. The application can query intermediate RAISERROR
statuses by examining the @@error global variable at different execution
points.

CONVERSION_ERROR option
Function Controls the reporting of data type conversion failures on fetching
information from the database.
Allowed values ON, OFF
Default ON
Description This option controls whether data type conversion failures, when data is
fetched from the database or inserted into the database, are reported by the
database as errors (CONVERSION_ERROR set to ON) or as a warning
(CONVERSION_ERROR set to OFF).

When CONVERSION_ERROR is set to ON, the


SQLE_CONVERSION_ERROR error is generated. If the option is set to
OFF, the warning SQLE_CANNOT_CONVERT is produced.

If conversion errors are reported as warnings only, the NULL value is used
in place of the value that could not be converted. In Embedded SQL, an
indicator variable is set to -2 for the column or columns that cause the error.

COOPERATIVE_COMMITS option
Function Controls when commits are written to disk.
Allowed values ON or OFF
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default ON
Description If COOPERATIVE_COMMITS is set to OFF, a COMMIT is written to disk
as soon as the database server receives it, and the application is then allowed
to continue.

168
Chapter 5 Database Options

If COOPERATIVE_COMMITS is set to ON (the default), the database


server does not immediately write the COMMIT to the disk. Instead, the
application waits for up to the maximum length set by the
COOPERATIVE_COMMIT_TIMEOUT option for something else to put on
the pages before they are written to disk.
Setting COOPERATIVE_COMMITS to ON, and increasing the
COOPERATIVE_COMMIT_TIMEOUT setting, increases overall database
server throughput by cutting down the number of disk I/Os, but at the
expense of a longer turnaround time for each individual connection.
If both COOPERATIVE_COMMITS and DELAYED_COMMITS are set to
ON, and the COOPERATIVE_COMMIT_TIMEOUT interval passes
without the pages getting written, the application is resumed (as if the
commit had worked), and the remaining interval
(DELAYED_COMMIT_TIMEOUT -
COOPERATIVE_COMMIT_TIMEOUT) is used as a
DELAYED_COMMIT interval. The pages will then be written, even if they
are not full.

COOPERATIVE_COMMIT_TIMEOUT option
Function Governs when a COMMIT entry in the transaction log is written to disk.
Allowed values Integer, in milliseconds
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default 250
Description This option has meaning only when COOPERATIVE_COMMITS is set to
ON. The database server waits for the specified number of milliseconds for
other connections to fill a page of the log before writing to disk. The default
setting is 250 milliseconds.

DATE_FORMAT option
Function Sets the format for dates retrieved from the database.
Allowed values String
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default ’YYYY-MM-DD’. This corresponds to ISO date format specifications.

169
Alphabetical list of options

Description The format is a string using the following symbols:

Symbol Description
yy Two digit year
yyyy Four digit year
mm Two digit month, or two digit minutes if following a colon(as in
hh:mm)
mmm[m...] Character short form for months—as many characters as there are
m's
d Single digit day of week, (0 = Sunday, 6 = Saturday)
dd Two digit day of month
ddd[d...] Character short form for day of the week
hh Two digit hours
nn Two digit minutes
ss[.ss..] Seconds and parts of a second
aa AM or PM (12 hour clock)
pp PM if needed (12 hour clock)
jjj Day of the year, from 1 to 366

Each symbol is substituted with the appropriate data for the date that’s being
formatted. Any format symbol that represents character rather than digit
output can be put in upper case which causes the substituted characters to
also be in upper case. For numbers, using mixed case in the format string
suppresses leading zeros.
You can control the padding of numbers by changing the case of the
symbols. Same-case symbols (MM, mm, DD, dd) all pad number with
zeroes. Mixed case (Mm, mM, Dd, or dD) cause the number to not be zero
padded: the value takes as much room as required. For example
SELECT dateformat( ’1998/01/01’, ’yyyy/Mm/Dd’)
returns the following value:
1998/1/1
Examples ♦ The following table illustrates DATE_FORMAT settings, together with
the output from the following statement, executed on Thursday May 21,
1998
SELECT CURRENT DATE

170
Chapter 5 Database Options

DATE_FORMAT SELECT CURRENT DATE


yyyy/mm/dd/ddd 1998/05/21/thu
Jjj 141
mmm yyyy may 1998
mm-yyyy 05-1998

DATE_ORDER option
Function Controls the interpretation of date formats.
Allowed values ’MDY’, ’YMD’, or ’DMY’
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default YMD. This corresponds to ISO date format specifications.
For Open Client and JDBC connections, the default is set to MDY.
Description The database option DATE_ORDER is used to determine whether 10/11/12
is Oct 11 1912, Nov 12 1910, or Nov 10 1912. The option can have the value
’MDY’, ’YMD’, or ’DMY’.

DEFAULT_TIMESTAMP_INCREMENT option
Function Specifies the number of microseconds to add to a column of type
TIMESTAMP in order to keep values in the column unique.
Allowed values Integer
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default 1
Description Since a TIMESTAMP value is precise to six decimal places in Adaptive
Server Anywhere, by default 1 microsecond (0.000001 of a second) is added
to differentiate between two identical TIMESTAMP values.
Some software, such as Microsoft Access, truncates TIMESTAMP values to
three decimal places, making valid comparisons a problem. Setting this value
to a larger number, such as 0.001 of a second (an option value of 1000),
alleviates this problem.

171
Alphabetical list of options

DELAYED_COMMITS option
Function Determines when the server returns control to an application following a
COMMIT.
Allowed values ON or OFF
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default OFF. This corresponds to ISO COMMIT behavior.
Description When set to ON, the database server replies to a COMMIT statement
immediately instead of waiting until the transaction log entry for the
COMMIT has been written to disk. When set to OFF, the application must
wait until the COMMIT is written to disk.
When this option is ON, the log is written to disk when the log page is full or
according to the DELAYED_COMMIT_TIMEOUT option setting,
whichever is first. There is a slight chance that a transaction may be lost even
though committed if a system failure occurs after the server replies to a
COMMIT, but before the page is written to disk. Setting
DELAYED_COMMITS to ON, and the DELAYED_COMMIT_TIMEOUT
option to a high value, promotes a quick response time at the cost of security.
If both COOPERATIVE_COMMITS and DELAYED_COMMITS are set to
ON, and if the COOPERATIVE_COMMIT_TIMEOUT interval passes
without the pages getting written, the application is resumed (as if the
commit had worked), and the remaining interval
(DELAYED_COMMIT_TIMEOUT -
COOPERATIVE_COMMIT_TIMEOUT) is used as a
DELAYED_COMMIT interval, after which the pages will be written, even if
they are not full.

DELAYED_COMMIT_TIMEOUT option
Function Determines when the server returns control to an application following a
COMMIT.
Allowed values Integer, in milliseconds.
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default 500

172
Chapter 5 Database Options

Description This option has meaning only when DELAYED_COMMITS is set to ON. it
governs when a COMMIT entry in the transaction log is written to disk.
With DELAYED_COMMITS set to ON, the database engine waits for the
number of milliseconds set in the DELAYED_COMMIT_TIMEOUT option
for other connections to fill a page of the log before writing the current page
contents to disk.
$ For more information, see "DELAYED_COMMITS option" on
page 172.

DELETE_OLD_LOGS option
Function Controls whether transaction logs are deleted when their messages have been
replicated.
Allowed values ON, OFF
Default OFF
Description This option is used by SQL Remote and by the Adaptive Server Anywhere
Replication Agent. The default setting is OFF. When it is set to ON, the
Message Agent (DBREMOTE) deletes each old transaction log when all the
changes it contains have been sent and confirmed as received.

DESCRIBE_JAVA_FORMAT option [ISQL]


Function Controls whether Java objects are interpreted as strings (for display) or as
binary (for loading and unloading).
Allowed values varchar, binary
Default varchar
Description When set to varchar, Interactive SQL converts all data fetched from the
database to strings. The database server calls the toString() method on
Java columns to provide formatted output for the Interactive SQL data
window.
When set to binary, Interactive SQL does no data conversion.

DIVIDE_BY_ZERO_ERROR option
Function Controls the reporting of division by zero.
Allowed values ON, OFF
173
Alphabetical list of options

Default ON
Description This option indicates whether division by zero is reported as an error. If the
option is set ON, then division by zero results in an error with SQLSTATE
22012.

If the option is set OFF, division by zero is not an error. Instead, a NULL is
returned.

ECHO option [ISQL]


Function Controls whether statements are echoed before they are executed.
Allowed values ON, OFF
Default ON
Description This option is most useful when you use the READ statement to execute a
Interactive SQL command file.

ESCAPE_CHARACTER option
This option is reserved for system use. Do not change the setting of this
option.

EXTENDED_JOIN_SYNTAX option
Function Controls whether queries with an ambiguous syntax for multi-table joins are
allowed, or reported as an error.
Allowed values ON, OFF
Default ON
Description This option reports a syntax error for those queries containing outer joins that
have ambiguous syntax due to the presence of duplicate correlation names on
a null-supplying table.
The following join clause illustrates the kind of query that is reported.
( R left outer join T , T join S on ( C1 ) )
where C1 is a condition. If the option is set to ON, this query is interpreted as
follows.
( R left outer join T on ( C1 ) ) join S on ( C2 )

174
Chapter 5 Database Options

where C1 and C2 are conditions.

FIRE_TRIGGERS option
Function Controls whether triggers are fired in the database.
Allowed values ON, OFF
Default ON
Description When set to ON, triggers are fired. When set to OFF, no triggers are fired,
including referential integrity triggers (such as cascading updates and
deletes). Only a user with DBA authority can set this option. The option is
overridden by the -gf command-line option, which turns off all trigger firing
regardless of the FIRE_TRIGGERS setting.

This option is relevant when replicating data from Adaptive Server


Enterprise to Adaptive Server Anywhere, because all actions from Adaptive
Server Enterprise transaction logs are replicated to Adaptive Server
Anywhere, including actions carried out by triggers.

FLOAT_AS_DOUBLE option
Function Controls the interpretation of the FLOAT keyword.
Allowed values ON, OFF
Default OFF
ON for Open Client and JDBC connections
Description The FLOAT_AS_DOUBLE option makes the FLOAT keyword behave like
Adaptive Server Enterprise’s FLOAT keyword when a precision is not
specified.

When enabled (set to ON), all occurrences of the keyword FLOAT are
interpreted as equivalent to the keyword DOUBLE within SQL statements.

By default, Adaptive Server Anywhere FLOAT values are interpreted by


Adaptive Server Enterprise as REAL values. Since Adaptive Server
Enterprise treats its own FLOAT values as DOUBLE, enabling this option
makes Adaptive Server Anywhere treat FLOAT values in the same way
Enterprise treats FLOAT values.

175
Alphabetical list of options

REAL values are four bytes; DOUBLE values are eight bytes. According to
the ANSI SQL/92 specification, FLOAT can be interpreted based on the
platform. It is up to the database to decide what size the value is, so long as it
can handle the necessary precision. Adaptive Server Enterprise and Adaptive
Server Anywhere exhibit different default behavior.
The FLOAT_AS_DOUBLE option takes effect only when no precision is
specified. For example, the following statement is not affected by the option
setting:
create table t1(
c1 float(5)
)
The following statement is affected by the option setting:
create table t2(
c1 float)
// affected by option setting

GLOBAL_DATABASE_ID option
Function For use in generating unique primary keys in a replication environment.
Controls the beginning of the range of values for columns created with
DEFAULT GLOBAL AUTOINCREMENT.
Allowed values Integer
Default 0
Scope PUBLIC setting only. Takes effect when the database is next started.
See also "CREATE TABLE statement" on page 453
"Database-level properties" on page 1070
"Ensuring unique primary keys" on page 357 of the book Replication and
Synchronization Guide
Description If you create a column with DEFAULT GLOBAL AUTOINCREMENT, its
value is incremented starting from the value of GLOBAL_DATABASE_ID.
A setting of 0 (the default) indicates that GLOBAL DEFAULT
AUTOINCREMENT is disabled, and NULL is generated as a default.
You can find the value of the option in the current database using the
following statement:
select db_property( ’GlobalDBId’ )
You need to shut down and restart the database when you change this option
for it to take effect.

176
Chapter 5 Database Options

This feature is of particular use in replication environments to ensure unique


primary keys. For more information, see "Ensuring unique primary keys" on
page 357 of the book Replication and Synchronization Guide.

HEADINGS option [ISQL]


Function Controls whether headings will be displayed for the results of a SELECT
statement.
Allowed values ON, OFF
Default ON
Description Set this option according to your preference.

INPUT_FORMAT option [ISQL]


Function Sets the default data format expected by the INPUT statement.
Allowed values String. See below.
Default ASCII
Description Certain file formats contain information about column names and types.
Using this information, the INPUT statement will create the database table if
it does not already exist. This is a very easy way to load data into the
database. The formats that have enough information to create the table are:
DBASEII, DBASEIII, DIF, FOXPRO, LOTUS, and WATFILE.
Allowable input formats are:
♦ ASCII Input lines are assumed to be ASCII characters, one row per
line, with values separated by commas. Alphabetic strings may be
enclosed in apostrophes (single quotes) or quotation marks (double
quotes). Strings containing commas must be enclosed in either single or
double quotes. If single or double quotes are used, double the quote
character to use it within the string. Optionally, you can use the
DELIMITED BY clause to specify a different delimiter string than the
default, which is a comma (,).
Three other special sequences are also recognized. The two characters \n
represent a newline character, \\ represents a single backslash character,
and the sequence \xDD represents the character with hexadecimal code
DD.

177
Alphabetical list of options

♦ DBASE The file is in dBASE II or dBASE III format. Interactive SQL


will attempt to determine which format, based on information in the file.
If the table doesn’t exist, it will be created.
♦ DBASEII The file is in dBASE II format. If the table doesn’t exist, it
will be created.
♦ DBASEIII The file is in dBASE III format. If the table doesn’t exist, it
will be created.
♦ DIF The file is in Data Interchange Format. If the table doesn’t exist, it
will be created.
♦ FIXED Input lines are in fixed format. The width of the columns can be
specified using the COLUMN WIDTHS clause. If they are not specified,
column widths in the file must be the same as the maximum number of
characters required by any value of the corresponding database column’s
type.
♦ FOXPRO The file is in FoxPro format. The FoxPro memo field is
different than the dBASE memo field. If the table doesn’t exist, it will be
created.
♦ LOTUS The file is a Lotus WKS format worksheet. INPUT assumes
that the first row in the Lotus WKS format worksheet consists of column
names. If the table doesn’t exist, it will be created. In this case, the types
and sizes of the columns created may not be correct because the
information in the file pertains to a cell, not to a column.
♦ WATFILE The input will be a WATFILE file. If the table doesn’t exist,
it will be created.

ISQL_COMMAND_TIMING option [ISQL]


Function Controls whether SQL statements are timed or not.
Allowed values ON, OFF, YES, NO, 1, 0
Default ON
Description This boolean option controls whether SQL statements are timed or not. If
you set the option to ON, YES, or 1, the time of execution appears in the
Messages pane after you execute a statement. If you set the option to OFF,
NO, or 0, the time does not appear.
You can also set this option on the Messages page of the Options dialog.

178
Chapter 5 Database Options

ISQL_ESCAPE_CHARACTER option [ISQL]


Function Controls the escape character used in place of unprintable characters in data
exported to ASCII files.
Allowed values Any single character
Default A backslash ( \ )
Description When Interactive SQL exports strings that contain unprintable characters
(such as a carriage return), it converts each unprintable character into a
hexadecimal format and precedes it with an escape character. The character
you specify for this setting is used in the output if your OUTPUT statement
does not contain an ESCAPE CHARACTER clause. This setting is used only
if you are exporting to an ASCII file.
Example ♦ Create a table that contains one string value with an embedded carriage
return (denoted by the "\n" in the INSERT statement). Then export the
data to c:\escape.txt with a # sign as the escape character.
CREATE TABLE escape_test( TEXT varchar(10 ) );
INSERT INTO escape_test VALUES( ’one\ntwo’ );
SET TEMPORARY OPTION ISQL_ESCAPE_CHARACTER=’#’;
SELECT * FROM escape_test;
OUTPUT TO c:\escape.txt FORMAT ASCII
This code places the following data in escape.txt:
’one#x0Atwo’
where # is the escape character and x0A is the hexadecimal
equivalent of the "\n" character.
The start and end characters (in this case, single quotation marks)
depend on the ISQL_QUOTE setting.

ISQL_FIELD_SEPARATOR option [ISQL]


Function Controls the default string used for separating values in data exported to
ASCII files.
Allowed values Any string
Default A comma ( , )
Description Controls the default string used for separating (or delimiting) values in data
exported to ASCII files. If an OUTPUT statement does not contain a
DELIMITED BY clause, the value of this setting is used.

179
Alphabetical list of options

Example ♦ Set the field separator to a colon in the data exported to c:\employee.txt.
SET TEMPORARY OPTION ISQL_FIELD_SEPARATOR=’:’;
SELECT emp_lname, emp_fname FROM employee WHERE
emp_id < 150;
OUTPUT TO c:\employee.txt FORMAT ASCII
This code places the following data in employee.txt:
’Cobb’:’Matthew’
’Chin’:’Philip’
’Jordan’:’Julie’
The start and end characters (in this case, single quotation marks)
depend on the ISQL_QUOTE setting.

ISQL_LOG option [ISQL]


Function Controls logging behavior.
Allowed values String containing a file name.
Default Empty string.
Description If ISQL_LOG is set to a non-empty string, all Interactive SQL statements are
added to the end of the named file. Otherwise, if ISQL_LOG is set to the
empty string, Interactive SQL statements are not logged.

Individual session only


This option logs an individual Interactive SQL session only. See "Backup
and Data Recovery" on page 627 of the book ASA User’s Guide for a
description of the transaction log that logs all changes to the database by
all users.

ISQL_PLAN option [ISQL]


Function Controls the amount of information displayed in the Messages pane after you
execute statements.
Allowed values NONE, SHORT, LONG
Default SHORT

180
Chapter 5 Database Options

Description After you execute a SQL statement in Interactive SQL, the optimizer
provides information in the Messages pane about how it optimized the
execution. To determine the amount of information displayed, you can
choose one of three plans: NONE provides no information; SHORT provides
basic information; LONG provides detailed information.
You can specify whether the time of execution is included with any of these
plans by setting the "ISQL_COMMAND_TIMING option" on page 178.
You can also specify a plan on the Messages page of the Options dialog.

ISQL_QUOTE option [ISQL]


Function Controls the default string that begins and ends all strings in data exported to
ASCII files.
Allowed values Any string
Default A single apostrophe ( ’ )
Description Controls the default string that begins and ends all strings in data exported to
ASCII files. If an OUTPUT statement does not contain a QUOTE clause,
this value is used by default.
Example ♦ Set the field separator to a colon in the data exported to c:\employee.txt.
SET TEMPORARY OPTION ISQL_QUOTE=’"’;
SELECT emp_lname, emp_fname FROM employee WHERE
emp_id < 150;
OUTPUT TO c:\employee.txt FORMAT ASCII
This code places the following data in employee.txt:
"Cobb","Matthew"
"Chin","Philip"
"Jordan","Julie"
The separator characters (in this case, commas) depend on the
ISQL_FIELD_SEPARATOR setting.

ISOLATION_LEVEL option
Function Controls the locking isolation level.
Allowed values 0, 1, 2, or 3

181
Alphabetical list of options

Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default 0
1 for Open Client and JDBC connections
Description This option controls the locking isolation level as follows.
♦ 0 Allow dirty reads, nonrepeatable reads, and phantom rows.
♦ 1 Prevent dirty reads. Allow nonrepeatable reads and phantom rows.
♦ 2 Prevent dirty reads and guarantee repeatable reads. Allow phantom
rows.
♦ 3 Serializable. Do not allow dirty reads, guarantee repeatable reads,
and do not allow phantom rows.
$ For more information, see "Isolation levels and consistency" on
page 374 of the book ASA User’s Guide.

JAVA_HEAP_SIZE option
Function To limit the memory used by Java applications for a connection.
Allowed values Integer
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately. DBA permissions are required to set this option for any
connection.
Default 1000000
Description This option sets the maximum size (in bytes) of the memory that is allocated
to Java applications on a per-connection basis. Per-connection memory
allocations typically consist of the user’s working set of allocated Java
variables and Java application stack space.
While a Java application is executing on a connection, the per-connection
allocations come out of the fixed cache of the database server, so it is
important that a run-away Java application is prevented from using up too
much memory.

JAVA_INPUT_OUTPUT option
Function To enable file access from Java in the database

182
Chapter 5 Database Options

Allowed values ON, OFF


Supported on NT only.
Scope Can be set for the PUBLIC group only. DBA authority required. Takes effect
when the database is restarted.
Default OFF
See also "Supported Java packages" on page 276
Description By default, the java.io package is only partially supported. In particular,
classes that handle file access are disabled. If JAVA_INPUT_OUTPUT is set
to ON, Java file access classes in java.io are enabled for all connections to
the database.

JAVA_NAMESPACE_SIZE option
Function To limit the memory used by Java applications for a connection.
Allowed values Integer
Scope Can be set only for the PUBLIC group. Takes effect immediately.
Default 4000000
Description This option sets the maximum size (in bytes) of the memory that is allocated
to Java applications on a per-database basis.
Per-database memory allocations include Java class definitions. Because
class definitions are effectively read-only, they are shared between
connections. Consequently, their allocations come right out of the fixed
cache, and this option sets a limit on the size of these allocations.

LOGIN_MODE option
Function Controls the use of integrated logins for the database.
Allowed values Standard, Mixed, or Integrated
Scope Can be set only for the PUBLIC group. Takes effect immediately.
Default Standard
Description This option specifies whether integrated logins are permitted. The following
values are accepted (the values are case insensitive):
♦ Standard This is the default setting, which does not permit integrated
logins. An error occurs if an integrated login connection is attempted.
183
Alphabetical list of options

♦ Mixed With this setting, both integrated logins and standard logins are
allowed.
♦ Integrated With this setting, all logins to the database must be made
using integrated logins.

Caution
Setting the LOGIN_MODE database option to Integrated restricts
connections to only those users who have been granted an
integrated login mapping. Attempting to connect with a user ID
and password generates an error. The only exceptions to this are
users with DBA authority (full administrative rights).

$ For more information on integrated logins see "Using integrated logins"


on page 73 of the book ASA User’s Guide.

LOGIN_PROCEDURE option
Function A login procedure that sets connection compatibility options at startup. By
default the procedure calls the sp_login_environment procedure to determine
which options to set.
Allowed values String
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default sp_login_environment
Description This login procedure calls the sp_login_environment procedure at run time to
determine the database connection settings.
You can customize the default database option settings by creating a new
procedure and setting LOGIN_PROCEDURE to call the new procedure. You
should not edit either sp_login_procedure or sp_tsql_environment.

MAX_CURSOR_COUNT option
Function A resource governor to limit the maximum number of cursors that a
connection can use at once.
Allowed values Integer
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately. DBA permissions are required to set this option for any
connection.

184
Chapter 5 Database Options

Default 50
Description This resource governor allows a DBA to limit the number of cursors per
connection that a user can use. If an operation would exceed the limit for a
connection, an error is generated, indicating that the governor for the
resource has been exceeded.
If a connection executes a stored procedure, that procedure is executed under
the permissions of the procedure owner. However, the resources used by the
procedure are assigned to the current connection.
You can remove resource limits by setting the option to 0 (zero).

MAX_HASH_SIZE option
Function Specify the default maximum hash size for new indexes.
Allowed values Integer, from 2 to 64 inclusive.
Scope Can be set for the PUBLIC group only. Takes effect immediately. DBA
permissions are required to set this option.
Default 10
See also "CREATE INDEX statement" on page 435
"CREATE TABLE statement" on page 453
Description This option controls the default hash size for indexes. For performance
implications, see "How indexes work" on page 795 of the book ASA User’s
Guide.

MAX_WORK_TABLE_HASH_SIZE option
Function Specify the maximum hash size used during query optimization for internal
temporary tables.
Allowed values Integer, from 2 to 64 inclusive.
Scope Can be set for the PUBLIC group only. Takes effect immediately. DBA
permissions are required to set this option.
Default 20
"Temporary tables used in query processing" on page 802 of the book ASA
See also
User’s Guide.

185
Alphabetical list of options

Description In general, you should not need to use this option, as the query optimizer
allocates hash sizes for the internal temporary tables based on the data
distribution within the table. The option allows you to override the optimizer
behavior to either increase the maximum hash size it can use beyond 20, or
to restrict it further.

MAX_STATEMENT_COUNT option
Function A resource governor to limit the maximum number of prepared statements
that a connection can use at once.
Allowed values Integer
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately. DBA permissions are required to set this option for any
connection.
Default 50
Description This resource governor allows a DBA to limit the number of prepared
statements per connection a user can use. If an operation would exceed the
limit for a connection, an error is generated, indicating that the governor for
the resource has been exceeded.
If a connection executes a stored procedure, that procedure is executed under
the permissions of the procedure owner. However, the resources used by the
procedure are assigned to the current connection.
You can remove resource limits by setting the option to 0 (zero).

MIN_PASSWORD_LENGTH option
Function Sets the minimum length for new passwords in the database.
Allowed values Integer, greater than or equal to zero.
The value is in bytes. For single-byte character sets, this is the same as the
number of characters.
Scope Can be set for the PUBLIC group. Takes effect immediately. DBA
permissions are required to set this option.
Default 0 characters
Description This option allows the database administrator to impose a minimum length
on all new passwords for greater security. Existing passwords are not
affected.

186
Chapter 5 Database Options

♦ Set the minimum length for new passwords to 6 bytes.


Example
SET OPTION PUBLIC.MIN_PASSWORD_LENGTH = 6

NEAREST_CENTURY option
Function Controls the interpretation of two-digit years, in string-to-date conversions.
Allowed values Integer between 0 and 100
Default 50 for databases created with Version 6 or later.
0 for databases created with Version 5.5 or earlier.
Description This option controls the handling of two-digit years, when converting from
strings to dates or timestamps.
The NEAREST_CENTURY setting is a numeric value that acts as a rollover
point. Two digit years less than the value are converted to 20yy, while years
greater than or equal to the value are converted to 19yy.

The historical Adaptive Server Anywhere behavior is to add 1900 to the


year. Adaptive Server Enterprise behavior is to use the nearest century, so
any year where value yy is less than 50, the year is set to 20yy.

NON_KEYWORDS option
Function Turns off individual keywords, allowing their use as identifiers.
Allowed values String
Default The empty string.
Description This option turns off individual keywords, or all keywords introduced since a
specific release of the product. This provides a way of ensuring that
applications created with older versions of the product are not broken by new
keywords. If you have an identifier in your database that is now a keyword,
you can either add double quotes around the identifier in all applications or
scripts, or turn off the keyword using the NON_KEYWORDS option.
In addition to specifying individual keywords, you can turn off all keywords
since a specified release, using one of the following special values in the list
of keywords:
keywords_4_0_d, keywords_4_0_c, keywords_4_0_b,
keywords_4_0_a, keywords_4_0, keywords_5_0_01,
keywords_5_0

187
Alphabetical list of options

The following statement prevents TRUNCATE and SYNCHRONIZE from


being recognized as keywords:
SET OPTION NON_KEYWORDS = ’TRUNCATE, SYNCHRONIZE’
The following statement prevents all keywords introduced since release 4.0d
from being recognized as keywords:
SET OPTION NON_KEYWORDS = ’keywords_4_0_d’
Each new setting of this option replaces the previous setting. The following
statement clears all previous settings.
SET OPTION NON_KEYWORDS =
A side-effect of this options is that SQL statements that use a turned off
keyword cannot be used: they produce a syntax error.

NULLS option [ISQL]


Function Specifies how NULL values in the database are displayed.
Allowed values String
Default (NULL)
Description Set this according to your preference.

ON_ERROR option [ISQL]


Function Controls what happens if an error is encountered while reading statements
from a command file.
Allowed values String. See below for allowed values.
Default PROMPT
Description Controls what happens if an error is encountered while reading statements
from a command file, as follows:
♦ STOP Interactive SQL stops reading statements from the file and
returns to the statement window for input.
♦ PROMPT Interactive SQL prompts the user to see if the user wishes to
continue.
♦ CONTINUE The error is ignored and Interactive SQL continues
reading statements from the command file. The INPUT statement
continues with the next row, skipping the row that caused the error.
♦ EXIT Interactive SQL terminates.

188
Chapter 5 Database Options

♦ NOTIFY_CONTINUE The error is displayed in a message box with a


single button. Execution continues once the button is clicked.
♦ NOTIFY_STOP The error is displayed in a message box with a single
button. Execution of the script stops once the button is clicked.
♦ NOTIFY_EXIT The error is displayed in a message box with a single
button. Interactive SQL terminates once the button is clicked.

ON_TSQL_ERROR option
Function Controls error-handling in stored procedures.
Allowed values String. See below for allowed values.
Default CONDITIONAL
See also "CREATE PROCEDURE statement" on page 440
"CREATE PROCEDURE statement" on page 447
"Transact-SQL procedure language overview" on page 954 of the book ASA
User’s Guide
Description This option controls error handling in stored procedures.
♦ STOP Stop execution immediately upon finding an error.
♦ CONDITIONAL If the procedure uses ON EXCEPTION RESUME,
and the statement following the error handles the error, continue,
otherwise exit.
♦ CONTINUE Continue execution, regardless of the following statement.
If there are multiple errors, the first error encountered in the stored
procedure is returned. This option most closely mirrors Adaptive Server
Enterprise behavior.
This option deprecates CONTINUE_AFTER_RAISERROR as a way of
simulating Adaptive Server Enterprise behavior for stored procedures.

OPTIMIZATION_GOAL option
Function Determines whether query processing is optimized towards returning the first
row quickly, or minimizing the cost of returning the complete result set.
Allowed values first-row or all-rows
Default first-row

189
Alphabetical list of options

Description By default, Adaptive Server Anywhere chooses an access plan that is


intended to reduce the time to fetch the first row of output, possibly at the
expense of total retrieval time. In particular, Adaptive Server Anywhere
typically avoids materializing results if possible in order to reduce the time to
return the first row.
The OPTIMIZATION_GOAL option controls whether Adaptive Server
Anywhere optimizes for response time or total resource consumption. If the
option is set to all-rows (as opposed to the default first-row), then Adaptive
Server Anywhere optimizes the total retrieval time instead of the time for the
first row. In this case, Adaptive Server Anywhere does not avoid
materialization unless the estimated total execution time is longer than a plan
without materialization.
Setting OPTIMIZATION_GOAL to Resource-consumption may be
appropriate for applications that require the entire result set before
processing, such as PowerBuilder DataWindow applications.

OUTPUT_FORMAT option [ISQL]


Function Sets the output format for the data retrieved by the SELECT statement and
redirected into a file, or output using the OUTPUT statement.
Allowed values String. See below for allowed values.
Default ASCII
Description The valid output formats are:
♦ ASCII The output is an ASCII format file with one row per line in the
file. All values are separated by commas, and strings are enclosed in
apostrophes (single quotes). The delimiter and quote strings can be
changed using the DELIMITED BY and QUOTE clauses. If ALL is
specified in the QUOTE clause, then all values (not just strings) will be
quoted.
Three other special sequences are also used. The two characters \n
represent a newline character, \\ represents a single backslash character,
and the sequence \xDD represents the character with hexadecimal code
DD.
♦ DBASEII The output is a dBASE II format file with the column
definitions at the top of the file. Note that a maximum of 32 columns can
be output. Also, note that columns longer than 255 characters will be
truncated in the file.

190
Chapter 5 Database Options

♦ DBASEIII The output is a dBASE III format file with the column
definitions at the top of the file. Note that a maximum of 128 columns
can be output. Also, note that columns longer than 255 characters will be
truncated in the file.
♦ DIF The output is a file in the standard Data Interchange Format.
♦ FIXED The output is fixed format, with each column having a fixed
width. The width for each column can be specified using the COLUMN
WIDTH clause. If this clause is omitted, the width for each column is
computed from the data type for the column, and is large enough to hold
any value of that data type. No column headings are output in this
format.
♦ FOXPRO The output is a FoxPro format file (the FoxPro memo field is
different than the dBASE memo field) with the column definitions at the
top of the file. Note that a maximum of 128 columns can be output.
Also, note that columns longer than 255 characters will be truncated in
the file.
♦ LOTUS The output is a Lotus WKS format worksheet. Column names
will be put as the first row in the worksheet. Note that there are certain
restrictions on the maximum size of Lotus WKS format worksheets that
other software (such as Lotus 1-2-3) can load. There is no limit to the
size of file Interactive SQL can produce.
♦ SQL The output is an Interactive SQL INPUT statement required to
recreate the information in the table.
♦ TEXT The output is a TEXT format file, which prints the results in
columns with the column names at the top and vertical lines separating
the columns. This format is similar to that used to display data in the
Interactive SQL data window.
♦ WATFILE The output is a WATFILE format file, with the column
definitions at the top of the file.

OUTPUT_LENGTH option [ISQL]


Function Controls the length used when Interactive SQL exports information to an
external file.
Allowed values Integer
Default 0 (no truncation)
Description This option controls the length used when Interactive SQL exports
information to an external file (using output redirection with the OUTPUT
statement). This option affects only ASCII, HTML, and SQL output formats.

191
Alphabetical list of options

OUTPUT_NULLS option [ISQL]


Function Controls the way NULL values appear in result sets.
Allowed values String
Default ’NULL’
Description This option controls the way NULL values appear in result sets. Every time a
NULL value is found in the result set, the string from this option is returned
instead. This setting applies to data showing in the Interactive SQL Results
pane as well as to data in output files generated by the OUTPUT statement.
This option affects only ASCII, HTML, and SQL output formats.

PERCENT_AS_COMMENT option
Function Controls the interpretation of the percent character.
Allowed values ON, OFF
Default ON
Description It is recommended that you not use % as a comment marker.
Versions of this product before Version 6 treated the percent character (%) in
SQL statements exclusively as a comment delimiter. Since Version 5,
alternative comment markers such as //, /* */, and -- (double dash) have been
available. The double-dash style is the SQL/92 comment delimiter.
Adaptive Server Enterprise treats % as a modulo operator and does not
support the Adaptive Server Anywhere mod function. Writing a statement
that works in both environments and performs a modulo operation was
previously impossible.
The PERCENT_AS_COMMENT option controls the meaning of %. The
default setting is ON, for backwards compatibility. You can set the option to
OFF for compatibility with Adaptive Server Enterprise.
Procedures, triggers and views that were created with %-style comments are
converted to double-dash comments when they are stored in the catalog.

Existing procedures must be recreated before changing option


Any existing procedures that contain %-style comments must be recreated
before you change the option setting; otherwise, the procedures will fail to
load.

192
Chapter 5 Database Options

The Sybase Central code editor does not highlight %-style comments. If you
wish to have your comments highlighted in the Sybase Central editor, you
should use one of the other comment delimiters.

PRECISION option
Function Specifies the maximum number of digits in the result of any decimal
arithmetic.
Allowed values Integer, with a maximum of 127
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default 30
Description Precision is the total number of digits to the left and right of the decimal
point. The "SCALE option" on page 198 specifies the minimum number of
digits after the decimal point when an arithmetic result is truncated to the
maximum PRECISION.
Multiplication, division, addition, subtraction, and aggregate functions can
all have results that exceed the maximum precision.
For example, when a DECIMAL(8,2) is multiplied with a DECIMAL(9,2),
the result could require a DECIMAL(17,4). If PRECISION is 15, only 15
digits will be kept in the result. If SCALE is 4, the result will be a
DECIMAL(15,4). If SCALE is 2, the result will be a DECIMAL(15,2). In
both cases, there is a possibility of overflow.

PREFETCH option
Function The PREFETCH option acts as a toggle allowing you to turn fetching on and
off.
Allowed values ON, OFF
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default ON

193
Alphabetical list of options

Description This option controls whether rows are fetched to the client side in advance of
being made available to the client application. Fetching a number of rows at
a time, even when the client application requests rows one at a time (for
example, when looping over the rows of a cursor) cuts down on response
time and improves overall throughput by cutting down the number of
requests to the database.
The setting of PREFETCH is ignored by Open Client and JDBC
connections.

QUALIFY_OWNERS option

Function Controls whether SQL statements being replicated by SQL Remote should
use qualified object names.
Allowed values ON, OFF
Default The default in Adaptive Server Anywhere is ON. The default in Adaptive
Server Enterprise is OFF.
Description Qualifying owners in Adaptive Server Enterprise setups is rarely needed
because it is common for objects to be owned by dbo. When qualification is
not needed in Adaptive Server Anywhere setups, messages will be slightly
smaller with the option OFF.

QUERY_PLAN_ON_OPEN option
Function Controls whether a plan is returned when a cursor is opened.
Allowed values ON, OFF
Default OFF
Description In early versions of the software, each time an OPEN was done on a cursor,
the server would return in the SQLCA sqlerrmc field a string representing
the query plan (limited to 70 bytes). A more complete description can be
obtained using the EXPLAIN statement or the PLAN function. For this
reason, computing and returning the query plan on an OPEN is needed only
for compatibility with old applications. The QUERY_PLAN_ON_OPEN
option controls whether the plan is returned on an OPEN. By default, the
setting is OFF.

194
Chapter 5 Database Options

QUOTE_ALL_IDENTIFIERS option

Function Controls whether SQL statements being replicated by SQL Remote should
use quoted identifiers
Allowed values ON, OFF
Default OFF
Description When this option is off, dbremote quotes identifiers that require quotes by
Adaptive Server Anywhere (as it has always done) and ssremote does not
quote any identifiers.
When the option is on, all identifiers are quoted.

QUOTED_IDENTIFIER option
Function Controls the interpretation of strings that are enclosed in double quotes.
Allowed values ON, OFF
Default ON
OFF for Open Client and JDBC connections
Description This option controls whether strings that are enclosed in double quotes are
interpreted as identifiers (ON) or as literal strings (OFF). The
QUOTED_IDENTIFIER option is included for Transact-SQL compatibility.
Sybase Central sets QUOTED_IDENTIFER temporarily to ON if it is set to
OFF. A message is displayed informing you of this change. The change is in
effect only for the Sybase Central connection.
$ For more information, see "Setting options for Transact-SQL
compatibility" on page 943 of the book ASA User’s Guide.

RECOVERY_TIME option
Function Sets the maximum length of time, in minutes, that the database server will
take to recover from system failure.
Allowed values Integer, in minutes
Scope Can be set only for the PUBLIC group. Takes effect when server is restarted.
Default 2

195
Alphabetical list of options

Description This option is used with the "CHECKPOINT_TIME option" on page 165 to
decide when checkpoints should be done.

Adaptive Server Anywhere uses a heuristic to estimate the recovery time


based on the operations that have been performed since the last checkpoint.
Thus, the recovery time is not exact.
$ For more information, see "The automatic recovery process" on
page 652 of the book ASA User’s Guide.

ROW_COUNTS option
Function Specifies whether the database will always count the number of rows in a
query when it is opened.
Allowed values ON, OFF
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default OFF
Description If this option is set to OFF, the row count is usually only an estimate. If this
option is set to ON, the row count is always accurate. Opening queries may
take significantly longer.

REPLICATE_ALL option
Function Allows an entire database to act as a primary site in a Replication Server
setup.
Allowed values ON, OFF
Default OFF
Description This option is used by the LTM only. When it is set to ON, the entire
database is set to act as a primary site in a Replication Server installation. All
changes to the database are sent to Replication Server by the LTM.

REPLICATION_ERROR option
Function For SQL Remote, allows you to specify a stored procedure to be called by
the Message Agent when a SQL error occurs.
Allowed values Stored procedure name.
196
Chapter 5 Database Options

Default No procedure
Description For SQL Remote, the REPLICATION_ERROR option allows you to specify
a stored procedure to be called by the Message Agent when a SQL error
occurs. By default no procedure is called.
The procedure must have a single argument of type CHAR, VARCHAR, or
LONG VARCHAR. The procedure is called once with the SQL error
message and once with the SQL statement that causes the error.
Although the option allows you to track and monitor SQL errors in
replication, you must still design them out of your setup; this option is not
intended to resolve such errors.

RETURN_JAVA_AS_STRING option
Function To control how a Java object is passed to the client application when queried.
Allowed values ON, OFF
Scope Can be set for as a temporary option only, for the duration of the current
connection.
Default OFF
Description The option indicates how a Java object is returned to applications connecting
over Open Client or jConnect.
By default, a Java object is returned over TDS as a Sun serialization of the
object. The client, or receiver of the object serialization, is responsible for
deserializing the object into an instance.
If Return_java_as_string is set to ON, the object is first converted to an
instance of java.lang.String using the toString() method, and the String
object is returned to the client.

RI_TRIGGER_TIME option
Function Controls the relative timing of referential integrity checks and trigger actions.
Allowed values BEFORE, AFTER
Scope Can be set for the PUBLIC option only. DBA authority is required to set this
option.
Default AFTER

197
Alphabetical list of options

Description The option can be set to either BEFORE or AFTER. When it’s set to AFTER,
referential integrity actions are executed after the UPDATE or DELETE.

Only the PUBLIC setting can be used; any other setting is ignored.

SCALE option
Function Specifies the minimum number of digits after the decimal point when an
arithmetic result is truncated to the maximum PRECISION.
Allowed values Integer, with a maximum of 127.
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default 6
Description Multiplication, division, addition, subtraction, and aggregate functions can
all have results that exceed the maximum precision. See "PRECISION
option" on page 193 for an example.

SQL_FLAGGER_ERROR_LEVEL option
Function Controls the response to any SQL that is not part of a specified set of
SQL/92.
Allowed values E, I, F, or W
Default W
Description This option flags any SQL that is not part of a specified set of SQL/92 as an
error.

The allowed values of level are as follows:


♦ E Flag syntax that is not entry-level SQL/92 syntax
♦ I Flag syntax that is not intermediate-level SQL/92 syntax
♦ F Flag syntax that is not full-SQL/92 syntax
♦ W Allow all supported syntax

198
Chapter 5 Database Options

SQL_FLAGGER_WARNING_LEVEL option
Function Controls the response to any SQL that is not part of a specified set of
SQL/92.
Allowed values E, I, F, or W
Default W
Description This option flags any SQL that is not part of a specified set of SQL/92 as a
warning.

The allowed values of level are as follows:


♦ E Flag syntax that is not entry-level SQL/92 syntax
♦ I Flag syntax that is not intermediate-level SQL/92 syntax
♦ F Flag syntax that is not full-SQL/92 syntax
♦ W Allow all supported syntax

STATISTICS option [ISQL]


Function Controls whether the execution time and the default message plan are
enabled.
Allowed values Any non-negative integer.
Default 7
See also

"ISQL_COMMAND_TIMING option" on page 178


"ISQL_PLAN option" on page 180
Description This option is an older version of the ISQL_PLAN option. It combines the
default message plan with the execution time.

When you set the STATISTICS option to 0, no information appears in the


Messages pane after you execute a SQL statement. When you set the option
to any other number, both the execution time and the default plan appear in
the Messages pane after you execute a statement. The number you specify is
also used as the default height (in lines) of the Messages pane.

199
Alphabetical list of options

STRING_TRUNCATION option
Function Determines whether an error is raised when an INSERT or UPDATE
truncates a CHAR or VARCHAR string.
Allowed values ON, OFF
Default OFF
Description If the truncated characters consist only of spaces, no exception is raised. The
setting of ON corresponds to ANSI/ISO SQL/92 behavior. When it is set to
OFF, the exception is not raised and the character string is silently truncated.

SUBSCRIBE_BY_REMOTE option
Function Controls interpretation of NULL or empty-string SUBSCRIBE BY values.
Allowed values ON, OFF
Default ON
Description When the option is set to ON, operations from remote databases on rows
with a SUBSCRIBE BY value that is NULL or an empty string assume that
the remote user is subscribed to the row. When it is set to OFF, the remote
user is assumed not to be subscribed to the row.

THREAD_COUNT option
Function Historical
Allowed values Integer
Default Not applicable
Description This option is now ignored by the server. For Version 6 you should use the -
gn server command-line option to set the maximum number of requests that
the server handles simultaneously.
$ For information on the command-line switch, see "The database server"
on page 14.

TIME_FORMAT option
Function Sets the format for times retrieved from the database.
Allowed values A string composed of the symbols listed below.

200
Chapter 5 Database Options

Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default HH:NN:SS.SSS
For Open Client and JDBC connections the default is set to HH:NN:SS.SSS.
Description The format is a string using the following symbols:
♦ hh Two digit hours (24 hour clock)
♦ nn Two digit minutes
♦ mm Two digit minutes if following a colon (as in hh:mm)
♦ ss[.s...] Two digit seconds plus optional fraction
Each symbol is substituted with the appropriate data for the time that is being
formatted. Any format symbol that represents character rather than digit
output can be put in uppercase, which causes the substituted characters to
also be in uppercase. For numbers, using mixed case in the format string
suppresses leading zeros.

TIMESTAMP_FORMAT option
Function Sets the format for timestamps that are retrieved from the database.
Allowed values A string composed of the symbols listed below.
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default YYYY-MM-DD HH:NN:ss.SSS
For Open Client and JDBC connections the default is set to YYYY-MM-DD
HH:NN:SS.SSS.
Description The format is a string using the following symbols:

Symbol Description
yy Two digit year
Yyyy Four digit year
Mm Two digit month, or two digit minutes if following a colon (as in
’hh:mm’)
Mmm[m...] Character short form for months—as many characters as there are
m's
dd Two digit day of month

201
Alphabetical list of options

Symbol Description
Ddd[d...] Character short form for day of the week
hh Two digit hours
nn Two digit minutes
ss.ssssss Seconds and fractions of a second, up to six decimal places. Not all
platforms support timestamps to a precision of six places.
aa am or pm (12 hour clock)
pp Pm if needed (12 hour clock)
f Use French days and months (deprecated)

Each symbol is substituted with the appropriate data for the timestamp that is
being formatted. Any format symbol that represents character rather than
digit output can be put in uppercase, which causes the substituted characters
to also be in uppercase. For numbers, using mixed case in the format string
suppresses leading zeros.

TRUNCATE_DATE_VALUES option
Function To change the storage of time values within DATE data type values.
Allowed values ON, OFF
Default ON for databases created with Version 7 or later software, or upgraded to
Version 7 or later.
OFF for older databases
See also "DATE_FORMAT option" on page 169
"DATE data type" on page 269
Description When the option is set to ON, columns or variables declared as DATE data
types have no hours and minutes stored.
When the option is set to OFF, DATE columns or variables have hours and
minutes stored also. These time components are typically not displayed
because of the DATE_FORMAT setting. However, exact comparisons
between DATE values may unexpectedly fail because of non-matching time
components.

TRUNCATE_WITH_AUTO_COMMIT option
Function To speed up TRUNCATE TABLE statements

202
Chapter 5 Database Options

Allowed values ON, OFF


Default ON
See also "TRUNCATE TABLE statement" on page 615
Description If TRUNCATE_WITH_AUTO_COMMIT is set to ON, then a COMMIT is
executed both before and after the TRUNCATE TABLE statement is
executed. The primary purpose of the option is to enable faster table
truncation (delete of all rows).
There are some cases where a fast TRUNCATE cannot be done:
♦ If there are foreign keys either to or from the table
♦ If the TRUNCATE TABLE statement is executed within a trigger
♦ If the TRUNCATE TABLE statement is executed within an atomic
statement

TRUNCATION_LENGTH option [ISQL]


Function Controls the truncation of wide columns for displays to fit on a screen.
Allowed values Integer
Default 30
Description When SELECT statement results are displayed on the screen, each column of
output is limited to the width of the screen. The TRUNCATION_LENGTH
option is used to reduce the width of wide columns so that more than one
column will fit on the screen. A value of 0 means that columns are not
truncated.
The default TRUNCATION_LENGTH is 30. For character-mode systems,
this is an actual number of characters. For windowing systems,
TRUNCATION_LENGTH is used to estimate an area of the screen to be
used for display since proportional fonts are used.

TSQL_HEX_CONSTANT option
Function Controls whether hexadecimal constants are treated as binary typed
constants.
Allowed values ON, OFF
Default ON

203
Alphabetical list of options

Description When this option is set to ON, hexadecimal constants are treated as binary
typed constants. To get the historical behavior, set the option to OFF.

TSQL_VARIABLES option
Function Controls whether the @ sign can be used as a prefix for Embedded SQL host
variable names.
Allowed values ON, OFF
Default OFF
ON for Open Client and JDBC connections
Description When this options set to ON, you can use the @ sign instead of the colon as a
prefix for host variable names in Embedded SQL. This is implemented
primarily for Transact-SQL compatibility.

VERIFY_ALL_COLUMNS option
Function Controls whether messages that contain updates published by the local
database are sent with all column values included.
Allowed values ON, OFF
Default OFF
Description This option is used by SQL Remote only. When it is set to ON, messages
that contain updates published by the local database are sent with all column
values included, and a conflict in any column triggers a RESOLVE
UPDATE trigger at the subscriber database.

VERIFY_THRESHOLD option
Function Controls which columns are verified when updates are replicated.
Allowed values Integer, in bytes
Default 1000
Description This option is used by SQL Remote only. If the data type of a column is
longer than the threshold, old values for the column are not verified when an
UPDATE is replicated. This keeps the size of SQL Remote messages down,
but has the disadvantage that conflicting updates of long values are not
detected.

204
Chapter 5 Database Options

WAIT_FOR_COMMIT option
Function Determines when foreign key integrity is checked, as data is manipulated.
Allowed values ON or OFF
Scope Can be set for an individual connection or for the PUBLIC group. Takes
effect immediately.
Default OFF
Description If this option is set to ON, the database does not check foreign key integrity
until the next COMMIT statement. Otherwise, all foreign keys that are not
created with the CHECK ON COMMIT option are checked as they are
inserted, updated or deleted.

205
Alphabetical list of options

206
C H A P T E R 6

SQL Language Elements

About this chapter This chapter describes the elements and conventions of the SQL language.
Contents
Topic Page
Keywords 208
Identifiers 211
Strings 212
Operators 213
Expressions 218
Search conditions 226
Special values 234
Variables 237
Comments 246
NULL value 247

207
Keywords

Keywords
Each SQL statement contains one or more keywords. SQL is case insensitive
to keywords, but throughout these manuals, keywords are indicated in upper
case.
For example, in the following statement, SELECT and FROM are keywords:
SELECT *
FROM employee
The following statements are equivalent to the one above:
Select *
From employee
select * from employee
sELECT * FRoM employee
Some keywords cannot be used as identifiers without surrounding them in
double quotes. These are called reserved words. Other keywords, such as
DBA, do not require double quotes, and are not reserved words.

Reserved words
Some keywords in SQL are also reserved words. To use a reserved word in
a SQL statement as an identifier, you must enclose it in double quotes.
Many, but not all, of the keywords that appear in SQL statements are
reserved words. For example, you must use the following syntax to retrieve
the contents of a table named SELECT.
SELECT *
FROM "SELECT"
Because SQL is not case sensitive with respect to keywords, each of the
following words may appear in upper case, lower case, or any combination
of the two. All strings that differ only in capitalization from one of the
following words, are reserved words.
If you are using Embedded SQL, you can use the database library function
sql_needs_quotes to determine whether a string requires quotation marks.
A string requires quotes if it is a reserved word or if it contains a character
not ordinarily allowed in an identifier.
The SQL keywords in Adaptive Server Anywhere 7 are as follows:

208
Chapter 6 SQL Language Elements

add all alter and


any as asc backup
begin between bigint binary
bit bottom break by
call capability cascade case
cast char char_convert character
check checkpoint close comment
commit connect constraint continue
convert create cross cube
current cursor date dbspace
deallocate dec decimal declare
default delete desc distinct
do double drop dynamic
else elseif encrypted end
endif escape exception exec
execute existing exists externlogin
fetch first float for
foreign forward from full
goto grant group having
holdlock identified if in
index inner inout insensitive
insert install instead int
integer integrated into iq
is isolation join key
left like lock login
long match membership message
mode modify natural new
no noholdlock not notify
null numeric of off
on open option options
or order others out
outer passthrough precision prepare

209
Keywords

primary print privileges proc


procedure publication raiserror readtext
real reference references release
remote remove rename resource
restore restrict return revoke
right rollback rollup save
savepoint schedule scroll select
session set setuser share
smallint some sqlcode sqlstate
start stop subtrans subtransaction
synchronize syntax_error table temporary
then time timestamp tinyint
to top tran trigger
truncate tsequal union unique
unknown unsigned update user
using validate values varbinary
varchar variable varying view
wait when where while
with work writetext

210
Chapter 6 SQL Language Elements

Identifiers
Function Identifiers represent names of objects in the database, such as user IDs,
tables, and columns.
Description Identifiers consist of any string of alphabetic characters or digits. The first
character of an identifier must be an alphabetic character, not a digit.
Alternatively, any string of characters can be used as an identifier by
enclosing it in quotation marks ("double quotes") as long as the
QUOTED_IDENTIFIER database option is set to ON.
The underscore character (_), at sign (@), number sign (#), and dollar sign
($) are considered alphabetic characters. The database collation sequence
dictates which characters are considered alphabetic or digit characters.
A quotation mark inside the identifier is represented by two quotation marks
in a row.
Identifiers have a maximum length of 128 bytes.
Reserved words play an important role in the syntax of the SQL language. If
you choose to use a reserved word as an identifier, you must enclose it in
double quotes even if it does not have spaces.
Examples The following are all valid identifiers.
Surname
"Surname"
SomeBigName
"Client Number"
"With a quotation "" mark"
See also $ For a complete list of the reserved words, see "Reserved words" on
page 208.
$ For information on the QUOTED_IDENTIFIER option, see
"QUOTED_IDENTIFIER option" on page 195.

211
Strings

Strings
Strings are of the following types:
♦ literal strings
♦ expressions with CHAR or VARCHAR data types.
An expression with a CHAR data type may be a built-in or user-defined
function, or one of the many other kinds of expressions available.
$ For more information on expressions, see "Expressions" on page 218.
A literal string is any sequence of characters enclosed in apostrophes (’single
quotes’). A SQL variable of character data type can hold a string. The
following is a simple example of a literal strings:
’This is a string.’

Special characters You represent special character in strings by escape sequences, as follows:
in strings
♦ To represent an apostrophe inside a string, use two apostrophes in a row.
For example:
’John’’s database’
♦ To represent a new line character, use a backslash followed by n (\n).
For example:
’First line:\nSecond line:’
♦ To represent a backslash character, use two backslashes in a row (\\). For
example:
’c:\\temp’
♦ Hexadecimal escape sequences can be used for any character, printable
or not. A hexadecimal escape sequence is a backslash followed by an x
followed by two hexadecimal digits (for example, \x6d represents the
letter m). For example:
’\x00\x01\x02\x03’

Compatibility For compatibility with Adaptive Server Enterprise, you can set the
QUOTED_IDENTIFIER database option to OFF. With this setting, you can
also use double quotes to mark the beginning and end of strings. The option
is set to ON by default.

212
Chapter 6 SQL Language Elements

Operators
This section describes arithmetic, string, and bit-wise operators. For
information on comparison operators, see the section "Search conditions" on
page 226.
The normal precedence of operations applies. Expressions in parentheses are
evaluated first, then multiplication and division before addition and
subtraction. String concatenation happens after addition and subtraction.

Comparison operators
The syntax for comparison conditions is as follows:
... expression compare expression
where compare is a comparison operator. The following comparison
operators are available:

operator description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
!= Not equal to
<> Not equal to
!> Not greater than
!< Not less than

Case sensitivity
All string comparisons are case insensitive unless the database was
created as case sensitive.

Compatibility ♦ Trailing blanks Any trailing blanks in character data are ignored for
comparison purposes by Adaptive Server Enterprise. The behavior of
Adaptive Server Anywhere when comparing strings is controlled the –b
command-line switch that is set when creating the database.

213
Operators

♦ Case sensitivity By default, Adaptive Server Anywhere databases are


created as case insensitive, while Adaptive Server Enterprise databases
are created as case sensitive. Comparisons are carried out with the same
attention to case as the database they are operating on. You can control
the case sensitivity of Adaptive Server Anywhere databases when
creating the database.

Logical operators
Search conditions can be combined using AND, OR and NOT.
Conditions are combined using AND as follows:
... condition1 AND condition2
The combined condition is TRUE if both conditions are TRUE, FALSE if
either condition is FALSE, and UNKNOWN otherwise.
Conditions are combined using OR as follows:
... condition1 OR condition2
The combined condition is TRUE if either condition is TRUE, FALSE if
both conditions are FALSE, and UNKNOWN otherwise.
The syntax for the NOT operator is as follows:
... NOT condition
The NOT condition is TRUE if condition is FALSE, FALSE if condition is
TRUE, and UNKNOWN if condition is UNKNOWN.
The IS operator provides a means to test a logical value. The syntax for the
IS operator is as follows:
...expression IS [ NOT ] truth-value
The condition is TRUE if the expression evaluates to the supplied truth-
value, which must be one of TRUE, FALSE, UNKNOWN, or NULL.
Otherwise, the value is FALSE.
$ For more information, see "Three-valued logic" on page 231.
Compatibility ♦ The logical operators are compatible between Adaptive Server
Anywhere and Adaptive Server Enterprise.

Arithmetic operators
expression + expression Addition. If either expression is the NULL
value, the result is the NULL value.

214
Chapter 6 SQL Language Elements

expression – expression Subtraction. If either expression is the NULL


value, the result is the NULL value.

–expression Negation. If the expression is the NULL value, the result is


the NULL value.

expression * expression Multiplication. If either expression is the


NULL value, the result is the NULL value.

expression / expression Division. If either expression is the NULL


value or if the second expression is 0, the result is the NULL value.

expression % expression Modulo finds the integer remainder after a


division involving two whole numbers. For example, 21 % 11 = 10 because
21 divided by 11 equals 1 with a remainder of 10.

String operators
expression || expression String concatenation (two vertical bars). If
either string is the NULL value, it is treated as the empty string for
concatenation.

expression + expression Alternative string concatenation. When using


the + concatenation operator, you must ensure the operands are explicitly set
to character data types rather than relying on implicit data conversion.
Standards and ♦ SQL/92 The || operator is the SQL/92 string concatenation operator.
compatibility
♦ Sybase The + operator is supported by Adaptive Server Enterprise.

Bitwise operators
The following operators can be used on bit data types, in both Adaptive
Server Anywhere and Adaptive Server Enterprise.

Operator Description
& and
| or
^ exclusive or
~ not

215
Operators

Join operators
The Transact-SQL outer join operators *= and =* are supported in Adaptive
Server Anywhere, in addition to the SQL/92 join syntax that uses a table
expression in the FROM clause.
Compatibility ♦ Modulo The % operator can be used in Adaptive Server Anywhere
only if the PERCENT_AS_COMMENT option is set to OFF. The
default value is ON.
♦ String concatenation When using the + concatenation operator in
Adaptive Server Anywhere, you should explicitly set the operands to
strings rather than relying on implicit data conversion. For example, the
following query returns the integer value 579
SELECT 123 + 456
whereas the following query returns the character string 123456
SELECT ’123’ + ’456’
You can use the CAST or CONVERT function to explicitly convert data
types.
The || concatenation operator is not supported by Adaptive Server
Enterprise.

Operator precedence
The precedence of operators in expressions is as follows. The operators at the
top of the list are evaluated before those at the bottom of the list.
1 unary operators
2 ’.’ (the Java reference operator)
3 ’&’, ’|’, ’^’, ’~’
4 ’*’, ’/’, ’%’
5 ’+’, ’-’
6 ’||’
7 not
8 and
9 or

216
Chapter 6 SQL Language Elements

When you use more than one operator in an expression, it is recommended


that you make the order of operation explicit using parentheses rather than
relying on an identical operator precedence between Adaptive Server
Enterprise and Adaptive Server Anywhere.

217
Expressions

Expressions
Syntax expression:
case-expression
| constant
| [correlation-name .] column-name [ java-ref ]
| - expression
| expression operator expression
| ( expression )
| function-name ( expression, ... )
| if-expression
| [ java-package-name.] java-class-name java-ref
| special value
| ( subquery )
| variable-name [ java-ref ]
Parameters case-expression:
{ CASE search-condition
... WHEN expression
... THEN,...
... [ ELSE expression ]
END
| CASE
... WHEN search-condition
... THEN expression,...
... [ ELSE expression ]
END
}
constant:
integer | number | ’string’ | host-variable
special-value:
CURRENT { DATE | TIME | TIMESTAMP }
| NULL
| SQLCODE
| SQLSTATE
| USER
if-expression:
IF condition
... THEN expression
... [ ELSE expression ]
... ENDIF
java-ref:
.field-name [ java-ref ]
| >> field-name [ java-ref ]
| .method-name ( [expression,...] ) [ java-ref ]
| >> method-name ( [expression,...] ) [ java-ref ]

218
Chapter 6 SQL Language Elements

operator:
{ + | - | * | / | || | % }
Usage Anywhere.
Authorization Must be connected to the database.
Side effects None.
See also "Constants in expressions" on page 219
"Special values" on page 234
"Column names in expressions" on page 219
"SQL Functions" on page 291
"Subqueries in expressions" on page 220
"Search conditions" on page 226
"SQL Data Types" on page 251
"SQL Functions" on page 291
"Variables" on page 237
Description Expressions are formed from several different kinds of elements, discussed
in the following sections.
$ For information on functions, see "SQL Functions" on page 291. For
information on variables, see "Variables" on page 237.
Compatibility ♦ The IF condition is not supported in Adaptive Server Enterprise.
♦ Java expressions are not currently supported in Adaptive Server
Enterprise.
♦ For other differences, see the separate descriptions of each class of
expression, in the following sections.

Constants in expressions
Constants are numbers or strings. String constants are enclosed in
apostrophes (’single quotes’). An apostrophe is represented inside the string
by two apostrophes in a row.

Column names in expressions


A column name is an identifier preceded by an optional correlation name. (A
correlation name is usually a table name. For more information on
correlation names, see "FROM clause" on page 518.) If a column name has
characters other than letters, digits and underscore, it must be surrounded by
quotation marks (""). For example, the following are valid column names:
employee.name

219
Expressions

address
"date hired"
"salary"."date paid"
$ For more information on identifiers, see "Identifiers" on page 211.

Subqueries in expressions
A subquery is a SELECT statement enclosed in parentheses. The SELECT
statement must contain one and only one select list item. When used as an
expression, a subquery is generally allowed to return only one value.
A subquery can be used anywhere that a column name can be used. For
example, a subquery can be used in the select list of another SELECT
statement.
$ For other uses of subqueries, see "Subqueries in search conditions" on
page 227.

IF expressions
The syntax of the IF expression is as follows:
IF condition
THEN expression1
[ ELSE expression2 ]
ENDIF
This expression returns the following:
♦ If condition is TRUE, the IF expression returns expression1.
♦ If condition is FALSE, the IF expression returns expression2.
♦ If condition is FALSE, and there is no expression2, the IF expression
returns NULL.
♦ If condition is NULL, the IF expression returns NULL.
$ For more information about TRUE, FALSE and UNKNOWN
conditions, see "NULL value" on page 247, and "Search conditions" on
page 226.

220
Chapter 6 SQL Language Elements

IF statement is different from IF expression


Do not confuse the syntax of the IF expression with that of the IF
statement.
$ For information on the IF statement, see "IF statement" on page 531.

CASE expressions
The CASE expression provides conditional SQL expressions. Case
expressions can be used anywhere an expression can be used.
The syntax of the CASE expression is as follows:
CASE expression
WHEN expression
THEN expression,...
[ ELSE expression ]
END
If the expression following the CASE statement is equal to the expression
following the WHEN statement, then the expression following the THEN
statement is returned. Otherwise the expression following the ELSE
statement is returned, if it exists.
For example, the following code uses a case expression as the second clause
in a SELECT statement.
SELECT id,
( CASE name
WHEN ’Tee Shirt’ then ’Shirt’
WHEN ’Sweatshirt’ then ’Shirt’
WHEN ’Baseball Cap’ then ’Hat’
ELSE ’Unknown’
END ) as Type
FROM "DBA".Product
An alternative syntax is as follows:
CASE
WHEN search-condition
THEN expression,...
[ ELSE expression ]
END

If the search-condition following the WHEN statement is satisfied, the


expression following the THEN statement is returned. Otherwise the
expression following the ELSE statement is returned, if it exists.

221
Expressions

For example, the following statement uses a case expression as the third
clause of a SELECT statement to associate a string with a search-condition.
SELECT id, name,
( CASE
WHEN name=’Tee Shirt’ then ’Sale’
WHEN quantity >= 50 then ’Big Sale’
ELSE ’Regular price’
END ) as Type
FROM "DBA".Product

NULLIF function The NULLIF function provides a way to write some CASE statements in
for abbreviated short form. The syntax for NULLIF is as follows:
CASE expressions
NULLIF ( expression-1, expression-2 )
NULLIF compares the values of the two expressions. If the first expression
equals the second expression, NULLIF returns NULL. If the first expression
does not equal the second expression, NULLIF returns the first expression.

Java expressions
The following kinds of Java expressions can be used as SQL expressions:
♦ Java fields Any field of an installed Java class can be invoked
wherever an expression is required. The data type of the expression is
converted from the Java field data type according to the table in "Java
to-SQL-data type conversion" on page 282. Both instance fields and
class fields can be used as expressions.
♦ Java methods Any method of an installed Java class can be invoked
wherever an expression is required. The data type of the expression is
converted from the return type of the Java method according to the table
in "Java to-SQL-data type conversion" on page 282. Both instance fields
and class fields can be used as expressions.
♦ Java objects The NEW operator is an extension to the SQL language
that allows it to better assimilate Java syntax.
The NEW SQL operator performs the same operation as the new
keyword in Java code: invoke a constructor method of a Java class. The
data type of the NEW expression is a Java class, specifically the Java
class that is being constructed.
The following expression invokes the constructor method of the String
class, a member of the java.lang package.
NEW java.lang.String( ’This argument is optional’ )

222
Chapter 6 SQL Language Elements

This expression returns a reference to the newly-created String object,


which can be passed to a variable or column of type java.lang.String.
The method constructor that is being invoked determines the number
and type of arguments.
The class whose constructor method is invoked must first be installed to
the database.
$ For more information on class and instance fields and methods, see "A
Java seminar" on page 509 of the book ASA User’s Guide.
Referencing fields When referencing a Java field or method from within Java code, you use the
and methods dot (.) operator. For example, to invoke the getConnection method of
the DriverManager class you use the following:
conn = DriverManager.getConnection( temp.toString() ,
_props )
There are two ways of referencing Java fields or methods from within SQL
statements. You can use either the dot operator or the >> operator.
The dot operator has the advantage that it looks like Java code, but has the
disadvantage that in SQL the dot is also used to indicate the owner, table,
and column hierarchy, so this could be confusing to read.
Using the dot operator, a name method of an object named Employee is
invoked from SQL as follows:
select Employee.name ...
The same expression could refer to a name column of an Employee table.
The >> operator is unambiguous, but does not look like what Java
programmers may expect.

Compatibility of expressions
The following tables describe the compatibility of expressions and constants
between Adaptive Server Enterprise and Adaptive Server Anywhere. These
tables are a guide only, and a marking of Both may not mean that the
expression performs in an identical manner for all purposes under all
circumstances. For detailed descriptions, you should refer to the Adaptive
Server Enterprise documentation and the Adaptive Server Anywhere
documentation on the individual expression.
In the following table, expr represents an expression, and op represents an
operator.

223
Expressions

Expression Supported by
constant Both
column name Both
variable name Both
function (expr) Both
- expr Both
expr op expr Both
( expr ) Both
( subquery ) Both
if-expression Adaptive Server Anywhere only

Constant Supported by
integer Both
number Both
’string’ Both
special-constant Both
host-variable Adaptive Server Anywhere

Default By default, Adaptive Server Enterprise and Adaptive Server Anywhere give
interpretation of different meanings to delimited strings: that is, strings enclosed in
delimited strings apostrophes (single quotes) and in quotation marks (double quotes).
Adaptive Server Anywhere employs the SQL/92 convention, that strings
enclosed in apostrophes are constant expressions, and strings enclosed in
quotation marks (double quotes) are delimited identifiers (names for database
objects). Adaptive Server Enterprise employs the convention that strings
enclosed in quotation marks are constants, while delimited identifiers are not
allowed by default and are treated as strings.

The quoted_identifier option


Both Adaptive Server Enterprise and Adaptive Server Anywhere provide a
quoted_identifier option that allows the interpretation of delimited strings to
be changed. By default, the quoted_identifier option is set to OFF in
Adaptive Server Enterprise, and to ON in Adaptive Server Anywhere.
You cannot use SQL reserved words as identifiers if the quoted_identifier
option is off.

224
Chapter 6 SQL Language Elements

$ For a complete list of reserved words, see "Reserved words" on


page 208.
Setting the option While the Transact-SQL SET statement is not supported for most Adaptive
Server Enterprise connection options, it is supported for the
quoted_identifier option.
The following statement in either Adaptive Server Anywhere or Adaptive
Server Enterprise changes the setting of the quoted_identifier option to ON:
SET quoted_identifier ON
With the quoted_identifier option set to ON, Adaptive Server Enterprise
allows table, view, and column names to be delimited by quotes. Other
object names cannot be delimited in Adaptive Server Enterprise.
The following statement in Adaptive Server Anywhere or Adaptive Server
Enterprise changes the setting of the quoted_identifier option to OFF:
SET quoted_identifier OFF

Compatible You can choose to use either the SQL/92 or the default Transact-SQL
interpretation of convention in both Adaptive Server Enterprise and Adaptive Server
delimited strings Anywhere as long as the quoted_identifier option is set to the same value in
each DBMS.
Examples If you choose to operate with the quoted_identifier option on (the default
Adaptive Server Anywhere setting), then the following statements involving
the SQL keyword user are valid for both DBMS’s.
CREATE TABLE "user" (
col1 char(5)
) ;
INSERT "user" ( col1 )
VALUES ( ’abcde’ ) ;
If you choose to operate with the quoted_identifier option off (the default
Adaptive Server Enterprise setting), then the following statements are valid
for both DBMSs.
SELECT *
FROM employee
WHERE emp_lname = "Chin"

225
Search conditions

Search conditions
Function To specify a search condition for a WHERE clause, a HAVING clause, a
CHECK clause, a JOIN clause, or an IF expression.
Syntax search condition:
expression compare expression
| expression compare { [ ANY | SOME ] | ALL }( subquery )
| expression IS [ NOT ] NULL
| expression [ NOT ] BETWEEN expression AND expression
| expression [ NOT ] LIKE expression [ ESCAPE expression ]
| expression [ NOT ] IN ( { expression | subquery | value-expr1 ,
value-expr2 [, value-expr3 ] ...} )
| EXISTS ( subquery )
| NOT condition
| condition AND condition
| condition OR condition
| ( condition )
| ( condition , estimate )
| condition IS [ NOT ] { TRUE | FALSE | UNKNOWN }
Parameters compare:
= | > | < | >= | <= | <> | != | !< | !>
Usage Anywhere.
Authorization Must be connected to the database.
Side effects None.
See also "Expressions" on page 218
Description Conditions are used to choose a subset of the rows from a table, or in a
control statement such as an IF statement to determine control of flow.
SQL conditions do not follow boolean logic, where conditions are either true
or false. In SQL, every condition evaluates as one of TRUE, FALSE, or
UNKNOWN. This is called three-valued logic. The result of a comparison is
UNKNOWN if either value being compared is the NULL value. For tables
showing how logical operators combine in three-valued logic, see the section
"Three-valued logic" on page 231.
Rows satisfy a search condition if and only if the result of the condition is
TRUE. Rows for which the condition is UNKNOWN do not satisfy the
search condition. For more information about NULL, see "NULL value" on
page 247.
Subqueries form an important class of expression that is used in many search
conditions. For information about using subqueries in search conditions, see
"Subqueries in search conditions" on page 227.

226
Chapter 6 SQL Language Elements

The different types of search condition are discussed in the following


sections.

Subqueries in search conditions


Subqueries that return exactly one column and either zero or one row can be
used in any SQL statement wherever a column name could be used,
including in the middle of an expression.
For example, expressions can be compared to subqueries in comparison
conditions (see "Comparison operators" on page 213) as long as the subquery
does not return more than one row. If the subquery (which must have one
column) returns one row, then the value of that row is compared to the
expression. If a subquery returns no rows, its value is NULL.
Subqueries that return exactly one column and any number of rows can be
used in IN conditions, ANY conditions, and ALL conditions. Subqueries that
return any number of columns and rows can be used in EXISTS conditions.
These conditions are discussed in the following sections.

ALL or ANY conditions


The syntax for ANY conditions is
... expression compare ANY ( subquery )
where compare is a comparison operator.
For example, an ANY condition with an equality operator,
... expression = ANY ( subquery )
is TRUE if expression is equal to any of the values in the result of the
subquery, and FALSE is the expression is not NULL and does not equal any
of the columns of the subquery. The ANY condition is UNKNOWN if
expression is the NULL value, unless the result of the subquery has no rows,
in which case the condition is always FALSE.
The keyword SOME can be used instead of ANY.
Compatibility ♦ ANY and ALL subqueries are compatible between Adaptive Server
Enterprise and Adaptive Server Anywhere. Only Adaptive Server
Anywhere supports SOME as a synonym for ANY.

BETWEEN conditions
The syntax for BETWEEN conditions is as follows:
227
Search conditions

... expr [ NOT ] BETWEEN start-expr AND end-expr


The BETWEEN condition can evaluate as TRUE, FALSE, or UNKNOWN.
Without the NOT keyword, the condition evaluates as TRUE if expr is
between start-expr and end-expr. The NOT keyword reverses the meaning of
the condition but leaves UNKNOWN unchanged.
The BETWEEN conditions is equivalent to a combination of two
inequalities:
expr >= start-expr AND expr <= end-expr
Compatibility ♦ The BETWEEN condition is compatible between Adaptive Server
Anywhere and Adaptive Server Enterprise.

LIKE conditions
The syntax for LIKE conditions is as follows:
... expression [NOT] LIKE pattern [ESCAPE escape-expr]
The LIKE condition can evaluate as TRUE, FALSE, or UNKNOWN.
Without the NOT keyword, the condition evaluates as TRUE if expression
matches the pattern. If either expression or pattern is the NULL value, this
condition is UNKNOWN. The NOT keyword reverses the meaning of the
condition, but leaves UNKNOWN unchanged.
The pattern may contain any number of wild cards. The wild cards are:

Wild card Matches


_ (underscore) Any one character
% (percent) Any string of zero or more characters
[] Any single character in the specified range or set
[^] Any single character not in the specified range or set

All other characters must match exactly.


For example, the search condition
... name LIKE ’a%b_’
is TRUE for any row where name starts with the letter a and has the letter b
as its second last character.

228
Chapter 6 SQL Language Elements

If an escape-expr is specified, it must evaluate to a single character. The


character can precede a percent, an underscore, a left square bracket, or
another escape character in the pattern to prevent the special character from
having its special meaning. When escaped in this manner, a percent will
match a percent, and an underscore will match an underscore.
All patterns of length 126 characters or less are supported. Patterns of length
greater than 254 characters are not supported. Some patterns of length
between 127 and 254 characters are supported, depending on the contents of
the pattern.
Searching for one A set of characters to look for is specified by listing the characters inside
of a set of square brackets. For example, the following condition finds the strings smith
characters and smyth:
... LIKE ’sm[iy]th’

Searching for one A range of characters to look for is specified by giving the ends of the range
of a range of inside square brackets, separated by a hyphen. For example, the following
characters condition finds the strings bough and rough, but not tough:
... LIKE ’[a-r]ough’
The range of characters [a-z] is interpreted as "greater than or equal to a, and
less than or equal to z", where the greater than and less than operations are
carried out within the collation of the database. For information on ordering
of characters within a collation, see "International Languages and Character
Sets" on page 279 of the book ASA User’s Guide.
The lower end of the range must precede the higher end of the range. For
example, a LIKE condition containing the expression [z-a] returns no rows,
because no character matches the [z-a] range.
Unless the database is created as case-sensitive, the range of characters is
case insensitive. For example, the following condition finds the strings
Bough, rough, and TOUGH:
... LIKE ’[a-z]ough’
If the database is created as a case-sensitive database, the search condition is
case sensitive also.
Combining You can combine ranges and sets within a square bracket. For example, the
searches for following condition finds the strings bough, rough, and tough:
ranges and sets ... LIKE ’[a-rt]ough’
The bracket [a-mpqs-z] is interpreted as "exactly one character that is either
in the range a to m inclusive, or is p, or is q, or is in the range s to z
inclusive".

229
Search conditions

Searching for one The caret character (^) is used to specify a range of characters that is
character not in a excluded from a search. For example, the following condition finds the string
range tough, but not the strings rough, or bough:
... LIKE ’[^a-r]ough’
The caret negates the entire rest of the contents of the brackets. For example,
the bracket [^a-mpqs-z] is interpreted as "exactly one character that is not in
the range a to m inclusive, is not p, is not q, and is not in the range s to z
inclusive".
Special cases of Any single character in square brackets means that character. For example,
ranges and sets [a] matches just the character a. [^] matches just the caret character, [%]
matches just the percent character (the percent character does not act as a
wild card in this context), and [_] matches just the underscore character.
Also, [[] matches just the character [.
Other special cases are as follows:
♦ The expression [a-] matches either of the characters a or -.
♦ The expression [] is never matched and always returns no rows.
♦ The expressions [ or [abp-q are ill-formed expressions, and give syntax
errors.
♦ You cannot use wild cards inside square brackets. The expression [a%b]
finds one of a, %, or b.
♦ You cannot use the caret character to negate ranges except as the first
character in the bracket. The expression [a^b] finds one of a, ^, or b.
Compatibility ♦ The ESCAPE clause is supported by Adaptive Server Anywhere only.

IN conditions
The syntax for IN conditions is as follows:
...expression [ NOT ] IN ( subquery )
| expression [ NOT ] IN ( expression )
| expression [ NOT ] IN (value-expr1 , value-expr2 [, value-
expr3 ] ... )
Without the NOT keyword, the IN conditions is TRUE if expression equals
any of the listed values, UNKNOWN if expression is the NULL value, and
FALSE otherwise. The NOT keyword reverses the meaning of the condition,
but leaves UNKNOWN unchanged.
Compatibility ♦ IN conditions are compatible between Adaptive Server Enterprise and
Adaptive Server Anywhere.

230
Chapter 6 SQL Language Elements

EXISTS conditions
The syntax for EXISTS conditions is as follows:
... EXISTS( subquery )
The EXISTS condition is TRUE if the subquery result contains at least one
row, and FALSE if the subquery result does not contain any rows. The
EXISTS condition cannot be UNKNOWN.
Compatibility ♦ The EXISTS condition is compatible between Adaptive Server
Enterprise and Adaptive Server Anywhere.

IS NULL conditions
The syntax for IS NULL conditions is as follows:
expression IS [ NOT ] NULL
Without the NOT keyword, the IS NULL condition is TRUE if the
expression is the NULL value, and FALSE otherwise. The NOT keyword
reverses the meaning of the condition.
Compatibility ♦ The IS NULL condition is compatible between Adaptive Server
Enterprise and Adaptive Server Anywhere.

Truth value conditions


The syntax for truth-value conditions is as follows:
... IS [ NOT ] truth-value
Without the NOT keyword, the condition is TRUE if the condition evaluates
to the supplied truth-value, which must be one of TRUE, FALSE, or
UNKNOWN. Otherwise, the value is FALSE. The NOT keyword reverses
the meaning of the condition, but leaves UNKNOWN unchanged.
Compatibility ♦ Adaptive Server Anywhere only supports truth-valued conditions.

Three-valued logic
The following tables show how the AND, OR, NOT, and IS logical operators
of SQL work in three-valued logic.

231
Search conditions

AND operator AND TRUE FALSE UNKNOWN


TRUE TRUE FALSE UNKNOWN
FALSE FALSE FALSE FALSE
UNKNOWN UNKNOWN FALSE UNKNOWN

OR operator OR TRUE FALSE UNKNOWN


TRUE TRUE TRUE TRUE
FALSE TRUE FALSE UNKNOWN
UNKNOWN TRUE UNKNOWN UNKNOWN

NOT operator TRUE FALSE UNKNOWN


FALSE TRUE UNKNOWN

IS operator IS TRUE FALSE UNKNOWN


TRUE TRUE FALSE FALSE
FALSE FALSE TRUE FALSE
UNKNOWN FALSE FALSE TRUE

Explicit selectivity estimates


The Adaptive Server Anywhere optimizer uses statistical information to
decide upon the best strategy for executing each statement. Adaptive Server
Anywhere automatically gathers and updates these statistics. These statistics
are stored permanently in the database in the column statistics registry.
Statistics gathered while processing one statement are available when
searching for efficient ways to execute subsequent statements.
Occasionally, the statistics may become inaccurate or relevant statistics may
be unavailable. This condition is most likely to arise when few queries have
been executed since a large amount of data was added, updated, or deleted.
In this situation, the best approach is to execute statements that allow
Adaptive Server Anywhere to scan the new rows sequentially. The internal
statistics are automatically updated as a side effect, allowing the optimizer to
choose better plans for subsequent queries.

232
Chapter 6 SQL Language Elements

In unusual circumstances, however, these measures may prove ineffective. In


such cases, you can sometimes improve performance by supplying explicit
selectivity estimates.
For each table in a potential execution plan, the optimizer must estimate the
number of rows that will be part of the result set. If you know that a
condition has a success rate that differs from the optimizer rule. You can
supply this information by including an estimate in the search condition.
The estimate is a percentage. It can be a positive integer or can contain
fractional values.
Whenever possible, avoid supplying explicit estimates in statements that are
to be used on an ongoing basis. Should the data change, the explicit estimate
may become inaccurate and may force the optimizer to select poor plans.
Examples ♦ The following query provides an estimate that one percent of the
ship_date values will be later than 1994/06/30:
SELECT ship_date
FROM sales_order_items
WHERE ( ship_date > ’1994/06/30’, 1 )
ORDER BY ship_date DESC
♦ The following query estimates that half a percent of the rows will satisfy
the condition:
SELECT *
FROM customer c, sales_order o
WHERE (c.id = o.cust_id, 0.5)

Fractional values enable more accurate user estimates for joins, particularly
for large tables.
Compatibility ♦ Adaptive Server Enterprise does not support explicit estimates.

233
Special values

Special values
Special values can be used in expressions, and as column defaults when
creating tables.

CURRENT DATE special value


Function CURRENT DATE returns the current year, month, and day.
Data type DATE
See also "Expressions" on page 218
"TIME data type" on page 270

CURRENT TIME special value


Function The current hour, minute, second and fraction of a second.
Data type TIME.
Description The fraction of a second is stored to 6 decimal places. The accuracy of the
current time is limited by the accuracy of the system clock.
See also "Expressions" on page 218
"TIME data type" on page 270

CURRENT TIMESTAMP special value


Function Combines CURRENT DATE and CURRENT TIME to form a
TIMESTAMP value containing the year, month, day, hour, minute, second
and fraction of a second. Like CURRENT TIME, the system clock limits the
accuracy to a fraction of a second.
The fraction of a second is stored to 3 decimal places. The accuracy is
limited by the accuracy of the system clock.
Data type TIMESTAMP
See also "Expressions" on page 218
"TIMESTAMP data type" on page 271

234
Chapter 6 SQL Language Elements

SQLCODE special value


Function Current SQLCODE value.
Data type String.
Description The SQLCODE value is set after each statement. You can check the
SQLCODE to see whether or not the statement succeeded.
See also "Expressions" on page 218
"Database Error Messages" on page 633.

SQLSTATE special value


Function Current SQLSTATE value
Data type String.
Description The SQLSTATE value is set after each statement. You can check the
SQLSTATE to see whether or not the statement succeeded.
See also "Expressions" on page 218
"Database Error Messages" on page 633.

CURRENT USER special value


Function CURRENT USER returns a string that contains the user ID of the current
connection.
Data type String.
CURRENT USER can be used as a default value in columns with character
data types.
Description On UPDATE, columns with a default value of CURRENT USER are not
changed.
See also "Expressions" on page 218

CURRENT PUBLISHER special value


Function CURRENT PUBLISHER returns a string that contains the publisher user ID
of the database for SQL Remote replications.
Data type String.

235
Special values

CURRENT PUBLISHER can be used as a default value in columns with


character data types.
See also "Expressions" on page 218
"SQL Remote Design for Adaptive Server Anywhere" on page 315 of the
book Replication and Synchronization Guide

LAST USER special value


Function The name of the user who last modified the row.
Data type String.
LAST USER can be used as a default value in columns with character data
types.
Description On INSERT, this constant has the same effect as CURRENT USER. On
UPDATE, if a column with a default value of LAST USER is not explicitly
modified, it is changed to the name of the current user.
When combined with the DEFAULT TIMESTAMP, a default value of
LAST USER can be used to record (in separate columns) both the user and
the date and time a row was last changed.
See also "CURRENT USER special value" on page 235
"CURRENT TIMESTAMP special value" on page 234
"CREATE TABLE statement" on page 453

236
Chapter 6 SQL Language Elements

Variables
Adaptive Server Anywhere supports three levels of variables:
♦ Local variables These are defined inside a compound statement in a
procedure or batch using the DECLARE statement. They exist only
inside the compound statement.
♦ Connection-level variables These are defined with a CREATE
VARIABLE statement. They belong to the current connection, and
disappear when you disconnect from the database or when you use the
DROP VARIABLE statement.
♦ Global variables These are system-supplied variables that have
system-supplied values.
Local and connection-level variables are declared by the user, and can be
used in procedures or in batches of SQL statements to hold information.
Global variables are system-supplied variables that provide system-supplied
values. All global variables have names beginning with two @ signs. For
example, the global variable @@version has a value that is the current
version number of the database server. Users cannot define global variables.

Local variables
Local variables are declared using the DECLARE statement, which can be
used only within a compound statement (that is, bracketed by the BEGIN and
END keywords). The variable is initially set as NULL. The value of the
variable can be set using the SET statement, or can be assigned using a
SELECT statement with an INTO clause.
The syntax of the DECLARE statement is as follows:
DECLARE variable-name data-type
Local variables can be passed as arguments to procedures, as long as the
procedure is called from within the compound statement.
Examples ♦ The following batch illustrates the use of local variables.
BEGIN
DECLARE local_var INT ;
SET local_var = 10 ;
MESSAGE ’local_var = ’, local_var TO CLIENT;
END
Running this batch from Interactive SQL gives the message local_var =
10 in the Interactive SQL Messages window.

237
Variables

♦ The variable local_var does not exist outside the compound statement in
which it is declared. The following batch is invalid, and gives a column
not found error.
-- This batch is invalid.
BEGIN
DECLARE local_var INT ;
SET local_var = 10 ;
MESSAGE ’local_var = ’, local_var TO CLIENT;
END;
MESSAGE ’local_var = ’, local_var TO CLIENT;
♦ The following example illustrates the use of SELECT with an INTO
clause to set the value of a local variable:
BEGIN
DECLARE local_var INT ;
SELECT 10 INTO local_var ;
MESSAGE ’local_var = ’, local_var TO CLIENT;
END
Running this batch from Interactive SQL gives the message local_var =
10 on the server window.

Compatibility ♦ Names Adaptive Server Enterprise and Adaptive Server Anywhere


both support local variables. In Adaptive Server Enterprise, all variables
must be prefixed with an @ sign. In Adaptive Server Anywhere, the @
prefix is optional. To write compatible SQL, prefix all of your variables
with @.
♦ Scope The scope of local variables is different in Adaptive Server
Anywhere and Adaptive Server Enterprise. Adaptive Server Anywhere
supports the use of the DECLARE statement to declare local variables
within a batch. However, if the DECLARE is executed within a
compound statement, the scope is limited to the compound statement.
♦ Declaration Only one variable can be declared for each DECLARE
statement in Adaptive Server Anywhere. In Adaptive Server Enterprise,
more than one variable can be declared in a single statement.

$ For more information on batches and local variable scope, see


"Variables in Transact-SQL procedures" on page 959 of the book ASA User’s
Guide.

Connection-level variables
Connection-level variables are declared with the CREATE VARIABLE
statement. Connection-level variables can be passed as parameters to
procedures.

238
Chapter 6 SQL Language Elements

The syntax for the CREATE VARIABLE statement is as follows:


CREATE VARIABLE variable-name data-type
When a variable is created, it is initially set to NULL. The value of
connection-level variables can be set in the same way as local variables,
using the SET statement or using a SELECT statement with an INTO clause.
Connection-level variables exist until the connection is terminated, or until
the variable is explicitly dropped using the DROP VARIABLE statement.
The following statement drops the variable con_var:
DROP VARIABLE con_var

Example ♦ The following batch of SQL statements illustrates the use of connection-
level variables.
CREATE VARIABLE con_var INT;
SET con_var = 10;
MESSAGE ’con_var = ’, con_var TO CLIENT;
Running this batch from Interactive SQL gives the message local_var =
10 on the server window.

Compatibility ♦ Adaptive Server Enterprise does not support connection-level variables.

Global variables
Global variables have values set by the database server. For example, the
global variable @@version has a value that is the current version number of
the database server.
Global variables are distinguished from local and connection-level variables
by having two @ signs preceding their names. For example, @@error and
@@rowcount are global variables. Users cannot create global variables, and
cannot update the value of global variables directly.
Some global variables, such as @@identity, hold connection-specific
information, and so have connection-specific values. Other variables, such as
@@connections, have values that are common to all connections.
Global variable and The special constants (for example, CURRENT DATE, CURRENT TIME,
special constants USER, and SQLSTATE) are similar to global variables.
The following statement retrieves a value of the version global variable.
SELECT @@version
In procedures and triggers, global variables can be selected into a variable
list. The following procedure returns the server version number in the ver
parameter.

239
Variables

CREATE PROCEDURE VersionProc ( OUT ver


VARCHAR( 100 ) )
BEGIN
SELECT @@version
INTO ver;
END
In Embedded SQL, global variables can be selected into a host variable list.
List of global The following table lists the global variables available in Adaptive Server
variables Anywhere

Variable name Meaning


@@dbts A value of type TIMESTAMP representing the last generated
value used for a column defined with DEFAULT
TIMESTAMP.
@@error Commonly used to check the error status (succeeded or
failed) of the most recently executed statement. It contains 0
if the previous transaction succeeded; otherwise, it contains
the last error number generated by the system. A statement
such as if @@error != 0 return causes an exit if an error
occurs. Every SQL statement resets @@error, so the status
check must immediately follow the statement whose success
is in question.
@@identity Last value inserted into an IDENTITY or DEFAULT
AUTOINCREMENT column by an INSERT or SELECT
INTO statement.

$ For a description, see "@@identity global variable" on


page 244.
@@isolation Current isolation level. @@isolation takes the value of the
active level.

240
Chapter 6 SQL Language Elements

Variable name Meaning


@@procid Stored procedure ID of the currently executing procedure.
@@rowcount Number of rows affected by the last statement. The value of
@@rowcount should be checked immediately after the
statement.
Inserts, updates, and deletes set @@rowcount to the number
of rows affected.
With cursors, @@rowcount represents the cumulative
number of rows returned from the cursor result set to the
client, up to the last fetch request.
Unlike in Adaptive Server Enterprise, @@rowcount is not
reset to zero by any statement which does not affect rows,
such as an IF statement.
@@servername Name of the current database server.
@@sqlstatus Contains status information resulting from the last fetch
statement.
@@version Version number of the current version of Adaptive Server
Anywhere.

Compatibility The following list includes all Adaptive Server Enterprise global variables
supported in Adaptive Server Anywhere. Adaptive Server Enterprise global
variables not supported by Adaptive Server Anywhere are not included in the
list. In contrast to the above table, this list includes all global variables that
return a value, including those for which the value is fixed at NULL, 1, -1, or
0, and may not be meaningful.

Global variable Returns


@@char_convert Returns 0
@@client_csname In Adaptive Server Enterprise, the client’s character set
name. Set to NULL if client character set has never been
initialized; otherwise, it contains the name of the most
recently used character set. Returns NULL in Adaptive
Server Anywhere
@@client_csid In Adaptive Server Enterprise, the client’s character set ID.
Set to –1 if client character set has never been initialized;
otherwise, it contains the most recently used client character
set ID from syscharsets. Returns –1 in Adaptive Server
Anywhere
@@connections The number of logins since the server was last started
@@cpu_busy In Adaptive Server Enterprise, the amount of time, in ticks,
that the CPU has spent doing Adaptive Server Enterprise
work since the last time Adaptive Server Enterprise was

241
Variables

Global variable Returns


started. In Adaptive Server Anywhere, returns 0
@@error Commonly used to check the error status (succeeded or
failed) of the most recently executed statement. It contains 0
if the previous transaction succeeded; otherwise, it contains
the last error number generated by the system. A statement
such as
if @@error != 0 return
causes an exit if an error occurs. Every statement resets
@@error, including PRINT statements or IF tests, so the
status check must immediately follow the statement whose
success is in question
@@identity Last value inserted into an IDENTITY column by an
INSERT or SELECT INTO statement.
$ For a description, see "@@identity global variable" on
page 244.
@@idle In Adaptive Server Enterprise, the amount of time, in ticks,
that Adaptive Server Enterprise has been idle since it was
last started. In Adaptive Server Anywhere, returns 0
@@io_busy In Adaptive Server Enterprise, the amount of time, in ticks,
that Adaptive Server Enterprise has spent doing input and
output operations since it was last started. In Adaptive
Server Anywhere, returns 0
@@isolation Current isolation level of the connection. In Adaptive Server
Enterprise, @@isolation takes the value of the active level
@@langid In Adaptive Server Enterprise, defines the local language ID
of the language currently in use. In Adaptive Server
Anywhere, returns 0
@@language In Adaptive Server Enterprise, defines the name of the
language currently in use. In Adaptive Server Anywhere,
returns "English"
@@maxcharlen In Adaptive Server Enterprise, maximum length, in bytes, of
a character in Adaptive Server Enterprise’s default character
set. In Adaptive Server Anywhere, returns 1
@@max_ For the personal server, the maximum number of
connections simultaneous connections that can be made to the server,
which is 10
For the network server, the maximum number of active
clients (not database connections, as each client can support
multiple connections)
For Adaptive Server Enterprise, the maximum number of
connections to the server

242
Chapter 6 SQL Language Elements

Global variable Returns


@@ncharsize In Adaptive Server Enterprise, average length, in bytes, of a
national character. In Adaptive Server Anywhere, returns 1
@@nestlevel In Adaptive Server Enterprise, nesting level of current
execution (initially 0). Each time a stored procedure or
trigger calls another stored procedure or trigger, the nesting
level is incremented. In Adaptive Server Anywhere, returns
–1
@@pack_received In Adaptive Server Enterprise, number of input packets read
by Adaptive Server Enterprise since it was last started. In
Adaptive Server Anywhere, returns 0
@@pack_sent In Adaptive Server Enterprise, number of output packets
written by Adaptive Server Enterprise since it was last
started. In Adaptive Server Anywhere, returns 0
@@packet_errors In Adaptive Server Enterprise, number of errors that have
occurred while Adaptive Server Enterprise was sending and
receiving packets. In Adaptive Server Anywhere, returns 0
@@procid Stored procedure ID of the currently executing procedure
@@rowcount Number of rows affected by the last command.
@@rowcount is set to zero by any command which does not
return rows, such as an IF statement. With cursors,
@@rowcount represents the cumulative number of rows
returned from the cursor result set to the client, up to the last
fetch request
@@servername Name of the local Adaptive Server Enterprise or Adaptive
Server Anywhere server
@@spid In Adaptive Server Enterprise, server process ID number of
the current process. In Adaptive Server Anywhere, the
connection handle for the current connection. This is the
same value as that displayed by the sa_conn_info procedure
@@sqlstatus Contains status information resulting from the last fetch
statement. @@sqlstatus may contain the following values
0 The fetch statement completed successfully
1 The fetch statement resulted in an error
2 There is no more data in the result set
@@textsize Current value of the SET TEXTSIZE option, which specifies
the maximum length, in bytes, of text or image data to be
returned with a select statement. The default setting is
32765, which is the largest bytestring that can be returned
using READTEXT. The value can be set using the SET
statement
@@thresh_hysteresis In Adaptive Server Enterprise, change in free space required

243
Variables

Global variable Returns


to activate a threshold. In Adaptive Server Anywhere,
returns 0
@@timeticks In Adaptive Server Enterprise, number of microseconds per
tick. The amount of time per tick is machine-dependent. In
Adaptive Server Anywhere, returns 0
@@total_errors In Adaptive Server Enterprise, number of errors that have
occurred while Adaptive Server Enterprise was reading or
writing. In Adaptive Server Anywhere, returns 0.
@@total_read In Adaptive Server Enterprise, number of disk reads by
Adaptive Server Enterprise since it was last started. In
Adaptive Server Anywhere, returns 0
@@total_write In Adaptive Server Enterprise, number of disk writes by
Adaptive Server Enterprise since it was last started. In
Adaptive Server Anywhere, returns 0
@@tranchained Current transaction mode of the Transact-SQL program.
@@tranchained returns 0 for unchained or 1 for chained
@@trancount Nesting level of transactions. Each BEGIN
TRANSACTION in a batch increments the transaction count
@@transtate In Adaptive Server Enterprise, current state of a transaction
after a statement executes. In Adaptive Server Anywhere,
returns –1
@@version Information on the current version of Adaptive Server
Enterprise or Adaptive Server Anywhere

@@identity global variable


The @@identity variable holds the most recent value inserted into an
IDENTITY column or a DEFAULT AUTOINCREMENT column, or zero if
the most recent insert was into a table that had no such column.
The value of @@identity is reset each time a row is inserted into a table. If a
statement inserts multiple rows, @@identity reflects the IDENTITY value
for the last row inserted. If the affected table does not contain an IDENTITY
column, @@ identity is set to 0.
The value of @@identity is not affected by the failure of an INSERT or
SELECT INTO statement, or the rollback of the transaction that contained it.
@@identity retains the last value inserted into an IDENTITY column, even
if the statement that inserted it fails to commit.

244
Chapter 6 SQL Language Elements

@@identity and When an insert causes referential integrity actions or fires a trigger,
triggers @@identity behaves like a stack. For example, if an insert into a table T1
(with an identity or autoincrement column) fires a trigger that inserts a row
into table T2 (also with an identity or autoincrement column), then the value
returned to the application or procedure which carried out the insert is the
value inserted into T1. Within the trigger, @@identity has the T1 value
before the insert into T2 and the T2 value after. The trigger can copy the
values to local variables if it needs to access both.

245
Comments

Comments
Comments are used to attach explanatory text to SQL statements or
statement blocks. The database server does not execute comments.
Several comment indicators are available in Adaptive Server Anywhere.
♦ -- (Double hyphen) The database server ignores any remaining
characters on the line. This is the SQL/92 comment indicator.
♦ // (Double slash) The double slash has the same meaning as the
double hyphen.
♦ /* ... */ (Slash-asterisk) Any characters between the two comment
markers are ignored. The two comment markers may be on the same or
different lines. Comments indicated in this style can be nested. This
style of commenting is also called C-style comments.
♦ % (Percent sign) The percent sign has the same meaning as the
double hyphen, if the PERCENT_AS_COMMENT option is set to ON.
It is recommended that % not be used as a comment indicator.

Transact-SQL compatibility
The double-hyphen and the slash-asterisk comment styles are compatible
with Adaptive Server Enterprise.

Examples ♦ The following example illustrates the use of double-dash comments:


CREATE FUNCTION fullname (firstname CHAR(30),
lastname CHAR(30))
RETURNS CHAR(61)
-- fullname concatenates the firstname and lastname
-- arguments with a single space between.
BEGIN
DECLARE name CHAR(61);
SET name = firstname || ’ ’ || lastname;
RETURN ( name );
END

♦ The following example illustrates the use of C-style comments:


/*
Lists the names and employee IDs of employees
who work in the sales department.
*/
CREATE VIEW SalesEmployee AS
SELECT emp_id, emp_lname, emp_fname
FROM "dba".employee
WHERE dept_id = 200

246
Chapter 6 SQL Language Elements

NULL value
Function To specify a value that is unknown or not applicable.
Syntax NULL
Usage Anywhere.
Permissions Must be connected to the database.
Side effects None.
See also "Expressions" on page 218
"Search conditions" on page 226
Description The NULL value is a special value which is different from any valid value
for any data type. However, the NULL value is a legal value in any data
type. The NULL value is used to represent missing or inapplicable
information. Note that these are two separate and distinct cases where NULL
is used:

Situation Description
missing The field does have a value, but that value is unknown.
inapplicable The field does not apply for this particular row.

SQL allows columns to be created with the NOT NULL restriction. This
means that those particular columns cannot contain the NULL value.
The NULL value introduces the concept of three valued logic to SQL. The
NULL value compared using any comparison operator with any value
(including the NULL value) is "UNKNOWN." The only search condition
that returns TRUE is the IS NULL predicate. In SQL, rows are selected only
if the search condition in the WHERE clause evaluates to TRUE; rows that
evaluate to UNKNOWN or FALSE are not selected.
The IS [ NOT ] truth-value clause, where truth-value is one of TRUE,
FALSE or UNKNOWN can be used to select rows where the NULL value is
involved. See "Search conditions" on page 226 for a description of this
clause.
In the following examples, the column Salary contains NULL.

247
NULL value

Condition Truth value Selected?


Salary = NULL UNKNOWN NO
Salary <> NULL UNKNOWN NO
NOT (Salary = NULL) UNKNOWN NO
NOT (Salary <> NULL) UNKNOWN NO
Salary = 1000 UNKNOWN NO
Salary IS NULL TRUE YES
Salary IS NOT NULL FALSE NO
Salary = expression IS UNKNOWN TRUE YES

The same rules apply when comparing columns from two different tables.
Therefore, joining two tables together will not select rows where any of the
columns compared contain the NULL value.
NULL also has an interesting property when used in numeric expressions.
The result of any numeric expression involving the NULL value is NULL.
This means that if NULL is added to a number, the result is NULL—not a
number. If you want NULL to be treated as 0, you must use the ISNULL(
expression, 0 ) function (see "SQL Functions" on page 291).
Many common errors in formulating SQL queries are caused by the behavior
of NULL. You will have to be careful to avoid these problem areas. See
"Search conditions" on page 226 for a description of the effect of three-
valued logic when combining search conditions.
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase In some contexts, Adaptive Server Enterprise treats NULL as
a value, whereas Adaptive Server Anywhere does not. For example,
rows of a column c1 that are NULL are not included in the results of a
query with the following WHERE clause in Adaptive Server Anywhere,
as the condition has a value of UNKNOWN:
WHERE NOT( C1 = NULL )
In Adaptive Server Enterprise, the condition is evaluated as TRUE, and
these rows are returned. You should use IS NULL rather than a
comparison operator for compatibility.
Unique indexes in Adaptive Server Anywhere can hold rows that hold
NULL and are otherwise identical. Adaptive Server Enterprise does not
permit such entries in unique indexes.
Example ♦ The following INSERT statement inserts a NULL into the date_returned
column of the Borrowed_book table.

248
Chapter 6 SQL Language Elements

INSERT
INTO Borrowed_book
( date_borrowed, date_returned, book )
VALUES ( CURRENT DATE, NULL, ’1234’ )

249
NULL value

250
C H A P T E R 7

SQL Data Types

About this chapter This chapter describes the data types supported by Adaptive Server
Anywhere.
Contents
Topic Page
Character data types 252
Numeric data types 256
Money data types 263
Bit data type 264
Date and time data types 265
Binary data types 272
Domains 274
Java class data types 276
Data type conversions 281
Java / SQL data type conversion 282
Year 2000 compliance 285

251
Character data types

Character data types


Function For storing strings of letters, numbers and symbols.
Description Adaptive Server Anywhere treats CHAR, VARCHAR, and LONG
VARCHAR columns all as the same type. Values up to 254 characters are
stored as short strings, with a preceding length byte. Any values that are
longer than 255 bytes are considered long strings. Characters after the 255th
byte are stored separate from the row containing the long string value.
There are several functions (see "SQL Functions" on page 291) that will
ignore the part of any string past the 255th character. They are soundex,
similar, and all of the date functions. Also, any arithmetic involving the
conversion of a long string to a number will work on only the first 255
characters. It would be extremely unusual to run in to one of these
limitations.
All other functions and all other operators work with the full length of long
strings.
Character sets and Character data is placed in the database using the exact binary representation
code pages that is passed from the application. This usually means that character data is
stored in the database with the binary representation of the current code
page. The code page is the character set representation used by IBM-
compatible personal computers. You can find documentation about code
pages in the documentation for your operating system.
Most code pages are the same for the first 128 characters. If you use special
characters from the top half of the code page (accented international
language characters), you must be careful with your databases. In particular,
if you copy the database to a machine that uses a different code page, those
special characters will be retrieved from the database using the original code
page representation. With the new code page, they will appear on the screen
to be the wrong characters.
This problem also appears if you have two clients using the same multi-user
server, but run with different code pages. Data inserted or updated by one
client may appear incorrect to the other.
This problem also shows up if a database is used across platforms.
PowerBuilder and many other Windows applications insert data into the
database in the standard ANSI character set. If non-Windows applications
attempt to use this data, they will not properly display or update the extended
characters.
This problem is quite complex. If any of your applications use the extended
characters in the upper half of the code page, make sure that all clients and
all machines using the database use the same or a compatible code page.

252
Chapter 7 SQL Data Types

Notes Data type lengths of less than one are not allowed.
Compatibility ♦ The CHARACTER (n) alternative for CHAR is not supported in
Adaptive Server Enterprise.
♦ Adaptive Server Anywhere does not support the NCHAR and
NVARCHAR data types provided by Adaptive Server Enterprise.

CHAR data type [Character]


Function Character data of maximum length max-length bytes.
Syntax { CHAR | CHARACTER } [ ( max-length ) ]
Usage The default value of max-length is 1.
For strings up to 254 bytes in length, the storage requirement is the number
of bytes in the string plus one additional byte. For longer strings, there is
more overhead.
Strings of multi-byte characters can be held as the CHAR data type, but max-
length is in bytes, not characters.
Parameters max-length The maximum length in bytes of the string. The maximum
size allowed is 32,767.
Standards and ♦ SQL/92 Compatible with SQL/92.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise. In Adaptive
Server Enterprise, the storage requirements for CHAR data types is
always max-length. The maximum max-length for ASE is 255.
♦ Other database systems In many other database-management
systems, unlike Adaptive Server Anywhere,CHAR data types require
max-length bytes of storage, regardless of the length of the actual string.
"CHARACTER VARYING data type" on page 253
See also
"LONG VARCHAR data type" on page 254

CHARACTER VARYING data type [Character]


Function Same as CHAR.
Syntax { VARCHAR | CHARACTER VARYING } [ ( max-length ) ]
Usage The default value of max-length is 1.

253
Character data types

For strings up to 254 bytes in length, the storage requirements are the
number of bytes in the string plus one additional byte. For longer strings,
there is more overhead.
Strings of multi-byte characters can be held as the CHAR data type, but it is
important to note that max-length is in bytes, not characters.
Parameters max-length The maximum length of the string, in bytes. The maximum
size allowed is 32,767.
Standards and ♦ SQL/92 Compatible with SQL/92.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise. The maximum
max-length for Adaptive Server Enterprise is 255.
"CHAR data type" on page 253
See also
"LONG VARCHAR data type" on page 254

LONG VARCHAR data type [Character]


Function Arbitrary length character data.
Syntax LONG VARCHAR
Usage
Arbitrary length strings. The maximum size is limited by the maximum size
of the database file (currently 2 gigabytes).
In addition to the length of the string itself, there is some additional overhead
for storage.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
"CHAR data type" on page 253
See also
"CHARACTER VARYING data type" on page 253

TEXT data type [Character]


Function This is a domain. It is implemented as a LONG VARCHAR allowing NULL.
Syntax TEXT
Usage
Arbitrary length strings. The usage is as for LONG VARCHAR.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

254
Chapter 7 SQL Data Types

See also "LONG VARCHAR data type" on page 254

255
Numeric data types

Numeric data types


Function For storing numerical data.
Notes ♦ The NUMERIC and DECIMAL data types, and the various kinds of
INTEGER data types, are sometimes called exact numeric data types, in
contrast to the approximate numeric data types FLOAT, DOUBLE, and
REAL.
The exact numeric data types are those for which precision and scale
values can be specified, while approximate numeric data types are stored
in a predefined manner. Only exact numeric data is guaranteed accurate
to the least significant digit specified after an arithmetic operation.
♦ Before release 5.5, hexadecimal constants longer than four bytes were
treated as string constants, and others were treated as integers. The new
default behavior is to treat them as binary type constants. To use the
historical behavior, set the TSQL_HEX_CONSTANTS database option
to OFF.
♦ Data type lengths and precision of less than one are not allowed.
Compatibility ♦ Only the NUMERIC data type with scale = 0 can be used for the
Transact-SQL identity column.
♦ You should avoid default precision and scale settings for NUMERIC
and DECIMAL data types, because these are different between Adaptive
Server Anywhere and Adaptive Server Enterprise. In Adaptive Server
Anywhere, the default precision is 30 and the default scale is 6. In
Adaptive Server Enterprise, the default precision is 18 and the default
scale is 0.
♦ The FLOAT ( p ) data type is a synonym for REAL or DOUBLE,
depending on the value of p. For Adaptive Server Enterprise, REAL is
used for p less than or equal to 15, and DOUBLE for p greater than 15.
For Adaptive Server Anywhere, the cutoff is platform-dependent, but on
all platforms the cutoff value is greater than 15.
$ For information about changing the defaults by setting database
options, see "PRECISION option" on page 193 and "SCALE option" on
page 198.

BIGINT data type [Numeric]


Function A 64-bit integer.
Syntax [ UNSIGNED ] BIGINT

256
Chapter 7 SQL Data Types

Usage The BIGINT data type is an exact numeric data type: its accuracy is
preserved after arithmetic operations.
A BIGINT value requires 8 bytes of storage.
The range for signed BIGINT values is from ( -2e63) to ( +2e63 -1
).
The range for unsigned BIGINT values is from 0 to ( 2e64 - 1 ).
By default, the data type is signed.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
See also "INT or INTEGER data type" on page 259
"TINYINT data type" on page 261
"SMALLINT data type" on page 261

DECIMAL data type [Numeric]


Function A decimal number with precision total digits and with scale of the digits
after the decimal point.
Syntax { DECIMAL | DEC } [ ( precision [ , scale ] ) ]
Usage The DECIMAL data type is an exact numeric data type; its accuracy is
preserved to the least significant digit after arithmetic operations.
The storage required for a decimal number can be estimated as:
2 + int( ( before+1 ) / 2 ) + int( ( after + 1 )/2 )
where int takes the integer portion of its argument, and before and after are
the number of significant digits before and after the decimal point. The
storage is based on the value being stored, not on the maximum precision
and scale allowed in the column.
Parameters precision An integer expression that specifies the number of digits in the
expression. The default setting is 30.

scale An integer expression that specifies the number of digits after the
decimal point. The default setting is 6.
The defaults can be changed by setting database options. For information,
see "PRECISION option" on page 193 and "SCALE option" on page 198.
Standards and ♦ SQL/92 Compatible with SQL/92.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

257
Numeric data types

See also "FLOAT data type" on page 258


"REAL data type" on page 260
"DOUBLE data type" on page 258

DOUBLE data type [Numeric]


Function A double-precision floating-point number.
Syntax DOUBLE [ PRECISION ]
Usage The DOUBLE data type holds a double-precision floating point number. An
approximate numeric data type, it is subject to roundoff errors after
arithmetic operations. The approximate nature of DOUBLE values means
that queries using equalities should generally be avoided when comparing
DOUBLE values.

DOUBLE values require 8 bytes of storage.

The range of values is 2.22507385850721e-308 to 1.79769313486231e+308.


Values held as DOUBLE are accurate to 15 significant digits, but may be
subject to round-off error beyond the fifteenth digit.
Standards and ♦ SQL/92 Compatible with SQL/92.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "FLOAT data type" on page 258
"REAL data type" on page 260
"DECIMAL data type" on page 257

FLOAT data type [Numeric]


Function A floating point number, which may be single or double precision.
Syntax FLOAT [ ( precision ) ]
Usage When a column is created using the FLOAT ( precision ) data type, columns
on all platforms are guaranteed to hold the values to at least the specified
minimum precision. In contrast, REAL and DOUBLE do not guarantee a
platform-independent minimum precision.
If precision is not supplied, the FLOAT data type is a single precision
floating point number, equivalent to the REAL data type, and requires 4
bytes of storage.

258
Chapter 7 SQL Data Types

If precision is supplied, the FLOAT data type is either single or double


precision, depending on the value of precision specified. The cutoff between
REAL and DOUBLE is platform-dependent. Single precision FLOATs
require 4 bytes of storage, and double precision FLOATs require 8 bytes.
The FLOAT data type is an approximate numeric data type. It is subject to
roundoff errors after arithmetic operations. The approximate nature of
FLOAT values means that queries using equalities should generally be
avoided when comparing FLOAT values.
Parameters precision An integer expression that specifies the number of places after
the decimal.
Standards and ♦ SQL/92 Compatible with SQL/92.
compatibility
♦ Sybase You can tune the behavior of the FLOAT data type for
compatibility with Adaptive Server Enterprise, using the
"FLOAT_AS_DOUBLE option" on page 175.
See also "DECIMAL data type" on page 257
"REAL data type" on page 260
"DOUBLE data type" on page 258

INT or INTEGER data type [Numeric]


Function An integer value requiring 4 bytes of storage.
Syntax [ UNSIGNED ] { INT | INTEGER }
Usage The INTEGER data type is an exact numeric data type; its accuracy is
preserved after arithmetic operations.
If you specify UNSIGNED; the integer can never be assigned a negative
number. By default, the data type is signed.
The range for signed integers is from ( -2^31) to ( +2^31 -1 ).
The range for unsigned integers is from 0 to ( 2^32 - 1 ).
Standards and ♦ SQL/92 Compatible with SQL/92. The UNSIGNED keyword is a
compatibility vendor extension.
♦ Sybase The signed data type is compatible with Adaptive Server
Enterprise. Adaptive Server Enterprise does not support the UNSIGNED
data type.
See also "BIGINT data type" on page 256
"TINYINT data type" on page 261
"SMALLINT data type" on page 261

259
Numeric data types

NUMERIC data type [Numeric]


Function Same as DECIMAL.
Syntax NUMERIC [ ( precision [ , scale ] ) ]
Usage The NUMERIC data type is an exact numeric data type; its accuracy is
preserved to the least significant digit after arithmetic operations.
The storage required for a decimal number can be estimated as:
2 + int( (before+1) / 2 ) + int( (after+1)/2 )
where int takes the integer portion of its argument, and before and after are
the number of significant digits before and after the decimal point. The
storage is based on the value being stored, not on the maximum precision
and scale allowed in the column.
Parameters precision An integer expression that specifies the number of digits in the
expression. The default value is 30.

scale An integer expression that specifies the number of digits after the
decimal point. The default value is 6.
The defaults can be changed by setting database options. For information,
see "PRECISION option" on page 193 and "SCALE option" on page 198.
Standards and ♦ SQL/92 Compatible with SQL/92, if the SCALE option is set to zero.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "FLOAT data type" on page 258
"REAL data type" on page 260
"DOUBLE data type" on page 258

REAL data type [Numeric]


Function A single-precision floating-point number stored in 4 bytes.
Syntax REAL
Usage The REAL data type is an approximate numeric data type; it is subject to
roundoff errors after arithmetic operations.

The range of values is 1.175495e-38 to 3.402823e+38. Values held as REAL


are accurate to 10 significant digits, but may be subject to round-off error
beyond the sixth digit.
The approximate nature of REAL values means that queries using equalities
should generally be avoided when comparing REAL values

260
Chapter 7 SQL Data Types

Standards and ♦ SQL/92 Compatible with SQL/92..


compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

SMALLINT data type [Numeric]


Function Integer value requiring 2 bytes of storage.
Syntax [ UNSIGNED ] SMALLINT
Usage The SMALLINT data type is an exact numeric data type; its accuracy is
preserved after arithmetic operations. It requires 2 bytes of storage.
The range for signed SMALLINT values is from -32768 to + 32767.
The range for unsigned SMALLINT values is from 0 to 65535.
Standards and ♦ SQL/92 Compatible with SQL/92. The UNSIGNED keyword is a
compatibility vendor extension.
♦ Sybase The signed data type is compatible with Adaptive Server
Enterprise. Adaptive Server Enterprise does not support the UNSIGNED
data type.
See also "INT or INTEGER data type" on page 259
"TINYINT data type" on page 261
"BIGINT data type" on page 256

TINYINT data type [Numeric]


Function Unsigned integer, requiring 1 byte of storage.
Syntax [ UNSIGNED ] TINYINT
Usage The TINYINT data type is an exact numeric data type; its accuracy is
preserved after arithmetic operations.
You can explicitly specify TINYINT as UNSIGNED, but the UNSIGNED
modifier has no effect as the type is always unsigned.
The range for TINYINT values is from 0 to 255.
In Embedded SQL, TINYINT columns should not be fetched into variables
defined as char or unsigned char, since the result is an attempt to convert the
value of the column to a string and then assign the first byte to the variable in
the program. Instead, TINYINT columns should be fetched into 2-byte or 4-
byte integer columns. Also, to send a TINYINT value to a database, the C
variable type should be an integer.

261
Numeric data types

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "BIGINT data type" on page 256
"TINYINT data type" on page 261
"SMALLINT data type" on page 261

262
Chapter 7 SQL Data Types

Money data types


Function For storing monetary data.

MONEY data type [Money]


Function This data type is convenient for storing monetary data, and provides
compatibility with the Adaptive Server Enterprise MONEY data type.
Syntax MONEY
Usage The MONEY data type is implemented as a domain, as NUMERIC(19,4),
allowing NULL.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Monetary data types in Adaptive Server Anywhere are
implemented as domains, and are primarily intended for compatibility
with Adaptive Server Enterprise.
See also "SMALLMONEY data type" on page 263

SMALLMONEY data type [Money]


Function This data type is convenient for storing monetary data that is not too large,
and provides compatibility with the Adaptive Server Enterprise
SMALLMONEY data type.
Syntax SMALLMONEY
Usage The SMALLMONEY data type is implemented in Adaptive Server
Anywhere as a domain, as NUMERIC(10,4), allowing NULL.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Monetary data types in Adaptive Server Anywhere are
implemented as domains, and are primarily intended for compatibility
with Adaptive Server Enterprise.
See also "MONEY data type" on page 263

263
Bit data type

Bit data type


Function For storing Boolean values.
Syntax BIT
Usage By default, columns of BIT data type do not allow NULL. This behavior is
different from other data types. You can explicitly allow NULL if desired.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

264
Chapter 7 SQL Data Types

Date and time data types


Function For storing dates and times.

Sending dates and times to the database


Dates and times may be sent to the database in one of the following ways:
♦ Using any interface, as a string
♦ Using ODBC, as a TIMESTAMP structure
♦ Using Embedded SQL, as a SQLDATETIME structure
When a time is sent to the database as a string (for the TIME data type) or as
part of a string (for TIMESTAMP or DATE data types), the hours, minutes,
and seconds must be separated by colons in the format hh:mm:ss.sss, but can
appear anywhere in the string. The following are valid and unambiguous
strings for specifying times:
21:35 -- 24 hour clock if no am or pm specified
10:00pm -- pm specified, so interpreted as 12 hour clock
10:00 -- 10:00am in the absence of pm
10:23:32.234 -- seconds and fractions of a second
included
When a date is sent to the database as a string, conversion to a date is
automatic. The string can be supplied in one of two ways:
♦ As a string of format yyyy/mm/dd or yyyy-mm-dd, which is interpreted
unambiguously by the database
♦ As a string interpreted according to the DATE_ORDER database option

Transact-SQL compatibility of string-to-date/time conversions


There are some differences in behavior between Adaptive Server Anywhere
and Adaptive Server Enterprise, when converting strings to date and time
data types.
If a string containing only a time value (no date) is converted to a date/time
data type, Adaptive Server Enterprise uses a default date of January 1, 1900,
but Adaptive Server Anywhere uses the current date.

265
Date and time data types

If the fraction portion of a time is less than 3 digits Adaptive Server


Enterprise interprets the value differently depending on whether it was
preceded by a period or a colon. If preceded by a colon, the value means
thousandths of a second. If preceded by a period, one digit means tenths, two
digits mean hundredths, and three digits mean thousandths. Adaptive Server
Anywhere interprets the value the same way, regardless of the separator.
Examples Adaptive Server Enterprise converts the values below as shown. The second
line in each pair differs in the use of a colon rather than a period.
12:34:56.7 to 12:34:56.700
12:34:56:7 to 12:34:56.007
12.34.56.78 to 12:34:56.780
12.34.56:78 to 12:34:56.078
12:34:56.789 to 12:34:56.789
12:34:56:789 to 12:34:56.789
Adaptive Server Anywhere converts the milliseconds value in the manner
that Adaptive Server Enterprise does for values preceded by a period, in both
cases:
12:34:56.7 to 12:34:56.700
12:34:56:7 to 12:34:56.700
12.34.56.78 to 12:34:56.780
12.34.56:78 to 12:34:56.780
12:34:56.789 to 12:34:56.789
12:34:56:789 to 12:34:56.789

Retrieving dates and times from the database


Dates and times may be retrieved from the database in one of the following
ways:
♦ Using any interface, as a string
♦ Using ODBC, as a TIMESTAMP structure
♦ Using embedded SQL, as a SQLDATETIME structure
When a date or time is retrieved as a string, it is retrieved in the format
specified by the database options DATE_FORMAT, TIME_FORMAT and
TIMESTAMP_FORMAT. For descriptions of these options, see "SET
OPTION statement" on page 596.
$ For information on functions that deal with dates and times, see "Date
and time functions" on page 292. The following arithmetic operators are
allowed on dates:

266
Chapter 7 SQL Data Types

♦ timestamp + integer Add the specified number of days to a date or


timestamp.
♦ timestamp - integer Subtract the specified number of days from a
date or timestamp.
♦ date - date Compute the number of days between two dates or
timestamps.
♦ date + time Create a timestamp combining the given date and time.

Comparing dates and times in the database


By default, values stored as DATE do not have any hour or minute values,
and so comparison of dates is straightforward.
If you set the TRUNCATE_DATE_VALUES option to OFF, then the DATE
data type also contains a time, which introduces complications when
comparing dates. If the time is not specified when a date is entered into the
database, the time defaults to 0:00 or 12:00am (midnight). Any date
comparisons with this option setting compare the times as well as the date
itself. A database date value of ’1992-05-23 10:00’ is not equal to the
constant ’1992-05-23’. The DATEFORMAT function or one of the other date
functions can be used to compare parts of a date and time field. For example:
DATEFORMAT(invoice_date,’yyyy/mm/dd’) = ’1992/05/23’
If a database column requires only a date, client applications should ensure
that times are not specified when data is entered into the database. This way,
comparisons with date-only strings will work as expected.
If you wish to compare a date to a string as a string, you must use the
DATEFORMAT function or CAST function to convert the date to a string
before comparing.

Using unambiguous dates and times


Dates in the format yyyy/mm/dd or yyyy-mm-dd are always recognized
unambiguously as dates, regardless of the DATE_ORDER setting. Other
characters can be used as separators instead of "/" or "-"; for example, "?", a
space character, or ",". You should use this format in any context where
different users may be employing different DATE_ORDER settings. For
example, in stored procedures, use of the unambiguous date format prevents
misinterpretation of dates according to the user’s DATE_ORDER setting.
Also, a string of the form hh:mm:ss.sss is interpreted unambiguously as a
time.

267
Date and time data types

For combinations of dates and times, any unambiguous date and any
unambiguous time yield an unambiguous date-time value. Also, the form
YYYY-MM-DD HH.MM.SS.SSS
is an unambiguous date-time value. Periods can be used in the time only in
combination with a date.
In other contexts, a more flexible date format can be used. Adaptive Server
Anywhere can interpret a wide range of strings as dates. The interpretation
depends on the setting of the database option DATE_ORDER. The
DATE_ORDER database option can have the value MDY, YMD, or DMY
(see "SET OPTION statement" on page 596). For example, the following
statement sets the DATE_ORDER option to DMY:
SET OPTION DATE_ORDER = ’DMY’ ;
The default DATE_ORDER setting is ’YMD’. The ODBC driver sets the
DATE_ORDER option to ’YMD’ whenever a connection is made. The value
can still be changed using the SET TEMPORARY OPTION statement.
The database option DATE_ORDER determines whether the string 10/11/12
is interpreted by the database as Oct 11 1912, Nov 12 1910, or Nov 10 1912.
The year, month, and day of a date string should be separated by some
character (for example /, -, or space) and appear in the order specified by the
DATE_ORDER option. The year can be supplied as either 2 or 4 digits, with
2 digit years defaulting to the 20th century. The month can be the name or
number of the month. The hours and minutes are separated by a colon, but
can appear anywhere in the string.
Notes ♦ We recommend that you always specify the year using the four-digit
format.
$ For more information about Y2K compliance issues, see "Year
2000 compliance" on page 285.
♦ With an appropriate setting of DATE_ORDER, the following strings are
all valid dates:
92-05-23 21:35
92/5/23
1992/05/23
May 23 1992
23-May-1992
Tuesday May 23, 1992 10:00pm
♦ If a string contains only a partial date specification, default values are
used to fill out the date. The following defaults are used:
♦ year This year
268
Chapter 7 SQL Data Types

♦ month No default
♦ day 1 (useful for month fields; for example, May 1992 will be the
date 1992-05-01 00:00)
♦ hour, minute, second, fraction 0

DATE data type [Date and Time]


Function A calendar date, such as a year, month and day.
Syntax DATE
Usage The year can be from the year 0001 to 9999.

For historical reasons, a DATE column can also contain an hour and minute
if the TRUNCATE_DATE_VALUES option is set to OFF. The
TIMESTAMP data type is recommended for anything with hours and
minutes.
The format in which DATE values are retrieved by applications is controlled
by the DATE_FORMAT setting. For example, a date value representing the
19th of July, 2003 may be returned to an application as 2003/07/19, as
Jul 19, 2003, or as one of a number of other possibilities.
The way in which a string is interpreted by the database server as a date is
controlled by the DATE_ORDER option. For example, depending on the
DATE_ORDER setting, a value of 02/05/2002 supplied by an application
for a DATE value may be interpreted in the database as the 2nd of May or
the 5th of February.

A DATE value requires 4 bytes of storage.


Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "DATE_FORMAT option" on page 169
"DATE_ORDER option" on page 171
"DATETIME data type" on page 269
"SMALLDATETIME data type" on page 270
"TIMESTAMP data type" on page 271
"TRUNCATE_DATE_VALUES option" on page 202

DATETIME data type [Date and Time]


Function A domain, implemented as TIMESTAMP.

269
Date and time data types

Syntax DATETIME
Usage DATETIME is provided primarily for compatibility with Adaptive Server
Enterprise.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise. For an
exception, see "Transact-SQL compatibility of string-to-date/time
conversions" on page 265.
See also "DATE data type" on page 269
"SMALLDATETIME data type" on page 270
"TIMESTAMP data type" on page 271

SMALLDATETIME data type [Date and Time]


Function A domain, implemented as TIMESTAMP.
Syntax SMALLDATETIME
Usage SMALLDATETIME is provided primarily for compatibility with Adaptive
Server Enterprise.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise. For an
exception, see "Transact-SQL compatibility of string-to-date/time
conversions" on page 265.
See also "DATE data type" on page 269
"DATETIME data type" on page 269
"TIMESTAMP data type" on page 271

TIME data type [Date and Time]


Function The time of day, containing hour, minute, second and fraction of a second.
Syntax TIME
Usage The fraction is stored to 6 decimal places. A TIME value requires 8 bytes of
storage. (ODBC standards restrict TIME data type to an accuracy of seconds.
For this reason you should not use TIME data types in WHERE clause
comparisons that rely on a higher accuracy than seconds.)
Standards and ♦ SQL/92 Vendor extension.
compatibility

270
Chapter 7 SQL Data Types

♦ Sybase Not supported by Adaptive Server Enterprise.


See also "TIMESTAMP data type" on page 271

TIMESTAMP data type [Date and Time]


Function The point in time, containing year, month, day, hour, minute, second and
fraction of a second.
Syntax TIMESTAMP
Usage The fraction is stored to 6 decimal places. A TIMESTAMP value requires 8
bytes of storage.
Although the range of possible dates for the TIMESTAMP data type is the
same as the DATE type (covering years 0001 to 9999), the useful range of
TIMESTAMP date types is from 1600-02-28 23:59:59 to 7911-01-01
00:00:00. Prior to, and after this range the time portion of the TIMESTAMP
may be incomplete.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
See also "TIME data type" on page 270

271
Binary data types

Binary data types


Function For storing binary data, including images and other information that is not
interpreted by the database.

BINARY data type [Binary]


Function Binary data of a specified maximum length (in bytes).
Syntax BINARY [ ( max-length ) ]
Usage The default max-length is 1.

The maximum size allowed is 32,767. The BINARY data type is identical to
the CHAR data type except when used in comparisons. BINARY values are
compared exactly while CHAR values are compared using the collation
sequence of the database.
Parameters max-length An integer expression that specifies the maximum length of
the expression.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Adaptive Server Enterprise supports max-length up to 255.
See also "LONG BINARY data type" on page 272
"VARBINARY data type" on page 273

LONG BINARY data type [BINARY]


Function Arbitrary length binary data.
Syntax LONG BINARY
Usage The maximum size is limited by the maximum size of the database file.
$ For more information on limitations, see "Size and number limitations"
on page 932.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "BINARY data type" on page 272
"VARBINARY data type" on page 273

272
Chapter 7 SQL Data Types

IMAGE data type [BINARY]


Function LONG BINARY data allowing NULL.
Syntax IMAGE
Usage IMAGE is implemented in Adaptive Server Anywhere as a domain, as
LONG BINARY allowing NULL. It is provided primarily for compatibility
with Adaptive Server Enterprise.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

VARBINARY data type [BINARY]


Function Identical to BINARY.
Syntax VARBINARY [ ( max-length ) ]
Usage Variable length binary strings. The default value for max-length is one.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "BINARY data type" on page 272
"LONG BINARY data type" on page 272

273
Domains

Domains
Function Domains are aliases for built-in data types, including precision and scale
values where applicable, and optionally including DEFAULT values and
CHECK conditions. Some domains, such as the monetary data types, are pre-
defined in Adaptive Server Anywhere, but you can add more of your own.
Domains, sometimes called user-defined data types, allow columns
throughout a database to be automatically defined on the same data type,
with the same NULL or NOT NULL condition, with the same DEFAULT
setting, and with the same CHECK condition. Domains encourage
consistency throughout the database and can eliminate some types of errors.
Simple domains Domains are created using the CREATE DOMAIN statement For full
description of the syntax, see "CREATE DOMAIN statement" on page 421.
The following statement creates a data type named street_address, which is
a 35-character string.
CREATE DOMAIN street_address CHAR( 35 )
CREATE DATATYPE can be used as an alternative to CREATE DOMAIN,
but is not recommended because CREATE DOMAIN is the syntax used in
the draft SQL/3 standard.
Resource authority is required to create data types. Once a data type is
created, the user ID that executed the CREATE DOMAIN statement is the
owner of that data type. Any user can use the data type. Unlike with other
database objects, the owner name is never used to prefix the data type name.
The street_address data type may be used in exactly the same way as any
other data type when defining columns. For example, the following table
with two columns has the second column as a street_address column:
CREATE TABLE twocol (
id INT,
street street_address
)
Domains can be dropped by their owner or by the DBA, using the DROP
DOMAIN statement:
DROP DOMAIN street_address
This statement can be carried out only if the data type is not used in any table
in the database. If you attempt to drop a domain that is in use, the message
"Primary key for row in table ’SYSUSERTYPE’ is referenced in another
table" appears.

274
Chapter 7 SQL Data Types

Constraints and Many of the attributes associated with columns, such as allowing NULL
defaults with values, having a DEFAULT value, and so on, can be built into a domain.
domains Any column that is defined on the data type automatically inherits the NULL
setting, CHECK condition, and DEFAULT values. This allows uniformity to
be built into columns with a similar meaning throughout a database.
For example, many primary key columns in the sample database are integer
columns holding ID numbers. The following statement creates a data type
that may be useful for such columns:
CREATE DOMAIN id INT
NOT NULL
DEFAULT AUTOINCREMENT
CHECK( @col > 0 )
Any column created using the data type id is not allowed to hold NULLs,
defaults to an auto-incremented value, and must hold a positive number. Any
identifier could be used instead of col in the @col variable.
The attributes of the data type can be overridden if needed by explicitly
providing attributes for the column. A column created on data type id with
NULL values explicitly allowed does allow NULLs, regardless of the setting
in the id data type.
Compatibility ♦ Named constraints and defaults In Adaptive Server Anywhere,
domains are created with a base data type, and optionally a NULL or
NOT NULL condition, a default value, and a CHECK condition. Named
constraints and named defaults are not supported.
♦ Creating data types In Adaptive Server Anywhere, you can use the
sp_addtype system procedure to add a domain, or you can use the
CREATE DOMAIN statement. In Adaptive Server Enterprise, you must
use sp_addtype.

275
Java class data types

Java class data types


Function Any public Java class that is installed into a database can be used as a SQL
data type. Java class data types provide abstract data types for use within the
database.
Standard and user- Java classes in the database fall into one of the following categories:
defined Java
♦ Standard classes Standard Java classes are those that are part of the
classes
Sun Microsystems Java Development Kit (JDK). A subset of the
standard class set is installed into all Java-enabled databases as built-in
classes.
♦ User-defined classes Users with DBA permission can install
compiled Java classes into a database.

Not all standard Adaptive Server Anywhere supports JDK 1.1.6, but not all standard Java
Java classes are classes from JDK 1.1.6 are supported. This is intentional. Some classes are
supported not supported for security reasons. Other classes are not supported because
they are applicable to user interface programming. Lastly, only classes in
packages that begin with the word java are considered to be 100% pure
Java, so any packages that start with other words (like sun) are unsupported.
Definition of When a Java class is listed as supported, it means all its methods have been
supported implemented within the Sybase VM. If a class is listed as partially
supported then some of its methods have not been implemented.
Even if a class is supported, not all of the methods of a supported Java class
are guaranteed to work. Methods of supported classes can fail if they depend
on classes that are not supported.
Error condition When a method fails because of an unsupported class, the usual error
when not condition is an unhandled exception:
supported java.lang.UnsatisfiedLinkError for the method which has not
been implemented.

Supported Java packages


This section lists the packages of built-in classes available for use as SQL
data types in a Java-enabled database. For information about any classes
within the package that may be unsupported or partially supported, see
"Unsupported Java packages and classes" on page 277, and "Partially
supported packages and classes" on page 278.
♦ java.beans

276
Chapter 7 SQL Data Types

♦ java.io. The classes that govern file access are supported only on
Windows NT, and only if the JAVA_INPUT_OUTPUT option is set to
ON. See "JAVA_INPUT_OUTPUT option" on page 182.
♦ java.lang
♦ java.lang.reflect
♦ java.lang.Thread
♦ java.math
♦ java.net
♦ java.rmi
♦ java.rmi.dgc
♦ java.rmi.registry
♦ java.rmi.server
♦ java.security
♦ java.security.acl
♦ java.security.interfaces
♦ java.sql. For details on support for JDBC 2.0 features, see "Server-side
JDBC features" on page 579 of the book ASA User’s Guide.
♦ java.text
♦ java.util
♦ java.util.zip

Unsupported Java packages and classes


Classes in the following packages are not supported in the Sybase VM:
♦ java.applet
♦ java.awt
♦ java.awt.datatransfer
♦ java.awt.event
♦ java.awt.image
♦ All packages prefixed by sun. For example, sun.audio.

277
Java class data types

Partially supported packages and classes


The following classes are partially supported. They have some unsupported
native methods:
♦ java.lang.ClassLoader
♦ java.lang.Compiler
♦ java.lang.Runtime (exec/load/loadlibrary)
♦ java.lang.SecurityManager
♦ java.io.File
♦ java.io.FileDescriptor
♦ java.io.FileInputStream
♦ java.io.FileOutputStream
♦ java.io.RandomAccessFile
♦ java.net.PlainDatagramSocketImpl
♦ java.util.zip.Deflater
♦ java.util.zip.Inflater

User-defined Java classes


Users with DBA permissions can install Java classes into a database. Any
public class installed into the database becomes available as a data type.
Preparing classes The Java Development Kit (JDK) provides the tools necessary for preparing
using the JDK classes for installation into a database.

v To prepare a class for installation, using the JDK:


1 Using a text editor, write a Java class, outside the database, and store it
as a Java source code file (typically with an extension of .java).
For example, you may create a file named MyFirstClass.java.
2 Using the javac compiler, compile the Java class to produce a Java class
file (with .class extension).
For example, to compile the file MyFirstClass.java, type the following at
a command prompt:
javac MyFirstClass.java

278
Chapter 7 SQL Data Types

Installing a class Once you have a compiled Java class file, you can install it into the database.
You can do this conveniently using either Sybase Central or Interactive SQL.

v To install a class, using Sybase Central:


1 From Sybase Central, connect to the database as a user ID with DBA
permissions.
2 Open the Java Objects folder, and double-click Add Java Class or Jar.
Follow the instructions in the wizard to install the class.

v To install a class, using Interactive SQL:


1 From Interactive SQL, connect to the database as a user ID with DBA
permissions.
2 Enter the following command to install the class:
INSTALL JAVA NEW FROM filename

$ For more information about installing classes, see the "INSTALL


statement" on page 542.

Case sensitivity of Java class data types


Java identifiers, including data types, are case sensitive: the Java int data
type cannot be written as INT. SQL identifiers, including data types, are case
insensitive. The int data type can also be written as Int or any other
combination of upper and lower case characters.
When a Java class is used as a SQL data type, the data type is always case
sensitive. This is an exception to the rule for SQL identifier case
insensitivity.
Example If you install a class named Demo, the following statements are not
equivalent:
CREATE TABLE t1 (
id INT PRIMARY KEY
demo_column Demo )
CREATE TABLE t1 (
id INT PRIMARY KEY
demo_column DEMO )

279
Java class data types

Using classes as data types


Creating tables You can create a table with columns based on a Java class data type, just as
using Java class you can with any other data type. For example, if MyClass is a Java class
data types installed into the database, you can create a table using this class as follows:
CREATE TABLE mytable (
id INT NOT NULL PRIMARY KEY,
mycol MyClass )
In this statement, the MyClass data type is a SQL data type, but is case-
sensitive, as Java is a case-sensitive language.
Inserting Java You can insert a Java object into a table just as you would any other row,
objects using the INSERT statement. Because each row is a separate instance of the
class, you must use the NEW keyword to create an instance. For example,
INSERT INTO t2
VALUES ( 1, NEW MyClass() )
In this case, MyClass() is a Java class name, not a SQL data type, and so
must be entered in the proper case.
In this example, MyClass() has no arguments, so each row is created using
the default constructor. In general, you would supply arguments to a class to
place distinct values in each row.
Using subclasses If you install a class, say MySubClass, which is a subclass of MyClass,
you can insert instances of MySubClass into a column of data type
MyClass.

280
Chapter 7 SQL Data Types

Data type conversions


Type conversions can happen automatically, or they can be explicitly
requested using the CAST or CONVERT function.
If a string is used in a numeric expression or as an argument to a function
that expects a numeric argument, the string is converted to a number.
If a number is used in a string expression or as a string function argument, it
is converted to a string before being used.
All date constants are specified as strings. The string is automatically
converted to a date before use.
There are certain cases where the automatic database conversions are not
appropriate.
’12/31/90’ + 5
’a’ > 0
The automatic data type conversion fails here. The CAST or CONVERT
functions can be used to force type conversions. For information about the
CAST and CONVERT functions, see "Data type conversion functions" on
page 292.
The following functions can also be used to force type conversions (see
"SQL Functions" on page 291).
♦ DATE( value ) Converts the expression into a date, and removes any
hours, minutes or seconds. Conversion errors may be reported.
♦ STRING( value ) Similar to CAST( value AS CHAR ), except that
string( NULL ) is the empty string (’’), while CAST( NULL AS CHAR )
is the NULL value.
♦ VALUE+0.0 Equivalent to CAST( value AS DECIMAL ).

281
Java / SQL data type conversion

Java / SQL data type conversion


When a Java class field or method is invoked within a SQL statement, a Java
data type is returned by the Java object. This must be converted into a SQL
data type for use within the SQL statement, for example in comparisons.
Similarly, when a SQL value is assigned to a Java class field, or supplied as
an argument to a Java class method, the SQL value must be converted to a
Java data type.
Java to SQL and SQL to Java data type conversions are carried out according
to the JDBC standard. The conversions are described in the following tables.

Java to-SQL-data type conversion


Java type SQL type
String CHAR
String VARCHAR
String TEXT
java.math.BigDecimal NUMERIC
java.math.BigDecimal MONEY
java.math.BigDecimal SMALLMONEY
boolean BIT
byte TINYINT
Short SMALLINT
Int INTEGER
long INTEGER
float REAL
double DOUBLE
byte[ ] VARBINARY
byte[ ] IMAGE
java.sql.Date DATE
java.sql.Time TIME
java.sql.Timestamp TIMESTAMP

282
Chapter 7 SQL Data Types

Java type SQL type


java.lang.Double DOUBLE
java.lang.Float REAL
java.lang.Integer INTEGER
java.lang.Long INTEGER
void this*
* The method returns the object itself

SQL-to-Java data type conversion


SQL type Java type
CHAR String
VARCHAR String
TEXT String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
MONEY java.math.BigDecimal
SMALLMONEY java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[ ]
VARBINARY byte[ ]

283
Java / SQL data type conversion

SQL type Java type


LONG VARBINARY byte[ ]
IMAGE byte[ ]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp

284
Chapter 7 SQL Data Types

Year 2000 compliance


The problem of handling dates, in particular year values beyond the year
2000, is a significant issue for the computer industry.
This section examines the year 2000 compliance of Adaptive Server
Anywhere. It illustrates how date values are handled internally by Adaptive
Server Anywhere, and how Adaptive Server Anywhere handles ambiguous
date information, such as the conversion of a two digit year string value.
Users of Sybase Adaptive Server Anywhere and its predecessors can be
assured that dates are handled and stored internally in a manner not adversely
effected by the transition from the 20th century to the 21st century.
Consider the following measurements of Adaptive Server Anywhere year
2000 compliance:
♦ Adaptive Server Anywhere always returns correct values for any legal
arithmetic and logical operations on dates, regardless of whether the
calculated values span different centuries.
♦ At all times, the Adaptive Server Anywhere internal storage of dates
explicitly includes the century portion of a year value.
♦ The operation of Adaptive Server Anywhere is unaffected by any return
value, including the current date.
♦ Date values can always be output in full century format.
Many of the date–related topics summarized in this section are explained in
greater detail in other parts of the documentation.

How dates are stored


Dates containing year values are used internally and stored in Adaptive
Server Anywhere databases using either of the following data types:

285
Year 2000 compliance

Data type Contains Stored in Range of


possible
values
DATE Calendar date 4-bytes 0001-01-01 to
(year, month, day) 9999-12-31
TIMESTAMP Time stamp (year, 8-bytes 0001-01-01 to
month, day, hour 9999-12-31
minute, second, (precision of the
and fraction of time portion of
second accurate to TIMESTAMP is
6 decimal places) dropped prior to
1600-02-28
23:59:59 and
after 7911-01-01
00:00:00)

$ For more information on Adaptive Server Anywhere date and time data
types see "Date and time data types" on page 265.

Sending and retrieving date values


Date values are stored within Adaptive Server Anywhere as either a DATE
or TIMESTAMP data type, but they are passed to and retrieved from
Adaptive Server Anywhere using one of the following methods:
♦ As a string, using any Adaptive Server Anywhere programming
interface.
♦ As a TIMESTAMP structure, using ODBC.
♦ As a SQLDATETIME structure, using Embedded SQL.
A string containing a date value is considered unambiguous and is
automatically converted to a DATE or TIMESTAMP data type without
potential for misinterpretation if it is passed using the following format:
yyyy-mm-dd (the "-" dash separator is one of several characters that are
permitted).
For more Date formats other than yyyy-mm-dd can be used by setting the
information DATE_FORMAT database option. For more information, see
"DATE_FORMAT option" on page 169.
For more information on unambiguous date formats, see "Using
unambiguous dates and times" on page 267.

286
Chapter 7 SQL Data Types

For more information on the ODBC TIMESTAMP structure, see the


Microsoft Open Database Connectivity SDK, or "Sending dates and times to
the database" on page 265.
Used in the development of C programs, an embedded SQL
SQLDATETIME structure’s year value is a 16-bit signed integer.
For more information on the SQLDATETIME data type, see "Embedded
SQL data types" on page 17 of the book ASA Programming Interfaces
Guide.

Leap years
The year 2000 is also a leap year, with an additional day in the month of
February. Adaptive Server Anywhere uses a globally accepted algorithm for
determining which years are leap years. Using this algorithm, a year is
considered a leap year if it is divisible by four, unless the year is a century
date (such as the year 1900), in which case it is a leap year only if it is
divisible by 400.
Adaptive Server Anywhere handles all leap years correctly. For example:
The following SQL statement results in a return value of "Tuesday":
SELECT DAYNAME(’2000-02-29’);
Adaptive Server Anywhere accepts Feb 29, 2000 — a leap year — as a date,
and using this date determines the day of the week.
However, the following statement is rejected by Adaptive Server Anywhere:
SELECT DAYNAME(’2001-02-29’);
This statement results in an error (cannot convert '2001-02-29' to a date)
because Feb 29 does not exist in the year 2001.

Ambiguous string to date conversions


Adaptive Server Anywhere automatically converts a string into a date when a
date value is expected, even if the year is represented in the string by only
two digits.
If the century portion of a year value is omitted, the method of conversion is
determined by the NEAREST_CENTURY database option.
The NEAREST_CENTURY database option is a numeric value that acts as a
break point between 19YY date values and 20YY date values.
Two-digit years less than the NEAREST_CENTURY value are converted to
20yy, while years greater than or equal to the value are converted to 19yy.
287
Year 2000 compliance

If this option is not set, the default setting of 50 is assumed, thus adding 1900
to two digit year strings and placing them in the 20th century.
This NEAREST_CENTURY option was introduced in SQL Anywhere
Version 5.5. In version 5.5, the default setting was 0.
Ambiguous date The following statement creates a table that can be used to illustrate the
conversion conversion of ambiguous date information in Adaptive Server Anywhere.
example CREATE TABLE T1 (C1 DATE);
The table T1 contains one column, C1, of the type DATE.
The following statement inserts a date value into the column C1. Adaptive
Server Anywhere automatically converts a string that contains an ambiguous
year value, one with two digits representing the year but nothing to indicate
the century.
INSERT INTO T1 VALUES(’00-01-01’);
By default, the NEAREST_CENTURY option is set to 50, thus Adaptive
Server Anywhere converts the string into the date 2000-01-01. The following
statement verifies the result of this insert.
SELECT * FROM T1;
Changing the NEAREST_CENTURY option using the following statement
alters the conversion process.
SET OPTION NEAREST_CENTURY = 0;
When NEAREST_CENTURY option is set to 0, executing the previous
insert using the same statement will create a different date value:
INSERT INTO T1 VALUES(’00-01-01’);
The above statement now results in the insertion of the date 1900-01-01. Use
the following statement to verify the results.
SELECT * FROM T1;

Date to string conversions


Adaptive Server Anywhere provides several functions for converting
Adaptive Server Anywhere date and time values into a wide variety of
strings and other expressions. It is possible in converting a date value into a
string to reduce the year portion into a two digit number representing the
year, thereby losing the century portion of the date.
Wrong century Consider the following statement, which incorrectly converts a string
values representing the date Jan 1, 2000 into a string representing the date Jan 1,
1900 even though no database error occurs.

288
Chapter 7 SQL Data Types

SELECT DATEFORMAT (
DATEFORMAT(’2000-01-01’, ’Mmm dd/yy’ ),
’yyyy-Mmm-dd’ )
AS Wrong_year;
Although the unambiguous date string 2000-01-01 is automatically and
correctly converted by Adaptive Server Anywhere into a date value, the
’Mmm dd/yy’ formatting of the inner, or nested, DATEFORMAT function
drops the century portion of the date when it is converted back to a string and
passed to the outer DATEFORMAT function.
Because the database option NEAREST_CENTURY in this case is set to 0,
the outer DATEFORMAT function converts the string representing a date
with a two-digit year value into a year in the 20th century.
$ For more information on date and time functions, see "Date and time
functions" on page 292.

289
Year 2000 compliance

290
C H A P T E R 8

SQL Functions

About this chapter Functions are used to return information from the database. They are allowed
anywhere an expression is allowed.

NULL parameters
Unless otherwise stated, any function that receives NULL as a parameter
returns NULL.

Contents The chapter includes a grouping of functions by type, followed by an


alphabetical list of functions.

291
Function types

Function types
This section groups the available function by type.

Aggregate functions
Aggregate functions summarize data over a group of rows from the database.
The groups are formed using the GROUP BY clause of the SELECT
statement. Aggregate functions are allowed only in the select list and in the
HAVING and ORDER BY clauses of a SELECT statement.
List of functions The following aggregate functions are available:
♦ "AVG function " on page 304
♦ "COUNT function " on page 312
♦ "LIST function" on page 332
♦ "MAX function" on page 335
♦ "MIN function" on page 335
♦ "SUM function" on page 358

Data type conversion functions


These functions convert arguments from one data type to another.
Compatibility ♦ The Adaptive Server Anywhere cast function is not currently supported
by Adaptive Server Enterprise.

List of functions The following data type conversion functions are available:
♦ "CAST function" on page 306
♦ "CONVERT function" on page 310
♦ "HEXTOINT function" on page 327
♦ "INTTOHEX function" on page 330

Date and time functions


Date and time functions perform operations on date and time data types or
return date or time information.

292
Chapter 8 SQL Functions

In this chapter, the term datetime is used to mean date or time or timestamp.
The specific data type DATETIME is indicated as DATETIME.
$ For more information on datetime data types, see "Date and time data
types" on page 265.
List of functions The following date and time functions are available:
♦ "DATE function" on page 313
♦ "DATEADD function" on page 314
♦ "DATEDIFF function" on page 314
♦ "DATEFORMAT function" on page 316
♦ "DATENAME function" on page 316
♦ "DATEPART function" on page 317
♦ "DATETIME function" on page 317
♦ "DAY function" on page 318
♦ "DAYNAME function" on page 318
♦ "DAYS function" on page 318
♦ "DOW function" on page 321
♦ "GETDATE function" on page 326
♦ "HOUR function " on page 327
♦ "HOURS function " on page 327
♦ "MINUTE function" on page 336
♦ "MINUTES function" on page 336
♦ "MONTH function" on page 338
♦ "MONTHNAME function" on page 338
♦ "MONTHS function" on page 338
♦ "NOW function" on page 341
♦ "QUARTER function" on page 346
♦ "SECOND function" on page 351
♦ "SECONDS function" on page 351
♦ "TODAY function" on page 359
♦ "WEEKS function" on page 362
♦ "YEARS function" on page 363

293
Function types

♦ "YMD function" on page 364

Date parts
Many of the date functions use dates built from date parts. The following
table displays allowed values of date-parts.

Date Part Abbreviation Values


Year yy 1753 – 9999
Quarter qq 1-4
Month mm 1 - 12
Week wk 1 - 54
Day dd 1 - 31
Dayofyear dy 1 - 366
Weekday dw 1 - 7 (Sun.-Sat.)
Hour hh 0 - 23
Minute mi 0 - 59
Second ss 0 - 59
Millisecond ms 0 – 999
Calyearofweek cyr Integer. The year in which the week begins.
The week containing the first few days of the
year can be part of the last week of the
previous year, depending on the weekday on
which the year started. Years starting on
Monday through Thursday have no days that
are part of the previous year, but years
starting on Friday through Sunday start their
first week on the first Monday of the year.
Calweekofyear cwk An integer from 1 to 54 representing the
week number within the year that contains
the specified date.
Caldayofweek cdw The day number within the week (Sunday =
1, Saturday = 7)

Java and SQL user-defined functions


There are two mechanisms for creating user-defined functions in Adaptive
Server Anywhere. You can use the SQL language to write the function, or
you can use Java.
294
Chapter 8 SQL Functions

User-defined You can implement your own functions in SQL using the "CREATE
functions in SQL FUNCTION statement" on page 432. The RETURN statement inside the
CREATE FUNCTION statement determines the data type of the function.
Once a SQL user-defined function is created, it can be used anywhere a
built-in function of the same data type is used.
$ For more information on creating SQL functions, see "Using
Procedures, Triggers, and Batches" on page 423 of the book ASA User’s
Guide.
User-defined Although SQL functions are useful, Java classes provide a more powerful
functions in Java and flexible way of implementing user-defined functions, with the additional
advantage that they can be moved from the database server to a client
application if desired.
Any class method of an installed Java class can be used as a user-defined
function anywhere a built-in function of the same data type is used.
Instance methods are tied to particular instances of a class, and so have
different behavior from standard user-defined functions.
$ For more information on creating Java classes, and on class methods,
see "A Java seminar" on page 509 of the book ASA User’s Guide.

Miscellaneous functions
Miscellaneous functions perform operations on arithmetic, string or date/time
expressions, including the return values of other functions.
List of functions The following miscellaneous functions are available:
♦ "ARGN function" on page 302
♦ "COALESCE function" on page 308
♦ "ESTIMATE function" on page 322
♦ "EXPERIENCE_ESTIMATE function" on page 326
♦ "ESTIMATE_SOURCE function" on page 322
♦ "IFNULL function" on page 328
♦ "INDEX_ESTIMATE function" on page 329
♦ "ISNULL function" on page 330
♦ "NULLIF function" on page 341
♦ "NUMBER function" on page 342

295
Function types

♦ "PLAN function" on page 344


♦ "TRACEBACK function" on page 359

Numeric functions
Numeric functions perform mathematical operations on numerical data types
or return numeric information.
List of functions The following numeric functions are available:
♦ "ABS function" on page 301
♦ "ACOS function" on page 301
♦ "ASIN function" on page 302
♦ "ATAN function" on page 303
♦ "ATN2 function" on page 303
♦ "CEILING function" on page 306
♦ "COS function" on page 311
♦ "COT function" on page 312
♦ "DEGREES function" on page 321
♦ "EXP function" on page 325
♦ "FLOOR function" on page 326
♦ "LOG function" on page 333
♦ "LOG10 function" on page 334
♦ "MOD function" on page 337
♦ "PI function" on page 343
♦ "POWER function" on page 344
♦ "RADIANS function" on page 347
♦ "RAND function" on page 347
♦ "REMAINDER function" on page 348
♦ "ROUND function" on page 350
♦ "SIGN function" on page 352
♦ "SIN function" on page 353
♦ "SQRT function" on page 355

296
Chapter 8 SQL Functions

♦ "TAN function" on page 358


♦ "TRUNCATE function" on page 360
♦ "TRUNCNUM function" on page 361

String functions
String functions perform conversion, extraction or manipulation operations
on strings, or return information about strings.
When working in a multi-byte character set, check carefully whether the
function being used returns information concerning characters or bytes.
List of functions The following string functions are available:
♦ "ASCII function " on page 302
♦ "BYTE_LENGTH function" on page 304
♦ "BYTE_SUBSTR function" on page 305
♦ "CHAR function" on page 307
♦ "CHARINDEX function" on page 307
♦ "CHAR_LENGTH function" on page 308
♦ "DIFFERENCE function" on page 321
♦ "INSERTSTR function" on page 329
♦ "LCASE function" on page 330
♦ "LEFT function" on page 331
♦ "LENGTH function" on page 331
♦ "LOCATE function" on page 333
♦ "LTRIM function" on page 334
♦ "PATINDEX function" on page 342
♦ "REPEAT function" on page 348
♦ "REPLACE function" on page 348
♦ "REPLICATE function" on page 349
♦ "RIGHT function" on page 350
♦ "RTRIM function" on page 351
♦ "SIMILAR function" on page 353
♦ "SOUNDEX function" on page 354
297
Function types

♦ "SPACE function" on page 354


♦ "STR function" on page 355
♦ "STRING function" on page 356
♦ "STUFF function" on page 356
♦ "SUBSTRING function" on page 357
♦ "TRIM function" on page 360
♦ "UCASE function" on page 361
♦ "UPPER function" on page 362

System functions
System functions return system information.
List of functions The following system functions are available:
♦ "CONNECTION_PROPERTY function " on page 309
♦ "DATALENGTH function" on page 313
♦ "DB_ID function" on page 319
♦ "DB_NAME function " on page 320
♦ "DB_PROPERTY function" on page 320
♦ "EVENT_CONDITION function" on page 323
♦ "EVENT_PARAMETER function" on page 324
♦ "NEXT_CONNECTION function" on page 339
♦ "NEXT_DATABASE function" on page 340
♦ "PROPERTY function" on page 345
♦ "PROPERTY_DESCRIPTION function" on page 344
♦ "PROPERTY_NAME function" on page 345
♦ "PROPERTY_NUMBER function" on page 346
Compatibility The following table shows the Adaptive Server Enterprise system functions
and their status in Adaptive Server Anywhere:

298
Chapter 8 SQL Functions

Function Status
Col_length Implemented
Col_name Implemented
Db_id Implemented
Db_name Implemented
Index_col Implemented
Object_id Implemented
Object_name Implemented
Proc_role Always returns 0
Show_role Always returns NULL
Tsequal Implemented
User_id Implemented
User_name Implemented
Suser_id Implemented
Suser_name Implemented
Datalength Implemented
Curunreservedpgs Not implemented
Data_pgs Not implemented
Host_id Not implemented
Host_name Not implemented
Lct_admin Not implemented
Reserved_pgs Not implemented
Rowcnt Not implemented
Used_pgs Not implemented
Valid_name Not implemented
Valid_user Not implemented

Notes ♦ Some of the system functions are implemented in Adaptive Server


Anywhere as stored procedures.
♦ The db_id, db_name, and datalength functions are implemented as built-
in functions.
The implemented system functions are described in the following table.

299
Function types

System function Description


Col_length( table-name, column-name ) Returns the defined length of column
Col_name( table-id, column-id [, Returns the column name
database-id] )
Db_id( [ database-name ] ) Returns the database ID number
Db_name( [ database-id ] ) Returns the database name
Index_col (table-name, index-id, key_# [, Returns the name of the indexed
userid] ) column
Object_id (object-name ) Returns the object ID
Object_name ( object-id [, database-id ] ) Returns the object name
Tsequal ( timestamp, timestamp2 ) Compares timestamp values to
prevent update on a row that has been
modified since it was selected
User_id( [ user-name] ) Returns an integer user identification
number. This does not return the
Adaptive Server Anywhere user ID
User_name( [user-id] ) Returns the user ID (user name in
Adaptive Server Enterprise)
Suser_id( [user-name] ) Returns an integer user identification
number
Suser_name( [user-id] ) Returns the user ID (server user name
in Adaptive Server Enterprise)
Datalength( expression ) Returns the length of the expression,
in bytes

Text and image functions


Text and image functions operate on text and image data types. Adaptive
Server Adaptive Server Anywhere supports only the textptr text and image
function.
Compatibility ♦ Adaptive Server Anywhere does not currently support the Adaptive
Server Enterprise textvalid function.

List of functions The following text and image function is available:


♦ "TEXTPTR function" on page 359

300
Chapter 8 SQL Functions

Alphabetical list of functions


Each function is listed, and the function type (numeric, character, and so on)
is indicated next to it.
$ For links to all functions of a given type, see "Function types" on
page 292.

ABS function [Numeric]


Function Returns the absolute value of a numeric expression.
Syntax ABS ( numeric-expression )
Parameters numeric expression The number whose absolute value is to be returned.
Examples The following statement returns the value 66.
SELECT ABS( -66 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

ACOS function [Numeric]


Function Returns the arc-cosine, in radians, of a numeric expression.
Syntax ACOS ( numeric-expression )
Parameters numeric expression The cosine of the angle.
Examples The following statement returns the value 1.023945.
SELECT ACOS( 0.52 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "ASIN function" on page 302
"ATAN function" on page 303
"ATN2 function" on page 303
"COS function" on page 311

301
Alphabetical list of functions

ARGN function [Miscellaneous]


Function Returns a selected argument from a list of arguments.
Syntax ARGN ( integer-expression, expression [ , ...] )
Parameters integer expression The position of an argument within the list of
expressions.

expression An expression of any data type passed into the function. All
supplied expressions must be of the same data type.
Examples The following statement returns the value 6.
SELECT ARGN( 6, 1,2,3,4,5,6 )
Usage Using the value of the integer-expression as n, returns the n’th argument
(starting at 1) from the remaining list of arguments. While the expressions
can be of any data type, they must all be of the same data type. The integer
expression must be from one to the number of expressions in the list or
NULL is returned. Multiple expressions are separated by a comma.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

ASCII function [String]


Function Returns the integer ASCII value of the first byte in a string-expression.
Syntax ASCII ( string-expression )
Parameters string-expression The string.
Examples The following statement returns the value 90.
SELECT ASCII( ’Z’ )
Usage If the string is empty, then ASCII returns zero. Literal strings must be
enclosed in quotes.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

ASIN function [Numeric]


Function Returns the arc-sine, in radians, of a number.
Syntax ASIN ( numeric-expression )

302
Chapter 8 SQL Functions

Parameters numeric-expression The sine of the angle.


Examples The following statement returns the value 0.546850.
SELECT ASIN( 0.52 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "ACOS function" on page 301
"ATAN function" on page 303
"ATN2 function" on page 303
"SIN function" on page 353

ATAN function [Numeric]


Function Returns the arc-tangent, in radians, of a number.
Syntax ATAN ( numeric-expression )
Parameters numeric-expression The tangent of the angle.
Examples The following statement returns the value 0.479519.
SELECT ATAN( 0.52 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "ACOS function" on page 301
"ASIN function" on page 302
"ATN2 function" on page 303
"TAN function" on page 358

ATN2 function [Numeric]


Function Returns the arc-tangent, in radians, of the ratio of two numbers.
Syntax { ATN2 | ATAN2 } ( numeric-expression1, numeric-expression2 )
Parameters numeric-expression1 The numerator in the ratio whose arc tangent is
calculated.

numeric-expression2 The denominator in the ratio whose arc-tangent is


calculated.
Examples The following statement returns the value 0.008666.

303
Alphabetical list of functions

SELECT ATAN2( 0.52, 060 )


Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase ATN2 is compatible with Adaptive Server Enterprise.
ATAN2 is not supported by Adaptive Server Enterprise.
See also "ACOS function" on page 301
"ASIN function" on page 302
"ATAN function" on page 303
"TAN function" on page 358

AVG function [Aggregate]


Function Computes the average, for a set of rows, of a numeric-expression or of a set
unique values.
Syntax AVG (numeric-expression | DISTINCT column-name )
Parameters numeric-expression The value whose average is calculated over a set of
rows.

DISTINCT column-name Computes the average of the unique values in


column-name. This is of limited usefulness, but is included for completeness.
Examples The following statement returns the value 49988.6.
SELECT AVG( salary ) FROM employee
Usage This average does not include rows where the numeric expression is the
NULL value. Returns the NULL value for a group containing no rows.
Standards and ♦ SQL/92 SQL/92 compatible.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "SUM function" on page 358
"COUNT function " on page 312

BYTE_LENGTH function [String]


Function Returns the number of bytes in a string.
Syntax BYTE_LENGTH ( string-expression )
Parameters string-expression The string whose length is to be calculated.
Examples The following statement returns the value 12.
SELECT BYTE_LENGTH( ’Test Message’ )

304
Chapter 8 SQL Functions

Usage Trailing white space characters are included in the length returned.
The return value of a NULL string is NULL.
If the string is in a multi-byte character set, the BYTE_LENGTH value
differs from the number of characters returned by CHAR_LENGTH.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "CHAR_LENGTH function" on page 308
"DATALENGTH function" on page 313
"LENGTH function" on page 331

BYTE_SUBSTR function [String]


Function Returns a substring of a string. The substring is calculated using bytes, not
characters.
Syntax BYTE_SUBSTR ( string-expression, start [, length ] )
Parameters string- expression The string from which the substring is taken.

start An integer expression indicating the start of the substring. A positive


integer starts from the beginning of the string, with the first character being
position 1. A negative integer specifies a substring starting from the end of
the string, the final character being at position -1.

length An integer expression indicating the length of the substring. A


positive length specifies the number of bytes to be taken starting at the start
position. A negative length specifies the number of bytes to be taken ending
at the start position.
Examples The following statement returns the value age.
SELECT BYTE_SUBSTR( ’Test Message’,-1,-3 )
Usage If length is specified, the substring is restricted to that number of bytes. Both
start and length can be either positive or negative. A negative starting
position specifies a number of bytes from the end of the string instead of the
beginning. A positive length specifies that the substring ends length bytes to
the right of the starting position, while a negative length specifies that the
substring ends length bytes to the left of the starting position and ends at the
start position. Using appropriate combinations of negative and positive
numbers, you can get a substring from either the beginning or end of the
string.

305
Alphabetical list of functions

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
See also "SUBSTRING function" on page 357

CAST function [Data type conversion]


Function Returns the value of an expression converted to a supplied data type.
Syntax CAST ( expression AS data type )
Parameters expression The expression to be converted.

data type The target data type.


Examples The following function ensures a string is used as a date:
CAST( ’2000-10-31’ AS DATE )
The value of the expression 1 + 2 is calculated, and the result cast into a
single-character string.
CAST( 1 + 2 AS CHAR )
You can use the CAST function to shorten strings:
CAST( Surname AS CHAR(10) )
Usage If you do not indicate a length for character string types, the database server
chooses an appropriate length. If neither precision nor scale is specified for a
DECIMAL conversion, the database server selects appropriate values.
Standards and ♦ SQL/92 This function is SQL/92 compatible.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
See also "CONVERT function" on page 310

CEILING function [Numeric]


Function Returns the ceiling (smallest integer not less than) of a number.
Syntax CEILING ( numeric-expression )
Parameters numeric expression The number whose ceiling is to be calculated.
Examples The following statement returns the value 60.
SELECT CEILING( 59.84567 )

306
Chapter 8 SQL Functions

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "FLOOR function" on page 326

CHAR function [String]


Function Returns the character with the ASCII value of a number.
Syntax CHAR ( integer-expression )
Parameters integer expression The number to be converted to an ASCII character.
The number must be in the range 0 to 255, inclusive.
Examples The following statement returns the value Y.
SELECT CHAR( 89 )
Usage The character returned corresponds to the supplied numeric expression in the
current database character set, according to a binary sort order.
CHAR returns NULL for integer expressions with values greater than 255 or
less than zero.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

CHARINDEX function [String]


Function Returns the position of one string in another.
Syntax CHARINDEX ( string-expression1, string-expression2 )
Parameters string expression1 The string you are searching for.

string expression2 The string to be searched.


Examples The statement
SELECT emp_lname, emp_fname
FROM employee
WHERE CHARINDEX(’K’, emp_lname ) = 1
returns the following values:

307
Alphabetical list of functions

emp_lname Emp_fname
Klobucher James
Kuo Felicia
Kelly Moira

Usage The position of the first character in the string being searched is 1.
If the string being searched contains more than one instance of the other
string, then CHARINDEX returns the position of the first instance.
If the string being searched does not contain the other string, then
CHARINDEX returns 0.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "SUBSTRING function" on page 357

CHAR_LENGTH function [String]


Function Returns the number of characters in a string.
Syntax CHAR_LENGTH ( string-expression )
Parameters string-expression The string whose length is to be calculated.
Usage Trailing white space characters are included in the length returned.
The return value of a NULL string is NULL.
If the string is in a multi-byte character set, the CHAR_LENGTH value
differs from the number of bytes returned by BYTE_LENGTH.
Examples The following statement returns the value 8.
SELECT CHAR_LENGTH( ’Chemical’ )
Standards and ♦ SQL/92 This function is SQL/92 compatible.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "BYTE_LENGTH function" on page 304

COALESCE function [Miscellaneous]


Function Returns the first non-NULL expression from a list.

308
Chapter 8 SQL Functions

Syntax COALESCE ( expression, expression [ , ...] )


Parameters expression Any expression.
Examples The following statement returns the value 34.
SELECT COALESCE( NULL, 34, 13, 0 )
Standards and ♦ SQL/92 SQL/92.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

CONNECTION_PROPERTY function [System]


Function Returns the value of a given connection property as a string.
Syntax CONNECTION_PROPERTY ( { integer-expression | string-expression }
... [ , integer-expression ] )
Parameters integer expression In most cases it is more convenient to supply a string
expression as the first argument. If you do supply an integer-expression, it is
the connection property ID. You can determine this using the
PROPERTY_NUMBER function.

string-expression The connection property name. Either the property ID


or the property name must be specified.
$ For a list of connection properties, see "Connection-level properties" on
page 1060.

integer-expression The connection ID of the current database


connection. The current connection is used if this argument is omitted.
Examples The following statement returns the number of prepared statements being
maintained.
SELECT connection_property( ’PrepStmt’ )
Usage The current connection is used if the second argument is omitted.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "Connection-level properties" on page 1060
"PROPERTY_NUMBER function" on page 346

309
Alphabetical list of functions

CONVERT function [Data type conversion]


Function Returns an expression converted to a supplied data type.
Syntax CONVERT ( data type, expression [ , format-style ] )
Parameters data type The data type to which the expression will be converted.

expression The expression to be converted.

format-style For converting strings to date or time data types and vice
versa, the format-style is a style code number that describes the date format
string to be used. The values of the format-style argument have the following
meanings:

Without With century Output


century (yy) (yyyy)
- 0 or 100 mmm dd yyyy hh:nn:ss:sss AM (or PM)
1 101 mm/dd/yy[yy]
2 102 [yy]yy.mm.dd
3 103 dd/mm/yy[yy]
4 104 dd.mm.yy[yy]
5 105 dd-mm-yy[yy]
6 106 dd mmm yy[yy]
7 107 mmm dd, yy[yy]
8 108 hh:nn:ss
- 9 or 109 mmm dd yyyy hh:nn:ss:sssAM (or PM)
10 110 mm-dd-yy[yy]
11 111 [yy]yy/mm/dd
12 112 [yy]yymmdd
13 113 dd mmm yyy hh:nn:ss:sss (24 hour clock,
Europe default + milliseconds, 4-digit year )
14 114 hh:nn:ss:sss (24 hour clock)
20 120 yyyy-mm-dd hh:nn:ss:sss (24-hour clock,
ODBC canonical, 4-digit year)
21 121 yyyy-mm-dd hh:nn:ss.sss (24 hour clock,
ODBC canonical with milliseconds, 4-digit
year )

If no format-style argument is provided, Style Code 0 is used.

310
Chapter 8 SQL Functions

Examples The following statements illustrate the use of format styles:


SELECT CONVERT( CHAR( 20 ), order_date, 104 )
FROM sales_order

order_date
16.03.1993
20.03.1993
23.03.1993
25.03.1993
...

SELECT CONVERT( CHAR( 20 ), order_date, 7 )


FROM sales_order

order_date
mar 16, 93
mar 20, 93
mar 23, 93
mar 25, 93
...

The following statement illustrates conversion to an integer, and returns the


value 5:
SELECT CONVERT( integer, 5.2 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "CAST function" on page 306

COS function [Numeric]


Function Returns the cosine of a number.
Syntax COS ( numeric-expression )
Parameters numeric expression The angle, in radians.
Examples The statement
SELECT COS( 0.52 )

311
Alphabetical list of functions

returns the value 0.86781.


Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "ACOS function" on page 301
"COT function" on page 312
"SIN function" on page 353
"TAN function" on page 358

COT function [Numeric]


Function Returns the cotangent of a number.
Syntax COT ( numeric-expression )
Parameters integer expression The angle, in radians.
Examples The following statement returns the value 1.74653.
SELECT COT( 0.52 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "COS function" on page 311
"SIN function" on page 353
"TAN function" on page 358

COUNT function [Aggregate]


Function Counts the number of rows in a group depending on the specified
parameters.
Syntax COUNT ( * | expression | DISTINCT column-name )
Parameters * Returns the number of rows in each group.

expression Returns the number of rows in each group where the


expression is not the null value.

DISTINCT column-name Returns the number of different values in the


column with name column-name. Rows where the value is the NULL value
are not included in the count.
Example The following statement returns each unique city, and the number of rows
with that city value:

312
Chapter 8 SQL Functions

SELECT city , Count(*)


FROM employee
GROUP BY city
Standards and ♦ SQL/92 SQL/92 compatible.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "AVG function " on page 304
"SUM function" on page 358

DATALENGTH function [System]


Function Returns the length in bytes of the underlying storage for the result of an
expression.
Syntax DATALENGTH ( expression )
Parameters expression The expression is usually a column name. If the expression is
a string constant, it must be enclosed in quotes.
Usage The return values of DATALENGTH are as follows:

Data type DATALENGTH


SMALLINT 2
INTEGER 4
DOUBLE 8
CHAR Length of the data
BINARY Length of the data

Examples The following statement returns the value 27, the longest string in the
company_name column.
SELECT following MAX( DATALENGTH( company_name ) )
FROM customer
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

DATE function [Date and time]


Function Converts the expression into a date, and removes any hours, minutes or
seconds.
Syntax DATE ( expression )

313
Alphabetical list of functions

Parameters expression The value to be converted to date format. The expression is


usually a string.
Examples The following statement returns the value 1999-01-02 as a date.
SELECT DATE( ’1999-01-02 21:20:53’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

DATEADD function [Date and time]


Function Returns the date produced by adding a number of the date parts to a date.
Syntax DATEADD ( date-part, numeric-expression, date-expression )
Parameters date-part The date-part to be added to the date..
$ For a complete listing of allowed date-parts, see "Date parts" on
page 294.

numeric-expression The number of date-parts to be added to the date.


The numeric_expression can be any numeric type; the value is truncated to
an integer.

date-expression The date to be modified.


Examples The following statement returns the value: 1995-11-02 00:00:00.000.
SELECT dateadd( month, 102, ’1987/05/02’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

DATEDIFF function [Date and time]


Function Returns the interval between two dates.
Syntax DATEDIFF ( date-part, date-expression1, date-expression2 )
Parameters date-part Specifies the date-part in which the interval is to be measured.
$ For a complete listing of allowed date-parts, see "Date parts" on
page 294.

314
Chapter 8 SQL Functions

date-expression1 The starting date for the interval. This value is


subtracted from date-expression2 to return the number of date-parts between
the two arguments.

date-expression2 The ending date for the interval. Date-expression1 is


subtracted from this value to return the number of date-parts between the
two arguments.
Examples The following statement returns 1:
SELECT datediff( hour, ’4:00AM’, ’5:50AM’ )
The following statement returns 102:
SELECT datediff( month, ’1987/05/02’, ’1995/11/15’ )
.The following statement returns 0:
SELECT datediff( day, ’00:00’, ’23:59’ )
The following statement returns 4:
SELECT datediff( day, ’1999/07/19 00:00’, ’1999/07/23
23:59’ )
The following statement returns 0:
SELECT datediff( month, ’1999/07/19’, ’1999/07/23’ )
The following statement returns 1:
SELECT datediff( month, ’1999/07/19’, ’1999/08/23’ )
Usage This function calculates the number of date parts between two specified
dates. The result is a signed integer value equal to (date2 - date1), in date
parts.
DATEDIFF results are truncated, not rounded, when the result is not an even
multiple of the date part.
When you use day as the date part, DATEDIFF returns the number of
midnights between the two times specified, including the second date but not
the first.
When you use month as the date part, DATEDIFF returns the number of
first-of-the-months between two dates, including the second date but not the
first.
When you use week as the date part, DATEDIFF returns the number of
Sundays between the two dates, including the second date but not the first.
For the smaller time units there are overflow values:
♦ milliseconds 24 days
♦ seconds 68 years

315
Alphabetical list of functions

♦ minutes 4083 years


♦ others No overflow limit
The function returns an overflow error if you exceed these limits.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

DATEFORMAT function [Date and time]


Function Returns a string representing a date-expression in the specified format.
Syntax DATEFORMAT ( datetime-expression, string-expression )
Parameters datetime-expression The datetime to be converted.

string-expression The format of the converted date.


$ For information on date format descriptions, see "DATE_FORMAT
option" on page 169.
Examples The following statement returns the value Jan 01, 1989.
SELECT DATEFORMAT( ’1989-01-01’, ’Mmm dd, yyyy’ )
Usage Any allowable date format can be used for the string-expression.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

Year 2000 compliance


It is possible to use the DATEFORMAT function to produce a string with
the year value represented by only two digits. This can cause problems
with year 2000 compliance even though no error has occurred.
$ For more information on year 2000 compliance, please see "Year
2000 compliance" on page 285.

See also "DATE_FORMAT option" on page 169

DATENAME function [Date and time]


Function Returns the name of the specified part (such as the month "June") of a
datetime value, as a character string.
Syntax DATENAME ( date-part, date-expression )

316
Chapter 8 SQL Functions

Parameters date-part The date-part to be named.


$ For a complete listing of allowed date-parts, see "Date parts" on
page 294.

date-expression The date for which the date-part name is to be returned.


The date must contain the requested date-part.
Example The following statement returns the value May.
SELECT datename( month , ’1987/05/02’ )
Usage DATENAME returns a string, even if the result is numeric, such as 23 for
the day.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

DATEPART function [Date and time]


Function Returns the value of part of a datetime value.
Syntax DATEPART ( date-part, date-expression )
Parameters date-part The date-part to be returned.
$ For a complete listing of allowed date-parts, see "Date parts" on
page 294.

date-expression The date for which the part is to be returned. The date
must contain the date-part field.
Example The following statement returns the value 5.
SELECT datepart( month , ’1987/05/02’ )
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

DATETIME function [Date and time]


Function Converts an expression into a timestamp.
Syntax DATETIME ( expression )
Parameters expression The expression to be converted. It is generally a string.
Attempts to convert numerical values return an error.

317
Alphabetical list of functions

Examples The statement


SELECT DATETIME( ’1998-09-09 12:12:12.000’ )
returns a timestamp with value 1998-09-09 12:12:12.000.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

DAY function [Date and time]


Function Returns an integer from 1 to 31 corresponding to the day of the month of a
date.
Syntax DAY ( date-expression )
Parameters date-expression The date.
Examples The following statement returns the value 12.
SELECT DAY( ’2001-09-12’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

DAYNAME function [Date and time]


Function Returns the name of the day of the week from the a date.
Syntax DAYNAME( date-expression )
Parameters date-expression The date.
Example The following statement returns the value Saturday.
SELECT DAYNAME ( ’1987/05/02’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

DAYS function [Date and time]


Function Returns the number of days from an arbitrary date to a specified date,
between two specified times or adds the specified integer-expression days to
a time.

318
Chapter 8 SQL Functions

Syntax DAYS ( datetime-expression )


| ( datetime-expression, datetime-expression )
| ( datetime-expression, integer-expression )
Parameters datetime-expression A date and time.

integer-expression The number of days to be added to the datetime-


expression. If the integer-expression is negative, the appropriate number of
days are subtracted from the datetime. If you supply an integer expression,
the datetime-expression must be explicitly cast as a date.
$ For information on casting data types, see "CAST function" on
page 306
DAYS ignores hours, minutes, and seconds.
Examples The following statement returns the integer value 729889.
SELECT DAYS( ’1998-07-13 06:07:12’ )
The following statement returns the integer value -366, which is the
difference between the two dates.
SELECT DAYS( ’1998-07-13 06:07:12’,
’1997-07-12 10:07:12’ )
The following statement returns the timestamp value 1998-07-13:
SELECT DAYS( CAST(’1998-07-13’ AS DATE ), 366 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

DB_ID function [System]


Function Returns the database ID number.
Syntax DB_ID ( [ database-name ] )
Parameters database-name A string containing the database name. If no database-
name is supplied, the ID number of the current database is returned.
Examples The following statement returns the value 0 if asademo is the only running
database:
SELECT DB_ID( ’asademo’ )

The following statement returns the value 0 if executed against the only
running database.
SELECT DB_ID()

319
Alphabetical list of functions

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

DB_NAME function [System]


Function Returns the name of a database with a given ID number.
Syntax DB_NAME ( [ database-id ] )
Parameters database-id The ID of the database. The database-id must be a numeric
expression.
Examples The statement returns the database name asademo, when executed against
the sample database as the sole database on the server.
SELECT DB_NAME( 0 )
Usage If no database ID is supplied, the name of the current database is returned.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

DB_PROPERTY function [System]


Function Returns the value of the given property.
Syntax DB_PROPERTY ( { property_id | property_name }
... [, { database_id | database_name } ] )
Parameters property_id The database property ID.

property_name The database property name.

database_id The database ID number, as returned by DB_ID. Typically,


the database name is used.

database_name The name of the database, as returned by DB_NAME.


Example The following statement returns the page size of the current database, in
bytes.
SELECT DB_PROPERTY( ’PAGESIZE’ )
Usage Returns a string. The current database is used if the second argument is
omitted.
Standards and ♦ SQL/92 Vendor extension.
compatibility

320
Chapter 8 SQL Functions

♦ Sybase Not supported by Adaptive Server Enterprise.


See also "DB_ID function" on page 319
"DB_NAME function " on page 320
"Database-level properties" on page 1070

DEGREES function [Numeric]


Function Converts a number from radians to degrees.
Syntax DEGREES (numeric-expression )
Parameters numeric-expression An angle in radians.
Examples The following statement returns the value 29.793805.
SELECT DEGREES( 0.52 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

DIFFERENCE function [String]


Function Returns the difference in the SOUNDEX values between the two string
expressions.
Syntax DIFFERENCE ( string-expression-1, string-expression-2 )
Parameters string-expression-1 The first SOUNDEX argument.

string-expression-2 The second SOUNDEX argument.


Examples The following statement returns the value 3.
SELECT DIFFERENCE( ’test’, ’chest’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "SOUNDEX function" on page 354

DOW function [Date and time]


Function Returns a number from 1 to 7 representing the day of the week of a date,
with Sunday=1, Monday=2, and so on.
Syntax DOW ( date-expression )

321
Alphabetical list of functions

Parameters date-expression The date.


Examples The following statement returns the value 5.
SELECT DOW( ’1998-07-09’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

ESTIMATE function [Miscellaneous]


Function Provides selectivity estimates for the query optimizer, based on specified
parameters.
Syntax ESTIMATE ( column-name [ , value [, relation-string ] ] )
Parameters column-name The column used in the estimate.

value The value to which the column is compared.

relation-string The comparison operator used for the comparison,


enclosed in single quotes; the default is ’=’.
Examples The following statement returns the number of emp_id values estimated to be
greater than 200. The precise value depends on the actions you have carried
out on the database.
SELECT DISTINCT ESTIMATE( emp_id, 200, ’>’ )
FROM employee
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
See also "Query Optimization" on page 813 of the book ASA User’s Guide

ESTIMATE_SOURCE function [Miscellaneous]


Function Provides the source for selectivity estimates used by the query optimizer.
Syntax ESTIMATE_SOURCE ( column-name [, value [ , relation-string ] ]
Parameters column-name The name of the column that is being investigated.

value The value to which the column is compared.

relation-string The comparison operator used for the comparison,


enclosed in single quotes; the default is ’=’.

322
Chapter 8 SQL Functions

Return value ESTIMATE_SOURCE returns one of the following strings:


♦ Column
♦ Guess
♦ Index
♦ Value
Examples The following statement returns the value Index.
SELECT DISTINCT ESTIMATE_SOURCE( emp_id, 200, ’>’ )
FROM employee
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "Query Optimization" on page 813 of the book ASA User’s Guide

EVENT_CONDITION function [System]


Function To specify when an event handler is triggered.
Syntax EVENT_CONDITION ( condition-name )
Parameters condition-name The condition triggering the event. The possible values
are preset in the database, and are case insensitive. Each condition is valid
only for certain event types. The conditions and the events for which they are
valid are as follows:

Condition name Units Valid for… Comment


DBSize Megabytes GrowDB
LogSize Megabytes GrowLog
TempSize Megabytes GrowTemp
DBFreePercent N/A DBDiskSpace
LogFreePercent N/A LogDiskSpace
TempFreePercent N/A TempDiskSpace
DBFreeSpace Megabytes DBDiskSpace
LogFreeSpace Megabytes LogDiskSpace

323
Alphabetical list of functions

Condition name Units Valid for… Comment


TempFreeSpace Megabytes TempDiskSpace
IdleTime Seconds ServerIdle
Interval Seconds All Time since handler last
executed
RemainingValues Integer GlobalAutoincrement The number of
remaining values.
ErrorNumber N/A RAISERROR

Examples The following event definition uses the event_condition function:


create event LogNotifier
type LogDiskSpace
where event_condition( ’LogDiskSpacePercentFree’ ) < 50
handler
begin
message ’LogNotifier message’
end
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "CREATE EVENT statement" on page 423

EVENT_CONDITION_NAME function [System]


Function Can be used to list the possible parameters for EVENT_CONDITION.
Syntax EVENT_CONDITION_NAME ( integer )
Parameters integer Must be greater than or equal to zero.
Usage You can use EVENT_CONDITION_NAME to obtain a list of all
EVENT_CONDITION arguments by looping over integers until the function
returns NULL.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "CREATE EVENT statement" on page 423

EVENT_PARAMETER function [System]


Function Provides context information for event handlers.

324
Chapter 8 SQL Functions

Syntax EVENT_PARAMETER ( context-name )


context-name:
’ConnectionID’
| ’User’
| ’EventName’
| ’Executions’
| ’TableName’
| condition-name
Parameters context-name One of the preset strings. The strings are case insensitive,
and carry the following information:
♦ ConnectionId The connection ID, as returned by
connection_property( ’id’ )
♦ User The user ID for the user that caused the event to be triggered.
♦ EventName The name of the event that has been triggered.
♦ Executions The number of times the event handler has been executed.
♦ TableName The name of the table, for use with RemainingValues.
In addition, you can access any of the valid condition-name arguments to the
EVENT_CONDITION function from the EVENT_PARAMETER function.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "EVENT_CONDITION function" on page 323
"CREATE EVENT statement" on page 423

EXP function [Numeric]


Function Returns the exponential function, e to the power of a number.
Syntax EXP ( numeric-expression )
Parameters numeric-expression The exponent.
Examples The statement returns the value 3269017.372.
SELECT EXP( 15 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

325
Alphabetical list of functions

EXPERIENCE_ESTIMATE function [Miscellaneous]


Function This function is the same as the ESTIMATE function, except that it always
looks in the frequency table.
Syntax EXPERIENCE_ESTIMATE ( column-name [ , value [, relation-string ] ] )
Parameters column-name The name of the column that is being investigated.

value The value to which the column is compared.

relation-string The comparison operator used for the comparison,


enclosed in single quotes; the default is ’=’.
Examples The following statement returns NULL.
SELECT DISTINCT EXPERIENCE_ESTIMATE( emp_id, 200, ’>’ )
FROM employee
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
See also "ESTIMATE function" on page 322

FLOOR function [Numeric]


Function Returns the floor of (largest integer not greater than) a number.
Syntax FLOOR ( numeric-expression )
Parameters numeric- expression The number, usually a float.
Value FLOOR (Value)
Examples
123 123
123.45 123
-123.45 -124

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "CEILING function" on page 306

GETDATE function [Date and time]


Function Returns the current date and time.
Syntax GETDATE ()

326
Chapter 8 SQL Functions

Examples The following statement returns the system date and time.
SELECT GETDATE( )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

HEXTOINT function [Data type conversion]


Function Returns the decimal integer equivalent of a hexadecimal string.
Syntax HEXTOINT ( hexadecimal-string )
Parameters hexadecimal-string The string to be converted to an integer.
Examples The following statement returns the value 420.
SELECT HEXTOINT ( ’1A4’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "INTTOHEX function" on page 330

HOUR function [Date and time]


Function Returns a number from 0 to 23 corresponding to the hour component of a
datetime.
Syntax HOUR ( datetime-expression )
Parameters datetime-expression The datetime.
Examples The following statement returns the value 21:
SELECT HOUR( ’1998-07-09 21:12:13’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

HOURS function [Date and time]


Function Returns the number of hours since an arbitrary date and time, between two
specified times or adds the specified integer-expression amount of hours to a
time.

327
Alphabetical list of functions

Syntax HOURS ( datetime-expression


| datetime-expression, datetime-expression
| datetime-expression, integer-expression )
Parameters datetime-expression A date and time.

integer-expression The number of hours to be added to the datetime-


expression. If integer-expression is negative, the appropriate number of
hours are subtracted from the datetime. If you supply an integer expression,
the datetime-expression must be explicitly cast as a datetime data type.
$ For information on casting data types, see "CAST function" on
page 306.
Examples The following statement returns the value 17517342:
SELECT HOURS( ’1998-07-13 06:07:12’ )
The following statement returns the value 4, to signify the difference
between the two times:
SELECT HOURS( ’1999-07-13 06:07:12’,
’1999-07-13 10:07:12’ )
The following statement returns the datetime value 1999-05-13 02:05:07.
SELECT HOURS( CAST( ’1999-05-12 21:05:07’ AS DATETIME ),
5)
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

IFNULL function [Miscellaneous]


Function If the first expression is the NULL value, then the value of the second
expression is returned. If the first expression is not NULL, the value of the
third expression is returned. If the first expression is not NULL and there is
no third expression, NULL is returned.
Syntax IFNULL ( expression-1, expression-2 [ , expression-3 ] )
Parameters expression-1 The expression to be evaluated. Its value determines
whether expression-2 or expression-3 is returned.

expression-2 The return value if expression-1 is NULL.

expression-3 The return value if expression-1 is not NULL.


Examples The following statement returns the value –66:

328
Chapter 8 SQL Functions

SELECT IFNULL( NULL, -66 )


The following statement: returns NULL, because the first expression is not
NULL and there is no third expression:
SELECT IFNULL( -66, -66 )
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

INDEX_ESTIMATE function [Miscellaneous]


Function This function is the same as the ESTIMATE function, except that it always
looks only in an index.
Syntax INDEX_ESTIMATE( column-name, number [ , relation-string ] )
Parameters column-name The name of the column that is used in the estimate.

number If number is specified, the function returns as a REAL the


percentage estimate that the query optimizer uses.

relation-string The relation-string must be a comparison operator


enclosed in single quotes; the default is ’=’.
Examples The following statement returns the value 81.304607.
SELECT DISTINCT ESTIMATE( emp_id, 200, ’>’ )
FROM employee
Standards and ♦ SQL/92
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.

INSERTSTR function [String]


Function Inserts a string into another string at a specified position.
Syntax INSERTSTR ( integer-expression, string-expression-1, string-expression-2 )
Parameters integer expression The position after which the string is to be inserted.
Use zero to insert a string at the beginning.

string-expression-1 The string into which the other string is to be


inserted.

string-expression-2 The string to be inserted.


Examples The following statement returns the value backoffice.

329
Alphabetical list of functions

SELECT INSERTSTR( 0, ’office ’, ’back’ )


Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
See also "STUFF function" on page 356

INTTOHEX function [Data type conversion]


Function Returns a string containing the hexadecimal equivalent of an integer.
Syntax INTTOHEX ( integer-expression )
Parameters integer expression The integer to be converted to hexadecimal.
Examples The following statement returns the value 9c:
SELECT INTTOHEX( 156 )
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "HEXTOINT function" on page 327

ISNULL function [Miscellaneous]


Function Returns the first non-NULL expression in the parameter list.
Syntax ISNULL ( expression, expression [ , ... ] )
Parameters expression An expression to be tested against NULL.
At least two expressions must be passed into the function.
Examples The following statement returns the value -66.
SELECT ISNULL( NULL ,-66, 55, 45, NULL, 16 )
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise, except that
Adaptive Server Enterprise allows only two expressions.
See also "COALESCE function" on page 308

LCASE function [String]


Function Converts all characters in a string to lower case.

330
Chapter 8 SQL Functions

Syntax LCASE ( string-expression )


Parameters string-expression The string to be converted to lower case.
Examples The following statement returns the value lower case.
SELECT LCASE( ’LOWER CasE’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase LCASE is not supported in Adaptive Server Enterprise; you
can use LOWER to get the same functionality.
See also "LOWER function" on page 334
"UCASE function" on page 361
"UPPER function" on page 362

LEFT function [String]


Function Returns a number of characters from the beginning of a string.
Syntax LEFT ( string-expression, numeric-expression )
Parameters string-expression The string.

integer expression The number of characters to return.


Examples The following statement returns the value choco.
SELECT LEFT( ’chocolate’, 5 )
Usage If the string contains multi-byte characters, and the proper collation is being
used, the number of bytes returned may be greater than the specified number
of characters.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "RIGHT function" on page 350
"International Languages and Character Sets" on page 279 of the book ASA
User’s Guide

LENGTH function [String]


Function Returns the number of characters in the specified string.
Syntax LENGTH ( string-expression )

331
Alphabetical list of functions

Parameters string-expression The string.


Examples The following statement returns the value 9.
SELECT LENGTH( ’chocolate’ )
Usage If the string contains multi-byte characters, and the proper collation is being
used, LENGTH returns the number of characters, not the number of bytes. If
string is of BINARY data type, the LENGTH function behaves as
BYTE_LENGTH.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "BYTE_LENGTH function" on page 304
"International Languages and Character Sets" on page 279 of the book ASA
User’s Guide

LIST function [Aggregate]


Function Returns a comma-separated list of values
Syntax LIST ( { string-expression | DISTINCT column-name } [ , delimiter-string ] )
Parameters string-expression A string, usually a column name. For each row, the
expression’s value is added to the comma-separated result.

DISTINCT column-name The name of a column that you are using in the
query. For each unique value of that column, the value is added to the
comma-separated result.

delimiter-string This optional argument specifies a delimiter string for the


list items. The default setting is a comma. If a value of NULL, or an empty
string is supplied, there is no delimiter. The delimiter-string should be a
constant.
Examples The following statement returns the value 48 Kennedy Court,54 School
Street.
SELECT LIST( street ) FROM employee
WHERE emp_fname = ’Thomas’
Usage NULL values are not added to the list. Returns NULL for a group containing
no rows.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.

332
Chapter 8 SQL Functions

LOCATE function [String]


Function Returns the position of one string within another.
Syntax LOCATE ( string-expression-1, string-expression-2 [, integer-expression ] )
Parameters string-expression-1 The string to be searched.

string-expression-2 The string to be searched for. This string is limited


to 255 bytes.

integer-expression The character position in the string to begin the


search. The first character is position 1.
Examples The following statement returns the value 8.
SELECT LOCATE( 'office party this week – rsvp as soon as
possible', 'party', 2 )
Usage If integer-expression is specified, the search starts at that offset into the
string.
The first string can be a long string (longer than 255 bytes), but the second is
limited to 255 bytes. If a long string is given as the second argument, the
function returns a NULL value. If the string is not found, 0 is returned.
Searching for a zero-length string will return 1. If any of the arguments are
NULL, the result is NULL.
If multi-byte characters are used, with the appropriate collation, then the
starting position and the return value may be different from the byte
positions.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

LOG function [Numeric]


Function Returns the natural logarithm of a number.
Syntax LOG ( numeric-expression )
Parameters integer expression The number.
Examples The following statement returns the value 3.912023.
SELECT LOG( 50 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

333
Alphabetical list of functions

See also "LOG10 function" on page 334

LOG10 function [Numeric]


Function Returns the base 10 logarithm of a number.
Syntax LOG10 ( numeric-expression )
Parameters integer expression The number.
Examples The following statement returns the value 1.698970.
SELECT LOG10( 50 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "LOG function" on page 333

LOWER function [String]


Function Converts all characters in a string to lower case.
Syntax LOWER ( string-expression )
Parameters string-expression The string to be converted.
Examples The following statement returns the value lower case.
SELECT LOWER( ’LOWER CasE’ )
Standards and ♦ SQL/92 SQL/92 compatible.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "LCASE function" on page 330
"UCASE function" on page 361
"UPPER function" on page 362

LTRIM function [String]


Function Trims leading blanks from a string.
Syntax LTRIM ( string-expression )
Parameters string-expression The string to be trimmed.

334
Chapter 8 SQL Functions

Examples The following statement returns the value Test Message with all leading
blanks removed.
SELECT LTRIM( ’ Test Message’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "RTRIM function" on page 351
"TRIM function" on page 360

MAX function [Aggregate]


Function Returns the maximum expression value found in each group of rows.
Syntax MAX ( expression
| DISTINCT column name )
Parameters expression The expression for which the maximum value is to be
calculated. This is commonly a column name.

DISTINCT column-name Returns the same as MAX( expression ), and is


included for completeness.
Examples The following statement returns the value 138948.000, representing the
maximum salary in the employee table.
SELECT MAX( salary )
FROM employee
Usage Rows where expression is NULL are ignored. Returns NULL for a group
containing no rows.
Standards and ♦ SQL/92 SQL/92 compatible.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "MIN function" on page 335

MIN function [Aggregate]


Function Returns the minimum expression value found in each group of rows.
Syntax MIN ( expression
| DISTINCT column name )
Parameters expression The expression for which the minimum value is to be
calculated. This is commonly a column name.

335
Alphabetical list of functions

DISTINCT column-name Returns the same as MIN( expression ), and is


included for completeness.
Examples The following statement returns the value 24903.000, representing the
minimum salary in the employee table.
SELECT MIN( salary )
FROM employee
Usage Rows where expression is NULL are ignored. Returns NULL for a group
containing no rows.
Standards and ♦ SQL/92 SQL/92 compatible.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "MAX function" on page 335

MINUTE function [Date and time]


Function Returns a number from 0 to 59 corresponding to the minute component of a
datetime value.
Syntax MINUTE ( datetime-expression )
Parameters datetime-expression The datetime value.
Examples The following statement returns the value 22.
SELECT MINUTE( ’1998-07-13 12:22:34’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

MINUTES function [Date and time]


Function Returns the number of minutes since an arbitrary date and time, between two
specified times or adds the specified integer-expression amount of minutes to
a time.
Syntax MINUTES ( datetime-expression
| datetime-expression, datetime-expression
| datetime-expression, integer-expression )
Parameters datetime-expression A date and time.

336
Chapter 8 SQL Functions

integer-expression The number of minutes to be added to the datetime-


expression. If integer-expression is negative, the appropriate number of
minutes are subtracted from the datetime value. If you supply an integer
expression, the datetime-expression must be explicitly cast as a datetime data
type.
$ For information on casting data types, see "CAST function" on
page 306.
Examples The following statement returns the value 1051040527:
SELECT MINUTES( ’1998-07-13 06:07:12’ )
The following statement returns the value 240, to signify the difference
between the two times:
SELECT MINUTES( ’1999-07-13 06:07:12’,
’1999-07-13 10:07:12’ )
The following statement returns the datetime value 1999-05-12 21:10:07.
SELECT MINUTES( CAST( ’1999-05-12 21:05:07’
AS DATETIME ), 5)
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

MOD function [Numeric]


Function Returns the remainder when one whole number is divided by another.
Syntax MOD ( dividend, divisor )
Parameters dividend The dividend, or numerator of the division.

divisor The divisor, or denominator of the division.


Examples The following statement returns the value 2.
SELECT MOD( 5, 3 )
Usage Division involving a negative dividend will give a negative or zero result.
The sign of the divisor has no effect.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise. The % operator
is used as a modulo operator in Adaptive Server Enterprise.
See also "REMAINDER function" on page 348

337
Alphabetical list of functions

MONTH function [Date and time]


Function Returns a number from 1 to 12 corresponding to the month of the given date.
Syntax MONTH ( date-expression )
Parameters date-expression A datetime value.
Examples The following statement returns the value 7.
SELECT MONTH( ’1998-07-13’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

MONTHNAME function [Date and time]


Function Returns the name of the month from a date.
Syntax MONTHNAME ( date-expression )
Parameters date-expression The datetime value.
Examples The following statement returns the value September.
SELECT MONTHNAME( ’1998-09-05’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

MONTHS function [Date and time]


Function Returns the number of months since an arbitrary date and time, between two
specified times, or adds the specified integer-expression amount of months to
a datetime.
Syntax MONTHS ( datetime-expression
| datetime-expression, datetime-expression
| datetime-expression, integer-expression )
Parameters datetime-expression A date and time.

integer-expression The number of months to be added to the datetime-


expression. If integer-expression is negative, the appropriate number of
months are subtracted from the datetime value. If you supply an integer
expression, the datetime-expression must be explicitly cast as a datetime data
type.

338
Chapter 8 SQL Functions

$ For information on casting data types, see "CAST function" on


page 306.
Examples The following statement returns the value 23982:
SELECT MONTHS( ’1998-07-13 06:07:12’ )
The following statement returns the value 2, to signify the difference
between the two dates:
SELECT MONTHS( ’1999-07-13 06:07:12’,
’1999-09-13 10:07:12’ )
The following statement returns the datetime value 1999-10-12 21:05:07.
SELECT MONTHS( CAST( ’1999-05-12 21:05:07’
AS DATETIME ), 5)
Usage The value of MONTHS is calculated from the number of first days of the
month between the two dates.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

NEXT_CONNECTION function [System]


Function Returns an identifying number for a connection.
Syntax NEXT_CONNECTION ( [ connection-id ] [, database-id ] )
Parameters connection-id An integer, usually returned from a previous call to
NEXT_CONNECTION. If connection-id is NULL, NEXT_CONNECTION
returns the first connection ID.

database-id An integer representing one of the databases on the current


server. If you supply no database-id, the current database is used. If you
supply NULL, then NEXT_CONNECTION returns the next connection
regardless of database.
Examples The following statement returns an identifier for the first connection on the
current database. The identifier is an integer value like 569851433.
SELECT NEXT_CONNECTION( NULL )
The following statement returns a value like 1661140050.
SELECT NEXT_CONNECTION( 569851433 )
The following call returns the connection after connection-id on the current
database.
NEXT_CONNECTION( connection-id )

339
Alphabetical list of functions

The following call returns the the connection after connection-id (regardless
of database).
NEXT_CONNECTION( connection-id, NULL )
The following call returns the connection after connection-id on the specified
database.
NEXT_CONNECTION( connection-id, database-id )
The following call returns the first connection (regardless of database).
NEXT_CONNECTION(NULL, NULL)
The following call returns the first connection on the specified database.
NEXT_CONNECTION( NULL, database-id )
Usage NEXT_CONNECTION can be used to enumerate the connections to a
database. To get the first connection pass NULL; to get each subsequent
connection, pass the previous return value. The function returns NULL when
there are no more connections.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

NEXT_DATABASE function [System]


Function Returns an identifying number for a database.
Syntax NEXT_DATABASE ( { NULL | database-id } )
Parameters database-id An integer that specifies the ID number of the database.
Examples The following statement returns the value 0, the first database value.
SELECT NEXT_DATABASE( NULL )
The following statement returns NULL, indicating that there are no more
databases on the server.
SELECT NEXT_DATABASE( 0 )
Usage NEXT_DATABASE can be used to enumerate the databases running on a
database server. To get the first database pass NULL; to get each subsequent
database, pass the previous return value. The function returns NULL when
there are no more databases.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

340
Chapter 8 SQL Functions

NOW function [Date and time]


Function Returns the current date and time. This is the historical syntax for
CURRENT TIMESTAMP.
Syntax NOW ( * )
Examples The following statement returns the current date and time.
SELECT NOW(*)
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

NULLIF function [Miscellaneous]


Function To provide an abbreviated CASE expression by comparing expressions.
Syntax NULLIF ( expression-1, expression-2 )
Parameters expression-1 An expression to be compared.

expression-2 An expression to be compared.


Examples The following statement returns a:
SELECT NULLIF( ’a’, ’b’ )
The following statement returns NULL.
SELECT NULLIF( ’a’, ’a’ )
Usage NULLIF compares the values of the two expressions.
If the first expression equals the second expression, NULLIF returns NULL.
If the first expression does not equal the second expression, or if the second
expression is NULL, NULLIF returns the first expression.
The NULLIF function provides a short way to write some CASE
expressions.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "CASE expressions" on page 221

341
Alphabetical list of functions

NUMBER function [Miscellaneous]


Function Generates numbers starting at 1 for each successive row in the results of the
query.

Deprecated feature
The NUMBER function is deprecated. It will not be supported in future
versions of Adaptive Server Anywhere.

Syntax NUMBER ( * )
Examples The following statement returns a numbered list.
SELECT NUMBER( * )
FROM department
WHERE dept_id > 5
Usage The NUMBER(*) function can be used to generate primary keys when using
the INSERT from SELECT statement (see "INSERT statement" on
page 540), although using AUTOINCREMENT is a preferred mechanism for
generating sequential primary keys.
$ For information on AUTOINCREMENT, see "CREATE TABLE
statement" on page 453.
You should not use NUMBER( * ) anywhere but in a select-list. If you do
use NUMBER( * ) rather than the preferred AUTOINCREMENT, you
should check your results carefully, as the behavior is not reliable in several
circumstances. For example, including the function in a WHERE clause or a
HAVING clause produces unpredictable results, and you should not include
NUMBER( * ) in a UNION operation.
In Embedded SQL, care should be exercised when using a cursor that
references a query containing a NUMBER(*) function. In particular, this
function returns negative numbers when a database cursor is positioned using
relative to the end of the cursor (an absolute position with a negative offset).
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

PATINDEX function [String]


Function Returns an integer representing the starting position of the first occurrence of
a pattern in a string.
Syntax PATINDEX ( ’%pattern%’, string_expression )

342
Chapter 8 SQL Functions

Parameters pattern The pattern to be searched for. If the leading percent wild card is
omitted, PATINDEX returns one (1) if the pattern occurs at the beginning of
the string, and zero if not.
The pattern uses the same wild cards as the LIKE comparison. These are as
follows:

Wild card Matches


_ (underscore) Any one character
% (percent) Any string of zero or more characters
[] Any single character in the specified range or set
[^] Any single character not in the specified range or set

string-expression The string to be searched for the pattern.


Examples The following statement returns the value 2.
SELECT PATINDEX( ’%hoco%’, ’chocolate’ )
The following statement returns the value 11.
SELECT PATINDEX (’%4_5_’, ’0a1A 2a3A 4a5A’)
Usage PATINDEX returns the starting position of the first occurrence of the
pattern. If the pattern is not found, it returns zero (0).
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise, except that the
USING clause is not supported.
See also "LIKE conditions" on page 228
"LOCATE function" on page 333

PI function [Numeric]
Function Returns the numeric value PI.
Syntax PI ( * )
Examples The following statement returns the value 3.141592653....
SELECT PI( * )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase The PI() function is supported in Adaptive Server Enterprise,
but PI(*) is not.

343
Alphabetical list of functions

PLAN function [Miscellaneous]


Function Returns the optimization strategy of a SQL statement, as a string.
Syntax PLAN ( string-expression )
Parameters string-expression The SQL statement, which is commonly a SELECT
statement but which may also be an UPDATE or DELETE.
Examples The following statement returns a string containing the plan for executing the
query. This information can help with decisions about indexes to add or how
to structure your database for better performance.
SELECT PLAN( ’select * from department where dept_id >
100’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

POWER function [Numeric]


Function Calculates one number raised to the power of another.
Syntax POWER ( numeric-expression-1, numeric-expression-2 )
Parameters numeric-expression-1 The base.

numeric-expression-2 The exponent.


Examples The following statement returns the value 64.
SELECT Power( 2, 6 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

PROPERTY_DESCRIPTION function [System]


Function Returns a description of a property.
Syntax PROPERTY_DESCRIPTION ( { property-id | property-name } )
Parameters property-id An integer that is the property-number of the database
property. This number can be determined from the PROPERTY_NUMBER
function. The property-id is commonly used when looping through a set of
properties.

property-name A string giving the name of the database property.


344
Chapter 8 SQL Functions

Examples The following statement returns the description Number of index


insertions.
SELECT PROPERTY_DESCRIPTION( ’IndAdd’ )
Usage Each property has both a number and a name, but the number is subject to
change between releases, and should not be used as a reliable identifier for a
given property.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "Database Performance and Connection Properties" on page 1051

PROPERTY function [System]


Function Returns the value of the specified server-level property as a string.
Syntax PROPERTY ( { property-id | property-name } )
Parameters property-id An integer that is the property-number of the server-level
property. This number can be determined from the PROPERTY_NUMBER
function. The property-id is commonly used when looping through a set of
properties.

property-name A string giving the name of the database property.


Examples The following statement returns the name of the current database server:
SELECT PROPERTY( ’Name’ )
Usage Each property has both a number and a name, but the number is subject to
change between releases, and should not be used as a reliable identifier for a
given property.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "Server-level properties" on page 1065

PROPERTY_NAME function [System]


Function Returns the name of the property with the supplied property-number.
Syntax PROPERTY_NAME ( property-id )
Parameters property-id The property number of the database property.

345
Alphabetical list of functions

Examples The following statement returns the property associated with property
number 126. The actual property to which this refers changes from release to
release.
SELECT PROPERTY_NAME( 126 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "Database properties" on page 1060

PROPERTY_NUMBER function [System]


Function Returns the property number of the property with the supplied property-
name.
Syntax PROPERTY_NUMBER ( property-name )
Parameters property-name A property name.
Examples The following statement returns an integer value. The actual value changes
from release to release.
SELECT PROPERTY_NUMBER( ’PAGESIZE’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "Database properties" on page 1060

QUARTER function [Date and time]


Function Returns a number indicating the quarter of the year from the supplied date
expression.
Syntax QUARTER( date-expression )
Parameters date- expression The date.
Examples The following statement returns the value 2.
SELECT QUARTER ( ’1987/05/02’ )
Usage The quarters are as follows:

346
Chapter 8 SQL Functions

Quarter Period (inclusive)


1 January 1 to March 31
2 April 1 to June 30
3 July 1 to September 30
4 October 1 to December 31

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

RADIANS function [Numeric]


Function Converts a number from degrees to radians.
Syntax RADIANS ( numeric-expression )
Parameters numeric-expression A number, in degrees. This angle is converted to
radians.
Examples The following statement returns a value of approximately 0.5236.
SELECT RADIANS( 30 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

RAND function [Numeric]


Function Returns a random number in the interval 0 to 1, with an optional seed.
Syntax RAND ( [integer-expression] )
Parameters integer expression The optional seed used to create a random number.
This argument allows you to create repeatable random number sequences.
Examples The following statement returns a value of approximately 0.0554504.
SELECT RAND( 4 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

347
Alphabetical list of functions

REMAINDER function [Numeric]


Function Returns the remainder when one whole number is divided by another.
Syntax REMAINDER ( dividend, divisor )
Parameters dividend The dividend, or numerator of the division.

divisor The divisor, or denominator of the division.


Examples The following statement returns the value 2.
SELECT REMAINDER( 5, 3 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise. The % (modulo)
operator and the division operator can be used to produce a remainder.
See also "MOD function" on page 337

REPEAT function [String]


Function Concatenates a string a specified number of times.
Syntax REPEAT ( string-expression, integer-expression )
Parameters string-expression The string to be repeated.

integer-expression The number of times the string is to be repeated. If


integer-expression is negative, an empty string is returned.
Examples The following statement returns the value repeatrepeatrepeat.
SELECT REPEAT( ’repeat’, 3 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise, but
REPLICATE provides the same capabilities.
See also "REPLICATE function" on page 349

REPLACE function [String]


Function Replaces all occurrences of a substring with another substring.
Syntax REPLACE ( original-string, search-string, replace-string )
Parameters If any argument is NULL, the function returns NULL.

348
Chapter 8 SQL Functions

original-string The string to be searched. This can be any length.

search-string The string to be searched for and replaced with replace-


string. This string is limited to 255 bytes. If search-string is an empty string,
the original string is returned unchanged.

replace-string The replacement string, which replaces search-string. This


can be any length. If replacement-string is an empty string, all occurrences
of search-string are deleted.
Examples The following statement returns the value xx.def.xx.ghi.
SELECT REPLACE( ’abc.def.abc.ghi’, ’abc’, ’xx’ )
The following statement generates a result set containing ALTER
PROCEDURE statements which, when executed, would repair stored
procedures that reference a table that has been renamed. (To be useful, the
table name would need to be unique.)
SELECT REPLACE(
replace(proc_defn,’OldTableName’,’NewTableName’),
’create procedure’,
’alter procedure’)
FROM SYS.SYSPROCEDURE
WHERE proc_defn LIKE ’%OldTableName%’
Use a separator other than the comma for the LIST function:
SELECT REPLACE( list( table_id ), ’,’, ’--’)
FROM SYS.SYSTABLE
WHERE table_id <= 5
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "SUBSTRING function" on page 357

REPLICATE function [String]


Function Concatenates a string a specified number of times.
Syntax REPLICATE ( string-expression, numeric-expression )
Parameters string-expression The string to be repeated.

integer-expression The number of times the string is to be repeated.


Examples The following statement returns the value repeatrepeatrepeat.
SELECT REPLICATE( ’repeat’, 3 )

349
Alphabetical list of functions

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "REPEAT function" on page 348

RIGHT function [String]


Function Returns the rightmost characters of a string.
Syntax RIGHT ( string-expression, numeric-expression )
Parameters string-expression The string to be left-truncated.

integer expression The number of characters at the end of the string to


return.
Examples The following statement returns the value olate.
SELECT RIGHT( ’chocolate’, 5 )
Usage If the string contains multi-byte characters, and the proper collation is being
used, the number of bytes returned may be greater than the specified number
of characters.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "LEFT function" on page 331
"International Languages and Character Sets" on page 279 of the book ASA
User’s Guide

ROUND function [Numeric]


Function Rounds the numeric-expression to the specified integer-expression amount of
places after the decimal point.
Syntax ROUND ( numeric-expression, integer-expression )
Parameters numeric-expression The number, passed into the function, to be
rounded..

integer-expression A positive integer specifies the number of significant


digits to the right of the decimal point at which to round. A negative
expression specifies the number of significant digits to the left of the decimal
point at which to round.
Examples The following statement returns the value 123.200.
350
Chapter 8 SQL Functions

SELECT ROUND( 123.234, 1 )


Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "TRUNCNUM function" on page 361

RTRIM function [String]


Function Returns a string with trailing blanks removed.
Syntax RTRIM ( string-expression )
Parameters string-expression The string to be trimmed.
Examples The following statement returns the string Test Message, with all trailing
blanks removed.
SELECT RTRIM( ’Test Message ’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "LTRIM function" on page 334

SECOND function [Date and time]


Function Returns a number from 0 to 59 corresponding to the second component of
the given datetime value.
Syntax SECOND ( datetime-expression )
Parameters datetime-expression The datetime value.
Examples The following statement returns the value 21.
SELECT SECOND( ’1998-07-13:21:21:25’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

SECONDS function [Date and time]


Function Returns the number of seconds since an arbitrary date and time, between two
times, or adds an integer amount of seconds to a time.

351
Alphabetical list of functions

Syntax SECONDS ( datetime-expression


| datetime-expression, datetime-expression
| datetime-expression, integer-expression )
Parameters datetime-expression A date and time.

integer-expression The number of seconds to be added to the datetime-


expression. If integer-expression is negative, the appropriate number of
minutes are subtracted from the datetime value. If you supply an integer
expression, the datetime-expression must be explicitly cast as a datetime data
type.
$ For information on casting data types, see "CAST function" on
page 306.
Examples The following statement returns the value 3600:
SELECT ( SECONDS( ’1998-07-13 06:07:12’ ) -
SECONDS( ’1998-07-13 05:07:12’ ))
The following statement returns the value 14400, to signify the difference
between the two times:
SELECT SECONDS( ’1999-07-13 06:07:12’,
’1999-07-13 10:07:12’ )
The following statement returns the datetime value 1999-05-12 21:05:12.
SELECT SECONDS( CAST( ’1999-05-12 21:05:07’
AS TIMESTAMP ), 5)
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

SIGN function [Numeric]


Function Returns the sign of a number.
Syntax SIGN ( numeric-expression )
Parameters numeric-expression The number for which the sign is to be returned.
Examples The following statement returns the value -1
SELECT SIGN( -550 )
Return value For negative numbers, SIGN returns -1.
For zero, SIGN returns 0.
For positive numbers, SIGN returns 1.

352
Chapter 8 SQL Functions

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

SIMILAR function [String]


Function Returns a number indicating the similarity between two strings.
Syntax SIMILAR ( string-expression-1, string-expression-2 )
Parameters string-expression-1 The first string to be compared.

string-expression-2 The second string to be compared.


Examples The following statement returns the value 75.
SELECT SIMILAR( ’toast’, ’coast’ )
This signifies that the two values are 75% similar.
Usage The function returns an integer between 0 and 100 representing the similarity
between the two strings. The result can be interpreted as the percentage of
characters matched between the two strings. A value of 100 indicates that the
two strings are identical.
This function can be used to correct a list of names (such as customers).
Some customers may have been added to the list more than once with
slightly different names. Join the table to itself and produce a report of all
similarities greater than 90 percent but less than 100 percent.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

SIN function [Numeric]


Function Returns the sine of a number.
Syntax SIN ( numeric-expression )
Parameters numeric-expression The angle, in radians.
Examples The following statement returns the value 0.496880.
SELECT SIN( 0.52 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

353
Alphabetical list of functions

See also "ASIN function" on page 302


"COS function" on page 311
"COT function" on page 312
"TAN function" on page 358

SOUNDEX function [String]


Function Returns a number representing the sound of a string.
Syntax SOUNDEX ( string-expression )
Parameters string-expression The string.
Examples The following statement returns two numbers, representing the sound of each
name. The SOUNDEX value for each argument is 3827.
SELECT SOUNDEX( ’Smith’ ), SOUNDEX( ’Smythe’ )
Usage The SOUNDEX function value for a string is based on the first letter and the
next three consonants other than H, Y, and W. Doubled letters are counted as
one letter. For example,
SOUNDEX( ’apples’ )
is based on the letters A, P, L and S.
Multi-byte characters are ignored by the SOUNDEX function.
Although it is not perfect, soundex will normally return the same number for
words that sound similar and that start with the same letter.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise, except that
Adaptive Server Enterprise returns a CHAR(4) result and Adaptive
Server Anywhere returns an integer.

SPACE function [Miscellaneous]


Function Returns a specified number of spaces.
Syntax SPACE ( integer-expression )
Parameters integer expression The number of spaces to return.
Examples The following statement returns a string containing 10 spaces.
SELECT SPACE( 10 )

354
Chapter 8 SQL Functions

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

SQRT function [Miscellaneous]


Function Returns the square root of a number.
Syntax SQRT ( numeric-expression )
Parameters numeric-expression The number for which the square root is to be
calculated.
Examples The following statement returns the value 3.
SELECT SQRT( 9 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

STR function [String]


Function Returns the string equivalent of a number.
Syntax STR ( numeric_expression [, length [, decimal ] ] )
Parameters numeric-expression Any approximate numeric (float, real, or double
precision) expression.

length The number of characters to be returned (including the decimal


point, all digits to the right and left of the decimal point, and blanks). The
default is 10.

decimal The number of decimal digits to be returned. The default is 0.


Examples The following statement returns a string of six spaces followed by 1235, for
a total of ten characters:
SELECT STR( 1234.56 )
The following statement returns the result 1234.6:
SELECT STR( 1234.56, 6, 1 )
Usage If the integer portion of the number cannot fit in the length specified, then the
result is a string of the specified length containing all asterisks. For example,
the following statement returns ***
SELECT STR( 1234.56, 3 )

355
Alphabetical list of functions

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

STRING function [String]


Function Concatenates one or more strings into one large string.
Syntax STRING ( string-expression [, ...] )
Parameters string-expression A string.

If only one argument is supplied, it is converted into a single expression. If


more than one argument is supplied, they are concatenated into a single
string.
A NULL is treated as an empty string (’’).
Examples The following statement returns the value testing123.
SELECT STRING( ’testing’, NULL, 123 )
Usage Numeric or date parameters are converted to strings before concatenation.
The STRING function can also be used to convert any single expression to a
string by supplying that expression as the only parameter.
If all parameters are NULL, STRING returns NULL.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

STUFF function [String]


Function Deletes a number of characters from one string and replaces them with
another string.
Syntax STUFF ( string-expression1, start, length, string-expression2 )
Parameters string-expression1 The string to be modified by the STUFF function.

start The character position at which to begin deleting characters. The first
character in the string is position 1.

length The number of characters to delete.

string-expression2 The string to be inserted. To delete a portion of a


string using STUFF, use a replacement string of NULL.

356
Chapter 8 SQL Functions

Examples The following statement returns the value chocolate pie.


SELECT STUFF( ’chocolate cake’, 11, 4, ’pie’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "INSERTSTR function" on page 329

SUBSTRING function [String]


Function Returns a substring of a string.
Syntax { SUBSTRING | SUBSTR }( string-expression, start [, length ] )
Parameters string-expression The string from which a substring is to be returned.

start The start position of the substring to return, in characters. A negative


starting position specifies a number of characters from the end of the string
instead of the beginning. The first character in the string is at position 1.

length The length of the substring to return, in characters. A positive


length specifies that the substring ends length characters to the right of the
starting position, while a negative length specifies that the substring ends
length characters to the left of the starting position.
Examples The following statement returns back:
SELECT SUBSTRING( ’back yard’,1 ,4 )
The following statement returns yard:
SELECT SUBSTRING( ’back yard’, -1 , -4 )
Usage If length is specified, the substring is restricted to that length. If no length is
specified, the remainder of the string is returned, starting at the start position.
Both start and length can be negative. Using appropriate combinations of
negative and positive numbers, you can get a substring from either the
beginning or end of the string.
If string-expression is of binary data type, the SUBSTRING function
behaves as BYTE_SUBSTR.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase SUBSTRING is compatible with Adaptive Server Enterprise.
SUBSTR is not supported by Adaptive Server Enterprise.
See also "BYTE_SUBSTR function" on page 305

357
Alphabetical list of functions

SUM function [Aggregate]


Function Returns the total of the specified expression for each group of rows.
Syntax SUM ( expression
| DISTINCT column-name )
Parameters expression The object to be summed. This is commonly a column name.

DISTINCT column-name This is of limited usefulness, but is included


for completeness.
Examples The following statement returns the value 3749146.
SELECT SUM( salary )
FROM Employee
Usage Rows where the specified expression is NULL are not included.
Returns NULL for a group containing no rows.
Standards and ♦ SQL/92 SQL/92 compatible.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "COUNT function " on page 312
"AVG function " on page 304

TAN function [Numeric]


Function Returns the tangent of a number.
Syntax TAN ( numeric-expression )
Parameters numeric-expression An angle, in radians.
Examples The following statement returns the value 0.572561.
SELECT TAN( 0.52 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "COS function" on page 311
"SIN function" on page 353

358
Chapter 8 SQL Functions

TEXTPTR function [String]


Function Returns the 16-byte binary pointer to the first page of the specified text
column.
Syntax TEXTPTR ( column-name )
Parameters column-name The name of a text column.
Example Use TEXTPTR to locate the text column, copy, associated with au_id 486-
29-1786 in the author’s blurbs table.
The text pointer is put into a local variable @val and supplied as a parameter
to the readtext command, which returns 5 bytes, starting at the second byte
(offset of 1).
DECLARE @val VARBINARY(16)
SELECT @val = TEXTPTR(copy)
FROM blurbs
WHERE au_id = "486-29-1786"
READTEXT blurbs.copy @val 1 5
Usage This function is included for Transact-SQL compatibility.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.

TODAY function [Date and time]


Function Returns the current date. This is the historical syntax for CURRENT DATE.
Syntax TODAY ( * )
Examples The following statement returns the current day according to the system
clock.
SELECT TODAY( * )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

TRACEBACK function [Miscellaneous]


Function Returns a string containing a traceback of the procedures and triggers that
were executing when the most recent exception (error) occurred.
Syntax TRACEBACK ( * )

359
Alphabetical list of functions

Examples To use the traceback function, enter the following after an error occurs while
executing a procedure:
SELECT TRACEBACK ( * )
Usage This is useful for debugging procedures and triggers
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

TRIM function [String]


Function Removes leading and trailing blanks from a string.
Syntax TRIM ( string-expression )
Parameters string-expression The string to be trimmed.
Examples The following statement returns the value chocolate with no leading or
trailing blanks.
SELECT TRIM( ’ chocolate ’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
See also "LTRIM function" on page 334
"RTRIM function" on page 351

TRUNCATE function [Numeric]


Function Truncates a number at a specified number of places after the decimal point.
Deprecated in favor of TRUNCNUM.
Syntax "TRUNCATE" ( numeric-expression, integer-expression )
Parameters numeric-expression The number to be truncated.

integer-expression A positive integer specifies the number of significant


digits to the right of the decimal point at which to round. A negative
expression specifies the number of significant digits to the left of the decimal
point at which to round.
Examples The following statement returns the value 600
SELECT "TRUNCATE"( 655, -2 )

The following statement returns the value 655.340.

360
Chapter 8 SQL Functions

SELECT "TRUNCATE"( 655.348, 2 )


Usage This function is the same as TRUNCNUM. Using TRUNCNUM is
recommended as it does not cause keyword conflicts.
The quotation marks are required because of a keyword conflict with the
TRUNCATE TABLE statement. You can only use TRUNCATE without the
quotation marks if the QUOTED_IDENTIFIER option is set to OFF.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
See also "QUOTED_IDENTIFIER option" on page 195
"TRUNCNUM function" on page 361

TRUNCNUM function [Numeric]


Function Truncates a number at a specified number of places after the decimal point.
Syntax TRUNCNUM ( numeric-expression, integer-expression )
Parameters numeric-expression The number to be truncated.

integer-expression A positive integer specifies the number of significant


digits to the right of the decimal point at which to round. A negative
expression specifies the number of significant digits to the left of the decimal
point at which to round.
Examples The following statement returns the value 600
SELECT TRUNCNUM( 655, -2 )
The following statement: returns the value 655.340.
SELECT TRUNCNUM( 655.348, 2 )
Usage This function is the same as TRUNCATE, but does not cause keyword
conflicts.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
See also "ROUND function" on page 350
"TRUNCATE function" on page 360

UCASE function [String]


Function Converts all characters in a string to upper case.

361
Alphabetical list of functions

Syntax UCASE ( string-expression )


Parameters string-expression The string to be converted to upper case.
Examples The following statement returns the value CHOCOLATE.
SELECT UCASE( ’ChocoLate’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase UCASE is not supported by Adaptive Server Enterprise, but
UPPER provides the same feature in a compatible manner.
See also "UPPER function" on page 362
"LCASE function" on page 330

UPPER function [String]


Function Converts all characters in a string to upper case.
Syntax UPPER ( string-expression )
Parameters string-expression The string to be converted to upper case.
Examples The following statement returns the value CHOCOLATE.
SELECT UPPER( ’ChocoLate’ )
Standards and ♦ SQL/92 This function is SQL/92 compatible.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise.
See also "UCASE function" on page 361
"LCASE function" on page 330
"LOWER function" on page 334

WEEKS function [Date and time]


Function Returns the number of weeks since an arbitrary date and time, between two
specified times, or adds the specified integer-expression amount of weeks to
a datetime.
Syntax WEEKS ( datetime-expression
| datetime-expression, datetime-expression
| datetime-expression, integer-expression )
Parameters datetime-expression A date and time.

362
Chapter 8 SQL Functions

integer-expression The number of weeks to be added to the datetime-


expression. If integer-expression is negative, the appropriate number of
weeks are subtracted from the datetime value. If you supply an integer
expression, the datetime-expression must be explicitly cast as a datetime data
type.
$ For information on casting data types, see "CAST function" on
page 306.
Examples The following statement returns the value 104270:
SELECT WEEKS( ’1998-07-13 06:07:12’ )
The following statement returns the value 8, to signify the difference
between the two dates:
SELECT WEEKS( ’1999-07-13 06:07:12’,
’1999-09-13 10:07:12’ )
The following statement returns the timestamp value 1999-06-16 21:05:07.
SELECT WEEKS( CAST( ’1999-05-12 21:05:07’
AS TIMESTAMP ), 5)
Usage The value of WEEKS is calculated from the number of Sundays between the
two dates.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

YEARS function [Date and time]


Function Returns the number of years since an arbitrary date and time, between two
specified times, or adds the specified integer-expression amount of years to a
datetime.
Syntax YEARS ( datetime-expression
| datetime-expression, datetime-expression
| datetime-expression, integer-expression )
Parameters datetime-expression A date and time.

integer-expression The number of years to be added to the datetime-


expression. If integer-expression is negative, the appropriate number of years
are subtracted from the datetime value. If you supply an integer expression,
the datetime-expression must be explicitly cast as a datetime data type.
$ For information on casting data types, see "CAST function" on
page 306.
Examples The following statement returns the value 1998:
363
Alphabetical list of functions

SELECT YEARS( ’1998-07-13 06:07:12’ )


The following statement returns the value 0, to signify the difference
between the two dates:
SELECT YEARS( ’1999-07-13 06:07:12’,
’1999-09-13 10:07:12’ )
The following statement returns the timestamp value 2004-05-12 21:05:07.
SELECT YEARS( CAST( ’1999-05-12 21:05:07’
AS TIMESTAMP ), 5)
Usage The value of YEARS is calculated from the number of first days of the year
between the two dates.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

YMD function [Date and time]


Function Returns a date value corresponding to the given year, month, and day of the
month.
Syntax YMD ( integer-expression, integer-expression, integer-expression )
Parameters integer expression The year.

integer expression The number of the month. If the month is outside the
range 1-12, the year is adjusted accordingly.

integer expression The day number. The day is allowed to be any


integer, the date is adjusted accordingly.
Examples The following statement returns the value 1998-06-12.
SELECT YMD( 1998, 06, 12 )
If the values are outside their normal range, the date will adjust accordingly.
For example, the following statement returns the value 1993-03-01.
SELECT YMD( 1992, 15, 1 )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Compatible with Adaptive Server Enterprise

364
C H A P T E R 9

SQL Statements

About this chapter This chapter presents detailed descriptions of the SQL statements that are
available to users of Adaptive Server Anywhere.
This chapter contains an alphabetical listing of SQL statements, including
some that can only be used from embedded SQL or Interactive SQL.
Contents The chapter includes an alphabetical list of SQL statements.

365
Using the SQL statement reference

Using the SQL statement reference


This section describes some conventions used in documenting the SQL
statements.

Common elements in SQL syntax


This section lists language elements that are found in the syntax of many
SQL statements.
$ For more information on the elements described here, see "Identifiers"
on page 211, "SQL Data Types" on page 251, "Search conditions" on
page 226, "Expressions" on page 218, or "Strings" on page 212.
♦ column-name An identifier that represents the name of a column.
♦ An expression that evaluates to TRUE, FALSE, or
condition
UNKNOWN.
♦ connection-name A string representing the name of an active
connection.
♦ data-type A storage data type.
♦ expression An expression.
♦ filename A string containing a filename.
♦ host-variable A C language variable, declared as a host variable
preceded by a colon.
♦ indicator-variable A second host variable of type short int
immediately following a normal host variable. It must also be preceded
by a colon. Indicator variables are used to pass NULL values to and
from the database.
♦ number Any sequence of digits followed by an optional decimal part
and preceded by an optional negative sign. Optionally, the number can
be followed by an E and then an exponent. For example,
42
-4.038
.001
3.4e10
1e-10
♦ owner An identifier representing the user ID who owns a database
object.

366
Chapter 9 SQL Statements

♦ role-name An identifier representing the role name of a foreign key.


♦ savepoint-name An identifier that represents the name of a savepoint.
♦ search-condition A condition that evaluates to TRUE, FALSE, or
UNKNOWN.
♦ special-value One of the special values described in "Special values"
on page 234.
♦ statement-label An identifier that represents the label of a loop or
compound statement.
♦ table-list A list of table names, which may include correlation names.
$ For more information, see "FROM clause" on page 518.
♦ table-name An identifier that represents the name of a table.
♦ userid An identifier representing a user name.
♦ variable-name An identifier that represents a variable name.

Syntax conventions
The following conventions are used in the SQL syntax descriptions:
♦ Keywords All SQL keywords are shown like the words ALTER
TABLE in the following example:
ALTER TABLE [ owner.]table-name
♦ Placeholders Items that must be replaced with appropriate identifiers
or expressions are shown like the words owner and table-name in the
following example.
ALTER TABLE [ owner.]table-name
♦ Continuation Lines beginning with an ellipsis (…) are a continuation
from the previous line. For example,
ALTER TABLE [ owner.]table-name
… ADD column-definition [ column-constraint … ]
♦ Repeating items Lists of repeating items are shown with an element
of the list followed by an ellipsis (three dots), like column-constraint in
the following example:
ADD column-definition [ column-constraint … ]
One or more list elements are allowed. If more than one is specified,
they must be separated by commas.

367
Using the SQL statement reference

♦ Optional portions Optional portions of a statement are enclosed by


square brackets.
RELEASE SAVEPOINT [ savepoint-name ]
These square brackets indicate that the savepoint-name is optional. The
square brackets should not be typed.
♦ Options When none or only one of a list of items can be chosen,
vertical bars separate the items and the list is enclosed in square
brackets.
[ ASC | DESC ]
For example, you can choose one of ASC, DESC, or neither. The square
brackets should not be typed.
♦ Alternatives When precisely one of the options must be chosen, the
alternatives are enclosed in curly braces.
[ QUOTES { ON | OFF } ]
If the QUOTES option is chosen, one of ON or OFF must be provided.
The braces should not be typed.
♦ One or more options If you choose more than one, separate your
choices with commas.
{ CONNECT, DBA, RESOURCE }

Statement applicability indicators


Some statement titles are followed by an indicator in square brackets that
indicate where the statement can be used. These indicators are as follows:
♦ [ESQL] The statement is for use in Embedded SQL.
♦ [Interactive SQL] The statement can be used only in Interactive SQL.
♦ [SP] The statement is for use in stored procedures, triggers, or batches.
♦ [TSQL] The statement is implemented for compatibility with Adaptive
Server Enterprise. In some cases, the statement cannot be used in stored
procedures that are not in Transact-SQL format. In other cases, an
alternative statement closer to the SQL/92 standard is recommended
unless Transact-SQL compatibility is an issue.
If two sets of brackets are used, the statement can be used in both
environments. For example, [ESQL][SP] means a statement can be used
either in embedded SQL or in stored procedures.

368
Chapter 9 SQL Statements

ALLOCATE DESCRIPTOR statement [ESQL]


Function Use this statement to allocate space for a SQL descriptor area (SQLDA).
Syntax ALLOCATE DESCRIPTOR descriptor-name
… [ WITH MAX { integer | host-variable } ]
descriptor-name: string
Permissions None.
Side effects None.
See also "DEALLOCATE DESCRIPTOR statement" on page 472
"The SQL descriptor area (SQLDA)" on page 44 of the book ASA
Programming Interfaces Guide
Parameters WITH MAX clause Allows you to specify the number of variables within
the descriptor area. The default size is one. You must still call fill_sqlda to
allocate space for the actual data items before doing a fetch or any statement
that accesses the data within a descriptor area.
Description Allocates space for a descriptor area (SQLDA). You must declare the
following in your C code prior to using this statement:
struct sqlda * descriptor_name
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Example The following sample program includes an example of ALLOCATE
DESCRIPTOR statement usage.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
EXEC SQL INCLUDE SQLCA;
#include <sqldef.h>
EXEC SQL BEGIN DECLARE SECTION;
int x;
short type;
int numcols;
char string[100];
a_sql_statement_number stmt = 0;
EXEC SQL END DECLARE SECTION;
int main(int argc, char * argv[]){
struct sqlda * sqlda1;

369
ALLOCATE DESCRIPTOR statement [ESQL]

if( !db_init( &sqlca ) ) {


return 1;
}
db_string_connect( &sqlca,
"UID=dba;PWD=sql;DBF=d:\\asa6\\sample.db");
EXEC SQL ALLOCATE DESCRIPTOR sqlda1 WITH MAX 25;
EXEC SQL PREPARE :stmt FROM
’SELECT * FROM employee’;
EXEC SQL DECLARE curs CURSOR FOR :stmt;
EXEC SQL OPEN curs;
EXEC SQL DESCRIBE :stmt into sqlda1;
EXEC SQL GET DESCRIPTOR sqlda1 :numcols=COUNT;
// how many columns?
if( numcols > 25 ) {
// reallocate if necessary
EXEC SQL DEALLOCATE DESCRIPTOR sqlda1;
EXEC SQL ALLOCATE DESCRIPTOR sqlda1
WITH MAX :numcols;
EXEC SQL DESCRIBE :stmt into sqlda1;
}
type = DT_STRING; // change the type to string
EXEC SQL SET DESCRIPTOR sqlda1 VALUE 2 TYPE =
:type;
fill_sqlda( sqlda1 );
// allocate space for the variables
EXEC SQL FETCH ABSOLUTE 1 curs
USING DESCRIPTOR sqlda1;
EXEC SQL GET DESCRIPTOR sqlda1
VALUE 2 :string = DATA;
printf("name = %s", string );
EXEC SQL DEALLOCATE DESCRIPTOR sqlda1;
EXEC SQL CLOSE curs;
EXEC SQL DROP STATEMENT :stmt;
db_string_disconnect( &sqlca, "" );
db_fini( &sqlca );
return 0;
}

370
Chapter 9 SQL Statements

ALTER DATABASE statement


Function Use this statement to upgrade a database created with previous versions of
the software.
Syntax ALTER DATABASE UPGRADE
… [ JAVA { ON | OFF } ]
… [ JCONNECT { ON | OFF } ]
Permissions Must have DBA authority, and must be the only connection to the database.
Not supported on Windows CE.
Side effects Automatic commit
See also "CREATE DATABASE statement" on page 415
"The Upgrade utility" on page 133
Description You can use the ALTER DATABASE statement as an alternative to the
Upgrade utility to upgrade a database.

Backup before upgrading


As with any software, it is recommended that you make a backup of your
database before upgrading.

ALTER DATABASE upgrades databases created with earlier versions of the


software. This applies to maintenance releases as well, so you can upgrade a
database created with, for example, version 6.0.2, to 6.0.3 standards using
the ALTER DATABASE statement in version 6.0.3 of the software.
In general, changes in databases between minor versions are limited to
additional database options and minor system table changes.
ALTER DATABASE makes the following changes:
♦ Upgrades the system tables to the current version.
♦ Adds any new database options.
♦ All system stored procedures are dropped and recreated.
♦ Running ALTER DATABASE twice, or running ALTER DATABASE
on an already upgraded database, does not make any changes.
You cannot use ALTER DATABASE to just add Java or jConnect features if
the database was created with the current version of the software. In order to
add these features to a database created with the current version of the
software, you must use Sybase Central or Interactive SQL.

371
ALTER DATABASE statement

$ For information on adding Java support, see "Java-enabling a Version 7


database" on page 542 of the book ASA User’s Guide. For information on
adding jConnect support to a Version 6 database, see "Installing jConnect
system objects into a database" on page 599 of the book ASA User’s Guide.
Parameters JAVA clause The JAVA clause adds the entries for the Sybase runtime
Java classes to the system tables (JAVA ON) or does not (JAVA OFF). By
default, the classes are added during the upgrade. Setting JAVA OFF does
not remove Java support from a database.

JCONNECT clause If you wish to use the Sybase jConnect JDBC driver
to access system catalog information, you need to specify JCONNECT ON.
If you wish to exclude the jConnect system objects, specify JCONNECT
OFF. You can still use JDBC, as long as you do not access system catalog
information. The default is to include jConnect support (JCONNECT ON).
Setting JCONNECT OFF does not remove jConnect support from a
database.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example ♦ Upgrade a Version 5 database to enable Java operations:
ALTER DATABASE UPGRADE
JAVA ON

372
Chapter 9 SQL Statements

ALTER DBSPACE statement


Function Use this statement to modify the characteristics of a DBSPACE. To pre-
allocate space for a DBSPACE or for the transaction log.
Syntax ALTER DBSPACE { dbspace-name | TRANSLOG }
… ADD number | RENAME filename-string
Permissions Must have DBA authority. Must be the only connection to the database.
Side effects Automatic commit.
See also "CREATE DBSPACE statement" on page 419
"Working with databases" on page 111 of the book ASA User’s Guide
Description Each database is held in one or more files. A dbspace is a logical name
associated with each database file. ALTER DBSPACE modifies the main
dbspace (also called the root file) or an additional dbspace. The dbspace
names for a database are held in the SYSFILE system table. The main
database file has a dbspace name of SYSTEM.
When a multi-file database is started, the start line or ODBC data source
description tells Adaptive Server Anywhere where to find the main database
file. The main database file (which has the dbspace name SYSTEM) holds
the system tables. Adaptive Server Anywhere looks in these system tables to
find the location of the other dbspaces, and Adaptive Server Anywhere then
opens each of the other dbspaces.
Parameters ADD clause An ALTER DBSPACE with the ADD clause preallocates
disk space for a dbspace. It extends the size of the corresponding database
file by the number pages. The page size of a database is fixed when the
database is created.
If space is not preallocated, database files are extended by 32 pages at a time
when the space is needed. Preallocating space can improve performance for
loading large amounts of data and also serves to keep the database files more
contiguous within the file system.

TRANSLOG clause You supply the special dbspace name TRANSLOG,


to preallocate disk space for the transaction log. Preallocation improves
performance if the transaction log is expected to grow quickly. You may
want to use this feature if, for example, you are handling many binary large
objects (blobs), such as bitmaps.

RENAME clause If you rename or move a database file other than the
main file to a different directory or device, you can use ALTER DBSPACE
with the RENAME clause to ensure that Adaptive Server Anywhere finds the
new file when the database is started.

373
ALTER DBSPACE statement

Using ALTER DBSPACE with RENAME on the main dbspace, SYSTEM,


has no effect.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Examples ♦ Increase the size of the SYSTEM dbspace by 200 pages.
ALTER DBSPACE system
ADD 200
♦ Rename the file for dbspace system_2 to dbspace2.
ALTER DBSPACE system_2
RENAME ’e:\db\dbspace2.db’

374
Chapter 9 SQL Statements

ALTER EVENT statement


Function Use this statement to change the definition of an event or its associated
handler for automating predefined actions. Also, to alter the definition of
scheduled actions.
Syntax ALTER EVENT event-name
[ DELETE TYPE | TYPE event-type ]
{ WHERE { trigger-condition | NULL }
| { ADD | [ MODIFY ] | DELETE } SCHEDULE schedule-spec
}
[ ENABLE | DISABLE ]
[ [ MODIFY ] HANDLER compound-statement | DELETE HANDLER }
event-type:
BackupEnd | "Connect"
| ConnectFailed | DatabaseStart
| DBDiskSpace | "Disconnect"
| GlobalAutoincrement | GrowDB
| GrowLog | GrowTemp
| LogDiskSpace | "RAISERROR"
| ServerIdle | TempDiskSpace
trigger-condition:
[ event_condition( condition-name ) { = | < | > | != | <= | >= } value ]
schedule-spec:
[ schedule-name ]
{ START TIME start-time | BETWEEN start-time AND end-time }
[ EVERY period { HOURS | MINUTES | SECONDS } ]
[ ON { ( day-of-week, … ) | ( day-of-month, … ) } ]
[ START DATE start-date ]
event-name | schedule-name:
identifier
day-of-week :
string
value | period | day-of-month :
integer
start-time | end-time :
time
start-date :
date
Permissions Must have DBA authority.
Side effects Automatic commit.
See also "BEGIN statement" on page 392
"CREATE EVENT statement" on page 423
375
ALTER EVENT statement

Description This statement allows you to alter an event definition created with CREATE
EVENT. Possible uses include the following:
♦ You can use ALTER EVENT to change an event handler during
development.
♦ You may want to define and test an event handler without a trigger
condition or schedule during a development phase, and then add the
conditions for execution using ALTER EVENT once the event handler
is completed.
♦ You may want to disable an event handler temporarily by disabling the
event.
Parameters DELETE TYPE clause Removes an association of the event with an event
type.

ADD | MODIFY | DELETE SCHEDULE clause Change the definition of


a schedule. Only one schedule can be altered in any one ALTER EVENT
statement.

WHERE clause The WHERE NULL option deletes a condition.


For descriptions of most of the parameters, see "CREATE EVENT
statement" on page 423.

376
Chapter 9 SQL Statements

ALTER PROCEDURE statement


Function Use this statement to replace a procedure with a modified version, you must
include the entire new procedure in the ALTER PROCEDURE statement.
Also, to enable and disable a procedure for replication with Sybase
Replication Server.
Syntax 1 ALTER PROCEDURE [ owner.]procedure-name
procedure-definition
procedure-definition:
CREATE PROCEDURE syntax following the name
Syntax 2 ALTER PROCEDURE [ owner.]procedure-name
… REPLICATE { ON | OFF }
Permissions Must be the owner of the procedure or be DBA.
Side effects Automatic commit.
See also "CREATE PROCEDURE statement" on page 440
"CREATE PROCEDURE statement" on page 447
Description Syntax 1 The ALTER PROCEDURE statement is identical in syntax to
the CREATE PROCEDURE statement except for the first word. Either
version of the CREATE PROCEDURE statement can be altered.

Existing permissions on the procedure are maintained, and do not have to be


reassigned. If a DROP PROCEDURE and CREATE PROCEDURE were
carried out, execute permissions would have to be reassigned.

Syntax 2 If a procedure is to be replicated to other sites using Sybase


Replication Server, you must set REPLICATE ON for the procedure.
Syntax 2 of the ALTER PROCEDURE statement has the same effect as the
sp_setreplicate or sp_setrepproc ’table’ Adaptive Server Enterprise system
procedures.
You cannot combine Syntax 2 with Syntax 1.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

377
ALTER SERVER statement

ALTER SERVER statement


Function Use this statement to modify the attributes of a remote server.
Syntax ALTER SERVER server-name
[ CLASS ’server-class’ ]
[ USING ’connection-info’ ]
[ CAPABILITY ’cap-name’ { ON | OFF } ]
server-class:
{ ASAJDBC | ASEJDBC
| ASAODBC | ASEODBC
| DB2ODBC | MSSODBC
| ORAODBC | ODBC }
connection-info:
{ machine-name:port-number[/dbname ] | data-source-name }
cap-name:
Permissions Must have RESOURCE authority.
Supported on Windows 95 and Windows NT database servers only.
Side effects Automatic commit.
See also "CREATE SERVER statement" on page 451
"DROP SERVER statement" on page 497
"Server Classes for Remote Data Access" on page 899 of the book ASA
User’s Guide
"Troubleshooting remote data access" on page 896 of the book ASA User’s
Guide
Description The ALTER SERVER statement modifies the attributes of a server. These
changes do not take effect until the next connection to the remote server.
Parameters CLASS clause The CLASS clause is specified to change the server class.
$ For more information on server classes and how to configure a server,
see "Server Classes for Remote Data Access" on page 899 of the book ASA
User’s Guide.

USING clause The USING clause is specified to change the server


connection information. For information about connection-info, see
"CREATE SERVER statement" on page 451.

378
Chapter 9 SQL Statements

CAPABILITY clause The CAPABILITY clause turns a server capability


ON or OFF. Server capabilities are stored in the system table syscapability.
The names of these capabilities are stored in the system table
syscapabilityname. The syscapability table contains no entries for a remote
server until the first connection is made to that server. At the first connection,
Adaptive Server Anywhere interrogates the server about its capabilities and
then populates the syscapability table. For subsequent connections, the
server’s capabilities are obtained from this table.
In general, you do not need to alter a server’s capabilities. It may be
necessary to alter capabilities of a generic server of class ODBC.
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Examples ♦ Change the server class of the Adaptive Server named ase_prod so its
connection to Adaptive Server Anywhere is ODBC-based. Its Data
Source Name is ase_prod.
ALTER SERVER ase_prod
CLASS ’ASEODBC’
USING ’ase_prod’
♦ Change a capability of server infodc:
ALTER SERVER infodc
CAPABILITY ’insert select’ OFF

379
ALTER TABLE statement

ALTER TABLE statement


Function Use this statement to modify a table definition or to enable a table to take
part in Replication Server replication.
Syntax 1 ALTER TABLE [ owner.]table-name
… ADD column-definition [ column-constraint … ]
| ADD table-constraint
| MODIFY column-definition
| MODIFY column-name DEFAULT default-value
| ALTER column-name SET DEFAULT default-value
| ALTER column-name DROP DEFAULT
| ALTER column-name SET COMPUTE ( expression )
| ALTER column-name DROP COMPUTE
| MODIFY column-name [ NOT ] NULL
| MODIFY column-name CHECK NULL
| MODIFY column-name CHECK ( condition )
| { DELETE | DROP } column-name
| { DELETE | DROP } CHECK
| { DELETE | DROP } UNIQUE ( column-name, … )
| { DELETE | DROP } PRIMARY KEY
| { DELETE | DROP } FOREIGN KEY role-name
| RENAME new-table-name
| RENAME column-name TO new-column-name
column-definition:
column-name data-type [ NOT NULL ] [ DEFAULT default-value ]
column-constraint:
{ UNIQUE
| PRIMARY KEY
| REFERENCES table-name [ ( column-name ) ] [ actions ]
} [ WITH [ MAX | MAXIMUM ] HASH SIZE hash-size ]
| CHECK ( condition )
| COMPUTE ( expression )
default-value:
string
| global variable
| number
| AUTOINCREMENT
| CURRENT DATE
| CURRENT TIME
| CURRENT TIMESTAMP
| NULL
| TIMESTAMP
| USER

380
Chapter 9 SQL Statements

table-constraint:
{ UNIQUE ( column-name, … )
| PRIMARY KEY ( column-name, … )
} [ WITH [ MAX | MAXIMUM ] HASH SIZE hash-size ]
| CHECK ( condition )
| foreign-key-constraint
foreign-key-constraint:
[ NOT NULL ] FOREIGN KEY [ role-name ] [ (column-name, … ) ]
… REFERENCES table-name [ (column-name, … ) ]
… [ actions ] [ CHECK ON COMMIT ]
… [ WITH [ MAX | MAXIMUM ] HASH SIZE hash-size ]
actions:
[ ON UPDATE action ] [ ON DELETE action ]
action:
CASCADE
| SET NULL
| SET DEFAULT
| RESTRICT
Syntax 2 ALTER TABLE [ owner.]table-name
… REPLICATE { ON | OFF }
Permissions Must be one of the following:
♦ The owner of the table
♦ A user with DBA authority.
♦ A user granted ALTER permission on the table.
ALTER TABLE requires exclusive access to the table.
Global temporary tables cannot be altered unless all users that have
referenced the temporary table have disconnected.
Side effects Automatic commit.
The MODIFY and DELETE (DROP) options close all cursors for the current
connection.
A checkpoint is carried out at the beginning of the ALTER TABLE
operation.
Once you alter a column or table, any stored procedures, views or other items
that refer to the altered column no longer work.
See also "CREATE TABLE statement" on page 453
"DROP statement" on page 491
"SQL Data Types" on page 251
"Using computed columns with Java classes" on page 572 of the book ASA
User’s Guide
"Altering tables" on page 124 of the book ASA User’s Guide

381
ALTER TABLE statement

Description Syntax 1 The ALTER TABLE statement changes table attributes (column
definitions, constraints) in a table that was previously created. Note that the
syntax allows a list of alter clauses; however, only one table-constraint or
column-constraint can be added, modified or deleted in one ALTER TABLE
statement.
You cannot use ALTER TABLE on a local temporary table.
ALTER TABLE is prevented whenever the statement affects a table that is
currently being used by another connection. ALTER TABLE can be time-
consuming, and the server will not process requests referencing the table
while the statement is being processed.
Before version 5.0, all table and column constraints were held in a single
table constraint. Consequently, for these databases individual constraints on
columns cannot be deleted using the MODIFY column-name CHECK NULL
clause or replaced using the MODIFY column-name CHECK (condition )
clause. To use these statements, the entire table constraint should be deleted
and the constraints added back using the MODIFY column-name CHECK
(condition ) clause. At this point you can use MODIFY CHECK.

Syntax 2 When a table has REPLICATE ON, all changes to the table are
sent to Replication Server for replication. The replication definitions in
Replication Server are used to decide which table changes are sent to other
sites. The remainder of this section describes syntax 1.
Parameters ADD column-definition Add a new column to the table. The table must
be empty or the column must have a default if you specify NOT NULL.
If the column has a default value, all rows of the new column are populated
with that default value.

NULL values
Adaptive Server Anywhere optimizes the creation of columns that are
allowed to contain NULL. The first column allowed to contain NULL
allocates room for eight such columns, and initializes all eight to be
NULL. (This requires no extra storage.) Thus, the next seven columns
added require no changes to the rows of the table.
Adding a ninth column then allocates room for another eight such
columns and modifies each row of the table to allocate the extra space.
Consequently, seven out of eight column additions run quickly.

ADD table-constraint Add a constraint to the table. See "CREATE


TABLE statement" on page 453 for a full explanation of table constraints.

382
Chapter 9 SQL Statements

If PRIMARY KEY is specified, the table must not already have a primary
key that was created by the CREATE TABLE statement or another
ALTER TABLE statement.

MODIFY column-definition Change the length or data type of an existing


column in a table. If NOT NULL is specified, a NOT NULL constraint is
added to the named column. Otherwise, the NOT NULL constraint for the
column will not be changed. If necessary, the data in the modified column
will be converted to the new data type. If a conversion error occurs, the
operation will fail and the table will be left unchanged.
You cannot modify a column to make it a computed column. Computed
columns can only be added or dropped.

Deleting an index, constraint, or key


If the column is contained in a uniqueness constraint, a foreign key, or a
primary key, then the constraint or key must be deleted before the column
can be modified. If a primary key is deleted, all foreign keys referencing
the table will also be deleted.
You cannot MODIFY a table or column constraint. To change a
constraint, you must DELETE the old constraint and ADD the new
constraint.

MODIFY column-name DEFAULT default-value Change the default


value of an existing column in a table. To remove a default value for a
column, specify DEFAULT NULL. Modifying a default value does not
change any existing values in the table.

ALTER column-name SET DEFAULT default-value Change the


default value of an existing column in a table. You can also use the MODIFY
clause for this task, but ALTER is SQL/92 compliant, and MODIFY is not.
Modifying a default value does not change any existing values in the table.

ALTER column-name DROP DEFAULT Remove the default value of


an existing column in a table. You can also use the MODIFY clause for this
task, but ALTER is SQL/92 compliant, and MODIFY is not. Dropping a
default does not change any existing values in the table.

ALTER column-name SET COMPUTE (expression) Change the


expression associated with a computed column. The values in the column are
recalculated when the statement is executed, and the statement fails if the
new expression is invalid.

ALTER column-name DROP COMPUTE Change a column from being a


computed column to being a non-computed column. This statement does not
change any existing values in the table.

383
ALTER TABLE statement

MODIFY column-name [ NOT ] NULL Change the NOT NULL


constraint on the column to allow or disallow NULL values in the column.

MODIFY column-name CHECK NULL Delete the check constraint for


the column. This statement cannot be used on databases created before
version 5.0.

MODIFY column-name CHECK (condition) Replace the existing


CHECK condition for the column with the one specified. This statement
cannot be used on databases created before version 5.0.

DELETE column-name Delete the column from the table. If the column
is contained in any index, uniqueness constraint, foreign key, or primary key
then the index, constraint, or key must be deleted before the column can be
deleted. This does not delete CHECK constraints that refer to the column.

DELETE CHECK Delete all check constraints for the table. This includes
both table check constraints and column check constraints.

DELETE UNIQUE (column-name, …) Delete a uniqueness constraint for


this table. Any foreign keys referencing this uniqueness constraint (rather
than the primary key) will also be deleted.

DELETE PRIMARY KEY Delete the primary key constraint for this table.
All foreign keys referencing the primary key for this table will also be
deleted.

DELETE FOREIGN KEY role-name Delete the foreign key constraint for
this table with the given role name.

RENAME new-table-name Change the name of the table to new-table-


name. Note that any applications using the old table name must be modified.
Foreign keys that were automatically assigned the old table name will not
change names.

RENAME column-name TO new-column-name Change the name of


the column to the new-column-name. Note that any applications using the old
column name will need to be modified.
Standards and ♦ SQL/92 Intermediate level feature. MODIFY are not SQL/92
compatibility compliant.
♦ Sybase Some clauses are supported by Adaptive Server Enterprise.
Examples ♦ Add a new column to the employee table showing which office they
work in.
ALTER TABLE employee
ADD office CHAR(20) DEFAULT ’Boston’

384
Chapter 9 SQL Statements

♦ Drop the office column from the employee table.


ALTER TABLE employee
DELETE office
♦ The address column in the customer table can currently hold up to
35 characters. Allow it to hold up to 50 characters.
ALTER TABLE customer
MODIFY address CHAR(50)
♦ Add a column to the customer table assigning each customer a sales
contact.
ALTER TABLE customer
ADD sales_contact INTEGER
REFERENCES employee (emp_id)
ON UPDATE CASCADE
ON DELETE SET NULL
This foreign key is constructed with cascading updates and is set null on
deletes. If an employee has their employee ID changed, the column is
updated to reflect this change. If an employee leaves the company and
has their employee ID deleted, the column is set to NULL.

385
ALTER TRIGGER statement

ALTER TRIGGER statement


Function Use this statement to replace a trigger definition with a modified version.
You must include the entire new trigger definition in the ALTER TRIGGER
statement.
Syntax ALTER TRIGGER trigger-name
trigger-definition
trigger-definition:
CREATE TRIGGER syntax following the trigger name
Permissions Must be the owner of the table on which the trigger is defined, or be DBA, or
have ALTER permissions on the table and have RESOURCE authority.
Side effects Automatic commit.
See also "CREATE TRIGGER statement" on page 464
"CREATE TRIGGER statement" on page 467
"DROP statement" on page 491
Description The ALTER TRIGGER statement is identical in syntax to the CREATE
TRIGGER statement except for the first word. For information on trigger-
definition, see "CREATE TRIGGER statement" on page 464 and "CREATE
TRIGGER statement" on page 467.
Either the Transact-SQL or Watcom-SQL form of the CREATE TRIGGER
syntax can be used.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

386
Chapter 9 SQL Statements

ALTER VIEW statement


Function Use this statement to replace a view definition with a modified version. You
must include the entire new view definition in the ALTER VIEW statement.
Syntax ALTER VIEW
… [ owner.]view-name [( column-name, … )]
… AS select-without-order-by
… [ WITH CHECK OPTION ]
Permissions Must be owner of the view or have DBA authority.
Side effects Automatic commit.
All procedures and triggers are unloaded from memory, so that any
procedure or trigger that references the view reflects the new view definition.
The unloading and loading of procedures and triggers can have a
performance impact if you are regularly altering views.
See also "CREATE VIEW statement" on page 469
"DROP statement" on page 491
Description The ALTER VIEW statement is identical in syntax to the CREATE VIEW
statement except for the first word. The ALTER VIEW statement replaces
the entire contents of the CREATE VIEW statement with the contents of the
ALTER VIEW statement. Existing permissions on the view are maintained,
and do not have to be reassigned. If a DROP VIEW followed by a CREATE
VIEW is used, instead of ALTER VIEW, permissions on the view would
have to be reassigned.
$ For information on the keywords and options, see "CREATE VIEW
statement" on page 469.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

387
ALTER WRITEFILE statement

ALTER WRITEFILE statement


Function Use this statement to change the name of the read-only database file to which
a write file refers.
Syntax ALTER WRITEFILE write-file-name
… REFERENCES db-file-name
write-file-name | db-file-name:
string
Permissions The permissions required to execute this statement are set on the server
command line, using the -gu command-line option. The default setting is to
require DBA authority.
Not supported on Windows CE.
Side effects Automatic commit.
See also "CREATE WRITEFILE statement" on page 471
"The Write File utility" on page 139
"Working with write files" on page 770 of the book ASA User’s Guide
"Using the utility database" on page 772 of the book ASA User’s Guide
Description The ALTER WRITEFILE statement changes the name of the read-only
database file to which the write file refers. If you move the database file from
one directory to another, you can use this statement to point the write file to
the new location.
The path name of the database file is relative to the database server’s current
directory at startup.
$ For information on escaping backslash characters in strings, see
"Strings" on page 212.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example ♦ The following statement changes the existing write file c:\readwrite.wrt
to point to the database file h:\readonly.db.
ALTER WRITEFILE ’c:\\readwrite.wrt’
REFERENCES ’h:\\readonly.db’

388
Chapter 9 SQL Statements

BACKUP statement
Function Use this statement to back up a database and transaction log.
Syntax 1 (image BACKUP DATABASE
backup) DIRECTORY backup-directory
[ WAIT BEFORE START ]
[ DBFILE ONLY ]
[ TRANSACTION LOG ONLY ]
[ TRANSACTION LOG RENAME [ MATCH ] ]
[ TRANSACTION LOG TRUNCATE ]
backup-directory: string
Syntax 2 (archive BACKUP DATABASE TO archive-root
backup) [ ATTENDED { ON | OFF } ]
[ WITH COMMENT comment string ]
archive-root: string
comment-string: string
Permissions Must have DBA authority.
Side effects Causes a checkpoint.
See also "RESTORE statement" on page 577
"Backup and Data Recovery" on page 627 of the book ASA User’s Guide
Description Syntax 1 An image backup creates copies of each of the database files, in
the same way as the Backup utility (dbbackup). In the case of the BACKUP
statement, however, the backup is made on the server, while the Backup
utility makes the backup from a client machine.
Optionally, only the database file(s) or transaction log can be saved. The log
may also be renamed or truncated after the backup has completed.
To restore from an image backup, copy the saved files back to their original
locations and reapply transaction logs as described in the chapter "Backup
and Data Recovery" on page 627 of the book ASA User’s Guide.

Syntax 2 An archive backup creates a single file holding all the required
backup information. The destination can be either a file name or a tape drive
device name.
There can be only one backup on a given tape. The file backup.syb records
the BACKUP and RESTORE operations that have been performed on a
given server.
The tape is ejected at the end of the backup.

389
BACKUP statement

Archive backup is not supported on the Windows 95/98 operating system.


Archive backups to disk are supported by all versions of NetWare, but
archive backups to tape are not supported on versions of NetWare earlier
than NetWare 5.
Only one archive per tape is allowed, but a single archive can span multiple
tapes.
To restore a database from an archive backup, use the RESTORE statement.
Parameters backup-directory The target location on disk for those files, relative to
the server’s current directory at startup. If the directory does not already
exist, it is created.

WAIT BEFORE START clause This clause ensures that the backup copy
of the database does not contain any information required for recovery. In
particular, it ensures that the rollback log for each connection is empty.
If a backup is carried out using this clause, you can start the backup copy of
the database in read-only mode and validate it. By enabling validation of the
backup database, the customer can avoid making an additional copy of the
database.

MATCH keyword If you supply the MATCH keyword, the backup copy
of the transaction log is given a name of the form YYMMDDnn.log. This
enables the same statement to be executed several times without writing over
old data.

archive-root The file name or tape drive device name for the archive file.

To back up to tape, you must specify the device name of the tape drive. For
example, on Windows NT or NetWare, the first tape drive is \\.\tape0.
The ’\’ is an escape character in SQL strings, so each backslash must be
doubled. For more information on escape characters and strings, see
"Strings" on page 212.

WITH COMMENT Record a comment in the archive file and in the backup
history file.

ATTENDED The clause applies only when backing up to a tape device.


ATTENDED ON (the default) indicates that someone is available to monitor
the status of the tape drive and to place a new tape in the drive when needed.
A message is sent to the application that issued the BACKUP statement if the
tape drive requires intervention. The database server then waits for the drive
to become ready. This may happen, for example, when a new tape is
required.
If ATTENDED OFF is specified and a new tape is required or the drive is
not ready, no message is sent, and an error is given.
390
Chapter 9 SQL Statements

Each BACKUP operation, whether image or archive, updates a history file


called backup.syb. This file is stored in the same directory as the database
server executable.
Example ♦ Back up the current database and the transaction log to a file, renaming
the existing transaction log. An image backup is created.
BACKUP DATABASE
DIRECTORY ’d:\\temp\\backup’
TRANSACTION LOG RENAME
The option to rename the transaction log is useful especially in
replication environments, where the old transaction log is still required.
♦ Back up the current database and transaction log to tape:
BACKUP DATABASE
TO ’\\\\.\\tape0’

391
BEGIN statement

BEGIN statement
Function Use this statement to group SQL statements together.
Syntax [ statement-label : ]
… BEGIN [ [ NOT ] ATOMIC ]
… [ local-declaration; … ]
… statement-list
… [ EXCEPTION [ exception-case … ] ]
… END [ statement-label ]
local-declaration:
variable-declaration
| cursor-declaration
| exception-declaration
| temporary-table-declaration
variable-declaration:
DECLARE variable-name data-type
exception-declaration:
DECLARE exception-name EXCEPTION
FOR SQLSTATE [ VALUE ] string
exception-case:
WHEN exception-name [, … ] THEN statement-list
| WHEN OTHERS THEN statement-list
Permissions None.
Side effects None.
See also "DECLARE CURSOR statement" on page 475
"DECLARE LOCAL TEMPORARY TABLE statement" on page 481
"LEAVE statement" on page 544
"SIGNAL statement" on page 603
"RESIGNAL statement" on page 576
"Using Procedures, Triggers, and Batches" on page 423 of the book ASA
User’s Guide
Description The body of a procedure or trigger is a compound statement. Compound
statements can also be used in control statements within a procedure or
trigger.
A compound statement allows one or more SQL statements to be grouped
together and treated as a unit. A compound statement starts with the keyword
BEGIN and ends with the keyword END.

392
Chapter 9 SQL Statements

Parameters local-declaration Immediately following the BEGIN, a compound


statement can have local declarations for objects that only exist within the
compound statement. A compound statement can have a local declaration for
a variable, a cursor, a temporary table, or an exception. Local declarations
can be referenced by any statement in that compound statement, or in any
compound statement nested within it. Local declarations are not visible to
other procedures that are called from within a compound statement.

statement-label If the ending statement-label is specified, it must match


the beginning statement-label. The LEAVE statement can be used to resume
execution at the first statement after the compound statement. The compound
statement that is the body of a procedure or trigger has an implicit label that
is the same as the name of the procedure or trigger.
$ For a complete description of compound statements and exception
handling, see "Using Procedures, Triggers, and Batches" on page 423 of the
book ASA User’s Guide.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise. This does not mean
that all statements inside a compound statement are supported.
The BEGIN and END keywords are not required in Transact-SQL.
BEGIN and END are used in Transact-SQL to group a set of statements
into a single compound statement, so that control statements such as IF
… ELSE, which only affect the execution of a single SQL statement,
can affect the execution of the whole group. The ATOMIC keyword is
not supported by Adaptive Server Enterprise.
In Transact-SQL. DECLARE statements need not immediately follow a
BEGIN keyword, and the cursor or variable that is declared exists for
the duration of the compound statement. You should declare variables at
the beginning of the compound statement for compatibility.
Example ♦ The body of a procedure or trigger is a compound statement.

393
BEGIN statement

CREATE PROCEDURE TopCustomer (OUT TopCompany


CHAR(35), OUT TopValue INT)
BEGIN
DECLARE err_notfound EXCEPTION FOR
SQLSTATE ’02000’;
DECLARE curThisCust CURSOR FOR
SELECT company_name, CAST(
sum(sales_order_items.quantity *
product.unit_price) AS INTEGER) VALUE
FROM customer
LEFT OUTER JOIN sales_order
LEFT OUTER JOIN sales_order_items
LEFT OUTER JOIN product
GROUP BY company_name;
DECLARE ThisValue INT;
DECLARE ThisCompany CHAR(35);
SET TopValue = 0;
OPEN curThisCust;

CustomerLoop:
LOOP
FETCH NEXT curThisCust
INTO ThisCompany, ThisValue;
IF SQLSTATE = err_notfound THEN
LEAVE CustomerLoop;
END IF;
IF ThisValue > TopValue THEN
SET TopValue = ThisValue;
SET TopCompany = ThisCompany;
END IF;
END LOOP CustomerLoop;

CLOSE curThisCust;
END

394
Chapter 9 SQL Statements

BEGIN TRANSACTION statement


Function Use this statement to begin a user-defined transaction.
Syntax BEGIN TRAN[SACTION] [ transaction-name ]
Permissions None.
Side effects None.
See also "COMMIT statement" on page 408
"ISOLATION_LEVEL option" on page 181
"ROLLBACK statement" on page 583
"SAVEPOINT statement" on page 586
Description The optional parameter transaction-name is the name assigned to this
transaction. It must be a valid identifier. Use transaction names only on the
outermost pair of nested BEGIN/COMMIT or BEGIN/ROLLBACK
statements.
When executed inside a transaction, the BEGIN TRANSACTION statement
increases the nesting level of transactions by one. The nesting level is
decreased by a COMMIT statement. When transactions are nested, only the
outermost COMMIT makes the changes to the database permanent.
Both Adaptive Server Enterprise and Adaptive Server Anywhere have two
transaction modes.
The default Adaptive Server Enterprise transaction mode, called unchained
mode, commits each statement individually, unless an explicit BEGIN
TRANSACTION statement is executed to start a transaction. In contrast, the
ISO SQL/92 compatible chained mode only commits a transaction when an
explicit COMMIT is executed or when a statement that carries out an
autocommit (such as data definition statements ) is executed.
You can control the mode by setting the CHAINED database option. The
default setting for ODBC and embedded SQL connections in Adaptive
Server Anywhere is ON, in which case Adaptive Server Anywhere runs in
chained mode. (ODBC users should also check the AutoCommit ODBC
setting). The default for TDS connections is OFF.
In unchained mode, a transaction is implicitly started before any data
retrieval or modification statement. These statements include: DELETE,
INSERT, OPEN, FETCH, SELECT, and UPDATE. You must still explicitly
end the transaction with a COMMIT or ROLLBACK statement.
You cannot alter the CHAINED option within a transaction.

395
BEGIN TRANSACTION statement

Caution
When calling a stored procedure, you should ensure that it operates
correctly under the required transaction mode.

$ For more information, see "CHAINED option" on page 163.


The current nesting level is held in the global variable @@trancount. The
@@trancount variable has a value of zero before the first BEGIN
TRANSACTION statement is executed, and only a COMMIT executed
when @@trancount is equal to one makes changes to the database
permanent.
A ROLLBACK statement without a transaction or savepoint name always
rolls back statements to the outermost BEGIN TRANSACTION (explicit or
implicit) statement, and cancels the entire transaction.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Example ♦ The following batch reports successive values of @@trancount as 0, 1,
2, 1, and 0. The values are printed on the server window.
PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
COMMIT
PRINT @@trancount
COMMIT
PRINT @@trancount
You should not rely on the value of@@trancount for more than keeping
track of the number of explicit BEGIN TRANSACTION statements that
have been issued.
When Adaptive Server Enterprise starts a transaction implicitly, the
@@trancount variable is set to 1. Adaptive Server Anywhere does not set the
@@trancount value to 1 when a transaction is started implicitly.
Consequently, the Adaptive Server Anywhere @@trancount variable has a
value of zero before any BEGIN TRANSACTION statement (even though
there is a current transaction), while in Adaptive Server Enterprise (in
chained mode) it has a value of 1.

396
Chapter 9 SQL Statements

For transactions starting with a BEGIN TRANSACTION statement,


@@trancount has a value of 1 in both Adaptive Server Anywhere and
Adaptive Server Enterprise after the first BEGIN TRANSACTION
statement. If a transaction is implicitly started with a different statement, and
a BEGIN TRANSACTION statement is then executed, @@trancount has a
value of 1 in Adaptive Server Anywhere, and a value of 2 in Adaptive Server
Enterprise after the BEGIN TRANSACTION statement.

397
CALL statement

CALL statement
Function Use this statement to invoke a procedure.
Syntax 1 [variable = ] CALL procedure-name ( [ expression, … ] )
Syntax 2 [variable = ] CALL procedure-name ( [ parameter-name = expression, … ] )
Permissions Must be the owner of the procedure, have EXECUTE permission for the
procedure, or have DBA authority.
Side effects None.
See also "CREATE PROCEDURE statement" on page 440
"GRANT statement" on page 526
"EXECUTE statement" on page 502
"Using Procedures, Triggers, and Batches" on page 423 of the book ASA
User’s Guide
Description The CALL statement invokes a procedure that has been previously created
with a CREATE PROCEDURE statement. When the procedure completes,
any INOUT or OUT parameter values will be copied back.
The argument list can be specified by position or by using keyword format.
By position, the arguments will match up with the corresponding parameter
in the parameter list for the procedure. By keyword, the arguments are
matched up with the named parameters.
Procedure arguments can be assigned default values in the CREATE
PROCEDURE statement, and missing parameters are assigned the default
value or. If no default is set, and an argument is not provided, an error is
given.
Inside a procedure, a CALL statement can be used in a DECLARE statement
when the procedure returns result sets (see "Returning results from
procedures" on page 453 of the book ASA User’s Guide).
Procedures can return an integer value (as a status indicator, say) using the
RETURN statement. You can save this return value in a variable using the
equality sign as an assignment operator:
CREATE VARIABLE returnval INT;
returnval = CALL proc_integer ( arg1 = val1, ... )
$ For information on returning non-integer values, see "CREATE
FUNCTION statement" on page 432.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise. For an
alternative that is supported, see "EXECUTE statement" on page 502.

398
Chapter 9 SQL Statements

Examples ♦ Call the sp_customer_list procedure. This procedure has no parameters,


and returns a result set.
CALL sp_customer_list()
♦ The following Interactive SQL example creates a procedure to return the
number of orders placed by the customer whose ID is supplied, creates a
variable to hold the result, calls the procedure, and displays the result.
CREATE PROCEDURE OrderCount (IN customer_ID INT, OUT
Orders INT)
BEGIN
SELECT COUNT("DBA".sales_order.id)
INTO Orders
FROM "DBA".customer
KEY LEFT OUTER JOIN "DBA".sales_order
WHERE "DBA".customer.id = customer_ID;
END
go
-- Create a variable to hold the result
CREATE VARIABLE Orders INT
go
-- Call the procedure, FOR customer 101
CALL OrderCount ( 101, Orders)
go
-- Display the result
SELECT Orders FROM DUMMY
go

399
CASE statement

CASE statement
Function Use this statement to select an execution path based on multiple cases.
Syntax CASE value-expression
… WHEN [ constant | NULL ] THEN statement-list …
… [ WHEN [ constant | NULL ] THEN statement-list ] …
… ELSE statement-list
… END CASE
Permissions None.
Side effects None.
See also "BEGIN statement" on page 392
"Using Procedures, Triggers, and Batches" on page 423 of the book ASA
User’s Guide
Description The CASE statement is a control statement that allows you to choose a list of
SQL statements to execute based on the value of an expression. If a WHEN
clause exists for the value of value-expression, the statement-list in the
WHEN clause is executed. If no appropriate WHEN clause exists, and an
ELSE clause exists, the statement-list in the ELSE clause is executed.
Execution resumes at the first statement after the END CASE.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example The following procedure using a case statement classifies the products listed
in the product table of the sample database into one of shirt, hat, shorts, or
unknown.
The following procedure uses a case statement to classify the results of a
query.
CREATE PROCEDURE ProductType (IN product_id INT, OUT
type CHAR(10))
BEGIN
DECLARE prod_name CHAR(20);
SELECT name INTO prod_name FROM "DBA"."product"
WHERE id = product_id;
CASE prod_name
WHEN ’Tee Shirt’ THEN
SET type = ’Shirt’
WHEN ’Sweatshirt’ THEN
SET type = ’Shirt’
WHEN ’Baseball Cap’ THEN
SET type = ’Hat’
WHEN ’Visor’ THEN
SET type = ’Hat’

400
Chapter 9 SQL Statements

WHEN ’Shorts’ THEN


SET type = ’Shorts’
ELSE
SET type = ’UNKNOWN’
END CASE;
END

401
CHECKPOINT statement

CHECKPOINT statement
Function Use this statement to checkpoint the database.
Syntax CHECKPOINT
Permissions DBA authority is required to checkpoint the network database server.
No permissions are required to checkpoint the personal database server.
Side effects None.
See also "CHECKPOINT_TIME option" on page 165
"RECOVERY_TIME option" on page 195
Description The CHECKPOINT statement forces the database server to execute a
checkpoint. Checkpoints are also performed automatically by the database
server according to an internal algorithm. It is not normally required for
applications issue the CHECKPOINT statement.
$ For a full description of checkpoints, see "Backup and Data Recovery"
on page 627 of the book ASA User’s Guide.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.

402
Chapter 9 SQL Statements

CLEAR statement [Interactive SQL]


Function Use this statement to clear the Interactive SQL Data window.
Syntax CLEAR
Permissions None.
Side effects Closes the cursor associated with the data being cleared.
Description The CLEAR statement is used to clear the Interactive SQL Data window.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not applicable

403
CLOSE statement [ESQL] [SP]

CLOSE statement [ESQL] [SP]


Function Use this statement to close a cursor.
Syntax CLOSE cursor-name
cursor-name:
{ identifier | host-variable }
Permissions The cursor must have been previously opened.
Side effects None.
See also "OPEN statement" on page 556
"DECLARE CURSOR statement" on page 475
"PREPARE statement" on page 564
Description This statement closes the named cursor.
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Examples The following examples close cursors in embedded SQL.
EXEC SQL CLOSE employee_cursor;
EXEC SQL CLOSE :cursor_var;
The following procedure uses a cursor.
CREATE PROCEDURE TopCustomer (OUT TopCompany
CHAR(35), OUT TopValue INT)
BEGIN
DECLARE err_notfound EXCEPTION
FOR SQLSTATE ’02000’;
DECLARE curThisCust CURSOR FOR
SELECT company_name, CAST(
sum(sales_order_items.quantity *
product.unit_price) AS INTEGER) VALUE
FROM customer
LEFT OUTER JOIN sales_order
LEFT OUTER JOIN sales_order_items
LEFT OUTER JOIN product
GROUP BY company_name;
DECLARE ThisValue INT;
DECLARE ThisCompany CHAR(35);
SET TopValue = 0;
OPEN curThisCust;

404
Chapter 9 SQL Statements

CustomerLoop:
LOOP
FETCH NEXT curThisCust
INTO ThisCompany, ThisValue;
IF SQLSTATE = err_notfound THEN
LEAVE CustomerLoop;
END IF;
IF ThisValue > TopValue THEN
SET TopValue = ThisValue;
SET TopCompany = ThisCompany;
END IF;
END LOOP CustomerLoop;
CLOSE curThisCust;
END

405
COMMENT statement

COMMENT statement
Function Use this statement to store a comment in the system tables for a database
object.
Syntax COMMENT ON
{
COLUMN [ owner.]table-name.column-name
| EVENT event-name
| FOREIGN KEY [ owner.]table-name.role-name
| INDEX [ owner.]index-name
| JAVA CLASS java-class-name
| JAVA JAR java-jar-name
| LOGIN integrated_login_id
| PROCEDURE [ owner.]procedure-name
| TABLE [ owner.]table-name
| TRIGGER [ owner.]trigger-name
| USER userid
| VIEW [ owner.]view-name
}
IS comment
comment:
{ string | NULL }
Permissions Must either be the owner of the database object being commented, or have
DBA authority.
Side effects Automatic commit.
Description Several system tables have a column named Remarks that allows you to
associate a comment with a database item (SYSUSERPERM, SYSTABLE,
SYSCOLUMN, SYSINDEX, SYSLOGIN, SYSFOREIGNKEY,
SYSPROCEDURE, SYSTRIGGER). The COMMENT ON statement allows
you to set the Remarks column in these system tables. A comment can be
removed by setting it to NULL.
For a comment on an index or trigger, the owner of the comment is the
owner of the table on which the index or trigger is defined.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Examples The following examples show how to add and remove a comment.
♦ Add a comment to the employee table.
COMMENT
ON TABLE employee
IS ’Employee information’

406
Chapter 9 SQL Statements

♦ Remove the comment from the employee table.


COMMENT
ON TABLE employee
IS NULL

407
COMMIT statement

COMMIT statement
Function Use this statement to make changes to the database permanent, or to
terminate a user-defined transaction.
Syntax 1 COMMIT [ WORK ]
Syntax 2 COMMIT TRAN[SACTION] [ transaction-name ]
Permissions None.
Side effects Closes all cursors except those opened WITH HOLD.
Deletes all rows of declared temporary tables on this connection, unless they
were declared using ON COMMIT PRESERVE ROWS..
See also "BEGIN TRANSACTION statement" on page 395
"PREPARE TO COMMIT statement" on page 566
"ROLLBACK statement" on page 583
Description Syntax 1 The COMMIT statement ends a transaction and makes all
changes made during this transaction permanent in the database.
Data definition statements all carry out a commit automatically. For
information, see the Side effects listing for each SQL statement.
The COMMIT statement fails if the database server detects any invalid
foreign keys. This makes it impossible to end a transaction with any invalid
foreign keys. Usually, foreign key integrity is checked on each data
manipulation operation. However, if the database option
WAIT_FOR_COMMIT is set ON or a particular foreign key was defined
with a CHECK ON COMMIT clause, the database server delays integrity
checking until the COMMIT statement is executed.
Syntax 2 You can use BEGIN TRANSACTION and COMMIT
TRANSACTION statements in pairs to construct nested transactions.
Nested transactions are similar to savepoints. When executed as the
outermost of a set of nested transactions, the statement makes changes to the
database permanent. When executed inside a transaction, the COMMIT
TRANSACTION statement decreases the nesting level of transactions by
one. When transactions are nested, only the outermost COMMIT makes the
changes to the database permanent.
Parameters transaction-name An optional name assigned to this transaction. It must
be a valid identifier. You should use transaction names only on the outermost
pair of nested BEGIN/COMMIT or BEGIN/ROLLBACK statements.

408
Chapter 9 SQL Statements

$ For more information on transaction nesting in Adaptive Server


Enterprise and Adaptive Server Anywhere, see "BEGIN TRANSACTION
statement" on page 395. For more information on savepoints, see
"SAVEPOINT statement" on page 586.
You can use a set of options to control the detailed behavior of the COMMIT
statement. For information, see "COOPERATIVE_COMMIT_TIMEOUT
option" on page 169, "COOPERATIVE_COMMITS option" on page 168,
"DELAYED_COMMITS option" on page 172, and
"DELAYED_COMMIT_TIMEOUT option" on page 172. You can use the
Commit connection property to return the number of Commits on the current
connection.
Standards and ♦ SQL/92 Syntax 1 is an entry-level feature. Syntax 2 is a Transact-SQL
compatibility extension.
♦ Sybase Supported by Adaptive Server Enterprise.
Examples ♦ The following statement commits the current transaction:
COMMIT
♦ The following Transact-SQL batch reports successive values of
@@trancount as 0, 1, 2, 1, 0.
PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
COMMIT TRANSACTION
PRINT @@trancount
COMMIT TRANSACTION
PRINT @@trancount
go

409
CONFIGURE statement [Interactive SQL]

CONFIGURE statement [Interactive SQL]


Function Use this statement to activate the Interactive SQL configuration window.
Syntax CONFIGURE
Permissions None.
Side effects None.
See also "SET OPTION statement" on page 596
Description The CONFIGURE statement activates the Interactive SQL configuration
window. This window displays the current settings of all Interactive SQL
options. It does not display or allow you to modify database options.
If you select Permanent, the options are written to the SYSOPTION table in
the database and the database server performs an automatic COMMIT. If you
do not choose Permanent, and instead click OK, the options are set
temporarily and remain in effect for the current database connection only.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

410
Chapter 9 SQL Statements

CONNECT statement [ESQL] [Interactive SQL]


Function Use this statement to establish a connection to a database.
Syntax 1 CONNECT
… [ TO engine-name ]
… [ DATABASE database-name ]
… [ AS connection-name ]
… [ USER ] userid [ IDENTIFIED BY password ]
engine-name | database-name | connection-name | userid | password:
{ identifier | string | host-variable }
Syntax 2 CONNECT USING connect-string
connect-string:
{ identifier | string | host-variable }
Permissions None.
Side effects None.
See also "GRANT statement" on page 526
"DISCONNECT statement" on page 490
"SET CONNECTION statement" on page 594
"SETUSER statement" on page 601
"Connection parameters" on page 44
Description The CONNECT statement establishes a connection to the database identified
by database-name running on the server identified by engine-name.

Embedded SQL behavior In Embedded SQL, if no engine-name is


specified, the default local database server will be assumed (the first database
server started). If no database-name is specified, the first database on the
given server will be assumed.
The WHENEVER statement, SET SQLCA and some DECLARE statements
do not generate code and thus may appear before the CONNECT statement
in the source file. Otherwise, no statements are allowed until a successful
CONNECT statement has been executed.
The user ID and password are used for permission checks on all dynamic
SQL statements.
You can connect without explicitly specifying a password by using a host
variable for the password and setting the value of the host variable to be the
null pointer.
$ For a detailed description of the connection algorithm, see
"Troubleshooting connections" on page 63 of the book ASA User’s Guide.

411
CONNECT statement [ESQL] [Interactive SQL]

Interactive SQL behavior If no database or server is specified in the


CONNECT statement, Interactive SQL remains connected to the current
database, rather than to the default server and database. If a database name is
specified without a server name, Interactive SQL attempts to connect to the
specified database on the current server. If a server name is specified without
a database name, Interactive SQL connects to the default database on the
specified server.
For example, if the following batch is executed while connected to a
database, the two tables are created in the same database.
CREATE TABLE t1( c1 int )
go
CONNECT DBA IDENTIFIED BY SQL
go
CREATE TABLE t2 (c1 int )
go
No other database statements are allowed until a successful CONNECT
statement has been executed.
The user ID and password are used for checking the permissions on SQL
statements. If the password or the user ID and password are not specified, the
user will be prompted to type the missing information.
Multiple connections are managed through the concept of a current
connection. After a successful connect statement, the new connection
becomes the current one. To switch to a different connection, use the
SET CONNECTION statement. The DISCONNECT statement is used to
drop connections.

Connecting with no password If you are connected to a user ID with


DBA authority, you can connect to another user ID without specifying a
password. (The output of dbtran requires this capability.) For example, if you
are connected to a database from Interactive SQL as DBA, you can connect
without a password with the statement:
CONNECT other_user_id

Syntax 2 A connect-string is a list of parameter settings of the form


keyword=value, and must be enclosed in single quotes.
$ For more information on connection strings, see "Connection
parameters" on page 60 of the book ASA User’s Guide.
Parameters AS clause A connection can optionally be named by specifying the AS
clause. This allows multiple connections to the same database, or multiple
connections to the same or different database servers, all simultaneously.
Each connection has its own associated transaction. You may even get
locking conflicts between your transactions if, for example, you try to
modify the same record in the same database from two different connections.
412
Chapter 9 SQL Statements

Standards and ♦ SQL/92 Syntax 1 is a full SQL feature; syntax 2 is a vendor extension.
compatibility
♦ Sybase Open Client Embedded SQL supports a different syntax for
the CONNECT statement.
Examples ♦ The following are examples of CONNECT usage within Embedded
SQL.
EXEC SQL CONNECT AS :conn_name
USER :userid IDENTIFIED BY :password;
EXEC SQL CONNECT USER "dba" IDENTIFIED BY "sql";
♦ Connect to a database from Interactive SQL. Interactive SQL prompts
for a user ID and a password.
CONNECT
♦ Connect to the default database as DBA, from Interactive SQL.
Interactive SQL promptS for a password.
CONNECT USER "DBA"
♦ Connect to the sample database as the DBA, from Interactive SQL.
CONNECT
TO asademo
USER DBA
IDENTIFIED BY sql
♦ Connect to the sample database using a connect string, from
Interactive SQL.
CONNECT
USING ’UID=DBA;PWD=sql;DBN=asademo’

413
CREATE COMPRESSED DATABASE statement

CREATE COMPRESSED DATABASE statement


Function Use this statement to create a compressed database from an existing database
file, or to expand a compressed database.
Syntax CREATE [ COMPRESSED | EXPANDED ] DATABASE new-db-file-name
… FROM old-db-file-name
new-db-file-name | old-db-file-name: 'file-name'

Permissions ♦ The permissions required to execute this statement are set on the server
command line, using the -gu command-line option. The default setting
is to require DBA authority.
♦ The operating system account under which the server is running must
have write permissions on the directories where files are created.
♦ The old database file must not be currently running.
♦ Not supported on Windows CE.
Side effects An operating system file is created.
See also "The Compression utility" on page 81
"The Uncompression utility" on page 124
Description Creates a compressed database file from an uncompressed database file, or
an uncompressed database file from a compressed one.
Any relative path is resolved relative to the current working directory of the
server.
You cannot use this statement on files other than the main database file.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example ♦ The following statement creates a compressed database file named
compress.db in the C:\ directory from a database file named full.db in the
current working directory of the server.
CREATE COMPRESSED DATABASE ’C:\\compress.db’
FROM ’full.db’
♦ The following statement creates an uncompressed database file named
full.db in the C:\ directory from a compressed database file named
compress.db in the current working directory of the server.
CREATE EXPANDED DATABASE ’C:\\full.db’
FROM ’compress.db’

414
Chapter 9 SQL Statements

CREATE DATABASE statement


Function Use this statement to create a database. The database is stored as an
operating-system file.
Syntax CREATE DATABASE db-file-name
…[
… [ [ TRANSACTION ] LOG OFF
| [ TRANSACTION ] LOG ON [ log-file-name-string ]
[ MIRROR mirror-file-name-string ]
]
… [ CASE { RESPECT | IGNORE } ]
… [ PAGE SIZE page-size ]
… [ COLLATION collation-label ]
… [ ENCRYPTED { ON | OFF } ]
… [ BLANK PADDING { ON | OFF } ]
… [ ASE [ COMPATIBLE ] ]
… [ JAVA { ON | OFF } ]
… [ JCONNECT { ON | OFF } ]
]
page-size :
1024 | 2048 | 4096 | 8192 | 16384 | 32768
collation-label: string

Permissions The permissions required to execute this statement are set on the server
command line, using the -gu command-line option. The default setting is to
require DBA authority.
The account under which the server is running must have write permissions
on the directories where files are created.
Not supported on Windows CE.
Side effects An operating system file is created.
See also "ALTER DATABASE statement" on page 371
"DROP DATABASE statement" on page 493
"The Initialization utility" on page 92
Description Creates a database file with the supplied name and attributes.
Parameters File name The file names ( db-file-name-string, log-file-name-string,
mirror-file-name-string) are strings containing operating system file names.
As literal strings, they must be enclosed in single quotes.

415
CREATE DATABASE statement

♦ If you specify a path, any backslash characters (\) must be doubled if


they are followed by an n or an x. Escaping them prevents them being
interpreted as new line characters (\n) or as hexadecimal numbers (\x),
according to the rules for strings in SQL.
It is safer to always escape the backslash character. For example:
CREATE DATABASE ’c:\\sybase\\my_db.db’
LOG ON ’e:\\logdrive\\my_db.log’
♦ If you specify no path, or a relative path, the database file is created
relative to the working directory of the server. If you specify no path for
a log file, the file is created in the same directory as the database file.
♦ If you provide no file extension, a file is created with extension .db for
databases, .log for the transaction log, or .mlg for the mirror log.

TRANSACTION LOG clause The transaction log is a file where the


database server logs all changes made to the database. The transaction log
plays a key role in backup and recovery (see "The transaction log" on
page 633 of the book ASA User’s Guide), and in data replication.

MIRROR clause A transaction log mirror is an identical copy of a


transaction log, usually maintained on a separate device, for greater
protection of your data. By default, Adaptive Server Anywhere does not use
a mirrored transaction log. If you do wish to use a transaction log mirror, this
option allows you to provide a filename.

CASE clause For databases created with CASE RESPECT, all values are
case sensitive in comparisons and string operations.
This option is provided for compatibility with the ISO/ANSI SQL standard.
The default value for the option is CASE IGNORE; that is, all comparisons
are case insensitive. If you create a case-sensitive database, all passwords are
case sensitive. User IDs and other identifiers in the database are case
insensitive, even in case sensitive databases.

PAGE SIZE clause The page size for a database can be 1024, 2048, 4096,
8192, 16384, or 32768 bytes. The default page size is 2048 bytes. Large
databases generally obtain performance benefits from a larger page size, but
there can be additional overhead associated with large page sizes.
$ For more information, see "Information utility options" on page 90.
For example:
CREATE DATABASE ’c:\\sybase\\my_db.db’
PAGE SIZE 4096

416
Chapter 9 SQL Statements

Page size limit


The page size cannot be larger than the page size used by the current
server. The server page size is taken from the first set of databases started
or is set on the server command line using the -gp command-line option.

COLLATION clause The collation sequence used for all string


comparisons in the database.
$ For more information on collation sequences, see "International
Languages and Character Sets" on page 279 of the book ASA User’s Guide.

ENCRYPTED clause Encryption makes it more difficult for someone to


decipher the data in your database by using a disk utility to look at the file.
Using this clause creates the database as an encrypted file.

BLANK PADDING clause If you specify BLANK PADDING ON,


trailing blanks are ignored in comparisons. For example, the two strings
’Smith’
’Smith ’
would be treated as equal in a database created with BLANK PADDING
ON.
This option is provided for compatibility with the ISO/ANSI SQL standard,
which is to ignore trailing blanks in comparisons. The default is that blanks
are significant for comparisons (BLANK PADDING OFF).

ASE COMPATIBLE clause Do not create the SYS.SYSCOLUMNS and


SYS.SYSINDEXES views. By default, these views are created for
compatibility with system tables available in Watcom SQL (versions 4 and
earlier of this software). These views conflict with the Sybase Adaptive
Server Enterprise compatibility views dbo.syscolumns and dbo.sysindexes.

JCONNECT clause If you wish to use the Sybase jConnect JDBC driver
to access system catalog information, you need to install jConnect support.
Specify JCONNECT OFF if you wish to exclude the jConnect system
objects. You can still use JDBC, as long as you do not access system
information.

JAVA clause If you wish to use Java in your database, you must install
entries for the Sybase runtime Java classes into the system tables. By default,
these entries are installed. You can specify JAVA OFF if you are sure you
will not be using Java, to avoid installing these entries.
Standards and ♦ SQL/92 Vendor extension.
compatibility

417
CREATE DATABASE statement

♦ Sybase Adaptive Server Enterprise provides a CREATE DATABASE


statement, but with different options.
Example ♦ The following statement creates a database file named mydb.db in the
C:\ directory.
CREATE DATABASE ’C:\\mydb’
TRANSACTION LOG ON
CASE IGNORE
PAGE SIZE 1024
COLLATION ’437’
ENCRYPTED OFF
BLANK PADDING OFF
JAVA ON
JCONNECT OFF
♦ The following statement creates a database with no Sybase runtime Java
classes. All database operations will execute normally, except for those
involving Java classes or objects.
CREATE DATABASE ’C:\\nojava’
JAVA OFF

418
Chapter 9 SQL Statements

CREATE DBSPACE statement


Function Use this statement to define a new database space and create the associated
database file.
Syntax CREATE DBSPACE dbspace-name
AS filename
Permissions Must have DBA authority.
Side effects Automatic commit. Automatic checkpoint.
See also "DROP statement" on page 491
"Using additional dbspaces" on page 766 of the book ASA User’s Guide
Description The CREATE DBSPACE statement creates a new database file. When a
database is created, it is composed of one file. All tables and indexes created
are placed in that file. CREATE DBSPACE adds a new file to the database.
This file can be on a different disk drive than the main file, which means that
the database can be larger than one physical device.
For each database, there is a limit of twelve dbspaces, including the main
file.
Each table is contained entirely within one database file. The IN clause of the
CREATE TABLE statement specifies the dbspace into which a table is
placed. Tables are put into the main database file by default.
Parameters dbspace-name An internal name for the database file. The filename
parameter is the actual name of the database file, with a path where
necessary.

filename A filename without an explicit directory is created in the same


directory as the main database file. Any relative directory is relative to the
main database file. The filename is relative to the database server. When you
are using the database server for NetWare, the filename should use a volume
name (not a drive letter) when an absolute directory is specified.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example ♦ Create a dbspace called library to hold the LibraryBooks table and its
indexes.
CREATE DBSPACE library
AS ’e:\\dbfiles\\library.db’;

419
CREATE DBSPACE statement

CREATE TABLE LibraryBooks (


title char(100),
author char(50),
isbn char(30),
) IN library;

420
Chapter 9 SQL Statements

CREATE DOMAIN statement


Function Use this statement to create a domain in a database.
Syntax CREATE { DOMAIN | DATATYPE } [ AS ] domain-name data-type
… [ [ NOT ] NULL ]
… [ DEFAULT default-value ]
… [ CHECK ( condition ) ]
domain-name: identifier
data-type: built-in data type, with precision and scale
Permissions Must have RESOURCE authority.
Side effects Automatic commit.
See also "DROP statement" on page 491
"SQL Data Types" on page 251
Description Domains are aliases for built-in data types, including precision and scale
values where applicable. They improve convenience and encourage
consistency in the database.
Domains are objects within the database. Their names must conform to the
rules for identifiers. Domain names are always case insensitive, as are built-
in data type names.
The user who creates a data type is automatically made the owner of that
data type. No owner can be specified in the CREATE DATATYPE
statement. The domain name must be unique, and all users can access the
data type without using the owner as prefix.
Domains can have CHECK conditions and DEFAULT values, and you can
indicate whether the data type permits NULL values or not. These conditions
and values are inherited by any column defined on the data type. Any
conditions or values explicitly specified on the column override those
specified for the data type.
To drop the data type from the database, use the DROP statement. You must
be either the owner of the data type or have DBA authority in order to drop a
domain.
Parameters DOMAIN | DATATYPE It is recommended that you use CREATE
DOMAIN, rather than CREATE DATATYPE, because CREATE DOMAIN
is the ANSI/ISO SQL3 term.

421
CREATE DOMAIN statement

NULL By default, domains allow NULLs unless the


allow_nulls_by_default option is set to OFF. In this case, new domains by
default do not allow NULLs. The nullability of a column created on a
domain depends on the setting of the definition of the domain, not on the
setting of the allow_nulls_by_default option when the column is referenced.
Any explicit setting of NULL or NOT NULL in the column definition
overrides the domain setting.

CHECK clause When creating a CHECK condition, you can use a


variable name prefixed with the @ sign in the condition. When the data type
is used in the definition of a column, such a variable is replaced by the
column name. This allows CHECK conditions to be defined on data types
and used by columns of any name.
Standards and ♦ SQL/92 Intermediate level feature.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise. Transact-SQL
provides similar functionality using the sp_addtype system procedure
and the CREATE DEFAULT and CREATE RULE statements.
Example ♦ The following statement creates a data type named address, which holds
a 35-character string, and which may be NULL.
CREATE DOMAIN address CHAR( 35 ) NULL
♦ The following statement creates a data type named id, which does not
allow NULLS, and which is autoincremented by default.
CREATE DOMAIN id INT
NOT NULL
DEFAULT AUTOINCREMENT

422
Chapter 9 SQL Statements

CREATE EVENT statement


Function Use this statement to define an event and its associated handler for
automating predefined actions. Also, to define scheduled actions.
Syntax CREATE EVENT event-name
… [ TYPE event-type
[ WHERE trigger-condition [ AND trigger-condition ], … ]
| SCHEDULE schedule-spec, … ]
… [ ENABLE | DISABLE ]
… [ AT { CONSOLIDATED | REMOTE | ALL } ]
…[ HANDLER
BEGIN

END ]
event-type
BackupEnd | "Connect"
| ConnectFailed | DatabaseStart
| DBDiskSpace | "Disconnect"
| GlobalAutoincrement | GrowDB
| GrowLog | GrowTemp
| LogDiskSpace | "RAISERROR"
| ServerIdle | TempDiskSpace
trigger-condition:
event_condition( condition-name ) { = | < | > | != | <= | >= } value
schedule-spec:
[ schedule-name ]
{ START TIME start-time | BETWEEN start-time AND end-time }
[ EVERY period { HOURS | MINUTES | SECONDS } ]
[ ON { ( day-of-week, … ) | ( day-of-month, … ) } ]
[ START DATE start-date ]
event-name | schedule-name:
identifier
day-of-week :
string
day-of-month | value | period :
integer
start-time | end-time :
time
start-date :
date
Permissions Must have DBA authority.

423
CREATE EVENT statement

Event handlers execute on a separate connection, with the permissions of the


event owner. To execute with permissions other than DBA, you can call a
procedure from within the event handler: the procedure executes with the
permissions of its owner. The separate connection does not count towards the
ten-connection limit of the personal database server.
Side effects Automatic commit.
The actions of an event handler are committed if no error is detected during
execution, and rolled back if errors are detected.
See also "BEGIN statement" on page 392
"ALTER EVENT statement" on page 375
"COMMENT statement" on page 406
"DROP statement" on page 491
"TRIGGER EVENT statement" on page 614
Description Events can be used in two main ways:
♦ Scheduling actions The database server carries out a set of actions on
a schedule of times. You could use this capability to schedule backups,
validity checks, queries to fill up reporting tables, and so on.
♦ Event handling actions The database server carries out a set of
actions when a predefined event occurs. The events that can be handled
include disk space restrictions (when a disk fills beyond a specified
percentage), when the server is idle, and so on.
An event definition includes two distinct pieces. The trigger condition can
be an occurrence, such as a disk filling up beyond a defined threshold. A
schedule is a set of times, each of which acts as a trigger condition. When a
trigger condition is satisfied, the event handler executes. The event handler
includes one or more actions specified inside a compound statement
(BEGIN… END).
If no trigger condition or schedule specification is supplied, only an explicit
TRIGGER EVENT statement can trigger the event. During development,
you may wish to develop and test event handlers using TRIGGER EVENT,
and add the schedule or WHERE clause once testing is complete.
Event errors are logged to the database server console.
When event handlers are triggered, the server makes context information,
such as the connection ID that caused the event to be triggered, available to
the event handler using the event_parameter function.
Parameters CREATE EVENT clause The event name is an identifier. An event has a
creator, which is the user creating the event, and the event handler executes
with the permissions of that creator. This is the same as stored procedure
execution. You cannot create events owned by other users.

424
Chapter 9 SQL Statements

TYPE clause The event-type is one of the listed set of system-defined


event types. The event types are case insensitive. To specify the conditions
under which this event-type triggers the event, use the WHERE clause.
♦ DiskSpace event types If the database contains an event handler for
one of the DiskSpace types, the database server checks the available
space on each device associated with the relevant file every 30 seconds.
In the event the database has more than one dbspace, on separate drives,
DBDiskSpace checks each drive and acts depending on the lowest
available space.
The LogDiskSpace event type checks the location of the transaction log
and any mirrored transaction log, and reports based on the least available
space.
The disk space event types require one of the following operating
systems:
♦ Windows 95 OSR2
♦ Windows 98
♦ Windows NT 4.0 or later
♦ Globalautoincrement event type This event fires when the GLOBAL
AUTOINCREMENT default value for a table is within one percent of
the end of its range. A typical action for the handler could be to request a
new value for the GLOBAL_DATABASE_ID option.
You can use the event_condition function with RemainingValues as
argument for this event type.
♦ ServerIdle event type If the database contains an event handler for the
ServerIdle type, the server checks for server activity every 30 seconds.

WHERE clause The trigger condition determines the condition under


which an event is fired. For example, to take an action when the disk
containing the transaction log becomes more than 80% full, use the
following triggering condition:
...
WHERE event_condition( ’LogDiskSpacePercentFree’ ) < 20
...
The argument to the event_condition function must be valid for the event
type.
You can use multiple AND conditions to make up the WHERE clause, but
you cannot use OR conditions or other conditions.
$ For information on valid arguments, see "EVENT_CONDITION
function" on page 323.

425
CREATE EVENT statement

SCHEDULE clause This clause specifies when scheduled actions are to


take place. The sequence of times acts as a set of triggering conditions for the
associated actions defined in the event handler.
You can create more than one schedule for a given event and its associated
handler. This permits complex schedules to be implemented. While it is
compulsory to provide a schedule-name when there is more than one
schedule, it is optional if you provide only a single schedule.
When a non-recurring scheduled event has passed, its schedule is deleted, but
the event handler is not deleted.
Scheduled event times are calculated when the schedules are created, and
again when the event handler completes execution. The next event time is
computed by inspecting the schedule or schedules for the event, and finding
the next schedule time that is in the future. If an event handler is instructed to
run every hour between 9:00 and 5:00, and it takes 65 minutes to execute, it
runs at 9:00, 11:00, 1:00, 3:00, and 5:00. If you want execution to overlap,
you must create more than one event.
The subclauses of a schedule definition are as follows:
♦ START TIME The first scheduled time for each day on which the event
is scheduled. If a START DATE is specified, the START TIME refers
to that date. If no START DATE is specified, the START TIME is on
the current day (unless the time has passed) and each subsequent day.
♦ BETWEEN … AND A range of times during the day outside of which
no scheduled times occur. If a START DATE is specified, the scheduled
times do not occur until that date.
♦ EVERY An interval between successive scheduled events. Scheduled
events occur only after the START TIME for the day, or in the range
specified by BETWEEN … AND.
♦ ON A list of days on which the scheduled events occur. The default is
every day. These can be specified as days of the week or days of the
month.
Days of the week are the abbreviated forms of the day, such as Mon,
Tue, and so on.
Days of the month are integers from 0 to 31. A value of 0 represents the
last day of any month.
♦ START DATE The date on which scheduled events are to start
occurring. The default is the current date.
Each time a scheduled event handler is completed, the next scheduled time
and date is calculated.

426
Chapter 9 SQL Statements

1 If the EVERY clause is used, find whether the next scheduled time falls
on the current day, and is before the end of the BETWEEN … AND
range. If so, that is the next scheduled time.
2 If the next scheduled time does not fall on the current day, find the next
date on which the event is to be executed.
3 Find the START TIME for that date, or the beginning of the BETWEEN
… AND range.

ENABLE | DISABLE By default, event handlers are enabled. When


DISABLE is specified, the event handler does not execute even when the
scheduled time or triggering condition occurs. A TRIGGER EVENT
statement does not cause a disabled event handler to be executed.

AT clause If you wish to execute events at remote or consolidated


databases in a SQL Remote setup, you can use this clause to restrict the
databases at which the event is handled. By default, all databases execute the
event.

HANDLER clause Each event has one handler.


Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Examples ♦ Instruct the database server to carry out an automatic backup to tape
using the first tape drive on a Windows NT machine, every day at 1 am.
CREATE EVENT DailyBackup
SCHEDULE daily_backup
START TIME ’1:00AM’ EVERY 24 HOURS
HANDLER
BEGIN
BACKUP DATABASE TO ’\\\\.\\tape0’
ATTENDED OFF
END

427
CREATE EXISTING TABLE statement

CREATE EXISTING TABLE statement


Function Use this statement to create a new proxy table, which represents an existing
object on a remote server.
Syntax CREATE EXISTING TABLE [owner.]table-name
[(column-definition, …)]
AT ’location-string’
column-definition:
column-name data-type [NOT NULL]
location-string:
remote-server-name.[db-name].[owner].object-name
| remote-server-name;[db-name];[owner];object-name
Permissions Must have RESOURCE authority. To create a table for another user, you
must have DBA authority.
Supported on Windows 95 and Windows NT only.
Side effects Automatic commit.
See also CREATE TABLE statement
Description The CREATE EXISTING TABLE statement creates a new local, proxy table
that maps to a table at an external location. The CREATE EXISTING
TABLE statement is a variant of the CREATE TABLE statement. The
EXISTING keyword is used with CREATE TABLE to specify that a table
already exists remotely and that its metadata is to be imported into Adaptive
Server Anywhere. This establishes the remote table as a visible entity to
Adaptive Server Anywhere users. Adaptive Server Anywhere verifies that
the table exists at the external location before it creates the table.
If the object does not exist (either host data file or remote server object), the
statement is rejected with an error message.
Index information from the host data file or remote server table is extracted
and used to create rows for the system table sysindexes. This defines indexes
and keys in server terms and enables the query optimizer to consider any
indexes that may exist on this table.
Referential constraints are passed to the remote location when appropriate.
If column-definitions are not specified, Adaptive Server Anywhere derives
the column list from the metadata it obtains from the remote table. If
column-definitions are specified, Adaptive Server Anywhere verifies the
column-definitions. Column names, data types, lengths, identity property,
and null properties are checked for the following:
♦ Column names must match identically (although case is ignored).

428
Chapter 9 SQL Statements

♦ Data types in the CREATE EXISTING TABLE statement must match


or be convertible to the data types of the column on the remote location.
For example, a local column data type is defined as money, while the
remote column data type is numeric.
♦ Each column’s NULL property is checked. If the local column’s NULL
property is not identical to the remote column’s NULL property, a
warning message is issued, but the statement is not aborted.
♦ Each column’s length is checked. If the length of char, varchar, binary,
varbinary, decimal and numeric columns do not match, a warning
message is issued, but the command is not aborted.
You may choose to include only a subset of the actual remote column
list in your CREATE EXISTING statement.
Parameters AT clause The AT clause specifies the location of the remote object. The
AT clause supports the semicolon (;) as a delimiter. If a semicolon is present
anywhere in the location-string string, the semicolon is the field delimiter. If
no semicolon is present, a period is the field delimiter. This allows filenames
and extensions to be used in the database and owner fields. For example, the
following statement maps the table a1 to the MS Access file mydbfile.mdb:
CREATE EXISTING TABLE a1
AT ’access;d:\mydbfile.mdb;;a1’
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Examples ♦ Create a proxy table named blurbs for the blurbs table at the remote
server server_a.
CREATE EXISTING TABLE blurbs
( author_id id not null,
copy text not null)
AT ’server_a.db1.joe.blurbs’
♦ Create a proxy table named blurbs for the blurbs table at the remote
server server_a. Adaptive Server Anywhere derives the column list from
the metadata it obtains from the remote table.
CREATE EXISTING TABLE blurbs
AT ’server_a.db1.joe.blurbs’
♦ Create a proxy table named rda_employee for the employee table at the
Adaptive Server Anywhere remote server asademo.
CREATE EXISTING TABLE rda_employee
AT ’asademo..dba.employee’

429
CREATE EXTERNLOGIN statement

CREATE EXTERNLOGIN statement


Function Use this statement to assign an alternate login name and password to be used
when communicating with a remote server.
Syntax CREATE EXTERNLOGIN login-name
TO remote-server
REMOTE LOGIN remote-user
[ IDENTIFIED BY remote-password ]
Permissions Only the login-name and the DBA account can add or modify an external
login for login-name.
Supported on Windows 95 and Windows NT only.
Side effects Automatic commit.
See also "DROP EXTERNLOGIN statement" on page 495
Description By default, Adaptive Server Anywhere uses the names and passwords of its
clients whenever it connects to a remote server on behalf of those clients.
CREATE EXTERNLOGIN assigns an alternate login name and password to
be used when communicating with a remote server.
The password is stored internally in encrypted form. The remote-server must
be known to the local server by an entry in the SYSERVERS table. For more
information, see "CREATE SERVER statement" on page 451.
Sites with automatic password expiration should plan for periodic updates of
passwords for external logins.
CREATE EXTERNLOGIN cannot be used from within a transaction.
Parameters login-name specifies the local user login name. When using integrated
logins, the login-name is the database user to which the Windows NT user
ID is mapped.

TO clause The TO clause specifies the name of the remote server.

REMOTE LOGIN clause The REMOTE LOGIN clause specifies the user
account on remote-server for the local user login-name.

IDENTIFIED BY clause The IDENTIFIED BY clause specifies the


remote-password for remote-user. The remote-user and remote-password
combination must be valid on the remote-server.
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Examples ♦ Map the local user named dba to the user sa with password Plankton
when connecting to the server sybase1.
430
Chapter 9 SQL Statements

CREATE EXTERNLOGIN dba


TO sybase1
REMOTE LOGIN sa
IDENTIFIED BY Plankton

431
CREATE FUNCTION statement

CREATE FUNCTION statement


Function Use this statement to create a new function in the database.
Syntax CREATE FUNCTION [ owner.]function-name ( [ parameter, … ] )
RETURNS data-type
{ EXTERNAL NAME library-call
| EXTERNAL NAME java-call LANGUAGE JAVA
| [ ON EXCEPTION RESUME ]
… compound-statement
}
parameter:
IN parameter-name data-type
library-call:
'[operating-system:]function-name@library.dll; …'
operating-system:
Windows95 | WindowsNT | NetWare | UNIX
java-call:
'[package-name.]class-name.method-name method-signature'
method-signature:
( [ field-descriptor, … ] ) return-descriptor
field-descriptor | return-descriptor:
Z | B | S | I | J | F | D | C | V | [descriptor | Lclass-name;
Permissions Must have RESOURCE authority.
External functions, including Java functions, must have DBA authority.
Side effects Automatic commit.
See also "DROP statement" on page 491
"BEGIN statement" on page 392
"CREATE PROCEDURE statement" on page 440
"RETURN statement" on page 579
"Using Procedures, Triggers, and Batches" on page 423 of the book ASA
User’s Guide
Description The CREATE FUNCTION statement creates a user-defined function in the
database. A function can be created for another user by specifying an owner
name. Subject to permissions, a user-defined function can be used in exactly
the same way as other non-aggregate functions.
Parameters CREATE FUNCTION clause Parameter names must conform to the rules
for database identifiers. They must have a valid SQL data type, and must be
prefixed by the keyword IN, signifying that the argument is an expression
that provides a value to the function.

432
Chapter 9 SQL Statements

EXTERNAL NAME clause A function using the EXTERNAL NAME


clause is a wrapper around a call to a function in an external library.
A function using EXTERNAL NAME can have no other clauses following
the RETURNS clause.
$ For information about external library calls, see "Calling external
libraries from procedures" on page 475 of the book ASA User’s Guide.

EXTERNAL NAME LANGUAGE JAVA clause A function that uses


EXTERNAL NAME with a LANGUAGE JAVA clause is a wrapper around
a Java method.
$ For information on calling Java procedures, see "CREATE
PROCEDURE statement" on page 440.

ON EXCEPTION RESUME clause Use Transact-SQL -like error


handling. For more information, see "CREATE PROCEDURE statement" on
page 440.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example ♦ The following function concatenates a firstname string and a lastname
string.
CREATE FUNCTION fullname (
firstname CHAR(30),
lastname CHAR(30) )
RETURNS CHAR(61)
BEGIN
DECLARE name CHAR(61);
SET name = firstname || ’ ’ || lastname;
RETURN (name);
END
The following examples illustrate the use of the fullname function.
♦ Return a full name from two supplied strings:
SELECT fullname (’joe’,’smith’)

fullname(’joe’, ’smith’)
joe smith

♦ List the names of all employees:


SELECT fullname (emp_fname, emp_lname)
FROM employee

433
CREATE FUNCTION statement

fullname (emp_fname, emp_lname)


Fran Whitney
Matthew Cobb
Philip Chin
Julie Jordan
Robert Breault

434
Chapter 9 SQL Statements

CREATE INDEX statement


Function Use this statement to create an index on a specified table. Indexes can
improve database performance.
Syntax CREATE [ UNIQUE ] INDEX index-name
… ON [ owner.]table-name
… ( column-name [ ASC | DESC ], … )
… [ { IN | ON } dbspace-name ]
… WITH [ MAX | MAXIMUM ] HASH SIZE hash-size
hash-size:
integer
Permissions Must be the owner of the table or have DBA authority.
The table must be a base table or a global temporary table.
Side effects Automatic commit.
See also "DROP statement" on page 491
"MAX_HASH_SIZE option" on page 185
"How indexes work" on page 795 of the book ASA User’s Guide
"Indexes on temporary tables" on page 797 of the book ASA User’s Guide
Description The CREATE INDEX statement creates a sorted index on the specified
columns of the named table. Indexes are automatically used to improve the
performance of queries issued to the database, and to sort queries with an
ORDER BY clause. Once an index is created, it is never referenced in a SQL
statement again except to validate it (VALIDATE INDEX) or delete it
(DROP INDEX).
You cannot create indexes on views or on local temporary tables.
♦ Index ownership There is no way of specifying the index owner in the
CREATE INDEX statement. Indexes are always owned by the owner of
the table. The index name must be unique for each owner.
♦ No indexes on views Indexes cannot be created for views.
♦ Index name space The name of each index must be unique for a
given table.
♦ Exclusive table use CREATE INDEX is prevented whenever the
statement affects a table currently being used by another connection.
CREATE INDEX can be time consuming and the server will not process
requests referencing the same table while the statement is being
processed.

435
CREATE INDEX statement

♦ Automatically created indexes Adaptive Server Anywhere


automatically creates indexes for primary keys and for unique
constraints. These automatically created indexes are held in the same
database file as the table.
Parameters UNIQUE keyword The UNIQUE attribute ensures that there will not be
two rows in the table with identical values in all the columns in the index.
Each index key must be unique or contain a NULL in at least one column.
There is a difference between a unique constraint on a table and a unique
index. Columns of a unique index are allowed to be NULL, while columns in
a unique constraint are not. A foreign key can reference either a primary key
or a column with a unique constraint, but not a unique index, because it can
include multiple instances of NULL.

ASC | DESC option Columns are sorted in ascending (increasing) order


unless descending (DESC) is explicitly specified. An index will be used for
both an ascending and a descending ORDER BY, whether the index was
ascending or descending. However, if an ORDER BY is performed with
mixed ascending and descending attributes, an index will be used only if the
index was created with the same ascending and descending attributes.

IN | ON clause By default, the index is placed in the same database file as


its table. You can place the index in a separate database file by specifying a
dbspace name in which to put the index. This feature is useful mainly for
large databases to circumvent file size limitations.
$ For more information on limitations, see "Size and number limitations"
on page 932.

WITH HASH SIZE clause By default, at most ten bytes of each index
entry is actually hashed (stored in the index). If a query needs access to more
than the hashed data, it needs to fetch it from the underlying row, and this
may affect index performance. You can explicitly configure the amount of
data that is stored in the index by specifying WITH HASH SIZE. Increasing
the hash size can reduce the number of times the underlying row needs to be
accessed. However, this is at the expense of a decreased index fanout. For
optimal performance, you should not increase hash size for all indexes, only
for indexes for which the first ten bytes of data does not provide high
selectivity.
If the data in the index does not require the whole space set aside by the
WITH HASH clause, it is not used. For example, a single column index
holding an integer (four bytes) takes only five bytes for each index entry,
even if the WITH HASH clause specifies a larger value.
The maximum hash size is 64 bytes.
The MAX and SIZE keywords are optional.

436
Chapter 9 SQL Statements

The MAX_HASH_SIZE database option changes the default hash size for
indexes.

Using WITH HASH on old databases


If you use the WITH HASH clause on databases created before the Aspen
release, no error is raised. However, all index entries will use a ten byte
limit on the database. The database must be created with Aspen or later
software.

$ For more information, see "How indexes work" on page 795 of the
book ASA User’s Guide.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Adaptive Server Enterprise has a more complex CREATE
INDEX statement than Adaptive Server Anywhere. While the Adaptive
Server Enterprise syntax is permitted in Adaptive Server Anywhere,
some clauses and keywords are ignored.
The full syntax for Adaptive Server Enterprise 11.5 is as follows:
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ]
… INDEX index-name
… ON [ [ database.]owner.]table_name
(column_name [, column_name], …)
… [ WITH {
… { FILLFACTOR | MAX_ROWS_PER_PAGE } = x,
CONSUMERS = x,
… IGNORE_DUP_KEY,
… SORTED_DATA,
[ IGNORE_DUP_ROW | ALLOW_DUP_ROW ]
}]
… [ ON segment_name ]
Adaptive Server Enterprise indexes can be either clustered or
nonclustered. A clustered index almost always retrieves data faster than
a nonclustered index. Only one clustered index is permitted per table.
Adaptive Server Anywhere does not support clustered indexes. The
CLUSTERED and NONCLUSTERED keywords are allowed by
Adaptive Server Anywhere, but no action is taken.
Adaptive Server Anywhere also allows, by ignoring, the following
keywords:
♦ FILLFACTOR
♦ IGNORE_DUP_KEY
♦ SORTED_DATA
♦ IGNORE_DUP_ROW
437
CREATE INDEX statement

♦ ALLOW_DUP_ROW
Physical placement of an index is carried out differently in Adaptive
Server Enterprise and Adaptive Server Anywhere. The ON segment-
name clause is supported in Adaptive Server Anywhere, but segment-
name refers to a dbspace.
Unique indexes in Adaptive Server Anywhere permit entries that contain
NULL, and are otherwise identical. Unique indexes in Adaptive Server
Enterprise do not permit entries that contain NULL and are otherwise
identical.
Index names must be unique on a given table for both Adaptive Server
Anywhere and Enterprise.
Examples ♦ Create a two-column index on the employee table.
CREATE INDEX employee_name_index
ON employee
( emp_lname, emp_fname )
♦ Create an index on the sales_order_items table for the prod_id column.
CREATE INDEX item_prod
ON sales_order_items
( prod_id )

438
Chapter 9 SQL Statements

CREATE MESSAGE statement [T-SQL]


Function Use this statement to add a user-defined message to the
SYSUSERMESSAGES system table for use by PRINT and RAISERROR
statements.
Syntax CREATE MESSAGE message-number
… AS message-text
message-number: integer
message-text: string
Permissions Must have RESOURCE authority
Side effects Automatic commit.
See also "PRINT statement" on page 567
"RAISERROR statement" on page 570
Description CREATE MESSAGE associates a message number with a message string.
The message number can be used in PRINT and RAISERROR statements.
Parameters message_num The message number of the message to add. The message
number for a user-defined message must be 20000 or greater.

message_text The text of the message to add. The maximum length is


255 bytes. PRINT and RAISERROR recognize placeholders in the message
text. A single message can contain up to 20 unique placeholders in any order.
These placeholders are replaced with the formatted contents of any
arguments that follow the message when the text of the message is sent to the
client.
The placeholders are numbered to allow reordering of the arguments when
translating a message to a language with a different grammatical structure. A
placeholder for an argument appears as "%nn!": a percent sign (%), followed
by an integer from 1 to 20, followed by an exclamation mark (!), where the
integer represents the position of the argument in the argument list. "%1!" is
the first argument, "%2!" is the second argument, and so on.
There is no parameter corresponding to the language argument for
sp_addmessage.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase The functionality of CREATE MESSAGE is provided by the
sp_addmessage procedure in Adaptive Server Enterprise.

439
CREATE PROCEDURE statement

CREATE PROCEDURE statement


Function Use this statement to create a procedure in the database.
Syntax CREATE PROCEDURE [ owner.]procedure-name ( [ parameter, … ] )
{ [ RESULT ( result-column, … ) ]
… [ ON EXCEPTION RESUME ]
… compound-statement
| AT location-string
| EXTERNAL NAME library-call
| [ DYNAMIC RESULT SETS integer-expression ]
… EXTERNAL NAME java-call LANGUAGE JAVA
}
parameter:
parameter_mode parameter-name data-type [ DEFAULT expression ]
| SQLCODE
| SQLSTATE
parameter_mode:
IN | OUT | INOUT
result-column:
column-name data-type
library-call:
'[operating-system:]function-name@library.dll; …'
operating-system:
Windows95 | WindowsNT | NetWare | UNIX
java-call:
'[package-name.]class-name.method-name method-signature'
method-signature:
( [ field-descriptor, … ] ) return-descriptor
field-descriptor | return-descriptor:
Z | B | S | I | J | F | D | C | V | [descriptor | Lclass-name;
Permissions Must have RESOURCE authority.
For external procedures, must have DBA authority.
Side effects Automatic commit.
See also "BEGIN statement" on page 392
"CALL statement" on page 398
"CREATE FUNCTION statement" on page 432
"CREATE PROCEDURE statement" on page 447
"DROP statement" on page 491
"EXECUTE IMMEDIATE statement" on page 504
"GRANT statement" on page 526

440
Chapter 9 SQL Statements

"Using Procedures, Triggers, and Batches" on page 423 of the book ASA
User’s Guide
Description The CREATE PROCEDURE statement creates a procedure in the database.
Users with DBA authority can create procedures for other users by
specifying an owner. A procedure is invoked with a CALL statement.
Parameters CREATE PROCEDURE clause Parameter names must conform to the
rules for other database identifiers such as column names. They must be a
valid SQL data type (see "SQL Data Types" on page 251), and must be
prefixed by one of the keywords IN, OUT or INOUT. The keywords have
the following meanings:
♦ IN The parameter is an expression that provides a value to the
procedure.
♦ OUT The parameter is a variable that could be given a value by the
procedure.
♦ INOUT The parameter is a variable that provides a value to the
procedure, and could be given a new value by the procedure.
When procedures are executed using the CALL statement, not all parameters
need to be specified. If a default value is provided in the CREATE
PROCEDURE statement, missing parameters are assigned the default values.
If an argument is not provided in the CALL statement, and no default is set,
an error is given.
SQLSTATE and SQLCODE are special parameters that output the
SQLSTATE or SQLCODE value when the procedure ends (they are OUT
parameters). Whether or not a SQLSTATE and SQLCODE parameter is
specified, the SQLSTATE and SQLCODE special values can always be
checked immediately after a procedure call to test the return status of the
procedure.
The SQLSTATE and SQLCODE special values are modified by the next
SQL statement. Providing SQLSTATE or SQLCODE as procedure
arguments allows the return code to be stored in a variable.

RESULT clause The RESULT clause declares the number and type of
columns in the result set. The parenthesized list following the RESULT
keyword defines the result column names and types. This information is
returned by the Embedded SQL DESCRIBE or by ODBC SQLDescribeCol
when a CALL statement is being described. Allowable data types are listed
in "SQL Data Types" on page 251.
$ For more information on returning result sets from procedures, see
"Returning results from procedures" on page 453 of the book ASA User’s
Guide.

441
CREATE PROCEDURE statement

Some procedures can more than one result set, with different numbers of
columns, depending on how they are executed. For example, the following
procedure returns two columns under some circumstances, and one in others.
CREATE PROCEDURE names( IN formal char(1))
BEGIN
IF formal = ’n’ THEN
SELECT emp_fname
FROM employee
ELSE
SELECT emp_lname,emp_fname
FROM employee
END IF
END
Procedures with variable result sets must be written without a RESULT
clause, or in Transact-SQL. Their use is subject to the following limitations:
♦ Embedded SQL You must DESCRIBE the procedure call after the
cursor for the result set is opened, but before any rows are returned, in
order to get the proper shape of result set. The CURSOR cursor-name
clause on the DESCRIBE statement is required.
♦ ODBC Variable result-set procedures can be used by ODBC
applications. The proper description of the result sets is carried out by
the ODBC driver.
♦ Open Client applications Variable result-set procedures can be used
by Open Client applications.
If your procedure returns only one result set, you should use a RESULT
clause. The presence of this clause prevents ODBC and Open Client
applications from re-describing the result set after a cursor is open.
In order to handle multiple result sets, ODBC must describe the currently
executing cursor, not the procedure’s defined result set. Therefore, ODBC
does not always describe column names as defined in the RESULT clause of
the procedure definition. To avoid this problem, use column aliases in the
SELECT statement that generates the result set.

ON EXCEPTION RESUME clause This clause enables Transact-SQL -


like error handling to be used within a Watcom-SQL syntax procedure.
If you use ON EXCEPTION RESUME, the procedure takes an action that
depends on the setting of the ON_TSQL_ERROR option. If
ON_TSQL_ERROR is set to CONDITIONAL (which is the default) the
execution continues if the next statement handles the error; otherwise, it
exits.
Error-handling statements include the following:
♦ IF

442
Chapter 9 SQL Statements

♦ SELECT @variable =
♦ CASE
♦ LOOP
♦ LEAVE
♦ CONTINUE
♦ CALL
♦ EXECUTE
♦ SIGNAL
♦ RESIGNAL
♦ DECLARE
♦ SET VARIABLE

You should not use explicit error handling code with an ON EXCEPTION
RESUME clause.
$ For more information, see "ON_TSQL_ERROR option" on page 189.
EXTERNAL NAME clause A procedure using the EXTERNAL NAME
clause is a wrapper around a call to an external library. A stored procedure
using EXTERNAL NAME can have no other clauses following the
parameter list.
$ For information about external library calls, see "Calling external
libraries from procedures" on page 475 of the book ASA User’s Guide.

AT location-string clause Create a proxy stored procedure on the


current database for a remote procedure specified by location-string. The AT
clause supports the semicolon (;) as a field delimiter in location-string. If no
semicolon is present, a period is the field delimiter. This allows filenames
and extensions to be used in the database and owner fields.

For example, the following statement creates a proxy procedure (remotewho)


that calls the dbo.sp_who procedure on the master database of the bostonase
server:
CREATE PROCEDURE remotewho ()
AT ’bostonase.master.dbo.sp_who
Remote procedures can return only up to 254 characters in output variables.
$ For information on remote servers, see "CREATE SERVER statement"
on page 451. For information on using remote procedures, see "Using remote
procedure calls (RPCs)" on page 888 of the book ASA User’s Guide.

443
CREATE PROCEDURE statement

DYNAMIC RESULT SETS clause This clause is for use with procedures
that are wrappers around Java methods. If the DYNAMIC RESULT SETS
clause is not provided, it is assumed that the method returns no result set.

EXTERNAL NAME LANGUAGE JAVA clause A procedure that uses


EXTERNAL NAME with a LANGUAGE JAVA clause is a wrapper around
a Java method.
If the number of parameters is less than the number indicated in the method-
signature then the difference must equal the number specified in DYNAMIC
RESULT SETS, and each parameter in the method signature in excess of
those in the procedure parameter list must have a method signature of
[Ljava/sql/ResultSet;.
A Java method signature is a compact character representation of the types of
the parameters and the type of the return value.
The field-descriptor and return-descriptor have the following meanings:

Field type Java data type


B byte
C char
D double
F float
I int
J long
Lclass-name; an instance of the class class-name. The class name must be fully
qualified, and any dot in the namemust be replaced by a /. For
example, java/lang/String
S short
V void
Z boolean
[ use one for each dimension of an array

For example,
double some_method(
boolean a,
int b,
java.math.BigDecimal c,
byte [][] d,
java.sql.ResultSet[] d ) {
}

444
Chapter 9 SQL Statements

would have the following signature:


’(ZILjava/math/BigDecimal;[[B[Ljava/sql/ResultSet;)D’
$ For more information, see "Returning result sets from Java methods"
on page 563 of the book ASA User’s Guide.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase The Transact-SQL CREATE PROCEDURE statement is
different.
♦ SQLJ The syntax extensions for Java result sets are as specified in the
proposed SQLJ1 standard.
Example ♦ The following procedure uses a case statement to classify the results of a
query.
CREATE PROCEDURE ProductType (IN product_id INT, OUT
type CHAR(10))
BEGIN
DECLARE prod_name CHAR(20);
SELECT name INTO prod_name FROM "DBA"."product"
WHERE id = product_id;
CASE prod_name
WHEN ’Tee Shirt’ THEN
SET type = ’Shirt’
WHEN ’Sweatshirt’ THEN
SET type = ’Shirt’
WHEN ’Baseball Cap’ THEN
SET type = ’Hat’
WHEN ’Visor’ THEN
SET type = ’Hat’
WHEN ’Shorts’ THEN
SET type = ’Shorts’
ELSE
SET type = ’UNKNOWN’
END CASE;
END
♦ The following procedure uses a cursor and loops over the rows of the
cursor to return a single value.
CREATE PROCEDURE TopCustomer (OUT TopCompany
CHAR(35), OUT TopValue INT)
BEGIN
DECLARE err_notfound EXCEPTION
FOR SQLSTATE ’02000’;
DECLARE curThisCust CURSOR FOR
SELECT company_name, CAST(
sum(sales_order_items.quantity *
product.unit_price) AS INTEGER) VALUE
FROM customer
LEFT OUTER JOIN sales_order

445
CREATE PROCEDURE statement

LEFT OUTER JOIN sales_order_items


LEFT OUTER JOIN product
GROUP BY company_name;

DECLARE ThisValue INT;


DECLARE ThisCompany CHAR(35);
SET TopValue = 0;
OPEN curThisCust;
CustomerLoop:
LOOP
FETCH NEXT curThisCust
INTO ThisCompany, ThisValue;
IF SQLSTATE = err_notfound THEN
LEAVE CustomerLoop;
END IF;
IF ThisValue > TopValue THEN
SET TopValue = ThisValue;
SET TopCompany = ThisCompany;
END IF;
END LOOP CustomerLoop;
CLOSE curThisCust;
END

446
Chapter 9 SQL Statements

CREATE PROCEDURE statement [T-SQL]


Function Use this statement to create a new procedure in the database in a manner
compatible with Adaptive Server Enterprise.
Syntax The following subset of the Transact-SQL CREATE PROCEDURE
statement is supported in Adaptive Server Anywhere.
CREATE PROCEDURE [owner.]procedure_name
…[ [ ( ] @parameter_name data-type [ = default ] [ OUTPUT ], … [ ) ]
]
…[ WITH RECOMPILE ]
…AS
… statement-list
Permissions Must have RESOURCE authority.
Side effects Automatic commit.
See also "CREATE PROCEDURE statement" on page 440
Description The following differences between Transact-SQL and Adaptive Server
Anywhere statements (Watcom-SQL) are listed to help those writing in both
dialects.
♦ Variable names prefixed by @ The "@" sign denotes a Transact-SQL
variable name, while Watcom-SQL variables can be any valid identifier,
and the @ prefix is optional.
♦ Input and output parameters Watcom-SQL procedure parameters are
specified as IN, OUT, or INOUT, while Transact-SQL procedure
parameters are INPUT parameters by default or can be specified as
OUTPUT. Those parameters that would be declared as INOUT or as
OUT in Adaptive Server Anywhere should be declared with OUTPUT
in Transact-SQL.
♦ Parameter default values Watcom-SQL procedure parameters are
given a default value using the keyword DEFAULT, while Transact-
SQL uses an equality sign (=) to provide the default value.
♦ Returning result sets Watcom-SQL uses a RESULT clause to specify
returned result sets. In Transact-SQL procedures, the column names or
alias names of the first query are returned to the calling environment.
The following Transact-SQL procedure illustrates how result sets are
returned from Transact-SQL stored procedures:
CREATE PROCEDURE showdept @deptname varchar(30)
AS
SELECT employee.emp_lname, employee.emp_fname
FROM department, employee
WHERE department.dept_name = @deptname
447
CREATE PROCEDURE statement [T-SQL]

AND department.dept_id = employee.dept_id


The following is the corresponding Watcom-SQL procedure:
CREATE PROCEDURE showdept(in deptname
varchar(30) )
RESULT ( lastname char(20), firstname char(20))
ON EXCEPTION RESUME
BEGIN
SELECT employee.emp_lname, employee.emp_fname
FROM department, employee
WHERE department.dept_name = deptname
AND department.dept_id = employee.dept_id
END
♦ Procedure body The body of a Transact-SQL procedure is a list of
Transact-SQL statements prefixed by the AS keyword. The body of a
Watcom-SQL procedure is a compound statement, bracketed by BEGIN
and END keywords.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Anywhere supports a subset of the Adaptive Server Enterprise
CREATE PROCEDURE statement syntax.
If the Transact-SQL WITH RECOMPILE optional clause is supplied, it
is ignored. Adaptive Server Anywhere always recompiles procedures the
first time they are executed after a database is started, and stores the
compiled procedure until the database is stopped.
Groups of procedures are not supported.

448
Chapter 9 SQL Statements

CREATE SCHEMA statement


Function Use this statement to create a collection of tables, views, and permissions for
a database user.
Syntax CREATE SCHEMA AUTHORIZATION userid
…[
create-table-statement
| create-view-statement
| grant-statement
], …
Permissions Must have RESOURCE authority.
Side effects Automatic commit.
See also "CREATE TABLE statement" on page 453
"CREATE VIEW statement" on page 469
"GRANT statement" on page 526
Description The CREATE SCHEMA statement creates a schema. A schema is a
collection of tables, views, and their associated permissions.
The userid must be the user ID of the current connection. You cannot create
a schema for another user.
If any statement contained in the CREATE SCHEMA statement fails, the
entire CREATE SCHEMA statement is rolled back.
The CREATE SCHEMA statement is simply a way of collecting together
individual CREATE and GRANT statements into one operation. There is no
SCHEMA database object created in the database, and to drop the objects
you must use individual DROP TABLE or DROP VIEW statements. To
revoke permissions, you must use a REVOKE statement for each permission
granted.
The individual CREATE or GRANT statements are not separated by
statement delimiters. The statement delimiter marks the end of the CREATE
SCHEMA statement itself.
The individual CREATE or GRANT statements must be ordered such that
the objects are created before permissions are granted on them.
Although you can currently create more than one schema for a user, this is
not recommended, and may not be supported in future releases.
Standards and ♦ SQL/92 Entry level feature.
compatibility
♦ Sybase Adaptive Server Anywhere does not support the use of
REVOKE statements within the CREATE SCHEMA statement, and
does not allow its use within Transact-SQL batches or procedures.

449
CREATE SCHEMA statement

Examples ♦ The following CREATE SCHEMA statement creates a schema


consisting of two tables. The statement must be executed by the user ID
sample_user, who must have RESOURCE authority. If the statement
creating table t2 fails, neither table is created.
CREATE SCHEMA AUTHORIZATION sample_user
CREATE TABLE t1 ( id1 INT PRIMARY KEY )
CREATE TABLE t2 ( id2 INT PRIMARY KEY );
♦ The statement delimiter in the following CREATE SCHEMA statement
is placed after the first CREATE TABLE statement. As the statement
delimiter marks the end of the CREATE SCHEMA statement, the
example is interpreted as a two statement batch by the database server.
Consequently, if the statement creating table t2 fails, the table t1 is still
created.
CREATE SCHEMA AUTHORIZATION sample_user
CREATE TABLE t1 ( id1 INT PRIMARY KEY );
CREATE TABLE t2 ( id2 INT PRIMARY KEY );

450
Chapter 9 SQL Statements

CREATE SERVER statement


Function Use this statement to add a server to the SYSSERVERS system table.
Syntax CREATE SERVER server-name
CLASS ’server-class’
USING ’connection-info’
[ READ ONLY ]
server-class:
{ ASAJDBC | ASEJDBC
| ASAODBC | ASEODBC
| DB2ODBC | MSSODBC
| ORAODBC | ODBC }
connection-info:
{ machine-name:port-number[/dbname ] | data-source-name }
Permissions Must have RESOURCE authority.
Supported on Windows 95 and Windows NT only.
Side effects Automatic commit.
See also "ALTER SERVER statement" on page 378
"DROP SERVER statement" on page 497
"Server Classes for Remote Data Access" on page 899 of the book ASA
User’s Guide
Description The CREATE SERVER statement defines a remote server from the Adaptive
Server Anywhere catalogs.
$ For more information on server classes and how to configure a server,
see "Server Classes for Remote Data Access" on page 899 of the book ASA
User’s Guide.
Parameters USING clause If a JDBC-based server class is used, the USING clause is
of the form hostname:portnumber [/dbname], where:
♦ hostname is the machine the remote server runs on
♦ portnumber is the TCP/IP port number the remote server listens on.
The default port number for Adaptive Server Anywhere is 2638.
♦ dbname For Adaptive Server Anywhere remote servers, if you do not
specify a dbname, then the default database is used. For Adaptive Server
Enterprise, the default is the master database, and an alternative to using
dbname is to another database by some other means (for example, in the
FORWARD TO statement).
If an ODBC-based server class is used, the USING clause is the data-source-
name. The data-source-name is the ODBC Data Source Name.

451
CREATE SERVER statement

READ ONLY The READ ONLY clause specifies that the remote server is
a read-only data source. Any update request is rejected by Adaptive Server
Anywhere.
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Examples ♦ Create an Adaptive Server Anywhere remote server named testasa,
located on the machine apple and listening on port number 2638, use:
CREATE SERVER testasa
CLASS ’asajdbc’
USING ’apple:2638’
♦ Create a remote server for the JDBC-based Adaptive Server named
ase_prod. Its machine name is banana and port number is 3025.
CREATE SERVER ase_prod
CLASS ’asejdbc’
USING ’banana:3025’
♦ Create a remote server for the Oracle server named oracle723. Its ODBC
Data Source Name is oracle723.
CREATE SERVER oracle723
CLASS ’oraodbc’
USING ’oracle723’

452
Chapter 9 SQL Statements

CREATE TABLE statement


Function Use this statement to create a new table in the database and, optionally, to
create a table on a remote server.
Syntax CREATE [ GLOBAL TEMPORARY ] TABLE [ owner.]table-name
… ( { column-definition | table-constraint }, … )
… [ { IN | ON } dbspace-name ]
… [ ON COMMIT { DELETE | PRESERVE } ROWS ]
[ AT location-string ]
column-definition:
column-name data-type [ NOT NULL ]
… [ DEFAULT default-value ] [ column-constraint … ]
default-value:
AUTOINCREMENT
| GLOBAL AUTOINCREMENT [ ( partition-size ) ]
| ( constant-expression ) | global variable | NULL | number
| string | special-value | TIMESTAMP
special-value:
CURRENT { DATE | TIME | TIMESTAMP | USER | PUBLISHER }
| SQLCODE | SQLSTATE | LAST USER
column-constraint:
{ UNIQUE
| PRIMARY KEY
| REFERENCES table-name [( column-name )] [ actions ]
} [ WITH [ MAX | MAXIMUM ] HASH SIZE hash-size ]
| CHECK ( condition )
| COMPUTE ( expression )
table-constraint:
{ UNIQUE ( column-name, … )
| PRIMARY KEY ( column-name, … )
} [ WITH [ MAX | MAXIMUM ] HASH SIZE n ]
| CHECK ( condition ) | foreign-key-constraint
foreign-key-constraint:
[ NOT NULL ] FOREIGN KEY [role-name] [(column-name, … )]
… REFERENCES table-name [(column-name, … )]
… [ actions ] [ CHECK ON COMMIT ]
… [ WITH [ MAX | MAXIMUM ] HASH SIZE n ]
action:
ON { UPDATE | DELETE }
…{ CASCADE | SET NULL | SET DEFAULT | RESTRICT }
location-string:
remote-server-name.[db-name].[owner].object-name
| remote-server-name;[db-name];[owner];object-name

453
CREATE TABLE statement

Permissions Must have RESOURCE authority.


Must have DBA authority to create a table for another user.
The AT clause to create proxy tables is supported on Windows 95 and
Windows NT only.
Side effects Automatic commit.
See also "ALTER TABLE statement" on page 380
"CREATE DBSPACE statement" on page 419
"CREATE EXISTING TABLE statement" on page 428
"DECLARE LOCAL TEMPORARY TABLE statement" on page 481
"DROP statement" on page 491
"Special values" on page 234
"SQL Data Types" on page 251
"Creating tables" on page 122 of the book ASA User’s Guide
Description The CREATE TABLE statement creates a new table. A table can be created
for another user by specifying an owner name. If GLOBAL TEMPORARY
is specified, the table is a temporary table. Otherwise, the table is a base
table.
The definition of a temporary table exists in the database, like that of a base
table, and remains in the database until it is explicitly removed by a DROP
TABLE statement. The rows in a temporary table are visible only to the
connection that inserted the rows. Multiple connections from the same or
different applications can use the same temporary table at the same time, and
each connection will see only its own rows. The rows of a temporary table
for a connection are deleted when the connection ends.
Parameters IN clause The IN clause specifies the dbspace in which the table is to be
created. If the table is a GLOBAL TEMPORARY table, the IN clause is
ignored.
$ For more information about dbspaces, see "CREATE DBSPACE
statement" on page 419.

ON COMMIT clause The ON COMMIT clause is allowed only for


temporary tables. By default, the rows of a temporary table are deleted on
COMMIT.

AT clause Create a remote table on a different server specified by


location-string and also a proxy table on the current database that maps to
the remote table. The AT clause supports the semicolon (;) as a field
delimiter in location-string. If no semicolon is present, a period is the field
delimiter. This allows filenames and extensions to be used in the database
and owner fields.

454
Chapter 9 SQL Statements

For example, the following statement maps the table a1 to the MS Access
file mydbfile.mdb:
CREATE TABLE a1
AT ’access;d:\mydbfile.mdb;;a1’
$ For information on remote servers, see "CREATE SERVER statement"
on page 451. For information on proxy tables, see "CREATE EXISTING
TABLE statement" on page 428.
Foreign key definitions are ignored on remote tables. Foreign key definitions
on local tables that refer to remote tables are also ignored. Primary key
definitions are sent to the remote server if the server supports primary keys.
The COMPUTE clause is ignored for remote tables.

column-definition Define a column in the table. The following are part of


column definitions.
♦ column-name The column name is an identifier. Two columns in the
same table cannot have the same name. For more information, see
"Identifiers" on page 211.
♦ data-type For information on data types, see "SQL Data Types" on
page 251.
♦ NOT NULL If NOT NULL is specified, or if the column is in a
UNIQUE or PRIMARY KEY constraint, the column cannot contain
NULL in any row.
♦ DEFAULT For more information on the special-value, see "Special
values" on page 234.
If a DEFAULT value is specified, it is used as the value for the column
in any INSERT statement that does not specify a value for the column. If
no DEFAULT is specified, it is equivalent to DEFAULT NULL.
Some of the defaults require more description:
♦ AUTOINCREMENT When using AUTOINCREMENT, the
column must be one of the integer data types, or an exact numeric
type.
For performance reasons, it is highly recommended that DEFAULT
AUTOINCREMENT be used only with columns defined as a
PRIMARY KEY, with a UNIQUE constraint, or the first column of
an index. This allows the maximum value to be found at startup
time without scanning the entire table.

455
CREATE TABLE statement

On inserts into the table, if a value is not specified for the


AUTOINCREMENT column, a unique value larger than any other
value in the column is generated. If an INSERT specifies a value for
the column, it is used; if the specified value is larger than the
current maximum value for the column, that value will be used as a
starting point for subsequent inserts.
Deleting rows does not decrement the AUTOINCREMENT
counter. Gaps created by deleting rows can only be filled by explicit
assignment when using an insert. After an explicit insert of a row
number less then the maximum, subsequent rows without explicit
assignment are still automatically incremented with a value of one
greater than the previous maximum.
The next value to be used for each column is stored as an integer.
Using values greater than (2**31 – 1) may cause wraparound to
incorrect values, and AUTOINCREMENT should not be used in
such cases.
You can find the most recently inserted value of the column by
inspecting the @@identity global variable.
The identity column is a Transact-SQL-compatible alternative to
using the AUTOINCREMENT default. In Adaptive Server
Anywhere, the identity column is implemented as
AUTOINCREMENT default. For information, see "The special
IDENTITY column" on page 947 of the book ASA User’s Guide.
♦ GLOBAL AUTOINCREMENT This default is intended for use
when multiple databases will be used in a replication environment.
This default is similar to AUTOINCREMENT, with the following
exceptions.
The domain is partitioned. The size of each partition can be
specified in parentheses immediately following the
AUTOINCREMENT key word. This value may be any positive
integer, although the partition size is generally chosen so that the
supply of numbers within any one partition will rarely, if ever, be
exhausted. If the column is of type BIGINT or UNSIGNED
BIGINT, the default partition size is 2**32 = 4294967296; for
columns of other types the default partition size is 2**16 = 65536.

456
Chapter 9 SQL Statements

When using this default, the value of the public option


Global_database_id in each database must be set to a unique,
positive integer. This value uniquely identifies the database and
indicates from which partition default values are to be assigned. The
range of allowed values is n p + 1 to (n + 1) p, where n is the value
of the public option Global_database_id and p is the partition size.
For example, if the partition size is 1000 and Global_database_id
is set to 3, then the range is from 3001 to 4000.
If the previous value is less than (n + 1) p, the next default value
will be one greater than the previous largest value in column. If the
column contains no values, the first default value is n p + 1.
If the public option Global_database_id is set to zero, a null value
is inserted into the column. Should null values not be permitted, the
attempt to insert the row causes an error. This situation arises, for
example, if the column is contained in the table’s primary key. The
public option Global_database_id is set to zero by default.
Null default values are also generated when the supply of values
within the partition has been exhausted. In this case, a new value of
Global_database_id should be assigned to the database to allow
default values to be chosen from another partition. Attempting to
insert the null value causes an error if the column does not permit
nulls. To detect that the supply of unused values is low and handle
this condition, create an event of type GlobalAutoincrement.
You cannot use DEFAULT GLOBAL AUTOINCREMENT on
databases created with version 6 or earlier software, even if they
have been upgraded.
♦ Constant expressions Constant expressions that do not reference
database objects are allowed in a DEFAULT clause, so functions
such as GETDATE or DATEADD can be used. If the expression is
not a function or simple value, it must be enclosed in parentheses.
♦ TIMESTAMP Provides a way of indicating when each row in the
table was last modified. When a column is declared with
DEFAULT TIMESTAMP, a default value is provided for inserts,
and the value is updated with the current date and time whenever
the row is updated.
To provide a default value on insert, but not update the column
whenever the row is updated, use DEFAULT CURRENT
TIMESTAMP instead of DEFAULT TIMESTAMP.
$ For more information on timestamp columns, see "The special
Transact-SQL timestamp column and data type" on page 946 of the
book ASA User’s Guide.

457
CREATE TABLE statement

Columns declared with DEFAULT TIMESTAMP contain unique


values, so that applications can detect near-simultaneous updates to
the same row. If the current timestamp value is the same as the last
value, it is incremented by the value of the
DEFAULT_TIMESTAMP_INCREMENT option.
$ For more information, see
"DEFAULT_TIMESTAMP_INCREMENT option" on page 171.
The global variable @@dbts returns a TIMESTAMP value
representing the last value generated for a column using DEFAULT
TIMESTAMP. For more information, see "Global variables" on
page 239.
♦ string For more information, see "Strings" on page 212.
♦ global-variable For more information, see "Global variables" on
page 239.
♦ column-constraint A column constraint restricts the values the
column can hold.

table-constraint A table constraint restricts the values that one or more


columns in the table can hold.

Constraints Column and table constraints help ensure the integrity of data
in the database. If a statement would cause a violation of a constraint,
execution of the statement does not complete, any changes made by the
statement before error detection are undone, and an error is reported. Column
constraints are abbreviations for the corresponding table constraints.
For example, the following statements are equivalent:
CREATE TABLE Product (
product_num integer UNIQUE
)
CREATE TABLE Product (
product_num integer,
UNIQUE ( product_num )
)

Column constraints are normally used unless the constraint references more
than one column in the table. In these cases, a table constraint must be used.
Constraints include the following:
♦ CHECK This allows arbitrary conditions to be verified. For example, a
check constraint could be used to ensure that a column called Sex only
contains the values M or F.

458
Chapter 9 SQL Statements

No row in a table is allowed to violate a constraint. If an INSERT or


UPDATE statement would cause a row to violate a constraint, the
operation is not permitted and the effects of the statement are undone.
The change is rejected only if a constraint condition evaluates to
FALSE, the change is allowed if a constraint condition evaluates to
TRUE or UNKNOWN.
$ For more information about TRUE, FALSE, and UNKNOWN
conditions, see "NULL value" on page 247 and "Search conditions" on
page 226.
♦ COMPUTE The COMPUTE constraint is a column constraint only.
When a column is created using a COMPUTE constraint, its value in
any row is the value of the supplied expression. Columns created with
this constraint are read-only columns for applications: the value is
changed by the database server when the expression is evaluated.
Any UPDATE statement that attempts to change the value of a
computed column does fire any triggers associated with the column.
$ The Compute constraint is particularly useful when designing
databases using Java class data types. For more information, see "Using
computed columns with Java classes" on page 572 of the book ASA
User’s Guide.

♦ UNIQUE Identifies one or more columns that uniquely identify each


row in the table. No two rows in the table can have the same values in
all the named column(s). A table may have more than one unique
constraint.
There is a difference between a unique constraint and a unique index.
Columns of a unique index are allowed to be NULL, while columns in a
unique constraint are not. A foreign key can reference either a primary
key or a column with a unique constraint, but not a unique index,
because it can include multiple instances of NULL.
$ For information on unique indexes, and on the WITH HASH
clause, see "CREATE INDEX statement" on page 435.
♦ PRIMARY KEY This is the same as a unique constraint, except that a
table can have only one primary key constraint. The primary key usually
identifies the best identifier for a row. For example, the customer
number might be the primary key for the customer table.
Columns included in primary keys cannot allow NULL. Each row in the
table has a unique primary key value. A table can have only one
PRIMARY KEY.

459
CREATE TABLE statement

The order of the columns in a primary key is the order in which the
columns were created in the table, not the order in which they are listed
when the primary key is created.
$ For information on the WITH HASH clause that can be used with
this constraint, see "CREATE INDEX statement" on page 435.
♦ Foreign key A foreign key constraint can be implemented using a
REFERENCES column constraint (single column only) or a FOREIGN
KEY table constraint. It restricts the values for a set of columns to match
the values in a primary key or, less commonly, a unique constraint of
another table (the primary table). For example, a foreign key constraint
could be used to ensure that a customer number in an invoice table
corresponds to a customer number in the customer table.
If you specify column name in a REFERENCES column constraint, it
must be a column in the primary table, must be subject to a unique
constraint or primary key constraint, and that constraint must consist of
only that one column. If you do not specify column-name, the foreign
key references the primary key of the primary table.
If you do not explicitly define a foreign key column, it is created with
the same data type as the corresponding column in the primary table.
These automatically-created columns cannot be part of the primary key
of the foreign table. Thus, a column used in both a primary key and
foreign key of the same table must be explicitly created.
If foreign key column names are specified, then primary key column
names must also be specified, and the column names are paired
according to position in the lists. If the primary table column names are
not specified in a FOREIGN KEY table constraint, then the primary key
columns are used. If foreign key column names are not specified then
the foreign key columns are give the same names as the columns in the
primary table.
If at least one value in a multi-column foreign key is NULL, there is no
restriction on the values that can be held in other columns of the key.
A temporary table cannot have a foreign key that references a base table
and a base table cannot have a foreign key that references a temporary
table.
♦ NOT NULL Disallow NULL in the foreign key columns. A NULL
in a foreign key means that no row in the primary table corresponds
to this row in the foreign table.
♦ role-name The role name is the name of the foreign key. The
main function of the role name is to distinguish two foreign keys to
the same table. If no role name is specified, the role name is
assigned as follows:

460
Chapter 9 SQL Statements

1 If there is no foreign key with a role name the same as the table
name, the table name is assigned as the role name.
2 If the table name is already taken, the role name is the table
name concatenated with a zero-padded three-digit number
unique to the table.
♦ action The referential integrity action defines the action to be
taken to maintain foreign key relationships in the database.
Whenever a primary key value is changed or deleted from a
database table, there may be corresponding foreign key values in
other tables that should be modified in some way. You can specify
either an ON UPDATE clause, an ON DELETE clause, or both,
followed by one of the following actions:
♦ CASCADE When used with ON UPDATE, updates the
corresponding foreign keys to match the new primary key
value. When used with ON DELETE, deletes the rows from the
foreign table that match the deleted primary key.
♦ SET NULL Sets to NULL all the foreign key values that
correspond to the updated or deleted primary key.
♦ SET DEFAULT Sets foreign key values that match the
updated or deleted primary key value to values specified on the
DEFAULT clause of each foreign key column.
♦ RESTRICT Generates an error if an attempt is made to update
or delete a primary key value while there are corresponding
foreign keys elsewhere in the database. RESTRICT is the
default action.
♦ CHECK ON COMMIT The CHECK ON COMMIT clause
overrides the WAIT_FOR_COMMIT database option, and causes
the database server to wait for a COMMIT before checking
RESTRICT actions on a foreign key. The CHECK ON COMMIT
clause does not delay CASCADE, SET NULL, or SET DEFAULT
actions.
If you use CHECK ON COMMIT with out specifying any actions,
then RESTRICT is implied as an action for UPDATE and
DELETE.
$ For information on the WITH HASH clause that can be used with
this constraint, see "CREATE INDEX statement" on page 435.
Standards and ♦ SQL/92 Entry level feature.
compatibility
The following are vendor extensions:
♦ The { IN | ON } dbspace-name clause.

461
CREATE TABLE statement

♦ The ON COMMIT clause


♦ Some of the default values.
♦ Sybase Supported by Adaptive Server Enterprise, with some
differences.
♦ Temporary tables You can create a temporary table by preceding
the table name in a CREATE TABLE statement with a pound sign
(#). In Adaptive Server Anywhere, these are declared temporary
tables, which are available only in the current connection. For
information, see "DECLARE LOCAL TEMPORARY TABLE
statement" on page 481.
♦ Physical placement Physical placement of a table is carried out
differently in Adaptive Server Anywhere and in Adaptive Server
Enterprise. The ON segment-name clause supported by Adaptive
Server Enterprise is supported in Adaptive Server Anywhere, but
segment-name refers to a dbspace name.
♦ Constraints Adaptive Server Anywhere does not support named
constraints or named defaults, but does support domains, which
allow constraint and default definitions to be encapsulated in the
data type definition. It also supports explicit defaults and CHECK
conditions in the CREATE TABLE statement.
♦ NULL default By default, columns in Adaptive Server Enterprise
default to NOT NULL, whereas in Adaptive Server Anywhere the
default setting is NULL. This setting can be controlled using the
ALLOW_NULLS_BY_DEFAULT database option. You should
explicitly specify NULL or NOT NULL to make your data
definition statements transferable between Adaptive Server
Anywhere and Adaptive Server Enterprise.
$ For more information, see
"ALLOW_NULLS_BY_DEFAULT option" on page 157.
Examples ♦ Create a table for a library database to hold book information.
CREATE TABLE library_books (
-- NOT NULL is assumed for primary key columns
isbn CHAR(20) PRIMARY KEY,
copyright_date DATE,
title CHAR(100),
author CHAR(50),
-- column(s) corresponding to primary key of room
-- are created automatically
FOREIGN KEY location REFERENCES room
)
♦ Create a table for a library database to hold information on borrowed
books.
462
Chapter 9 SQL Statements

CREATE TABLE borrowed_book (


-- Default on insert is that book is borrowed today
-- date_borrowed DATE NOT NULL DEFAULT CURRENT DATE,
-- date_returned will be NULL until the book is
-- returned
date_returned DATE,
book CHAR(20)
REFERENCES library_books (isbn),
-- The check condition is UNKNOWN until
-- the book is returned, which is allowed
CHECK( date_returned >= date_borrowed )
)

♦ Create tables for a sales database to hold order and order item
information.
CREATE TABLE Orders (
order_num INTEGER NOT NULL PRIMARY KEY,
date_ordered DATE,
name CHAR(80)
);
CREATE TABLE Order_item (
order_num INTEGER NOT NULL,
item_num SMALLINT NOT NULL,
PRIMARY KEY (order_num, item_num),
-- When an order is deleted, delete all of its
-- items.
FOREIGN KEY (order_num)
REFERENCES Orders (order_num)
ON DELETE CASCADE
)

♦ Creates a table named t1 at the remote server SERVER_A and creates a


proxy table named t1 that is mapped to the remote table.
CREATE TABLE t1
( a INT,
b CHAR(10))
AT ’SERVER_A.db1.joe.t1’

463
CREATE TRIGGER statement

CREATE TRIGGER statement


Function Use this statement to create a new trigger in a database.
Syntax CREATE TRIGGER trigger-name trigger-time trigger-event [, trigger-event,..]
… [ ORDER integer ] ON table-name
… [ REFERENCING [ OLD AS old-name ]
[ NEW AS new-name ] ]
[ REMOTE AS remote-name ] ]
… [ FOR EACH { ROW | STATEMENT } ]
… [ WHEN ( search-condition ) ]
… compound-statement
trigger-time:
BEFORE | AFTER | RESOLVE
trigger-event:
DELETE | INSERT | UPDATE | UPDATE OF column-list
Permissions Must have RESOURCE authority and have ALTER permissions on the table,
or must have DBA authority. CREATE TRIGGER puts a table lock on the
table, and thus requires exclusive use of the table.
Side effects Automatic commit.
See also "BEGIN statement" on page 392
"CREATE PROCEDURE statement" on page 440
"CREATE TRIGGER statement" on page 467
"DROP statement" on page 491
"Using Procedures, Triggers, and Batches" on page 423 of the book ASA
User’s Guide
Description The CREATE TRIGGER statement creates a trigger associated with a table
in the database, and stores the trigger in the database.
The trigger is declared as either a row-level trigger, in which case it
executes before or after each row is modified, or as a statement-level
trigger, in which case it executes after the entire triggering statement is
completed.
Parameters Trigger events Triggers can be fired by one or more of the following
events:
♦ DELETE Invoked whenever a row of the associated table is deleted.
♦ INSERT Invoked whenever a new row is inserted into the table
associated with the trigger.
♦ UPDATE Invoked whenever a row of the associated table is updated.
♦ UPDATE OF column-list Invoked whenever a row of the associated
table is updated and a column in the column-list has been modified.
464
Chapter 9 SQL Statements

trigger-time Row-level triggers can be defined to execute BEFORE or


AFTER the insert, update, or delete. Statement-level triggers execute
AFTER the statement. The RESOLVE trigger time is for use with
SQL Remote: it fires before row-level UPDATE or UPDATE OF column-
lists only.
BEFORE UPDATE triggers fire any time an UPDATE occurs on a row,
whether or not the new value differs from the old value. AFTER UPDATE
triggers fire only if the new value is different from the old value.

FOR EACH clause To declare a trigger as a row-level trigger, use the


FOR EACH ROW clause. To declare a trigger as a statement-level trigger,
you can either use a FOR EACH STATEMENT clause or omit the FOR
EACH clause. For clarity, it is recommended that you enter the FOR EACH
STATEMENT clause if declaring a statement-level trigger.

ORDER clause Triggers of the same type (insert, update, or delete) that
fire at the same time (before, after, or resolve) can use the ORDER clause to
determine the order that the triggers are fired.

REFERENCING clause The REFERENCING OLD and REFERENCING


NEW clauses allow you to refer to the deleted and inserted rows. For the
purposes of this clause, an UPDATE is treated as a delete followed by an
insert.
The REFERENCING REMOTE clause is for use with SQL Remote. It
allows you to refer to the values in the VERIFY clause of an UPDATE
statement. It should be used only with RESOLVE UPDATE or RESOLVE
UPDATE OF column-list triggers.
The meaning of REFERENCING OLD and REFERENCING NEW differs,
depending on whether the trigger is a row-level or a statement-level trigger.
For row-level triggers, the REFERENCING OLD clause allows you to refer
to the values in a row prior to an update or delete, and the REFERENCING
NEW clause allows you to refer to the inserted or updated values. The OLD
and NEW rows can be referenced in BEFORE and AFTER triggers. The
REFERENCING NEW clause allows you to modify the new row in a
BEFORE trigger before the insert or update operation takes place.
For statement-level triggers, the REFERENCING OLD and
REFERENCING NEW clauses refer to declared temporary tables holding
the old and new values of the rows. The default names for these tables are
deleted and inserted.

WHEN clause The trigger fires only for rows where the search-condition
evaluates to true. The WHEN clause can be used only with row level
triggers.

465
CREATE TRIGGER statement

Standards and ♦ SQL/92 Persistent stored module feature. Some clauses are vendor
compatibility extensions.
♦ Sybase This syntax is different to that supported by Adaptive Server
Enterprise.
Example ♦ When a new department head is appointed, update the manager_id
column for employees in that department.
CREATE TRIGGER tr_manager
BEFORE UPDATE OF dept_head_id
ON department
REFERENCING OLD AS old_dept NEW AS new_dept
FOR EACH ROW
BEGIN
UPDATE employee
SET employee.manager_id=new_dept.dept_head_id
WHERE employee.dept_id=old_dept.dept_id
END

466
Chapter 9 SQL Statements

CREATE TRIGGER statement [T-SQL]


Function Use this statement to create a new trigger in the database in a manner
compatible with Adaptive Server Enterprise.
Syntax 1 CREATE TRIGGER [owner.]trigger_name
… ON [owner.]table_name
… FOR { INSERT, UPDATE, DELETE }
… AS
… statement-list
Syntax 2 CREATE TRIGGER [owner.]trigger_name
… ON [owner.]table_name
… FOR {INSERT, UPDATE}
… AS
… [ IF UPDATE ( column_name )
… [ { AND | OR} UPDATE ( column_name ) ] … ]
… statement-list
… [ IF UPDATE ( column_name )
… [ { AND | OR} UPDATE ( column_name ) ] … ]
… statement-list
Permissions Must have RESOURCE authority and have ALTER permissions on the table,
or must have DBA authority.
CREATE TRIGGER locks all the rows on the table, and thus requires
exclusive use of the table.
Side effects Automatic commit.
See also "CREATE TRIGGER statement" on page 464
Description The rows deleted or inserted are held in two temporary tables. In the
Transact-SQL form of triggers, they can be accessed using the table names
deleted, and inserted, as in Adaptive Server Enterprise. In the Watcom-SQL
CREATE TRIGGER statement, these rows are accessed using the
REFERENCING clause.
Trigger names must be unique in the database.
Transact-SQL triggers are executed AFTER the triggering statement.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Anywhere supports a subset of the Adaptive Server Enterprise
syntax.

467
CREATE VARIABLE statement

CREATE VARIABLE statement


Function Use this statement to create a SQL variable.
Syntax CREATE VARIABLE identifier data-type
Permissions None.
Side effects None.
See also "BEGIN statement" on page 392
"SQL Data Types" on page 251
"DROP VARIABLE statement" on page 499
"SET statement" on page 591
Description The CREATE VARIABLE statement creates a new variable of the specified
data type. The variable contains the NULL value until it is assigned a
different value by the SET VARIABLE statement.
A variable can be used in a SQL expression anywhere a column name is
allowed. If a column name exists with the same name as the variable, the
variable value is used.
Variables belong to the current connection, and disappear when you
disconnect from the database or when you use the DROP VARIABLE
statement. Variables are not visible to other connections. Variables are not
affected by COMMIT or ROLLBACK statements.
Variables are useful for creating large text or binary objects for INSERT or
UPDATE statements from embedded SQL programs.
Local variables in procedures and triggers are declared within a compound
statement (see "Using compound statements" on page 447 of the book ASA
User’s Guide).
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example For an example, see "SET statement" on page 591

468
Chapter 9 SQL Statements

CREATE VIEW statement


Function Use this statement to create a view on the database. Views are used to give a
different perspective on the data, even though it is not stored that way.
Syntax CREATE VIEW
… [ owner.]view-name [( column-name, … )]
… AS select-without-order-by
… [ WITH CHECK OPTION ]
Permissions Must have RESOURCE authority and SELECT permission on the tables in
the view definition.
Side effects Automatic commit.
See also "DROP statement" on page 491
"CREATE TABLE statement" on page 453
Description The CREATE VIEW statement creates a view with the given name. You can
create a view owned by another user by specifying the owner. You must
have DBA authority to create a view for another user.
A view name can be used in place of a table name in SELECT, DELETE,
UPDATE, and INSERT statements. Views, however, do not physically exist
in the database as tables. They are derived each time they are used. The view
is derived as the result of the SELECT statement specified in the
CREATE VIEW statement. Table names used in a view should be qualified
by the user ID of the table owner. Otherwise, a different user ID might not be
able to find the table or might get the wrong table.
Views can be updated unless the SELECT statement defining the view
contains a GROUP BY clause, an aggregate function, or involves a UNION
operation. An update to the view causes the underlying table(s) to be
updated.
Parameters view-name The view-name is an identifier. The default owner is the
current user ID.

column-name The columns in the view are given the names specified in
the column-name list. If the column name list is not specified, the view
columns are given names from the select list items. In order to use the names
from the select list items, each item must be a simple column name or have
an alias-name specified (see "SELECT statement" on page 587).
AS clause The SELECT statement on which the view is based must not
have an ORDER BY clause on it. It may have a GROUP BY clause and may
be a UNION. The SELECT statement must not refer to local temporary
tables.

469
CREATE VIEW statement

WITH CHECK OPTION clause The WITH CHECK OPTION clause


rejects any updates and inserts to the view that do not meet the criteria of the
views as defined by its SELECT statement.
Standards and ♦ SQL/92 Entry level feature.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Examples ♦ Create a view showing information for male employees only. This view
has the same column names as the base table.
CREATE VIEW male_employee
AS SELECT *
FROM Employee
WHERE Sex = ’M’
♦ Create a view showing employees and the departments they belong to.
CREATE VIEW emp_dept
AS SELECT emp_lname, emp_fname, dept_name
FROM Employee JOIN Department
ON Employee.dept_id = Department.dept_id

470
Chapter 9 SQL Statements

CREATE WRITEFILE statement


Function Use this statement to create a write file for a database.
Syntax CREATE WRITEFILE write-file-name
… FOR DATABASE db-file-name
… [ LOG OFF | LOG ON [ log-file-name [ MIRROR mirror-file-name ] ] ]
write-file-name | db-file-name | log-file-name | mirror-file-name :string
Permissions The permissions required to execute this statement are set on the server
command line, using the -gu command-line option. The default setting is to
require DBA authority.
The account under which the server is running must have write permissions
on the directories where files are created.
Not supported on Windows CE.
Side effects An operating system file is created.
"CREATE DATABASE statement" on page 415
See also
"The Write File utility" on page 139
"Working with write files" on page 770 of the book ASA User’s Guide
Description Creates a database write file with the supplied name and attributes.
The file names (write-file-name, db-file-name, log-file-name, mirror-file-
name) are strings containing operating system file names.
$ For information on strings, see "Strings" on page 212.
If you specify no path, or a relative path, the file is created relative to the
current working directory of the server.
You cannot create a write file for a database that is currently loaded.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example ♦ The following statement creates a write file..
CREATE WRITEFILE ’c:\\sybase\\my_db.wrt’
FOR DATABASE ’c:\\sybase\\my_db.db’
LOG ON ’e:\\logdrive\\my_db.log’

471
DEALLOCATE DESCRIPTOR statement [ESQL]

DEALLOCATE DESCRIPTOR statement [ESQL]


Function Use this statement to free memory associated with a SQL descriptor area.
Syntax DEALLOCATE DESCRIPTOR descriptor-name
descriptor-name: string
Permissions None.
Side effects None.
See also "ALLOCATE DESCRIPTOR statement" on page 369
"The SQL descriptor area (SQLDA)" on page 44 of the book ASA
Programming Interfaces Guide
"SET DESCRIPTOR statement" on page 595
Description Frees all memory associated with a descriptor area, including the data items,
indicator variables, and the structure itself.
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Example ♦ For an example, see "ALLOCATE DESCRIPTOR statement" on
page 369.

472
Chapter 9 SQL Statements

Declaration section [ESQL]


Function Use this statement to declare host variables in an embedded SQL program.
Host variables are used to exchange data with the database.
Syntax EXEC SQL BEGIN DECLARE SECTION;
…C declarations
EXEC SQL END DECLARE SECTION;
Permissions None.
See also "BEGIN statement" on page 392
Description A declaration section is simply a section of C variable declarations
surrounded by the BEGIN DECLARE SECTION and
END DECLARE SECTION statements. A declaration section makes the
SQL preprocessor aware of C variables that will be used as host variables.
Not all C declarations are valid inside a declaration section. See "Using host
variables" on page 20 of the book ASA Programming Interfaces Guide for
more information.
Standards and ♦ SQL/92
compatibility
♦ Sybase

Examples EXEC SQL BEGIN DECLARE SECTION;


char *emp_lname, initials[5];
int dept;
EXEC SQL END DECLARE SECTION;

473
DECLARE statement

DECLARE statement
Function Use this statement to declare a SQL variable within a compound statement
(BEGIN … END).
Syntax DECLARE variable_name data-type
Description Variables used in the body of a procedure, trigger, or batch can be declared
using the DECLARE statement. The variable persists for the duration of the
compound statement in which it is declared.
The body of a Watcom-SQL procedure or trigger is a compound statement,
and variables must be declared immediately following BEGIN. In a
Transact-SQL procedure or trigger, there is no such restriction.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
♦ To be compatible with Adaptive Server Enterprise, the variable
name must be preceded by an @.
♦ In Adaptive Server Enterprise, a variable that is declared in a
procedure or trigger exists for the duration of the procedure or
trigger. In Adaptive Server Anywhere, if a variable is declared
inside a compound statement, it exists only for the duration of that
compound statement (whether it is declared in a Watcom-SQL or
Transact-SQL compound statement).
Examples ♦ The following batch illustrates the use of the DECLARE statement and
prints a message on the server window:
BEGIN
DECLARE varname CHAR(61);
SET varname = ’Test name’;
MESSAGE name;
END

474
Chapter 9 SQL Statements

DECLARE CURSOR statement [ESQL] [SP]


Function Use this statement to declare a cursor. Cursors are the primary means for
manipulating the results of queries.
Syntax DECLARE cursor-name
… [ UNIQUE
| NO SCROLL
| DYNAMIC SCROLL
| SCROLL
| INSENSITIVE
]
… CURSOR
FOR select-or-call-statement
| FOR statement-name [ FOR { UPDATE | READ ONLY } ]
| USING variable-name
cursor-name: identifier
statement-name: { identifier | host-variable }
variable-name: identifier
Permissions None.
Side effects None.
See also "PREPARE statement" on page 564
"OPEN statement" on page 556
"EXPLAIN statement" on page 507
"SELECT statement" on page 587
"CALL statement" on page 398
Description The DECLARE CURSOR statement declares a cursor with the specified
name for a SELECT statement or a CALL statement.
Parameters UNIQUE cursors When a cursor is declared UNIQUE, the query is forced
to return all the columns required to uniquely identify each row. Often this
will mean ensuring that all of the columns in the primary key or a uniqueness
table constraint are returned. Any columns that are required but were not
specified will be added.
A DESCRIBE done on a UNIQUE cursor sets the following additional flags
in the indicator variables:
♦ DT_KEY_COLUMN The column is part of the key for the row
♦ DT_HIDDEN_COLUMN The column was added to the query,
because it was required to uniquely identify the rows

475
DECLARE CURSOR statement [ESQL] [SP]

NO SCROLL cursors A cursor declared NO SCROLL is restricted to


FETCH NEXT and FETCH RELATIVE 0 seek operations.

DYNAMIC SCROLL cursors DYNAMIC SCROLL is the default cursor


type. DYNAMIC SCROLL cursors can use all formats of the FETCH
statement.

SCROLL cursors A cursor declared SCROLL can use all formats of the
FETCH statement.
SCROLL cursors behave differently from DYNAMIC SCROLL cursors
when a row in the cursor is modified or deleted after the first time the row is
read. SCROLL cursors have more predictable behavior when changes
happen.

Adaptive Server Anywhere maintains more information about SCROLL


cursors than DYNAMIC SCROLL cursors; thus, DYNAMIC SCROLL
cursors are more efficient and should be used unless the consistent behavior
of SCROLL cursors is required. There is no extra overhead in Adaptive
Server Anywhere for DYNAMIC SCROLL cursors versus NO SCROLL
cursors.
Each row fetched in a SCROLL cursor is remembered. If one of these rows
is deleted, either by your program or by another program in a multiuser
environment, it creates a hole in the cursor. If you fetch the row at this hole
with a SCROLL cursor, Adaptive Server Anywhere returns the error
SQLE_NO_CURRENT_ROW indicating that the row has been deleted, and
leaves the cursor positioned on the hole. (DYNAMIC SCROLL cursors skip
the hole and retrieve the next row.)
This allows your application to remember row positions within a cursor and
be assured that these positions will not change. For example, an application
could remember that Cobb is the second row in the cursor for SELECT *
FROM employee. If the first employee (Whitney) is deleted while the
SCROLL cursor is still open, FETCH ABSOLUTE 2 will still position on
Cobb while FETCH ABSOLUTE 1 will return
SQLE_NO_CURRENT_ROW. Similarly, if the cursor is on Cobb, FETCH
PREVIOUS will return SQLE_NO_CURRENT_ROW.
A fetch on a SCROLL cursor returns the warning
SQLE_ROW_UPDATED_WARNING if the row has changed since it was
last read. The warning only happens once; fetching the same row a third time
does not produce the warning. Similarly, a positioned UPDATE or DELETE
statement on a row that has been modified since it was last fetched returns
the error SQLE_ROW_UPDATED_SINCE_READ and cancels the
statement. An application must FETCH the row again before the UPDATE
or DELETE will be permitted.

476
Chapter 9 SQL Statements

An update to any column causes the warning/error, even if the column is not
referenced by the cursor. For example, a cursor on Surname and Initials
would report the update even if only the Birthdate column were modified.
These update warning and error conditions will not occur in bulk operations
mode (-b database server statement line switch) when row locking is
disabled. See "Performance tips" on page 695 of the book ASA User’s Guide.

INSENSITIVE cursors A cursor declared INSENSITIVE has its


membership fixed when it is opened; a temporary table is created with a copy
of all the original rows. FETCHING from an INSENSITIVE cursor does not
see the effect of any other INSERT, UPDATE, or DELETE statement, or any
other PUT, UPDATE WHERE CURRENT, DELETE WHERE CURRENT
operations on a different cursor. It does see the effect of PUT, UPDATE
WHERE CURRENT, DELETE WHERE CURRENT operations on the same
cursor.
INSENSITIVE cursors make it easier to write an application that deals with
cursors, since you only have to worry about changes you make explicitly to
the cursor; you do not have to worry about actions taken by other users or by
other parts of your application.
INSENSITIVE cursors can be expensive if the result set contains many rows.
Also, INSENSITIVE cursors are not affected by ROLLBACK or
ROLLBACK TO SAVEPOINT; the ROLLBACK is not an operation on the
cursor that changes the cursor contents.
INSENSITIVE cursors meet the ODBC requirements for static cursors.

FOR statement-name Statements are named using the PREPARE


statement. Cursors can be declared only for a prepared SELECT or CALL.

FOR UPDATE | READ ONLY A cursor declared FOR READ ONLY may
not be used in an UPDATE (positioned) or a DELETE (positioned)
operation. FOR UPDATE is the default.

USING variable-name For use within stored procedures only. The


variable is a string containing a SELECT statement for the cursor. The
variable must be available when the DECLARE is processed, and so must be
one of the following:
♦ A parameter to the procedure. For example:

477
DECLARE CURSOR statement [ESQL] [SP]

create function get_row_count(in qry long varchar)


returns int
begin
declare crsr cursor using qry;
declare rowcnt int;

set rowcnt = 0;
open crsr;
lp: loop
fetch crsr;
if SQLCODE <> 0 then leave lp end if;
set rowcnt = rowcnt + 1;
end loop;
return rowcnt;
end
♦ Nested inside another BEGIN..END after the variable has been assigned
a value. For example:
create procedure get_table_name(
in id_value int, out tabname char(128)
)
begin
declare qry long varchar;

set qry = ’select table_name from SYS.SYSTABLE ’


||
’where table_id=’ || string(id_value);
begin
declare crsr cursor using qry;

open crsr;
fetch crsr into tabname;
close crsr;
end
end
Standards and ♦ SQL/92 Entry level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Examples ♦ The following example illustrates how to declare a scroll cursor in
Embedded SQL:
EXEC SQL DECLARE cur_employee SCROLL CURSOR
FOR SELECT * FROM employee;
♦ The following example illustrates how to declare a cursor for a prepared
statement in Embedded SQL:
EXEC SQL PREPARE employee_statement
FROM ’SELECT emp_lname FROM employee’;
EXEC SQL DECLARE cur_employee CURSOR
FOR employee_statement;

478
Chapter 9 SQL Statements

♦ The following example illustrates the use of cursors in a stored


procedure:
BEGIN
DECLARE cur_employee CURSOR FOR
SELECT emp_lname
FROM employee;
DECLARE name CHAR(40);
OPEN cur_employee;
LOOP
FETCH NEXT cur_employee INTO name;
...
END LOOP
CLOSE cur_employee;
END

479
DECLARE CURSOR statement [T-SQL]

DECLARE CURSOR statement [T-SQL]


Function Use this statement to declare a cursor in a manner compatible with Adaptive
Server Enterprise.
Syntax DECLARE cursor-name
… CURSOR FOR select-statement
…[ FOR { READ ONLY | UPDATE } ]
cursor-name: identifier
select-statement: string
Permissions None.
Side effects None.
See also "DECLARE CURSOR statement" on page 475
Description Adaptive Server Anywhere supports a DECLARE CURSOR syntax that is
not supported in Adaptive Server Enterprise. For information on the full
DECLARE CURSOR syntax, see "DECLARE CURSOR statement" on
page 475.
This section describes the overlap between the Adaptive Server Anywhere
and Enterprise flavors of DECLARE CURSOR.
Standards and ♦ SQL/92 Entry-level compliant. The FOR UPDATE and
compatibility FOR READ ONLY options are Transact-SQL extensions.
♦ Sybase There are some features of the Adaptive Server Enterprise
DECLARE CURSOR statement that are not supported in Adaptive
Server Anywhere.
♦ Adaptive Server Enterprise supports cursors opened for update of a
list of columns from the tables specified in the select-statement.
This is not supported in Adaptive Server Anywhere.
♦ In the Watcom-SQL dialect, a DECLARE CURSOR statement in a
procedure, trigger, or batch must immediately follow the BEGIN
keyword. In the Transact-SQL dialect, there is no such restriction.
♦ In Adaptive Server Enterprise, when a cursor is declared in a
procedure, trigger, or batch, it exists for the duration of the
procedure, trigger, or batch. In Adaptive Server Anywhere, if a
cursor is declared inside a compound statement, it exists only for
the duration of that compound statement (whether it is declared in a
Watcom-SQL or Transact-SQL compound statement).
♦ CURSOR type (UNIQUE, NO SCROLL, and so on) and CURSOR
FOR statement-name are not supported in Adaptive Server
Anywhere.

480
Chapter 9 SQL Statements

DECLARE LOCAL TEMPORARY TABLE


statement
Function Use this statement to declare a local temporary table.
Syntax DECLARE LOCAL TEMPORARY TABLE table-name
… ( { column-definition [ column-constraint … ] | table-constraint }, … )
… [ ON COMMIT { DELETE | PRESERVE } ROWS ]
Permissions None.
Side effects None.
See also "CREATE TABLE statement" on page 453
"Using compound statements" on page 447 of the book ASA User’s Guide
Description The DECLARE LOCAL TEMPORARY TABLE statement declares a
temporary table. For definitions of column-definition, column-constraint, and
table-constraint, see "CREATE TABLE statement" on page 453.
Declared local temporary tables within compound statements exist within the
compound statement. (See "Using compound statements" on page 447 of the
book ASA User’s Guide). Otherwise, the declared local temporary table
exists until the end of the connection.
By default, the rows of a temporary table are deleted on COMMIT.
Standards and ♦ SQL/92 Conforms to the SQL/92 standard.
compatibility
♦ Sybase Adaptive Server Enterprise does not support DECLARE
TEMPORARY TABLE.
Examples ♦ The following example illustrates how to declare a temporary table in
Embedded SQL:
EXEC SQL DECLARE LOCAL TEMPORARY TABLE MyTable (
number INT
);
♦ The following example illustrates how to declare a temporary table in a
stored procedure:
BEGIN
DECLARE LOCAL TEMPORARY TABLE TempTab (
number INT
);
...
END

481
DELETE statement

DELETE statement
Function Use this statement to delete rows from the database.
Syntax DELETE [ FIRST | TOP n ]
… [FROM] [ owner.]table-name
… [FROM table-list]
… [WHERE search-condition]
Permissions Must have DELETE permission on the table.
Side effects None.
See also "TRUNCATE TABLE statement" on page 615
"INSERT statement" on page 540
"INPUT statement" on page 536
"FROM clause" on page 518
Description The DELETE statement deletes all the rows from the named table that satisfy
the search condition. If no WHERE clause is specified, all rows from the
named table are deleted.
The DELETE statement can be used on views, provided the SELECT
statement defining the view has only one table in the FROM clause and does
not contain a GROUP BY clause, an aggregate function, or involve a
UNION operation.
The optional second FROM clause in the DELETE statement allows rows to
be deleted based on joins. If the second FROM clause is present, the
WHERE clause qualifies the rows of this second FROM clause. Rows are
deleted from the table name given in the first FROM clause.
$ The second FROM clause can contain arbitrary complex table
expressions, such as KEY and NATURAL joins. For a full description of the
FROM clause and joins, see "FROM clause" on page 518.
The following statement illustrates a potential ambiguity in table names in
DELETE statements with two FROM clauses that use correlation names:
DELETE
FROM table_1
FROM table_1 AS alias_1, table_2 AS alias_2
WHERE ...
The table table_1 is identified without a correlation name in the first FROM
clause, but with a correlation name in the second FROM clause. In this case,
table_1 in the first clause is identified with alias_1 in the second clause—
there is only one instance of table_1 in this statement.

482
Chapter 9 SQL Statements

This is an exception to the general rule that where a table is identified with a
correlation name and without a correlation name in the same statement, two
instances of the table are considered.
Consider the following example:
DELETE
FROM table_1
FROM table_1 AS alias_1, table_1 AS alias_2
WHERE ...
In this case, there are two instances of table_1in the second FROM clause.
The statement will fail with a syntax error as it is ambiguous which instance
of the table_1 from the second FROM clause matches the first instance of
table_1 in the first FROM clause.
Standards and ♦ SQL/92 Entry level compliant. The use of more than one table in the
compatibility FROM clause is a vendor extension.
♦ Sybase Supported by Adaptive Server Enterprise, including the
vendor extension.
Examples ♦ Remove employee 105 from the database.
DELETE
FROM employee
WHERE emp_id = 105
♦ Remove all data prior to 1993 from the fin_data table.
DELETE
FROM fin_data
WHERE year < 1993
♦ Remove all orders from sales_order_items table if their ship date is
older than 1994-01-01 and their region is Central.
DELETE
FROM sales_order_items
FROM sales_order
WHERE sales_order_items.id = sales.order.id and
ship_date < ’1994-01-01’ and region =’Central’

483
DELETE (positioned) statement [ESQL] [SP]

DELETE (positioned) statement [ESQL] [SP]


Function Use this statement to delete the data at the current location of a cursor.
Syntax DELETE [ FROM table-spec ]
…WHERE CURRENT OF cursor-name
cursor-name: identifier | host-variable
table-spec: [ owner.]correlation-name
owner: identifier
Permissions Must have DELETE permission on tables used in the cursor.
Side effects None.
See also "UPDATE statement" on page 621
"UPDATE (positioned) statement" on page 625
"INSERT statement" on page 540
"PUT statement" on page 568
Description This form of the DELETE statement deletes the current row of the specified
cursor. The current row is defined to be the last row fetched from the cursor.
The table from which rows are deleted is determined as follows:
♦ If no FROM clause is included, the cursor must be on a single table
only.
♦ If the cursor is for a joined query (including using a view containing a
join), then the FROM clause must be used. Only the current row of the
specified table is deleted. The other tables involved in the join are not
affected.
♦ If a FROM clause is included, and no table owner is specified, table-
spec is first matched against any correlation names.
♦ If a correlation name exists, table-spec is identified with the
correlation name.
♦ If a correlation name does not exist, table-spec must be
unambiguously identifiable as a table name in the cursor.
♦ If a FROM clause is included, and a table owner is specified, table-spec
must be unambiguously identifiable as a table name in the cursor.
♦ The positioned DELETE statement can be used on a cursor open on a
view as long as the view is updatable.
Standards and ♦ SQL/92 Entry level feature. The range of cursors that can be updated
compatibility may contain vendor extensions if the ANSI_UPDATE_CONSTRAINTS
option is set to OFF.

484
Chapter 9 SQL Statements

♦ Sybase Embedded SQL use is supported by Open Client/Open Server.


Procedure and trigger use is supported only in Adaptive Server
Anywhere.
Example ♦ The following statement removes the current row from the database.
DELETE
WHERE CURRENT OF cur_employee

485
DESCRIBE statement [ESQL]

DESCRIBE statement [ESQL]


Function Use this statement to get information about the host variables required to
store data retrieved from the database, or host variables required to pass data
to the database.
Syntax DESCRIBE
… [ USER TYPES ]
… [ ALL
| BIND VARIABLES FOR
| INPUT
| OUTPUT
| SELECT LIST FOR
]
… [ LONG NAMES [long-name-spec ] | WITH VARIABLE RESULT ]
… [ FOR ] { statement-name | CURSOR cursor-name }
… INTO sqlda-name
long-name-spec:
OWNER.TABLE.COLUMN | TABLE.COLUMN | COLUMN
statement-name: { identifier | host-variable }
cursor-name: declared cursor
sqlda-name: identifier
Permissions None.
Side effects None.
See also "ALLOCATE DESCRIPTOR statement" on page 369
"DECLARE CURSOR statement" on page 475
"OPEN statement" on page 556
"PREPARE statement" on page 564
Description The DESCRIBE statement sets up the named SQLDA to describe either the
OUTPUT (equivalently SELECT LIST) or the INPUT (BIND
VARIABLES) for the named statement.
In the INPUT case, DESCRIBE BIND VARIABLES does not set up the data
types in the SQLDA: this needs to be done by the application. The ALL
keyword allows you to describe INPUT and OUTPUT in one SQLDA.
If you specify a statement name, the statement must have been previously
prepared using the PREPARE statement with the same statement name and
the SQLDA must have been previously allocated (see the "ALLOCATE
DESCRIPTOR statement" on page 369).

486
Chapter 9 SQL Statements

If you specify a cursor name, the cursor must have been previously declared
and opened. The default action is to describe the OUTPUT. Only SELECT
statements and CALL statements have OUTPUT. A DESCRIBE OUTPUT
on any other statement, or on a cursor that is not a dynamic cursor, indicates
no output by setting the sqld field of the SQLDA to zero.
Parameters USER TYPES A DESCRIBE statement with the USER TYPES clause
returns information about domains of a column. Typically, such a
DESCRIBE will be done when a previous DESCRIBE returns an indicator of
DT_HAS_USERTYPE_INFO.
The information returned is the same as for a DESCRIBE without the USER
TYPES keywords, except that the sqlname field holds the name of the
domain, instead of the name of the column.
If the DESCRIBE uses the LONG NAMES clause, the sqldata field holds
this information.

ALL DESCRIBE ALL allows you to describe INPUT and OUTPUT with
one request to the database server. This has a performance benefit. The
INPUT information will be filled in the SQLDA first, followed by the
OUTPUT information. The sqld field contains the total number of INPUT
and OUTPUT variables. The DT_DESCRIBE_INPUT bit in the indicator
variable is set for INPUT variables and clear for OUTPUT variables.

INPUT A bind variable is a value supplied by the application when the


database executes the statements. Bind variables can be considered
parameters to the statement. DESCRIBE INPUT fills in the name fields in
the SQLDA with the bind variable names. DESCRIBE INPUT also puts the
number of bind variables in the sqld field of the SQLDA.
DESCRIBE uses the indicator variables in the SQLDA to provide additional
information. DT_PROCEDURE_IN and DT_PROCEDURE_OUT are bits
that are set in the indicator variable when a CALL statement is described.
DT_PROCEDURE_IN indicates an IN or INOUT parameter and
DT_PROCEDURE_OUT indicates an INOUT or OUT parameter. Procedure
RESULT columns will have both bits clear. After a describe OUTPUT, these
bits can be used to distinguish between statements that have result sets (need
to use OPEN, FETCH, RESUME, CLOSE) and statements that do not (need
to use EXECUTE). DESCRIBE INPUT only sets DT_PROCEDURE_IN
and DT_PROCEDURE_OUT appropriately when a bind variable is an
argument to a CALL statement; bind variables within an expression that is an
argument in a CALL statement will not set the bits.

487
DESCRIBE statement [ESQL]

OUTPUT The DESCRIBE OUTPUT statement fills in the data type and
length for each select list item in the SQLDA. The name field is also filled in
with a name for the select list item. If an alias is specified for a select list
item, the name will be that alias. Otherwise, the name will be derived from
the select list item: if the item is a simple column name, it will be used;
otherwise, a substring of the expression will be used. DESCRIBE will also
put the number of select list items in the sqld field of the SQLDA.
If the statement being described is a UNION of two or more SELECT
statements, the column names returned for DESCRIBE OUTPUT are the
same column names which would be returned for the first SELECT
statement.

If you describe a CALL statement, the DESCRIBE OUTPUT statement fills


in the data type, length, and name in the SQLDA for each INOUT or OUT
parameter in the procedure. DESCRIBE OUTPUT also puts the number of
INOUT or OUT parameters in the sqld field of the SQLDA.

If you describe a CALL statement with a result set, the DESCRIBE


OUTPUT statement fills in the data type, length, and name in the SQLDA
for each RESULT column in the procedure definition. DESCRIBE OUTPUT
will also put the number of result columns in the sqld field of the SQLDA.

LONG NAMES The LONG NAMES clause is provided to retrieve column


names for a statement or cursor. Without this clause, there is a 29-character
limit on the length of column names; with the clause, names of an arbitrary
length are supported.
If LONG NAMES is used, the long names are placed into the SQLDATA
field of the SQLDA, as if you were fetching from a cursor. None of the other
fields (SQLLEN, SQLTYPE, and so on) are filled in. The SQLDA must be
set up like a FETCH SQLDA: it must contain one entry for each column, and
the entry must be a string type. If there is an indicator variable, truncation is
indicated in the usual fashion.
The default specification for the long names is TABLE.COLUMN.

WITH VARIABLE RESULT This clause is used to describe procedures


that may have more than one result set, with different numbers or types of
columns.
If WITH VARIABLE RESULT is used, the database server sets the
SQLCOUNT value after the DESCRIBE statement to one of the following
values:
♦ 0 The result set may change. The procedure call should be described
again following each OPEN statement.
♦ 1 The result set is fixed. No redescribing is required.

488
Chapter 9 SQL Statements

$ For more information on the use of the SQLDA structure, see "The SQL
descriptor area (SQLDA)" on page 44 of the book ASA Programming
Interfaces Guide.
Standards and ♦ SQL/92 Part of the SQL/92 standard. Some clauses are vendor
compatibility extensions.
♦ Sybase Some clauses supported by Open Client/Open Server.
Example ♦ The following example shows how to use the DESCRIBE statement:
sqlda = alloc_sqlda( 3 );
EXEC SQL DESCRIBE OUTPUT
FOR employee_statement
INTO sqlda;
if( sqlda->sqld > sqlda->sqln ) {
actual_size = sqlda->sqld;
free_sqlda( sqlda );
sqlda = alloc_sqlda( actual_size );
EXEC SQL DESCRIBE OUTPUT
FOR employee_statement
INTO sqlda;
}

489
DISCONNECT statement [ESQL][Interactive SQL]

DISCONNECT statement
[ESQL][Interactive SQL]
Function Use this statement to drop a connection with the database.
Syntax DISCONNECT
connection-name
| [ CURRENT ]
| ALL
connection-name: identifier, string, or host-variable.
Permissions None.
Side effects None.
See also "CONNECT statement" on page 411
"SET CONNECTION statement" on page 594
Description The DISCONNECT statement drops a connection with the database server
and releases all resources used by it. If the connection to be dropped was
named on the CONNECT statement, the name can be specified. Specifying
ALL will drop all of the application’s connections to all database
environments. CURRENT is the default, and will drop the current
connection.
An implicit ROLLBACK is executed on connections that are dropped.
Standards and ♦ SQL/92 Intermediate level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Examples ♦ The following statement shows how to use DISCONNECT in
Embedded SQL:
EXEC SQL DISCONNECT :conn_name
♦ The following statement shows how to use DISCONNECT from
Interactive SQL to disconnect all connections:
DISCONNECT ALL

490
Chapter 9 SQL Statements

DROP statement
Function Use this statement to remove objects from the database.
Syntax DROP
{ DATATYPE | DOMAIN } datatype-name
| DBSPACE dbspace-name
| EVENT event-name
| FUNCTION [ owner.]function-name
| INDEX [ [owner].table-name.]index-name
| PROCEDURE [ owner.]procedure-name
| TABLE [ owner.]table-name
| TRIGGER [ [ owner.]table-name.]trigger-name
| VIEW [ owner.]view-name
Permissions Any user who owns the object, or has DBA authority, can execute the DROP
statement.
For DROP DBSPACE, you must be the only connection to the database.
A user with ALTER permissions on the table can execute DROP TRIGGER.
A user with REFERENCES permissions on the table can execute DROP
INDEX.
Global temporary tables cannot be dropped unless all users that have
referenced the temporary table have disconnected.
Side effects Automatic commit. Clears the Data window in Interactive SQL. DROP
TABLE and DROP INDEX close all cursors for the current connection.
Local temporary tables is an exception; no commit is performed when one is
dropped.
When a view is dropped, all procedures and triggers are unloaded from
memory, so that any procedure or trigger that references the view reflects the
fact that the view does not exist. The unloading and loading of procedures
and triggers can have a performance impact if you are regularly dropping and
creating views.
See also "CREATE DATABASE statement" on page 415
"CREATE DOMAIN statement" on page 421
"CREATE INDEX statement" on page 435
"CREATE FUNCTION statement" on page 432
"CREATE PROCEDURE statement" on page 440
"CREATE TABLE statement" on page 453
"CREATE TRIGGER statement" on page 464
"CREATE VIEW statement" on page 469

491
DROP statement

Description The DROP statement removes the definition of the indicated database
structure. If the structure is a dbspace, all tables in that dbspace must be
dropped prior to dropping the dbspace. If the structure is a table, all data in
the table is automatically deleted as part of the dropping process. Also, all
indexes and keys for the table are dropped by the DROP TABLE statement.
DROP TABLE, DROP INDEX, and DROP DBSPACE are prevented
whenever the statement affects a table that is currently being used by another
connection.
DROP PROCEDURE and DROP FUNCTION are prevented when the
procedure or function is in use by another connection.
DROP DATATYPE is prevented if the data type is used in a table. You must
change data types on all columns defined on the domain in order to drop the
data type. It is recommended that you use DROP DOMAIN rather than
DROP DATATYPE, as DROP DOMAIN is the syntax used in the
ANSI/ISO SQL3 draft.
Standards and ♦ SQL/92 Entry level feature.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise for those objects
that exist in Adaptive Server Enterprise.
Examples ♦ Drop the department table from the database.
DROP TABLE department
♦ Drop the emp_dept view from the database.
DROP VIEW emp_dept

492
Chapter 9 SQL Statements

DROP DATABASE statement


Function Use this statement to delete all database files associated with a database.
Syntax DROP DATABASE database-name
Permissions Required permissions are set using the database server -gu command-line
option. The default setting is to require DBA authority.
The database must not be in use in order to be dropped.
Not supported on Windows CE.
Side effects In addition to deleting the database files from disk, any associated
transaction log file or transaction log mirror file is deleted.
See also "CREATE DATABASE statement" on page 415
Description The DROP DATABASE statement physically deletes all associated database
files from disk. If the database file does not exist, or is not in a suitable
condition for the database to be started, an error is generated.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Examples ♦ Drop the database temp.db, in the C:\temp directory..
DROP DATABASE ’c:\temp\temp.db’

493
DROP CONNECTION statement

DROP CONNECTION statement


Function Use this statement to drop a connection to the database, belonging to any
user.
Syntax DROP CONNECTION connection-id
Permissions Must have DBA authority.
Side effects None.
See also "CONNECT statement" on page 411
Description The DROP CONNECTION statement disconnects a user from the database
by dropping the connection to the database.
You can obtain the connection-id by using the connection_property
function to request the connection number. The following statement returns
the connection ID of the current connection:
SELECT connection_property( ’number’ )
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example ♦ The following statement drops the connection with ID number 4.
DROP CONNECTION 4

494
Chapter 9 SQL Statements

DROP EXTERNLOGIN statement


Function Use this statement to drop an external login from the Adaptive Server
Anywhere catalogs.
Syntax DROP EXTERNLOGIN login-name
TO remote-server
Permissions Must be the owner of login-name or have DBA authority.
Side effects Automatic commit.
See also "CREATE EXTERNLOGIN statement" on page 430
Description DROP EXTERNLOGIN deletes an external login from the Adaptive Server
Anywhere catalogs.
Parameters DROP clause Specifies the local user login name

TO clause Specifies the name of the remote server. The local user’s
alternate login name and password for that server is the external login that is
deleted.
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Example DROP EXTERNLOGIN dba TO sybase1

495
DROP OPTIMIZER STATISTICS statement

DROP OPTIMIZER STATISTICS statement


Function Use this statement to erase all optimizer statistics.
Syntax DROP OPTIMIZER STATISTICS
Permissions Must have DBA authority.
Side effects None.
Description The Adaptive Server Anywhere optimizer uses statistical information to
decide upon the best strategy for executing each statement. Adaptive Server
Anywhere automatically gathers and updates these statistics. These statistics
are stored permanently in the database in the column statistics registry.
Statistics gathered while processing one statement are available when
searching for efficient ways to execute subsequent statements.
Occasionally, the statistics may become inaccurate or relevant statistics may
be unavailable. This condition is most likely to arise when few queries have
been executed since a large amount of data was added, updated, or deleted.
In this situation, the best approach is to execute statements that allow
Adaptive Server Anywhere to scan the new rows sequentially. The internal
statistics are automatically updated as a side effect, allowing the optimizer to
choose better plans for subsequent queries.
The DROP OPTIMIZER STATISTICS statement deletes all internal
statistical data from the column statistics registry. This drastic step leaves the
optimizer with no access to essential statistical information. Without these
statistics, the optimizer may generate very inefficient data access plans,
causing poor database performance.
This statement should be used only during problem determination or when
reloading data into a database that differs substantially from the original data.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.

496
Chapter 9 SQL Statements

DROP SERVER statement


Function Use this statement to drop a remote server from the Adaptive Server
Anywhere catalog.
Syntax DROP SERVER server-name
Permissions Only the DBA account can delete a remote server.
Supported on Windows 95 and Windows NT only.
Side effects Automatic commit.
See also "CREATE SERVER statement" on page 451
Description DROP SERVER deletes a remote server from the Adaptive Server
Anywhere catalogs. You must drop all the proxy tables that have been
defined for the remote server before this statement will succeed.
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Example DROP SERVER ase_prod

497
DROP STATEMENT statement [ESQL]

DROP STATEMENT statement [ESQL]


Function Use this statement to free statement resources.
Syntax DROP STATEMENT [ owner.]statement-name
statement-name: identifier | host-variable
Permissions Must have prepared the statement.
Side effects None.
See also "PREPARE statement" on page 564
Description The DROP STATEMENT statement frees resources used by the named
prepared statement. These resources are allocated by a successful PREPARE
statement, and are normally not freed until the database connection is
released.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Open Client/Open Server
Example ♦ The following are examples of DROP STATEMENT use:
EXEC SQL DROP STATEMENT S1;
EXEC SQL DROP STATEMENT :stmt;

498
Chapter 9 SQL Statements

DROP VARIABLE statement


Function Use this statement to eliminate a SQL variable.
Syntax DROP VARIABLE identifier
Permissions None.
Side effects None.
See also "CREATE VARIABLE statement" on page 468
"SET statement" on page 591
Description The DROP VARIABLE statement eliminates a SQL variable that was
previously created using the CREATE VARIABLE statement. Variables will
be automatically eliminated when the database connection is released.
Variables are often used for large objects, so eliminating them after use or
setting them to NULL may free up significant resources (primarily disk
space).
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.

499
EXECUTE statement [ESQL]

EXECUTE statement [ESQL]


Function Use this statement to execute a prepared SQL statement.
Syntax 1 EXECUTE statement
… [ USING { DESCRIPTOR sqlda-name | host-variable-list ]
… [ INTO { DESCRIPTOR into-sqlda-name | into-host-variable-list ]
… [ ARRAY :integer ]
statement: identifier | host-variable | string
sqlda-name: identifier
into-sqlda-name: identifier
Syntax 2 EXECUTE IMMEDIATE statement
statement: string | host-variable
Permissions Permissions are checked on the statement being executed.
Side effects None.
See also "EXECUTE IMMEDIATE statement" on page 504
"PREPARE statement" on page 564
"DECLARE CURSOR statement" on page 475
Description The EXECUTE statement can be used for any SQL statement that can be
prepared. Cursors are used for SELECT statements or CALL statements that
return many rows from the database (see "Cursors in Embedded SQL" on
page 33 of the book ASA Programming Interfaces Guide).
After successful execution of an INSERT, UPDATE or DELETE statement,
the sqlerrd[2] field of the SQLCA (SQLCOUNT) is filled in with the
number of rows affected by the operation.

Syntax 1 Execute the named dynamic statement, which was previously


prepared. If the dynamic statement contains host variable place holders
which supply information for the request (bind variables), either the sqlda-
name must specify a C variable which is a pointer to an SQLDA containing
enough descriptors for all of the bind variables occurring in the statement, or
the bind variables must be supplied in the host-variable-list.

Syntax 2 A short form to PREPARE and EXECUTE a statement that does


not contain bind variables or output. The SQL statement contained in the
string or host-variable is immediately executed, and is dropped on
completion.

500
Chapter 9 SQL Statements

Parameters USING clause Results from a SELECT statement or a CALL statement


are put into either the variables in the variable list or the program data areas
described by the named SQLDA. The correspondence is one-to-one from the
OUTPUT (selection list or parameters) to either the host variable list or the
SQLDA descriptor array.

INTO clause If EXECUTE INTO is used with an INSERT statement, the


inserted row is returned in the second descriptor. For example, when using
auto-increment primary keys or BEFORE INSERT triggers that generate
primary key values, the EXECUTE statement provides a mechanism to re-
fetch the row immediately and determine the primary key value that was
assigned to the row. The same thing can be achieved by using @@identity
with auto-increment keys.

ARRAY clause The optional ARRAY clause can be used with prepared
INSERT statements to allow wide inserts, which insert more than one row at
a time and which may improve performance. The integer value is the number
of rows to be inserted. The SQLDA must contain a variable for each entry
(number of rows * number of columns). The first row is placed in SQLDA
variables 0 to (columns per row)-1, and so on.
Standards and ♦ SQL/92 Intermediate level feature.
compatibility
♦ Sybase Supported in Open Client/Open Server.
Examples ♦ Execute a DELETE.
EXEC SQL EXECUTE IMMEDIATE
’DELETE FROM employee WHERE emp_id = 105’;
♦ Execute a prepared DELETE statement.
EXEC SQL PREPARE del_stmt FROM
’DELETE FROM employee WHERE emp_id = :a’;
EXEC SQL EXECUTE del_stmt USING :employee_number;
♦ Execute a prepared query.
EXEC SQL PREPARE sel1 FROM
’SELECT emp_lname FROM employee WHERE emp_id = :a’;
EXEC SQL EXECUTE sel1 USING :employee_number INTO
:emp_lname;

501
EXECUTE statement [T-SQL]

EXECUTE statement [T-SQL]


Function Use this statement to invoke a procedure, as an Adaptive Server Enterprise-
compatible alternative to the CALL statement.
Syntax EXECUTE [ @return_status = ] [creator.]procedure_name
… | [@parameter-name = ] expression,
| [@parameter-name =] @variable [output] |, …
Authorization Must be the owner of the procedure, have EXECUTE permission for the
procedure, or have DBA authority.
Side effects None.
See also "CALL statement" on page 398
Description The EXECUTE statement executes a stored procedure, optionally supplying
procedure parameters and retrieving output values and return status
information.
The EXECUTE statement is implemented for Transact-SQL compatibility,
but can be used in either Transact-SQL or Watcom-SQL batches and
procedures.
Example ♦ The following procedure illustrates the EXECUTE statement.
CREATE PROCEDURE p1( @var INTEGER = 54 )
AS
PRINT ’on input @var = %1!’, @var
DECLARE @intvar integer
SELECT @intvar=123
SELECT @var=@intvar
PRINT ’on exit @var = %1!’, @var
The following statement executes the procedure, supplying the input
value of 23 for the parameter. If you are connected from an Open Client
or JDBC application, the PRINT messages are displayed on the client
window. If you are connected from an ODBC or Embedded SQL
application, the messages are displayed on the database server window.
EXECUTE p1 23
The following is an alternative way of executing the procedure, which is
useful if there are several parameters.
EXECUTE p1 @var = 23
The following statement executes the procedure, using the default value
for the parameter
EXECUTE p1

502
Chapter 9 SQL Statements

The following statement executes the procedure, and stores the return
value in a variable for checking return status.
EXECUTE @status = p1 23

503
EXECUTE IMMEDIATE statement [SP]

EXECUTE IMMEDIATE statement [SP]


Function Use this statement to enable dynamically constructed statements to be
executed from within a procedure.
Syntax 1 EXECUTE IMMEDIATE string-expression
Syntax 2 EXECUTE ( string-expression )
Permissions None. The statement is executed with the permissions of the owner of the
procedure, not with the permissions of the user who calls the procedure.
Side effects None. However, if the statement is a data definition statement with an
automatic commit as a side effect, that commit does take place.
$ For more information about using the EXECUTE IMMEDIATE
statement in procedures, see "Using the EXECUTE IMMEDIATE statement
in procedures" on page 470 of the book ASA User’s Guide.
See also "CREATE PROCEDURE statement" on page 440
"BEGIN statement" on page 392
"EXECUTE statement" on page 500
Description The EXECUTE IMMEDIATE statement extends the range of statements that
can be executed from within procedures and triggers. It lets you execute
dynamically prepared statements, such as statements that are constructed
using the parameters passed in to a procedure.
Literal strings in the statement must be enclosed in single quotes, and the
statement must be on a single line.
The EXECUTE IMMEDIATE statement does not support statements and
queries that return result sets.
Only syntax 2 can be used in Transact-SQL stored procedures and triggers.
Standards and ♦ SQL/92 Intermediate level feature.
compatibility
♦ Sybase Supported in Open Client/Open Server.
Example The following procedure creates a table, where the table name is supplied as
a parameter to the procedure. The EXECUTE IMMEDIATE statement must
all be on a single line.
CREATE PROCEDURE CreateTableProc(
IN tablename char(30)
)
BEGIN
EXECUTE IMMEDIATE ’CREATE TABLE ’ || tablename ||
’ ( column1 INT PRIMARY KEY)’
END

504
Chapter 9 SQL Statements

To call the procedure and create a table mytable:


CALL CreateTableProc( ’mytable’ )

505
EXIT statement [Interactive SQL]

EXIT statement [Interactive SQL]


Function Use this statement to leave Interactive SQL.
Syntax EXIT | QUIT | BYE
Permissions None.
Side effects This statement automatically performs a commit if option
COMMIT_ON_EXIT is set to ON (the default); otherwise it performs a
rollback.
See also "SET OPTION statement" on page 596
Description This statement closes your connection with the database, then closes the
Interactive SQL environment. Before closing the database connection,
Interactive SQL automatically executes a COMMIT statement if the
COMMIT_ON_EXIT option is set to ON. If this option is set to OFF,
Interactive SQL instead performs a ROLLBACK. By default, the
COMMIT_ON_EXIT option is set to ON.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not applicable in Adaptive Server Enterprise.

506
Chapter 9 SQL Statements

EXPLAIN statement [ESQL]


Function Use this statement to retrieve a text specification of the optimization strategy
used for a particular cursor.
Syntax EXPLAIN PLAN FOR CURSOR cursor-name INTO host-variable
… INTO host-variable
| USING DESCRIPTOR sqlda-name
cursor-name: identifier or host-variable
sqlda-name: identifier
Permissions Must have opened the named cursor.
Side effects None.
See also "DECLARE CURSOR statement" on page 475
"PREPARE statement" on page 564
"FETCH statement" on page 509
"CLOSE statement" on page 404
"OPEN statement" on page 556
"Cursors in Embedded SQL" on page 33 of the book ASA Programming
Interfaces Guide
"The SQL Communication Area" on page 27 of the book ASA Programming
Interfaces Guide
Description The EXPLAIN statement retrieves a text representation of the optimization
strategy for the named cursor. The cursor must be previously declared and
opened.
The host-variable or sqlda-name variable must be of string type. The
optimization string specifies in what order the tables are searched, and also
which indexes are being used for the searches if any.
This string may be long, depending on the query, and has the following
format:
table (index), table (index), ...
If a table has been given a correlation name, the correlation name will appear
instead of the table name. The order that the table names appear in the list is
the order in which they will be accessed by the database server. After each
table is a parenthesized index name. This is the index that will be used to
access the table. If no index will be used (the table will be scanned
sequentially) the letters "seq" will appear for the index name. If a particular
SQL SELECT statement involves subqueries, a colon (:) will separate each
subquery’s optimization string. These subquery sections will appear in the
order that the database server executes the queries.

507
EXPLAIN statement [ESQL]

After successful execution of the EXPLAIN statement, the sqlerrd[3] field


of the SQLCA (SQLIOESTIMATE) will be filled in with an estimate of the
number of input/output operations required to fetch all rows of the query.
A discussion with quite a few examples of the optimization string can be
found in "Monitoring and Improving Performance" on page 777 of the book
ASA User’s Guide.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
Example ♦ The following example illustrates use of EXPLAIN:
EXEC SQL BEGIN DECLARE SECTION;
char plan[300];
EXEC SQL END DECLARE SECTION;
EXEC SQL DECLARE employee_cursor CURSOR FOR
SELECT emp_id, emp_lname
FROM employee
WHERE emp_lname like :pattern;
EXEC SQL OPEN employee_cursor;
EXEC SQL EXPLAIN PLAN FOR CURSOR employee_cursor
INTO :plan;
printf( "Optimization Strategy: ’%s’.n", plan );
The plan variable contains the following string:
’employee (seq )’

508
Chapter 9 SQL Statements

FETCH statement [ESQL] [SP]


Function Use this statement to reposition a cursor and then get data from it.
Syntax FETCH
… cursor-position
… cursor-name
… [ INTO { host-variable-list | variable-list }
| USING DESCRIPTOR sqlda-name ]
… [ PURGE ]
… [ BLOCK n ]
… [ FOR UPDATE ]
… [ ARRAY fetch-count ]
… INTO variable-list [ FOR UPDATE ]
cursor-position:
NEXT | PRIOR | FIRST | LAST | { ABSOLUTE | RELATIVE } row-count
row-count: number or host variable
cursor-name: identifier or host-variable
host-variable-list: may contain indicator variables
variable-list: Stored procedure variables
sqlda-name: identifier
fetch-count: integer or host variable
Permissions The cursor must be opened, and the user must have SELECT permission on
the tables referenced in the declaration of the cursor.
Side effects None.
See also "DECLARE CURSOR statement" on page 475
"PREPARE statement" on page 564
"OPEN statement" on page 556
"Cursors in Embedded SQL" on page 33 of the book ASA Programming
Interfaces Guide
"Using cursors in procedures and triggers" on page 458 of the book ASA
User’s Guide
FETCH in PowerScript Reference
Description The FETCH statement retrieves one row from the named cursor. The cursor
must have been previously opened.

Embedded SQL use A DECLARE CURSOR statement must appear


before the FETCH statement in the C source code, and the OPEN statement
must be executed before the FETCH statement. If a host variable is being
used for the cursor name, the DECLARE statement actually generates code
and thus must be executed before the FETCH statement.

509
FETCH statement [ESQL] [SP]

The server returns in SQLCOUNT the number of records fetched, and


always returns a SQLCOUNT greater than zero unless there is an error or
warning. A SQLCOUNT of zero with no error condition indicates that one
valid row has been fetched.
If the SQLSTATE_NOTFOUND warning is returned on the fetch, the
sqlerrd[2] field of the SQLCA (SQLCOUNT) contains the number of rows
by which the attempted fetch exceeded the allowable cursor positions. The
value is 0 if the row was not found but the position is valid; for example,
executing FETCH RELATIVE 1 when positioned on the last row of a cursor.
The value is positive if the attempted fetch was beyond the end of the cursor,
and negative if the attempted fetch was before the beginning of the cursor.
After successful execution of the fetch statement, the sqlerrd[1] field of the
SQLCA (SQLIOCOUNT) is incremented by the number of input/output
operations required to perform the fetch. This field is actually incremented
on every database statement.

Single row fetch One row from the result of the SELECT statement is put
into the variables in the variable list. The correspondence is one-to-one from
the select list to the host variable list.

Multi-row fetch One or more rows from the result of the SELECT
statement are put into either the variables in variable-list or the program data
areas described by sqlda-name. In either case, the correspondence is one-to-
one from the select-list to either the host-variable-list or the sqlda-name
descriptor array.
Parameters INTO The INTO clause is optional. If it is not specified, the FETCH
statement positions the cursor only. The host-variable-list is for Embedded
SQL use only.

cursor position An optional positional parameter allows the cursor to be


moved before a row is fetched. If the fetch includes a positioning parameter
and the position is outside the allowable cursor positions, the
SQLE_NOTFOUND warning is issued and the SQLCOUNT field indicates
the offset from a valid position.

The OPEN statement initially positions the cursor before the first row.
♦ NEXT Next is the default positioning, and causes the cursor to be
advanced one row before the row is fetched.
♦ PRIOR Causes the cursor to be backed up one row before fetching.

510
Chapter 9 SQL Statements

♦ RELATIVE RELATIVE positioning is used to move the cursor by a


specified number of rows in either direction before fetching. A positive
number indicates moving forward and a negative number indicates
moving backwards. Thus, a NEXT is equivalent to RELATIVE 1 and
PRIOR is equivalent to RELATIVE -1. RELATIVE 0 retrieves the same
row as the last fetch statement on this cursor.
♦ ABSOLUTE The ABSOLUTE positioning parameter is used to go to a
particular row. A zero indicates the position before the first row (see
"Using cursors in procedures and triggers" on page 458 of the book ASA
User’s Guide).
A one (1) indicates the first row, and so on. Negative numbers are used
to specify an absolute position from the end of the cursor. A negative
one (-1) indicates the last row of the cursor.
♦ FIRST A short form for ABSOLUTE 1.
♦ LAST A short form for ABSOLUTE -1.

Cursor positioning problems


Inserts and some updates to DYNAMIC SCROLL cursors can cause
problems with cursor positioning. The database server does not put
inserted rows at a predictable position within a cursor unless there is an
ORDER BY clause on the SELECT statement. In some cases, the inserted
row does not appear at all until the cursor is closed and opened again.
This occurs if a temporary table had to be created to open the cursor (see
"Temporary tables used in query processing" on page 802 of the book
ASA User’s Guide for a description).
The UPDATE statement may cause a row to move in the cursor. This will
happen if the cursor has an ORDER BY that uses an existing index (a
temporary table is not created).

BLOCK clause Rows may be fetched by the client application more than
one at a time. This is referred to as block fetching, prefetching, or multi-
row fetching. The first fetch causes several rows to be sent back from the
server. The client buffers these rows, and subsequent fetches are retrieved
from these buffers without a new request to the server.

The BLOCK clause is for use in Embedded SQL only. It gives the client and
server a hint as to how many rows may be fetched by the application. The
special value of 0 means the request will be sent to the server and a single
row will be returned (no row blocking).
If no BLOCK clause is specified, the value specified on OPEN is used. For
more information, see "OPEN statement" on page 556.

511
FETCH statement [ESQL] [SP]

FETCH RELATIVE 0 always re-fetches the row.


PURGE clause The PURGE clause is for use in embedded SQL only. It
causes the client to flush its buffers of all rows, and then send the fetch
request to the server. Note that this fetch request may return a block of rows.

FOR UPDATE clause The FOR UPDATE clause indicates that the
fetched row will subsequently be updated with an UPDATE WHERE
CURRENT OF CURSOR statement. This clause causes the database server
to put a write lock on the row. The lock will be held until the end of the
current transaction. See "How locking works" on page 401 of the book ASA
User’s Guide.

ARRAY clause The ARRAY clause is for use in Embedded SQL only. It
allows so-called wide fetches, which retrieve more than one row at a time,
and which may improve performance.
To use wide fetches in embedded SQL, include the fetch statement in your
code as follows:
EXEC SQL FETCH . . . ARRAY nnn
where ARRAY nnn is the last item of the FETCH statement. The fetch count
nnn can be a host variable. The SQLDA must contain nnn * (columns per
row) variables. The first row is placed in SQLDA variables 0 to (columns
per row)-1, and so on.
$ For a detailed example of using wide fetches, see the section "Fetching
more than one row at a time" on page 36 of the book ASA Programming
Interfaces Guide.
Standards and ♦ SQL/92 Entry level feature. Use in procedures is a Persistent Stored
compatibility Module feature.
♦ Sybase Supported in Adaptive Server Enterprise.
Example ♦ The following is an Embedded SQL example.
EXEC SQL DECLARE cur_employee CURSOR FOR
SELECT emp_id, emp_lname FROM employee;
EXEC SQL OPEN cur_employee;
EXEC SQL FETCH cur_employee
INTO :emp_number, :emp_name:indicator;
♦ The following is a procedure example:
BEGIN
DECLARE cur_employee CURSOR FOR
SELECT emp_lname
FROM employee;
DECLARE name CHAR(40);
OPEN cur_employee;
LOOP

512
Chapter 9 SQL Statements

FETCH NEXT cur_employee into name;


...
END LOOP
CLOSE cur_employee;
END

513
FOR statement

FOR statement
Function Use this statement to repeat the execution of a statement list once for each
row in a cursor.
Syntax [ statement-label : ]
. . .FOR for-loop-name AS cursor-name
. . . CURSOR FOR statement
. . .[ FOR UPDATE | FOR READ ONLY ]
. . . DO statement-list
. . . END FOR [ statement-label ]
Permissions None.
Side effects None.
See also "DECLARE CURSOR statement" on page 475
"FETCH statement" on page 509
"LEAVE statement" on page 544
"LOOP statement" on page 553
Description The FOR statement is a control statement that allows you to execute a list of
SQL statements once for each row in a cursor. The FOR statement is
equivalent to a compound statement with a DECLARE for the cursor and a
DECLARE of a variable for each column in the result set of the cursor
followed by a loop that fetches one row from the cursor into the local
variables and executes statement-list once for each row in the cursor.
The name and data type of each local variable is derived from the statement
used in the cursor. With a SELECT statement, the data types will be the data
types of the expressions in the select list. The names will be the select list
item aliases, if they exist; otherwise, they will be the names of the columns.
Any select list item that is not a simple column reference must have an alias.
With a CALL statement, the names and data types will be taken from the
RESULT clause in the procedure definition.
The LEAVE statement can be used to resume execution at the first statement
after the END FOR. If the ending statement-label is specified, it must match
the beginning statement-label.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example ♦ The following fragment illustrates the use of the FOR loop.
FOR names AS curs CURSOR FOR
SELECT emp_lname
FROM employee
DO
CALL search_for_name( emp_lname );

514
Chapter 9 SQL Statements

END FOR;

515
FORWARD TO statement

FORWARD TO statement
Function Use this statement to send native syntax SQL statements to a remote server.
Syntax 1 FORWARD TO server-name { sql-statement }
Syntax 2 FORWARD TO [ server-name ]
Permissions None
Side effects The remote connection is set to AUTOCOMMIT (unchained) mode for the
duration of the FORWARD TO session. Any work that was pending prior to
the FORWARD TO statement is automatically committed.
Description The FORWARD TO statement enables users to specify the server to which a
passthrough connection is required. The statement can be used in two ways:
♦ Syntax 1 Send a single statement to a remote server.
♦ Syntax 2 Place Adaptive Server Anywhere into passthrough mode for
sending a series of statements to a remote server. All subsequent
statements are passed directly to the remote server. To turn passthrough
mode off, issue FORWARD TO without a server-name specification.
If you encounter an error from the remote server while in passthrough
mode, you must still issue a FORWARD TO statement to turn
passthrough off.
When establishing a connection to server-name on behalf of the user, the
server uses:
♦ A remote login alias set using CREATE EXTERNLOGIN, or
♦ If a remote login alias is not set up, the name and password used to
communicate with Adaptive Server Anywhere
If the connection cannot be made to the server specified, the reason is
contained in a message returned to the user.
After statements are passed to the requested server, any results are converted
into a form that can be recognized by the client program.
server-name The name of the remote server.

sql-statement A command in the native SQL syntax of the remote server.


The command or group of commands is enclosed in curly brackets ({}).
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Example ♦ The following example shows a passthrough session with the remote
server ase_prod:

516
Chapter 9 SQL Statements

FORWARD TO aseprod
SELECT * from titles
SELECT * from authors
FORWARD TO

517
FROM clause

FROM clause
Function Use this statement to specify the database tables or views involved in a
SELECT or UPDATE statement.
Syntax … FROM table-expression, …
table-expression:
table-spec
| table-expression join-type table-spec [ ON condition ]
| ( table-expression, … )
table-spec:
[userid.]table-name [ [AS] correlation-name ]
| select-statement [ AS ] correlation-name [ ( column-name, … ) ]
join-type:
CROSS JOIN
| [ NATURAL | KEY ] JOIN
| [ NATURAL | KEY ] INNER JOIN
| [ NATURAL | KEY ] LEFT OUTER JOIN
| [ NATURAL | KEY ] RIGHT OUTER JOIN
Permissions None.
Side effects None.
See also "DELETE statement" on page 482
"SELECT statement" on page 587
"UPDATE statement" on page 621
"Joins: Retrieving Data from Several Tables" on page 189 of the book ASA
User’s Guide
Description The SELECT, UPDATE, and DELETE statements require a table list, to
specify which tables will be used by the statement.

Views and derived tables


Although this description refers to tables, it applies to views and derived
tables unless otherwise noted.

The FROM table list creates a result set consisting of all the columns from
all the tables specified. Initially, all combinations of rows in the component
tables are in the result set, and the number of combinations is usually
reduced by join conditions and/or WHERE conditions.
Tables owned by a different user can be qualified by specifying the user ID.
Tables owned by groups to which the current user belongs will be found by
default without specifying the user ID (see "Referring to tables owned by
groups" on page 736 of the book ASA User’s Guide).

518
Chapter 9 SQL Statements

The correlation name is used to give a temporary name to the table for this
SQL statement only. This is useful when referencing columns from a table
with a long name. The correlation name is also necessary to distinguish
between table instances if you reference the same table more than once in the
same query. If no correlation name is specified, the table name is used as the
correlation name for the current statement.
If the same correlation name is used twice for the same table in a table
expression, that table is treated as if it were listed only once. For example, in:
SELECT *
FROM sales_order
KEY JOIN sales_order_items,
sales_order
KEY JOIN employee
the two instances of the sales_order table are treated as one instance, this is
equivalent to:
SELECT *
FROM sales_order
KEY JOIN sales_order_items
KEY JOIN employee
Whereas:
SELECT *
FROM Person HUSBAND, Person WIFE
would be treated as two instances of the Person table, with different
correlation names HUSBAND and WIFE.
You can supply SELECT statements instead of table or view names in the
FROM clause. This allows you to use groups on groups, or joins with
groups, without creating a view. The tables that you create in this way are
derived tables.
Standards and ♦ SQL/92 Entry level feature.
compatibility
♦ Sybase The JOIN clause is not supported in Adaptive Server
Enterprise. Instead, you must use the WHERE clause to build joins.
Examples ♦ The following are valid FROM clauses:
...
FROM employee
...
...
FROM employee NATURAL JOIN department
...
...
FROM customer

519
FROM clause

KEY JOIN sales_order


KEY JOIN sales_order_items
KEY JOIN product
...
♦ The following query illustrates how to use derived tables in a query:
SELECT lname, fname, number_of_orders
FROM customer JOIN
( SELECT cust_id, count(*)
FROM sales_order
GROUP BY cust_id )
AS sales_order_counts ( cust_id,
number_of_orders )
ON ( customer.id = sales_order_counts.cust_id )
WHERE number_of_orders > 3

520
Chapter 9 SQL Statements

GET DATA statement [ESQL]


Function Use this statement to get string or binary data for one column of the current
row of a cursor. GET DATA is usually used to fetch LONG BINARY or
LONG VARCHAR fields. See "SET statement" on page 591.
Syntax GET DATA cursor-name
… COLUMN column-num
… OFFSET start-offset
… [ WITH TEXTPTR ]
… USING DESCRIPTOR sqlda-name | INTO host-variable [, … ]
cursor-name: identifier, or host-variable
column-num: integer or host-variable
start-offset: integer or host-variable
sqlda-name: identifier
Permissions The cursor must be opened and positioned on a row, using FETCH.
Side effects None.
See also "FETCH statement" on page 509
"READTEXT statement" on page 573
Description Get a piece of one column value from the row at the current cursor position.
Parameters COLUMN clause The value of column-num starts at one, and identifies
the column whose data is to be fetched. That column must be of a string or
binary type.

OFFSET clause The start-offset indicates the number of bytes to skip


over in the field value. Normally, this would be the number of bytes
previously fetched. The number of bytes fetched on this GET DATA
statement is determined by the length of the target host variable.
The indicator value for the target host variable is a short integer, so it cannot
always contain the number of bytes truncated. Instead, it contains a negative
value if the field contains the NULL value, a positive value (NOT
necessarily the number of bytes truncated) if the value is truncated, and zero
if a non-NULL value is not truncated.

WITH TEXTPTR clause If the WITH TEXTPTR clause is given, a text


pointer is retrieved into a second host variable or into the second field in the
SQLDA. This text pointer can be used with the Transact-SQL READ TEXT
and WRITE TEXT statements. The text pointer is a 16-bit binary value, and
can be declared as follows:
DECL_BINARY( 16 ) textptr_var;

521
GET DATA statement [ESQL]

WITH TEXTPTR can be used only with long data types (LONG BINARY,
LONG VARCHAR, TEXT, IMAGE). If you attempt to use it with another
data type, the error INVALID_TEXTPTR_VALUE is returned.
The total length of the data is returned in the SQLCOUNT field of the
SQLCA structure.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Open Client/Open Server. An alternative is
the Transact-SQL READTEXT statement.
Example ♦ The following example uses GET DATA to fetch a binary large object
(often called a blob).
EXEC SQL BEGIN DECLARE SECTION;
DECL_BINARY(1000) piece;
short ind;
long offset;
EXEC SQL END DECLARE SECTION;
int size;
/* Open a cursor on a long varchar field */
EXEC SQL DECLARE big_cursor CURSOR FOR
SELECT long_data FROM some_table
WHERE key_id = 2;
EXEC SQL OPEN big_cursor;
EXEC SQL FETCH big_cursor INTO :piece;
for( offset = 0; ; offset += piece.len ) {
EXEC SQL GET DATA big_cursor COLUMN 1
OFFSET :offset INTO :piece:ind;
/* Done if the NULL value */
if( ind < 0 ) break;
write_out_piece( piece );
/* Done when the piece was not truncated */
if( ind == 0 ) break;
}
EXEC SQL CLOSE big_cursor;

522
Chapter 9 SQL Statements

GET DESCRIPTOR statement [ESQL]


Function Use this statement to retrieve information about a variable within a descriptor
area, or retrieves its value.
Syntax GET DESCRIPTOR descriptor-name
…{ hostvar = COUNT | VALUE n assignment [, …] }
assignment:
hostvar = { TYPE | LENGTH | PRECISION | SCALE | DATA |
INDICATOR | NAME | NULLABLE | RETURNED_LENGTH }
Permissions None.
Side effects None.
See also "ALLOCATE DESCRIPTOR statement" on page 369
"DEALLOCATE DESCRIPTOR statement" on page 472
"SET DESCRIPTOR statement" on page 595
"The SQL descriptor area (SQLDA)" on page 44 of the book ASA
Programming Interfaces Guide
Description The GET DESCRIPTOR statement is used to retrieve information about a
variable within a descriptor area, or to retrieve its value.
The value n specifies the variable in the descriptor area about which the
information will be retrieved. Type checking is performed when doing GET
… DATA to ensure that the host variable and the descriptor variable have the
same data type.
If an error occurs, it is returned in the SQLCA.
Standards and ♦ SQL/92 Entry level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Example ♦ For an example, see "ALLOCATE DESCRIPTOR statement" on
page 369.

523
GET OPTION statement [ESQL]

GET OPTION statement [ESQL]


Function Use this statement to get the current setting of an option. This statement is
deprecated in favor of system functions.
Syntax GET OPTION [ userid.]option-name
…[ INTO host-variable ]
…[ USING DESCRIPTOR sqlda-name ]
userid: identifier, string, or host-variable
option-name: identifier, string, or host-variable
host-variable: indicator variable allowed
sqlda-name: identifier
Permissions None required.
Side effects None.
See also "SET OPTION statement" on page 596
"System and catalog stored procedures" on page 935
"CONNECTION_PROPERTY function " on page 309
Description The GET OPTION statement is provided for compatibility with older
versions of the software. The recommended way to get the values of options
is to use the connection_property system function.
The GET OPTION statement gets the option setting of the option option-
name for the user userid or for the connected user if userid is not specified.
This will be either the user’s personal setting or the PUBLIC setting if there
is no setting for the connected user. If the option specified is a database
option and the user has a temporary setting for that option, then the
temporary setting is retrieved.
If option-name does not exist, GET OPTION returns the warning
SQLE_NOTFOUND.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Example ♦ The following statement illustrates use of GET OPTION.
EXEC SQL GET OPTION ’date_format’ INTO :datefmt;

524
Chapter 9 SQL Statements

GOTO statement [T-SQL]


Function Use this statement to branch to a labeled statement.
Syntax label:
GOTO label
Authorization None.
Side effects None.
Description Any statement in a Transact-SQL procedure, trigger, or batch can be labeled.
The label name is a valid identifier followed by a colon. In the GOTO
statement, the colon is not used.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase Adaptive Server Enterprise supports the GOTO statement.
Example ♦ The following Transact-SQL batch prints the message "yes" on the
server window four times:
declare @count smallint
select @count = 1
restart:
print ’yes’
select @count = @count + 1
while @count <=4
goto restart

525
GRANT statement

GRANT statement
Function Use this statement to create new user IDs, to grant or deny permissions to
specific users, and to create or change passwords.
Syntax 1 GRANT CONNECT TO userid, …
[ AT starting-id }
IDENTIFIED BY password, …
Syntax 2 GRANT {
DBA,
GROUP,
MEMBERSHIP IN GROUP userid, …,
[ RESOURCE | ALL ]
}
… TO userid, …
Syntax 3 GRANT {
ALL [ PRIVILEGES ],
ALTER,
DELETE,
INSERT,
REFERENCES [ ( column-name, … ) ],
SELECT [ ( column-name, … ) ],
UPDATE [ ( column-name, … ) ],
}
… ON [ owner.]table-name
… TO userid, …
[ WITH GRANT OPTION ]
Syntax 4 GRANT EXECUTE ON [ owner.]procedure-name TO userid, …
Syntax 5 GRANT INTEGRATED LOGIN TO user_profile_name, … AS USER userid
Permissions Syntax 1 or 2 One of the following conditions must be met.
♦ You are changing your own password using GRANT CONNECT
♦ You have DBA authority
If you are changing another user’s password (with DBA authority), the other
user must not be connected to the database.

Syntax 3 One of the following conditions must be met:


♦ You own the table
♦ You have been granted permissions on the table with GRANT OPTION
♦ You have DBA authority

Syntax 4 One of the following conditions must be met:

526
Chapter 9 SQL Statements

♦ You own the procedure


♦ You have DBA authority

Syntax 5 The following condition must be met:


♦ You have DBA authority
Side effects Automatic commit.
See also "REVOKE statement" on page 581
Description The GRANT statement is used to grant database permissions to individual
user IDs and groups. It is also used to create and delete users and groups.
If WITH GRANT OPTION is specified, then the named user ID is also given
permission to GRANT the same permissions to other user IDs.
Syntax 4 of the GRANT statement is used to grant permission to execute a
procedure.
Syntax 5 of the GRANT statement creates an explicit integrated login
mapping between one or more Windows NT user profiles and an existing
database user ID, allowing users who successfully log in to their local
machine to connect to a database without having to provide a user ID or
password.
$ For more information on integrated logins see "Using integrated logins"
on page 73 of the book ASA User’s Guide.
Parameters CONNECT TO Creates a new user. GRANT CONNECT can also be used
by any user to change their own password. To create a user with the empty
string as the password, type:
GRANT CONNECT TO userid IDENTIFIED BY ""
To create a user with no password, type:
GRANT CONNECT TO userid
A user with no password cannot connect to the database. This is useful if you
are creating a group and do not want anyone to connect to the database using
the group user ID. The password must be a valid identifier, as described in
"Identifiers" on page 211.

AT starting-id This clause is not for general purpose use. The clause
specifies the internal numeric value to be used for the first user ID in the list.
The clause is implemented primarily for use by the Unload utility.

DBA Database Administrator authority gives a user permission to do


anything. This is usually reserved for the person in the organization who is
looking after the database.

527
GRANT statement

GROUP Allows the user(s) to have members.


$ For more information, see "Managing groups" on page 732 of the book
ASA User’s Guide.

MEMBERSHIP IN GROUP This allows the user(s) to inherit table


permissions from a group and to reference tables created by the group
without qualifying the table name.
$ For more information, see "Managing groups" on page 732 of the book
ASA User’s Guide.
Syntax 3 of the GRANT statement is used to grant permission on individual
tables or views. The table permissions can be specified individually, or you
can use ALL to grant all six permissions at once.

RESOURCE Allows the user to create tables and views. In syntax 2, ALL
is a synonym for RESOURCE that is compatible with Sybase Adaptive
Server Enterprise.

ALL In Syntax 3, this grants all of the permissions outlined below.

ALTER The users will be allowed to alter the named table with the
ALTER TABLE statement. This permission is not allowed for views.

DELETE The users will be allowed to delete rows from the named table or
view.

INSERT The users will be allowed to insert rows into the named table or
view.

REFERENCES [(column-name, …)] The users will be allowed to create


indexes on the named table, and foreign keys which reference the named
tables. If column names are specified, the users will be allowed to reference
only those columns. REFERENCES permissions on columns cannot be
granted for views, only for tables.
INDEX is a synonym for REFERENCES.

SELECT [(column-name, …)] The users will be allowed to look at


information in this view or table. If column names are specified, the users
will be allowed to look at only those columns. SELECT permissions on
columns cannot be granted for views, only for tables.

UPDATE [(column-name, …)] The users will be allowed to update rows


in this view or table. If column names are specified, the users will be allowed
to update only those columns. UPDATE permissions on columns cannot be
granted for views, only for tables.

528
Chapter 9 SQL Statements

♦ SQL/92 Syntax 3 is an entry-level feature. Syntax 4 is a Persistent


Standards and
Stored Module feature. Other syntaxes are vendor extensions.
compatibility
♦ Sybase Syntaxes 2 and 3 are supported in Adaptive Server Enterprise.
The security model is different in Adaptive Server Enterprise and
Adaptive Server Anywhere, so other syntaxes differ.
Examples ♦ Make two new users for the database.
GRANT
CONNECT TO Laurel, Hardy
IDENTIFIED BY Stan, Ollie
♦ Grant permissions on the employee table to user Laurel.
GRANT
SELECT, UPDATE ( street )
ON employee
TO Laurel
More than one permission can be granted in a single statement. Separate
the permissions with commas.
♦ Allow the user Hardy to execute the Calculate_Report procedure.
GRANT
EXECUTE ON Calculate_Report
TO Hardy

529
HELP statement [Interactive SQL]

HELP statement [Interactive SQL]


Function Use this statement to receive help in the Interactive SQL environment.
Syntax HELP [topic]
Permissions None.
Side effects None.
Description The HELP statement is used to enter the Interactive SQL interactive help
facility. The topic for help can be optionally specified. If topic is not
specified, the help system is entered at the index.
If topic is a reserved word, it must be enclosed in single quotes.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not applicable

530
Chapter 9 SQL Statements

IF statement
Function Use this statement to control conditional execution of SQL statements.
Syntax IF search-condition THEN statement-list
… [ ELSEIF search-condition THEN statement-list ] …
… [ ELSE statement-list ]
… END IF
Permissions None.
Side effects None.
See also "BEGIN statement" on page 392
"Using Procedures, Triggers, and Batches" on page 423 of the book ASA
User’s Guide
Description The IF statement is a control statement that allows you to conditionally
execute the first list of SQL statements whose search-condition evaluates to
TRUE. If no search-condition evaluates to TRUE, and an ELSE clause
exists, the statement-list in the ELSE clause is executed.
Execution resumes at the first statement after the END IF.

IF statement is different from IF expression


Do not confuse the syntax of the IF statement with that of the IF
expression.
$ For information on the IF expression, see "IF expressions" on
page 220.

Standards and ♦ SQL/92 Persistent Stored Module feature.


compatibility
♦ Sybase The Transact-SQL IF statement has a slightly different syntax.
Example ♦ The following procedure illustrates the use of the IF statement:
CREATE PROCEDURE TopCustomer (OUT TopCompany
CHAR(35), OUT
TopValue INT)
BEGIN
DECLARE err_notfound EXCEPTION
FOR SQLSTATE ’02000’;
DECLARE curThisCust CURSOR FOR
SELECT company_name, CAST(
sum(sales_order_items.quantity *
product.unit_price) AS INTEGER) VALUE
FROM customer
LEFT OUTER JOIN sales_order
LEFT OUTER JOIN sales_order_items

531
IF statement

LEFT OUTER JOIN product


GROUP BY company_name;

DECLARE ThisValue INT;


DECLARE ThisCompany CHAR(35);
SET TopValue = 0;
OPEN curThisCust;
CustomerLoop:
LOOP
FETCH NEXT curThisCust
INTO ThisCompany, ThisValue;
IF SQLSTATE = err_notfound THEN
LEAVE CustomerLoop;
END IF;
IF ThisValue > TopValue THEN
SET TopValue = ThisValue;
SET TopCompany = ThisCompany;
END IF;
END LOOP CustomerLoop;
CLOSE curThisCust;
END

532
Chapter 9 SQL Statements

IF statement [T-SQL]
Function Use this statement to control conditional execution of a SQL statement, as an
alternative to the Watcom-SQL IF statement.
Syntax IF expression
… statement
… [ ELSE
… [ IF expression ]
… statement ]
Authorization None.
Side effects None.
Description The Transact-SQL IF conditional and the ELSE conditional each control the
execution of only a single SQL statement or compound statement (between
the keywords BEGIN and END).
In comparison to the Watcom-SQL IF statement, there is no THEN in the
Transact-SQL IF statement. The Transact-SQL version also has no ELSEIF
or END IF keywords.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Adaptive Server Enterprise supports the Transact-SQL IF
statement.
Example ♦ The following example illustrates the use of the Transact-SQL IF
statement:
IF (SELECT max(id) FROM sysobjects) < 100
RETURN
ELSE
BEGIN
PRINT "These are the user-created objects"
SELECT name, type, id
FROM sysobjects
WHERE id < 100
END
♦ The following two statement blocks illustrate Transact-SQL and
Watcom-SQL compatibility:
/* Transact-SQL IF statement */
IF @v1 = 0
PRINT ’0’
ELSE IF @v1 = 1
PRINT ’1’
ELSE
PRINT ’other’
/* Watcom-SQL IF statement */

533
IF statement [T-SQL]

IF v1 = 0 THEN
PRINT ’0’
ELSEIF v1 = 1 THEN
PRINT ’1’
ELSE
PRINT ’other’
END IF

534
Chapter 9 SQL Statements

INCLUDE statement [ESQL]


Function Use this statement to include a file into a source program to be scanned by
the SQL preprocessor.
Syntax INCLUDE filename
filename: { SQLDA | SQLCA | string }
Permissions None.
Side effects None.
Description The INCLUDE statement is very much like the C preprocessor #include
directive. The SQL preprocessor reads an embedded SQL source file and
replaces all the embedded SQL statements with C-language source code. If a
file contains information that the SQL preprocessor requires, include it with
the embedded SQL INCLUDE statement.
Two file names are specially recognized: SQLCA and SQLDA. The
following statement must appear before any embedded SQL statements in all
embedded SQL source files.
EXEC SQL INCLUDE SQLCA;
This statement must appear at a position in the C program where static
variable declarations are allowed. Many embedded SQL statements require
variables (invisible to the programmer), which are declared by the SQL
preprocessor at the position of the SQLCA include statement. The SQLDA
file must be included if any SQLDAs are used.
Standards and ♦ SQL/92 Entry level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.

535
INPUT statement [Interactive SQL]

INPUT statement [Interactive SQL]


Function Use this statement to import data into a database table from an external file
or from the keyboard.
Syntax INPUT INTO [ owner.]table-name
… [ FROM filename | PROMPT ]
… [ FORMAT input-format ]
… [ ESCAPE CHARACTER character ]
… [ BY ORDER | BY NAME ]
… [ DELIMITED BY string ]
… [ COLUMN WIDTHS (integer, …) ]
… [ NOSTRIP ]
… [ ( column-name, … ) ]
input-format:
ASCII | DBASE | DBASEII | DBASEIII
| EXCEL | FIXED | FOXPRO | LOTUS
Permissions Must have INSERT permission on the table or view.
Side effects None.
See also "OUTPUT statement" on page 559
"INSERT statement" on page 540
"UPDATE statement" on page 621
"DELETE statement" on page 482
"SET OPTION statement" on page 596
"LOAD TABLE statement" on page 546
Description The INPUT statement allows efficient mass insertion into a database table.
Lines of input are read either from the user via an input window (if
PROMPT is specified) or from a file (if FROM filename is specified). If
neither is specified, the input will be read from the command file that
contains the input statement—this can even be directly from the
Interactive SQL editor. In this case, input is ended with a line containing
only the string END.
These lines are inserted into the named table. If a column list is specified, the
data is inserted into the specified columns of the named table.
Normally, the INPUT statement stops when it attempts to insert a row that
causes an error. Errors can be treated in different ways by setting the
ON_ERROR and CONVERSION_ERROR options (see SET OPTION).
Interactive SQL will print a warning in the statistics window if any string
values are truncated on INPUT. Missing values for NOT NULL columns are
set to zero for numeric types and to the empty string for non-numeric types. f
INPUT attempts to insert a NULL row if the input file contains an empty
row.

536
Chapter 9 SQL Statements

Parameters ESCAPE CHARACTER clause The default escape character for


hexadecimal codes and symbols is a backslash (\), so \x0A is the linefeed
character, for example.
The escape character can be changed, using the ESCAPE CHARACTER
clause. For example, to use the exclamation mark as the escape character,
you would enter:
... ESCAPE CHARACTER ’!’
Only one single-byte character can be used as an escape character.

BY clause The BY clause allows the user to specify whether the columns
from the input file should be matched up with the table columns based on
their ordinal position in the lists (ORDER, the default) or by their names
(NAME). Not all input formats have column name information in the file.
NAME is allowed only for those formats that do. They are the same formats
that allow automatic table creation listed below: DBASEII, DBASEIII, DIF,
FOXPRO, LOTUS, and WATFILE.

DELIMITED BY clause The DELIMITED BY clause allows you to


specify a string to be used as the delimiter in ASCII input format.

COLUMN WIDTHS clause COLUMN WIDTHS can be specified for


FIXED format only. It specifies the widths of the columns in the input file. If
COLUMN WIDTHS is not specified, the widths are determined by the
database column types. This clause should not be used if inserting
LONG VARCHAR or BINARY data in FIXED format.

NOSTRIP clause Normally, for ASCII input format, trailing blanks will
be stripped from unquoted strings before the value is inserted. NOSTRIP can
be used to suppress trailing blank stripping. Trailing blanks are not stripped
from quoted strings, regardless of whether the option is used. Leading blanks
are stripped from unquoted strings, regardless of the NOSTRIP option
setting.
If the ASCII file has entries such that a column appears to be null, it is
treated as NULL. If the column in that position cannot be NULL, a zero is
inserted in numeric columns and an empty string in character columns.

FORMAT clause Each set of values must occupy one input line and must
be in the format specified by the FORMAT clause, or the format set by the
SET INPUT_FORMAT statement if the FORMAT clause is not specified.
When input is entered by the user, an empty screen is provided for the user to
enter one row per line in the input format.

537
INPUT statement [Interactive SQL]

Certain file formats contain information about column names and types.
Using this information, the INPUT statement will create the database table if
it does not already exist. This is a very easy way to load data into the
database. The formats that have enough information to create the table are:
DBASEII, DBASEIII, FOXPRO, and LOTUS.
Input from a command file is terminated by a line containing END. Input
from a file is terminated at the end of the file.
Allowable input formats are:
♦ ASCII Input lines are assumed to be ASCII characters, one row per
line, with values separated by commas. Alphabetic strings may be
enclosed in apostrophes (single quotes) or quotation marks (double
quotes). Strings containing commas must be enclosed in either single or
double quotes. If the string itself contains single or double quotes,
double the quote character to use it within the string. Optionally, you can
use the DELIMITED BY clause to specify a different delimiter string
than the default, which is a comma.
Three other special sequences are also recognized. The two characters \n
represent a newline character, \\ represents a single (\), and the sequence
\xDD represents the character with hexadecimal code DD.
♦ DBASE The file is in dBASE II or dBASE III format. Interactive SQL
will attempt to determine which format, based on information in the file.
If the table doesn’t exist, it will be created.
♦ DBASEII The file is in dBASE II format. If the table doesn’t exist, it
will be created.
♦ DBASEIII The file is in dBASE III format. If the table doesn’t exist, it
will be created.
♦ EXCEL Input file is in the format of Microsoft Excel 2.1. If the table
doesn’t exist, it will be created.
♦ FIXED Input lines are in fixed format. The width of the columns can be
specified using the COLUMN WIDTHS clause. If they are not specified,
column widths in the file must be the same as the maximum number of
characters required by any value of the corresponding database column’s
type.
The FIXED format cannot be used with binary columns that contain
embedded newline and End of File character sequences.
♦ FOXPRO The file is in FoxPro format (the FoxPro memo field is
different than the dBASE memo field). If the table doesn’t exist, it will
be created.

538
Chapter 9 SQL Statements

♦ LOTUS The file is a Lotus WKS format worksheet. INPUT assumes


that the first row in the Lotus WKS format worksheet is column names.
If the table doesn’t exist, it will be created. In this case, the types and
sizes of the columns created may not be correct because the information
in the file pertains to a cell, not to a column.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not applicable
Example ♦ The following is an example of an INPUT statement from an ASCII text
file.
INPUT INTO employee
FROM new_emp.inp
FORMAT ascii;

539
INSERT statement

INSERT statement
Function Use this statement to insert a single row (syntax 1) or a selection of rows
from elsewhere in the database (syntax 2) into a table.
Syntax 1 INSERT [ INTO ] [ owner.]table-name [( column-name, … )]
… VALUES ( expression | DEFAULT, … )
Syntax 2 INSERT [ INTO ] [ owner.]table-name [( column-name, … )]
… select-statement
Permissions Must have INSERT permission on the table.
Side effects None.
See also "INPUT statement" on page 536
"UPDATE statement" on page 621
"DELETE statement" on page 482
"PUT statement" on page 568
Description The INSERT statement is used to add new rows to a database table.

Syntax 1 Insert a single row, with the specified expression values. The
keyword DEFAULT can be used to cause the default value for the column to
be inserted. If the optional list of column names is given, the values are
inserted one for one into the specified columns. If the list of column names is
not specified, the values are inserted into the table columns in the order they
were created (the same order as retrieved with SELECT *). The row is
inserted into the table at an arbitrary position. (In relational databases, tables
are not ordered.)

Syntax 2 Carry out mass insertion into a table with the results of a fully
general SELECT statement. Insertions are done in an arbitrary order unless
the SELECT statement contains an ORDER BY clause. The columns from
the select list are matched ordinally with the columns specified in the column
list, or sequentially in the order in which the columns were created.
Inserts can be done into views, if the query specification defining the view is
updatable and has only one table in the FROM clause.
An inherently non-updatable view consists of a query expression or query
specification containing any of the following:
♦ DISTINCT clause
♦ GROUP BY clause
♦ Aggregate function
♦ A select-list item that is not a base table.

540
Chapter 9 SQL Statements

Character strings inserted into tables are always stored in the same case as
they are entered, regardless of whether the database is case sensitive or not.
Thus a string Value inserted into a table is always held in the database with
an upper-case V and the remainder of the letters lower case. SELECT
statements return the string as Value. If the database is not case-sensitive,
however, all comparisons make Value the same as value, VALUE, and so
on. Further, if a single-column primary key already contains an entry Value,
an INSERT of value is rejected, as it would make the primary key not
unique.

Performance tip
To insert many rows into a table, it is more efficient to declare a cursor
and insert the rows through the cursor, where possible, than to carry out
many separate INSERT statements.

Standards and ♦ SQL/92 Entry level feature.


compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Examples ♦ Add an Eastern Sales department to the database.
INSERT
INTO department ( dept_id, dept_name )
VALUES ( 230, ’Eastern Sales’ )
♦ Fill the table dept_head with the names of department heads and their
departments.
INSERT
INTO dept_head (name, dept)
SELECT emp_fname || ’ ’ || emp_lname
AS name,
dept_name
FROM employee JOIN department
ON emp_id = dept_head_id

541
INSTALL statement

INSTALL statement
Function Use this statement to make Java classes available for use within a database.
Syntax INSTALL JAVA
[ NEW | UPDATE ]
[ JAR jar-name ]
FROM { FILE filename | expression }
Permissions DBA permissions are required to execute the INSTALL statement.
All installed classes can be referenced in any way by any user.
Not supported on Windows CE.
See also "REMOVE statement" on page 575
Description The class definition for each class is loaded by each connection’s VM the
first time that class is used. When you INSTALL a class, the VM on your
connection is implicitly restarted. Therefore, you have immediate access to
the new class, whether the INSTALL has an install-mode of NEW or
UPDATE. Because the VM is restarted, any values stored in java static
variables are lost, and any SQL variables with java class types are dropped.
For other connections, the new class is loaded the next time a VM accesses
the class for the first time. If the class is already loaded by a VM, that
connection does not see the new class until the VM is restarted for that
connection (for example, with a STOP JAVA and START JAVA).
Parameters NEW | UPDATE keyword If you specify an install mode of NEW, the
referenced Java classes must be new classes, rather than updates of currently
installed classes. An error occurs if a class with the same name exists in the
database and the NEW install mode is used.
If you specify UPDATE, the referenced Java classes may include
replacements for Java classes that are already installed in the given database.
If install-mode is omitted, the default is NEW.
JAR clause If this is specified, then the filename must designate a jar file.
Jar files typically have extensions of .jar or .zip.
Installed jar and zip files can be compressed or uncompressed.
If the JAR option is specified, the jar is retained as a jar after the classes that
it contains have been installed. That jar is the associated jar of each of those
classes. The jars installed in a database with the JAR option are called the
retained jars of the database.
The jar-name is a character string value, of up to 255 bytes long. The jar-
name is used to identify the retained jar in subsequent INSTALL UPDATE
and REMOVE statements.

542
Chapter 9 SQL Statements

FROM FILE clause Specifies the location of the Java class(es) to be


installed.
The formats supported for file-name include fully qualified file names, such
as ’c:\libs\jarname.jar’ and ’/usr/u/libs/jarname.jar’, and relative file names,
which are relative to the current working directory of the database server.
The filename must identify either a class file, or a jar file.
FROM expression clause Expressions must evaluate to a binary type
whose value contains a valid class file or jar file.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Examples ♦ The following statement installs the user-created Java class named
Demo, by providing the filename and location of the class.
INSTALL JAVA NEW
FROM FILE ’D:\JavaClass\Demo.class’
After installation, the class is referenced using its name. Its original file
path location is no longer used. For example, the following statement
uses the class installed in the previous statement.
CREATE VARIABLE d Demo
If the Demo class was a member of the package sybase.work, the fully
qualified name of the class must be used, for example:
CREATE VARIABLE d sybase.work.Demo
♦ The following statement installs all the classes contained in a zip file,
and associates them within the database with a JAR file name.
INSTALL JAVA
JAR ’Widgets’
FROM FILE ’C:\Jars\Widget.zip’
Again, the location of the zip file is not retained and classes must be
referenced using the fully qualified class name (package name and class
name).

543
LEAVE statement

LEAVE statement
Function Use this statement to leave a compound statement or loop.
Syntax LEAVE statement-label
Permissions None.
Side effects None.
See also "LOOP statement" on page 553
"FOR statement" on page 514
"BEGIN statement" on page 392
"Using Procedures, Triggers, and Batches" on page 423 of the book ASA
User’s Guide
Description The LEAVE statement is a control statement that allows you to leave a
labeled compound statement or a labeled loop. Execution resumes at the first
statement after the compound statement or loop.
The compound statement that is the body of a procedure or trigger has an
implicit label that is the same as the name of the procedure or trigger.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise. The BREAK
statement provides a similar feature for Transact-SQL compatible
procedures.
Examples ♦ The following fragment shows how the LEAVE statement is used to
leave a loop.
SET i = 1;
lbl:
LOOP
INSERT
INTO Counters ( number )
VALUES ( i );
IF i >= 10 THEN
LEAVE lbl;
END IF;
SET i = i + 1
END LOOP lbl
♦ The following example fragment uses LEAVE in a nested loop.
outer_loop:
LOOP
SET i = 1;
inner_loop:
LOOP
...

544
Chapter 9 SQL Statements

SET i = i + 1;
IF i >= 10 THEN
LEAVE outer_loop
END IF
END LOOP inner_loop
END LOOP outer_loop

545
LOAD TABLE statement

LOAD TABLE statement


Function Use this statement to import bulk data into a database table from an external
ASCII-format file. Inserts are not recorded in the log file, raising the risk
that data will be lost in the event of a crash and making this statement
unusable with SQL Remote or with MobiLink client databases.
Syntax LOAD [ INTO ] TABLE [ owner ].table-name [( column-name, … )]
FROM 'filename-string'
[ load-option … ]
load-option:
CHECK CONSTRAINTS { ON | OFF }
| DEFAULTS { ON | OFF }
| DELIMITED BY string
| ESCAPE CHARACTER character
| ESCAPES { ON | OFF }
| FORMAT { ASCII | BCP }
| QUOTES { ON | OFF }
| STRIP { ON | OFF }
| WITH CHECKPOINT { ON | OFF }
Permissions The permissions required to execute an UNLOAD statement are set on the
database server command line, using the –gl command-line option.
$ For more information, see "–gl command-line option" on page 27.
Requires an exclusive lock on the table.
The table cannot be a declared local temporary table.
Side effects Inserts are not recorded in the log file. Thus, the inserted rows may not be
recovered in the event of a crash. In addition, the LOAD TABLE statement
should never be used in database involved in SQL Remote replication or
databases used as MobiLink clients because these technologies replicated
changes through analysis of the log file.
The LOAD TABLE statement does not fire triggers, including referential
integrity actions.
A COMMIT is automatically performed at the end of the load statement.
A checkpoint is carried out at the beginning of the operation. A second
checkpoint, at the end of the operation, is optional.
See also "UNLOAD TABLE statement" on page 619
"INPUT statement" on page 536
Description The LOAD TABLE statement allows efficient mass insertion into a database
table from an ASCII file. LOAD TABLE is more efficient than the
Interactive SQL statement INPUT.

546
Chapter 9 SQL Statements

LOAD TABLE places an exclusive lock on the whole table; it does not fire
any triggers associated with the table.
You can use LOAD TABLE on a global temporary table, but the temporary
table must have been created with the ON COMMIT PRESERVE ROWS
clause, because LOAD TABLE does a COMMIT after the load. LOAD
TABLE cannot be used on declared temporary tables.
If the ASCII file has entries such that a column appears to be NULL, LOAD
TABLE treats it as null. If the column in that position cannot be NULL, it
inserts a zero in numeric columns and an empty string in character columns.
LOAD TABLE skips empty lines in the input file.
Any columns not present in the column list become NULL if the
DEFAULTS option is off. If DEFAULTS is on and the column has a default
value, that value will be used. If DEFAULTS is off, and a non-nullable
column is omitted from the column list, the engine attempts to convert the
empty string to the column’s type.

Caution
LOAD TABLE is intended solely for fast loading of large amounts of data.
It is not intended for routine use in applications.

Parameters FROM option The filename-string is passed to the server as a string. The
string is therefore subject to the same formatting requirements as other SQL
strings. In particular:
♦ To indicate directory paths, the backslash character \ must be
represented by two backslashes. The statement to load data from the file
c:\temp\input.dat into the employee table is:
LOAD TABLE employee
FROM ’c:\\temp\\input.dat’ ...
♦ The pathname is relative to the database server, not to the client
application. If you are running the statement on a database server on
another computer, the directory names refers to directories on the server
machine, not on the client machine.
♦ You can use UNC path names to load data from files on computers other
than the server. For example, on a Windows for Workgroups,
Windows 95, or Windows NT network, you may use the following
statement to load data from a file on the client machine:
LOAD TABLE employee
FROM ’\\\\client\\temp\\input.dat’

547
LOAD TABLE statement

CHECK CONSTRAINTS option This option is ON by default, but the


Unload utility writes out LOAD TABLE statements with the option set to
OFF.
Setting CHECK CONSTRAINTS to off disables check constraints. This can
be useful, for example, during database rebuilding. If a table has check
constraints that call user-defined functions that are not yet created, the
rebuild would fail unless this option was set to OFF.
DEFAULTS option By default, DEFAULTS is OFF. If DEFAULTS is
OFF, any column not present in the column list is assigned NULL. If
DEFAULTS is OFF and a non-nullable column is omitted from the column
list, the database server attempts to convert the empty string to the column’s
type. If DEFAULTS is ON and the column has a default value, that value is
used.

DELIMITED BY option The default column delimiter character is a


comma. You can specify an alternative column delimiter by providing a
string. Only the first ASCII character of the string is read. The same
formatting requirements apply as to other SQL strings. In particular, to
specify tab-delimited values, the hexadecimal ASCII code of the tab
character (9) is used. The DELIMITED BY clause is as follows:
...DELIMITED BY ’\x09’ ...

ESCAPE CHARACTER option The default escape character for


characters stored as hexadecimal codes and symbols is a backslash (\), so
\x0A is the linefeed character, for example.
This can be changed using the ESCAPE CHARACTER clause. For example,
to use the exclamation mark as the escape character, you would enter
... ESCAPE CHARACTER ’!’
Only one single-byte character can be used as an escape character.

ESCAPES option With ESCAPES turned on (the default), characters


following the backslash character are recognized and interpreted as special
characters by the database server. New line characters can be included as the
combination \n, other characters can be included in data as hexadecimal
ASCII codes, such as \x09 for the tab character. A sequence of two backslash
characters ( \\ ) is interpreted as a single backslash. A backslash followed by
any character other than n, x, X or \ is interpreted as two separate characters.
For example, \q inserts a backslash and the letter q.

FORMAT option If you choose ASCII, input lines are assumed to be


ASCII characters, one row per line, with values separated by the column
delimiter character. Choosing BCP allows the import of ASE generated BCP
out files containing blobs.

548
Chapter 9 SQL Statements

QUOTES option With QUOTES turned on (the default), the LOAD


statement expects strings to be enclosed in quote characters. The quote
character is either an apostrophe (single quote) or a quotation mark (double
quote). The first such character encountered in a string is treated as the quote
character for the string. Strings must be terminated by a matching quote.
With quotes on, column delimiter characters can be included in column
values. Also, quote characters are assumed not to be part of the value.
Therefore, a line of the form
’123 High Street, Anytown’,(715)398-2354
is treated as two values, not three, despite the presence of the comma in the
address. Also, the quotes surrounding the address are not inserted into the
database.
To include a quote character in a value, with QUOTES on, you must use two
quotes. The following line includes a value in the third column that is a
single quote character:
’123 High Street, Anytown’,’(715)398-2354’,’’’’

STRIP option With STRIP turned on (the default), trailing blanks are
stripped from values before they are inserted. To turn the STRIP option off,
the clause is as follows:
...STRIP OFF ...
Trailing blanks are stripped only for non-quoted strings. Quoted strings
retain their trailing blanks. Leading blanks are trimmed, regardless of the
STRIP setting, unless they are enclosed in quotes.

WITH CHECKPOINT option The default setting is OFF. If set to ON, a


checkpoint is issued after successfully completing and logging the statement.
If WITH CHECKPOINT ON is not specified, and the database requires
automatic recovery before a CHECKPOINT is issued, the data file used to
load the table must be present for the recovery to complete successfully. If
WITH CHECKPOINT ON is specified, and recovery is subsequently
required, recovery begins after the checkpoint, and the data file need not be
present.

549
LOAD TABLE statement

Caution
If you set the database option CONVERSION_ERROR to OFF, you may
load bad data into your table without any error being reported. If you do
not specify WITH CHECKPOINT ON, and the database needs to be
recovered, the recovery may fail as CONVERSION_ERROR is ON (the
default value) during recovery. It is recommended that you do not load
tables with CONVERSION_ERROR set to OFF and WITH
CHECKPOINT ON not specified.

$ For more information, see "CONVERSION_ERROR option" on


page 168.
The data files are required, regardless of this option, if the database becomes
corrupt and you need to use a backup and apply the current log file.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not applicable.

550
Chapter 9 SQL Statements

LOCK TABLE statement


Function Use this statement to prevent other concurrent transactions from accessing or
modifying a table.
Syntax LOCK TABLE table-name
[ WITH HOLD ]
IN { SHARE | EXCLUSIVE } MODE
Permissions To lock a table in SHARE mode, SELECT privileges are required.
To lock a table in EXCLUSIVE mode; you must be the table owner or have
DBA authority.
Side effects Other transactions that require access to the locked table may be delayed or
blocked.
See also "SELECT statement" on page 587
"sa_locks system procedure" on page 941
Description The LOCK TABLE statement allows direct control over concurrency at a
table level, independent of the current isolation level.
While the isolation level of a transaction generally governs the kinds of locks
that are set when the current transaction executes a request, the LOCK
TABLE statement allows more explicit control locking of the rows in a table.
The locks placed by LOCK TABLE in SHARE mode are phantom and anti-
phantom locks, which are displayed by the sa_locks procedure as PT and
AT.
Parameters table-name The table must be a base table, not a view. As temporary table
data is local to the current connection, locking global or local temporary
tables has no effect.

WITH HOLD clause If this clause is specified, the lock is held until the
end of the connection. If the clause is not specified, the lock is release when
the current transaction is committed or rolled back.

SHARE mode Prevent other transactions from modifying the table, but
allow them read access. In this mode you can change data in the table as long
as no other transaction has locked the row being modified, either indirectly
or explicitly using LOCK TABLE.

EXCLUSIVE mode Prevent other transactions from accessing the table.


No other transaction can execute queries, updates of any kind, or any other
action against the table.
Standards and ♦ SQL/92 Vendor extension.
compatibility

551
LOCK TABLE statement

♦ Sybase Supported in Adaptive Server Enterprise. The WITH HOLD


clause is not supported in Adaptive Server Enterprise. Adaptive Server
Enterprise provides a WAIT clause that is not supported in Adaptive
Server Anywhere.
Examples ♦ The following statement prevents other transactions from modifying the
customer table for the duration of the current transaction:
LOCK TABLE customer
IN SHARE MODE

552
Chapter 9 SQL Statements

LOOP statement
Function Use this statement to repeat the execution of a statement list.
Syntax [ statement-label : ]
…[ WHILE search-condition ] LOOP
… statement-list
…END LOOP [ statement-label ]
Permissions None.
Side effects None.
See also "FOR statement" on page 514
"LEAVE statement" on page 544
Description The WHILE and LOOP statements are control statements that allow you to
execute a list of SQL statements repeatedly while a search-condition
evaluates to TRUE. The LEAVE statement can be used to resume execution
at the first statement after the END LOOP.
If the ending statement-label is specified, it must match the beginning
statement-label.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise. The WHILE
statement provides looping in Transact-SQL stored procedures.
Examples ♦ A While loop in a procedure.
...
SET i = 1;
WHILE i <= 10 LOOP
INSERT INTO Counters( number ) VALUES ( i );
SET i = i + 1;
END LOOP;
...
♦ A labeled loop in a procedure.
SET i = 1;
lbl:
LOOP
INSERT
INTO Counters( number )
VALUES ( i );
IF i >= 10 THEN
LEAVE lbl;
END IF;
SET i = i + 1;
END LOOP lbl

553
MESSAGE statement

MESSAGE statement
Function Use this statement to display a message.
Syntax MESSAGE expression, …
[ TYPE { INFO | ACTION | WARNING | STATUS } ]
[ TO { CONSOLE | CLIENT | LOG }]
Permissions None.
Side effects None.
See also "CREATE PROCEDURE statement" on page 440
Description The MESSAGE statement displays a message, which can be any expression.
Clauses can specify where the message appears.
Valid expressions can include a quoted string or other constant, variable, or
function. However, queries are not permitted in the output of a Message
statement even though the definition of an expression includes queries.
Parameters TYPE clause The TYPE clause only has an effect if the message is sent to
the client. The client application must decide how to handle the message.
Interactive SQL displays messages in the following locations:
♦ INFO The Message window. INFO is the default type.
♦ ACTION A Message box with an OK button.
♦ WARNING A Message box with an OK button.
♦ STATUS The Message window.

TO clause This clause specifies the destination of a message:


♦ CONSOLE Send messages to the database server window. CONSOLE
is the default.
♦ CLIENT Send messages to the client application. Your application
must decide how to handle the message, and you can use the TYPE as
information on which to base that decision.
♦ LOG Send messages to the server log file specified by the -o
command-line option.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise. The Transact-
SQL PRINT statement provides a similar feature, and is also available in
Adaptive Server Anywhere.
Example ♦ The following procedure displays a message on the server message
window:
554
Chapter 9 SQL Statements

CREATE PROCEDURE message_test ()


BEGIN
MESSAGE ’The current date and time: ’, Now();
END
♦ The statement:
CALL message_test()
displays the string The current date and time, and the current date and
time, on the database server message window.

555
OPEN statement [ESQL] [SP]

OPEN statement [ESQL] [SP]


Function Use this statement to open a previously declared cursor to access information
from the database.
Syntax OPEN cursor-name
… [ USING [ DESCRIPTOR sqlda-name | host-variable, …] ]
… [ WITH HOLD ]
… [ ISOLATION LEVEL n ]
… [ BLOCK n ]
cursor-name: identifier or host-variable
sqlda-name: identifier
Permissions Must have SELECT permission on all tables in a SELECT statement, or
EXECUTE permission on the procedure in a CALL statement.
Side effects None.
See also "DECLARE CURSOR statement" on page 475
"RESUME statement" on page 578
"PREPARE statement" on page 564
"FETCH statement" on page 509
"RESUME statement" on page 578
"CLOSE statement" on page 404
Description The OPEN statement opens the named cursor. The cursor must be previously
declared.
When the cursor is on a CALL statement, OPEN causes the procedure to
execute until the first result set (SELECT statement with no INTO clause) is
encountered. If the procedure completes and no result set is found, the
SQLSTATE_PROCEDURE_COMPLETE warning is set.
You can also open a cursor on an INSERT statement.
Parameters Embedded SQL usage After successful execution of the OPEN
statement, the sqlerrd[3] field of the SQLCA (SQLIOESTIMATE) is filled
in with an estimate of the number of input/output operations required to fetch
all rows of the query. Also, the sqlerrd[2] field of the SQLCA
(SQLCOUNT) is filled with either the actual number of rows in the cursor (a
value greater than or equal to 0), or an estimate thereof (a negative number
whose absolute value is the estimate). It will be the actual number of rows if
the database server can compute it without counting the rows. The database
can also be configured to always return the actual number of rows (see
"ROW_COUNTS option" on page 196), but this can be expensive.

556
Chapter 9 SQL Statements

If cursor-name is specified by an identifier or string, the corresponding


DECLARE CURSOR must appear prior to the OPEN in the C program; if
the cursor-name is specified by a host variable, the DECLARE CURSOR
statement must execute before the OPEN statement.

USING DESCRIPTOR clause The USING DESCRIPTOR clause is for


Embedded SQL only. It specifies the host variables to be bound to the place-
holder bind variables in the SELECT statement for which the cursor has been
declared.

WITH HOLD clause By default, all cursors are automatically closed at the
end of the current transaction (COMMIT or ROLLBACK). The optional
WITH HOLD clause keeps the cursor open for subsequent transactions. It
will remain open until the end of the current connection or until an explicit
CLOSE statement is executed. Cursors are automatically closed when a
connection is terminated.

ISOLATION LEVEL clause The ISOLATION LEVEL clause allows this


cursor to be opened at an isolation level different from the current setting of
the ISOLATION_LEVEL option. All operations on this cursor will be
performed at the specified isolation level regardless of the option setting. If
this clause is not specified, then the cursor’s isolation level for the entire time
the cursor is open is the value of the ISOLATION_LEVEL option when the
cursor is opened. See "How locking works" on page 401 of the book ASA
User’s Guide.
The cursor is positioned before the first row (see "Cursors in Embedded
SQL" on page 33 of the book ASA Programming Interfaces Guide or "Using
cursors in procedures and triggers" on page 458 of the book ASA User’s
Guide).

BLOCK clause This clause is for Embedded SQL use only. Rows are
fetched by the client application in blocks (more than one at a time). By
default, the number of rows in a block is determined dynamically based on
the size of the rows and how long it takes the database server to fetch each
row. The application can specify a maximum number of rows that should be
contained in a block by specifying the BLOCK clause. For example, if you
are fetching and displaying 5 rows at a time, use BLOCK 5. Specifying
BLOCK 0 will cause one row at a time to be fetched, and also cause a
FETCH RELATIVE 0 to always fetch the row again.
$ For more information, see "FETCH statement" on page 509.
Standards and ♦ SQL/92 Embedded SQL use is an entry-level feature. Procedures use
compatibility is a Persistent Stored Modules feature.

557
OPEN statement [ESQL] [SP]

♦ Sybase The simple OPEN cursor-name syntax is supported by


Adaptive Server Enterprise. None of the other clauses are supported in
Adaptive Server Enterprise stored procedures. Open Client/Open Server
supports the USING descriptor or host variable syntax.
Examples ♦ The following examples show the use of OPEN in Embedded SQL.
1. EXEC SQL OPEN employee_cursor;
2. EXEC SQL PREPARE emp_stat FROM
’SELECT empnum, empname FROM employee WHERE name
like ?’;
EXEC SQL DECLARE employee_cursor CURSOR FOR
emp_stat;
EXEC SQL OPEN employee_cursor USING :pattern;
♦ The following example is from a procedure or trigger.
BEGIN
DECLARE cur_employee CURSOR FOR
SELECT emp_lname
FROM employee;
DECLARE name CHAR(40);
OPEN cur_employee;
LOOP
FETCH NEXT cur_employee into name;
...
END LOOP
CLOSE cur_employee;
END

558
Chapter 9 SQL Statements

OUTPUT statement [Interactive SQL]


Function Use this statement to output the current query results to a file.
Syntax OUTPUT TO filename
… [ APPEND ]
… [ VERBOSE ]
… [ FORMAT output_format ]
… [ ESCAPE CHARACTER character ]
… [ DELIMITED BY string ]
… [ QUOTE string [ ALL ] ]
… [ COLUMN WIDTHS (integer, …) ]
… [ HEXADECIMAL { ON | OFF } ]
output-format:
ASCII | DBASE | DBASEII | DBASEIII | EXCEL
| FIXED | FOXPRO | HTML | LOTUS | SQL | TEXT
Permissions None.
Side effects The current query results that are displayed in the Interactive SQL data
window are repositioned to the top.
See also "SELECT statement" on page 587
"INPUT statement" on page 536
Description The OUTPUT statement copies the information retrieved by the current
query to a file.
If you include the optional APPEND keyword, you can append the results of
the query to the end of an existing file. If you include the optional
VERBOSE keyword, you can append any messages about the query to the
end of the file. Both the APPEND and VERBOSE keywords are only valid if
the output format is ASCII, Fixed, or SQL.
The output format can be specified with the optional FORMAT clause. If no
FORMAT clause is specified, the Interactive SQL OUTPUT_FORMAT
option setting is used (see "OUTPUT_FORMAT option" on page 190).
The current query is the SELECT or INPUT statement which generated the
information displayed in the Interactive SQL data window. The OUTPUT
statement will report an error if there is no current query.
When exporting Java data, you may wish to export objects as binary, or you
may want to export them as strings using the toString() method. You
can control which way Java data is exported using the
DESCRIBE_JAVA_FORMAT Interactive SQL option.
For example, consider the following script:

559
OUTPUT statement [Interactive SQL]

CREATE VARIABLE JavaString java.lang.String;


SET JavaString = NEW java.lang.String( ’TestVar’ );
SELECT JavaString FROM dummy;

If you set DESCRIBE_JAVA_FORMAT to Varchar:


♦ The following command gives the hexadecimal representation of
TestVar in the output file.
OUTPUT TO filename
♦ The following command gives a text representation of TestVar in the
output file (possibly escaped).
OUTPUT TO filename HEXADECIMAL OFF

If you set DESCRIBE_JAVA_FORMAT to binary:


♦ The following command gives the hexadecimal representation of
JavaString in the output file.
OUTPUT TO filename
♦ The following command gives the actual JavaString object in the output
file (with escape sequences).
OUTPUT TO filename HEXADECIMAL OFF

$ For more information, see "DESCRIBE_JAVA_FORMAT option" on


page 173.
Parameters DELIMITED BY clause The DELIMITED BY clause is for the ASCII
output format only. The delimiter string is placed between columns (default
comma).

QUOTE clause The QUOTE clause is for the ASCII output format only.
The quote string is placed around string values. The default is a single quote
character. If ALL is specified in the QUOTE clause, the quote string is
placed around all values, not just around strings.

COLUMN WIDTH clause The COLUMN WIDTH clause is used to


specify the column widths for the FIXED format output.

HEXADECIMAL clause The HEXADECIMAL clause specifies how


binary data is to be unloaded, for the ASCII format only. When set to ON,
binary data is unloaded in the format 0xabcd. When set to OFF, binary data
is escaped when unloaded (\xab\xcd)

FORMAT clause Allowable output formats are:

560
Chapter 9 SQL Statements

♦ ASCII The output is an ASCII format file with one row per line in the
file. All values are separated by commas, and strings are enclosed in
apostrophes (single quotes). The delimiter and quote strings can be
changed using the DELIMITED BY and QUOTE clauses. If ALL is
specified in the QUOTE clause, all values (not just strings) will be
quoted.
Three other special sequences are also used. The two characters \n
represent a newline character, \\ represents a single \, and the sequence
\xDD represents the character with hexadecimal code DD. This is the
default output format.
If you are exporting Java methods that have string return values, you
must use the HEXADECIMAL OFF clause.
♦ DBASEII The output is a dBASE II format file with the column
definitions at the top of the file. Note that a maximum of 32 columns can
be output. Also, note that columns longer than 255 characters will be
truncated in the file.
♦ DBASEIII The output is a dBASE III format file with the column
definitions at the top of the file. Note that a maximum of 128 columns
can be output. Also, note that columns longer than 255 characters will be
truncated in the file.
♦ FIXED The output is fixed format with each column having a fixed
width. The width for each column can be specified using the COLUMN
WIDTH clause. No column headings are output in this format.
If the COLUMN WIDTH clause is omitted, the width for each column is
computed from the data type for the column, and is large enough to hold
any value of that data type. The exception is that LONG VARCHAR
and LONG BINARY data defaults to 32 kb.
♦ FOXPRO The output is a FoxPro format file (the FoxPro memo field is
different than the dBASE memo field) with the column definitions at the
top of the file. Note that a maximum of 128 columns can be output.
Also, note that columns longer than 255 characters will be truncated in
the file.
♦ HTML The output is in the Hyper Text Markup Language format.
♦ LOTUS The output is a Lotus WKS format worksheet. Column names
will be put as the first row in the worksheet. Note that there are certain
restrictions on the maximum size of Lotus WKS format worksheets that
other software (such as Lotus 1-2-3) can load. There is no limit to the
size of file Interactive SQL can produce.
♦ SQL The output is a Interactive SQL INPUT statement required to
recreate the information in the table.

561
OUTPUT statement [Interactive SQL]

♦ TEXT The output is a TEXT format file which prints the results in
columns with the column names at the top and vertical lines separating
the columns. This format is similar to that used to display data in the
Interactive SQL data window.

ESCAPE CHARACTER clause The default escape character for


characters stored as hexadecimal codes and symbols is a backslash (\), so
\x0A is the linefeed character, for example.
This can be changed using the ESCAPE CHARACTER clause. For example,
to use the exclamation mark as the escape character, you would enter
... ESCAPE CHARACTER ’!’
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not applicable
Examples ♦ Place the contents of the employee table in a file, in ASCII format.
SELECT *
FROM employee;
OUTPUT TO employee.txt
FORMAT ASCII
♦ Place the contents of the employee table at the end of an existing file,
and include any messages about the query in this file as well.
SELECT *
FROM employee;
OUTPUT TO employee.txt APPEND VERBOSE
♦ Output the contents of the toString() method of the JProd column
to file:
SELECT JProd>>toString()
FROM jdba.product;
OUTPUT TO d:\temp\temp.txt
FORMAT ASCII HEXADECIMAL OFF

562
Chapter 9 SQL Statements

PARAMETERS statement [Interactive SQL]


Function Use this statement to specify parameters to an Interactive SQL command
file.
Syntax PARAMETERS parameter1, parameter2, …
Permissions None.
Side effects None.
See also "READ statement" on page 572
Description The PARAMETERS statement names the parameters for a command file, so
that they can be referenced later in the command file.
Parameters are referenced by putting:
{parameter1}
into the file where you wish the named parameter to be substituted. There
must be no spaces between the braces and the parameter name.
If a command file is invoked with less than the required number of
parameters, Interactive SQL prompts for values of the missing parameters.
Standards and ♦ SQL/92 Vendor extension
compatibility
♦ Sybase Not applicable.
Example ♦ The following Interactive SQL command file takes two parameters.
PARAMETERS department_id, file;
SELECT emp_lname
FROM employee
WHERE dept_id = {department_id}
>#{file}.dat;
If you save this script in a file named test.sql, you can run it from
Interactive SQL using the following command:
READ test.sql [100] [data]

563
PREPARE statement [ESQL]

PREPARE statement [ESQL]


Function Use this statement to prepare a statement to be executed later, or used to
define a cursor.
Syntax PREPARE statement-name
FROM statement
…[ DESCRIBE describe-type INTO [ [ SQL ] DESCRIPTOR ] descriptor ]
…[ WITH EXECUTE ]
statement-name: identifier or host-variable
statement : string or host-variable
describe-type:
{ ALL | BIND VARIABLES | INPUT | OUTPUT | SELECT LIST }
…[ LONG NAMES [ [ OWNER. ]TABLE. ]COLUMN ]
| WITH VARIABLE RESULT ]
Permissions None.
Side effects Any statement previously prepared with the same name is lost.
The statement is dropped after use only if you use WITH EXECUTE and the
execution is successful. You should ensure that you DROP the statement
after use in other circumstances. If you do not, the memory associated with
the statement is not reclaimed.
See also "DECLARE CURSOR statement" on page 475
"DESCRIBE statement" on page 486
"OPEN statement" on page 556
"EXECUTE statement" on page 500
"DROP STATEMENT statement" on page 498
Description The PREPARE statement prepares a SQL statement from the statement and
associates the prepared statement with statement-name. This statement name
is referenced to execute the statement, or to open a cursor if the statement is
a SELECT statement. The statement-name may be a host variable of type
a_sql_statement_number defined in the sqlca.h header file that is
automatically included. If an identifier is used for the statement-name, only
one statement per module may be prepared with this statement-name.
If a host variable is used for statement-name, it must have the type short int.
There is a typedef for this type in sqlca.h called a_sql_statement_number.
This type is recognized by the SQL preprocessor and can be used in a
DECLARE section. The host variable is filled in by the database during the
PREPARE statement, and need not be initialized by the programmer.

564
Chapter 9 SQL Statements

Parameters DESCRIBE clause If DESCRIBE INTO DESCRIPTOR is used, the


prepared statement is described into the specified descriptor. The describe
type may be any of the describe types allowed in the DESCRIBE statement.

WITH EXECUTE clause If the WITH EXECUTE clause is used, the


statement is executed if and only if it is not a CALL or SELECT statement,
and it has no host variables. The statement is immediately dropped after a
successful execution. If the PREPARE and the DESCRIBE (if any) are
successful but the statement cannot be executed, a warning SQLCODE 111,
SQLSTATE 01W08 is set, and the statement is not dropped.
The DESRIBE INTO DESCRIPTOR and WITH EXECUTE clauses may
improve performance, because they cut down on the required client/server
communication.

WITH VARIABLE RESULT clause The WITH VARIABLE RESULT


clause is used to describe procedures that may have more than one result set,
with different numbers or types of columns.
If WITH VARIABLE RESULT is used, the database server sets the
SQLCOUNT value after the describe to one of the following values:
♦ 0 The result set may change: The procedure call should be described
again following each OPEN statement.
♦ 1 The result set is fixed. No redescribing is required.

Static and dynamic


For compatibility reasons, preparing COMMIT, PREPARE TO
COMMIT, and ROLLBACK statements is still supported. However, we
recommend that you do all transaction management operations with static
Embedded SQL because certain application environments may require it.
Also, other Embedded SQL systems do not support dynamic transaction
management operations.

Standards and ♦ SQL/92 Entry level feature


compatibility
♦ Sybase Supported by Open Client/Open Server.
Example ♦ The following statement prepares a simple query:
EXEC SQL PREPARE employee_statement FROM
’SELECT emp_lname FROM employee’;

565
PREPARE TO COMMIT statement

PREPARE TO COMMIT statement


Function Use this statement to check whether a COMMIT can be performed
successfully.
Syntax PREPARE TO COMMIT
Permissions None.
Side effects None.
See also "COMMIT statement" on page 408
"ROLLBACK statement" on page 583
Description The PREPARE TO COMMIT statement tests whether a COMMIT can be
performed successfully. The statement will cause an error if a COMMIT is
impossible without violating the integrity of the database.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
Examples ♦ The following sequence of statements leads to an error because of
foreign key checking on the employee table.
EXECUTE IMMEDIATE
"SET OPTION wait_for_commit = ’on’";

EXECUTE IMMEDIATE "DELETE FROM employee


WHERE emp_id = 160";

EXECUTE IMMEDIATE "PREPARE TO COMMIT";


♦ The following sequence of statements does not cause an error when the
delete statement is executed, even though it causes integrity violations.
The PREPARE TO COMMIT statement returns an error.
SET OPTION wait_for_commit= ’ON’;

DELETE
FROM department
WHERE dept_id = 100;

PREPARE TO COMMIT;

566
Chapter 9 SQL Statements

PRINT statement [T-SQL]


Function Use this statement to return a message to the client, or display a message in
the message window of the database server.
Syntax PRINT format-string [, arg-list]
Authorization None.
Side effects None.
See also "MESSAGE statement" on page 554
Description The PRINT statement returns a message to the client window if you are
connected from an Open Client application or jConnect application. If you
are connected from an embedded SQL or ODBC application, the message is
displayed on the database server window.
The format string can contain placeholders for the arguments in the optional
argument list. These placeholders are of the form %nn!, where nn is an
integer between 1 and 20.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Examples ♦ The following statement displays a message:
PRINT ’Display this message’
♦ The following statement illustrates the use of placeholders in the PRINT
statement:
DECLARE @var1 INT, @var2 INT
SELECT @var1 = 3, @var2 = 5
PRINT ’Variable 1 = %1!, Variable 2 = %2!’, @var1,
@var2

567
PUT statement [ESQL]

PUT statement [ESQL]


Function Use this statement to insert a row into the specified cursor.
Syntax PUT cursor-name
… [ USING DESCRIPTOR sqlda-name | FROM host-variable-list ]
… [ INTO { DESCRIPTOR into-sqlda-name | into-host-variable-list } ]
… [ ARRAY :nnn ]
cursor-name: identifier or host-variable
sqlda-name: identifier
host-variable-list: may contain indicator variables
Permissions Must have INSERT permission.
Side effects When the cursor was defined using a join of two or more tables, inserting a
row into the cursor may require the database server to insert a row into more
than one of the tables involved in the join.
See also "UPDATE statement" on page 621
"UPDATE (positioned) statement" on page 625
"DELETE statement" on page 482
"DELETE (positioned) statement" on page 484
"INSERT statement" on page 540
Description Inserts a row into the named cursor. Values for the columns are taken from
the first SQLDA or the host variable list, in a one-to-one correspondence
with the columns in the INSERT statement (for an INSERT cursor) or the
columns in the select list (for a SELECT cursor).
The PUT statement can be used only on a cursor over an INSERT or
SELECT statement that references a single table in the FROM clause, or that
references an updatable view consisting of a single base table.
If the sqldata pointer in the SQLDA is the null pointer, no value is specified
for that column. If the column has a DEFAULT VALUE associated with it,
that will be used; otherwise, a NULL value will be used.
The second SQLDA or host variable list contains the results of the PUT
statement.
The optional ARRAY clause can be used to carry out wide puts, which insert
more than one row at a time and which may improve performance. The value
nnn is the number of rows to be inserted. The SQLDA must contain nnn *
(columns per row) variables. The first row is placed in SQLDA variables 0
to (columns per row)-1, and so on.

568
Chapter 9 SQL Statements

Inserting into a cursor


When inserting into a cursor, the position of the inserted row is
unpredictable. If the cursor is INSENSITIVE, the row appears. Otherwise,
it does not show up in the current cursor at all.

$ For information on putting LONG VARCHAR or LONG BINARY


values into the database, see "SET statement" on page 591.
Standards and ♦ SQL/92 Entry level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Example ♦ The following statement illustrates the use of PUT in Embedded SQL:
EXEC SQL PUT cur_employee FROM :emp_id, :emp_lname;

569
RAISERROR statement [T-SQL]

RAISERROR statement [T-SQL]


Function Use this statement to signal an error and to send a message to the client.
Syntax RAISERROR error-number [ format-string ] [, arg-list ]
Permissions None.
Side effects None.
See also "CREATE TRIGGER statement" on page 467
"ON_TSQL_ERROR option" on page 189
"CONTINUE_AFTER_RAISERROR option" on page 167
Description The RAISERROR statement allows user-defined errors to be signaled and
sends a message on the client.
Parameters error-number The error-number is a five-digit integer greater than 17000.
The error number is stored in the global variable @@error.

format-string If format-string is not supplied or is empty, the error


number is used to locate an error message in the system tables. Adaptive
Server Enterprise obtains messages 17000-19999 from the SYSMESSAGES
table. In Adaptive Server Anywhere this table is an empty view, so errors in
this range should provide a format string. Messages for error numbers of
20000 or greater are obtained from the SYS.SYSUSERMESSAGES table.
In Adaptive Server Anywhere, the format-string length can be up to 255
bytes.
The extended values supported by the Adaptive Server Enterprise
RAISERROR statement are not supported in Adaptive Server Anywhere.
The format string can contain placeholders for the arguments in the optional
argument list. These placeholders are of the form %nn!, where nn is an
integer between 1 and 20.
You can use ON_TSQL_ERROR to control error handling within
procedures. This option indicates to the engine what action to take on an
error within a procedure error. If you set it to continue, behavior is similar to
Adaptive Server Enterprise.
The CONTINUE_AFTER_RAISERROR database option is now deprecated
in favor of ON_TSQL_ERROR. The behavior of
CONTINUE_AFTER_RAISERROR is as follows. If it is set to ON, the
RAISERROR statement does not signal an error. Instead, the RAISERROR
status code and message are stored and the most recent RAISERROR is
returned when the procedure completes. If the procedure that caused the
RAISERROR was called from another procedure, the RAISERROR is not
returned until the outermost calling procedure terminates.

570
Chapter 9 SQL Statements

Intermediate RAISERROR status and code information is lost after the


procedure terminates. If at return time an error occurs along with the
RAISERROR then the error information is returned and the RAISERROR
information is lost. The application can query intermediate RAISERROR
statuses by examining @@error global variable at different execution points.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Example ♦ The following statement raises error 23000, which is in the range for
user-defined errors, and sends a message to the client.
RAISERROR 23000 ’Invalid entry for this column:
%1!’, @val
There is no comma between the error-number and the format-string
parameters. The first item following a comma is interpreted as the first
item in the argument list.

571
READ statement [Interactive SQL]

READ statement [Interactive SQL]


Function Use this statement to read Interactive SQL statements from a file.
Syntax READ filename [ parameters ]
Permissions None.
Side effects None.
See also "PARAMETERS statement" on page 563
Description The READ statement reads a sequence of Interactive SQL statements from
the named file. This file can contain any valid Interactive SQL statement
including other READ statements. READ statements can be nested to any
depth. To find the command file, Interactive SQL will first search the current
directory, then the directories specified in the environment variable
SQLPATH, then the directories specified in the environment variable
PATH. If the named file has no file extension, Interactive SQL searches
each directory for the same file name with the extension sql.
Parameters can be listed after the name of the command file. These
parameters correspond to the parameters named on the PARAMETERS
statement at the beginning of the statement file (see "PARAMETERS
statement" on page 563). Interactive SQL substitutes the corresponding
parameter wherever the source file contains
{parameter-name}
where parameter-name is the name of the appropriate parameter.
The parameters passed to a command file can be identifiers, numbers, quoted
identifiers, or strings. When quotes are used around a parameter, the quotes
are put into the text during the substitution. Parameters which are not
identifiers, numbers, or strings (contain spaces or tabs) must be enclosed in
square brackets ([ ]). This allows for arbitrary textual substitution in the
command file.
If not enough parameters are passed to the command file, Interactive SQL
prompts for values for the missing parameters.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not applicable.
Examples ♦ The following are examples of the READ statement.
READ status.rpt ’160’
READ birthday.sql [>= ’1988-1-1’] [<= ’1988-1-30’]

572
Chapter 9 SQL Statements

READTEXT statement [T-SQL]


Function Use this statement to read text and image values from the database, starting
from a specified offset and reading a specified number of bytes.
Syntax READTEXT table-name.column-name
… text-pointer offset size
… [HOLDLOCK]
Permissions SELECT permissions on the table.
Side effects None.
See also "WRITETEXT statement" on page 632
"GET DATA statement" on page 521
"TEXTPTR function" on page 359
Description READTEXT is used to read image and text values from the database. You
cannot perform READTEXT operations on views.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Adaptive Server Enterprise supports the following clause, which is not
supported by Adaptive Server Anywhere:
USING { BYTES | CHARS | CHARACTERS }
These options are identical for all single-byte character sets. Adaptive
Server Anywhere uses bytes only, which is the Adaptive Server
Enterprise default setting.
Adaptive Server Enterprise also provides isolation level control in the
READTEXT statement. This is not supported in Adaptive Server
Anywhere.

573
RELEASE SAVEPOINT statement

RELEASE SAVEPOINT statement


Function Use this statement to release a savepoint within the current transaction.
Syntax RELEASE SAVEPOINT [savepoint-name]
Permissions There must have been a corresponding SAVEPOINT within the current
transaction.
Side effects None.
See also "BEGIN TRANSACTION statement" on page 395
"COMMIT statement" on page 408
"ROLLBACK statement" on page 583
"ROLLBACK TO SAVEPOINT statement" on page 584
"SAVEPOINT statement" on page 586
"Savepoints within transactions" on page 373 of the book ASA User’s Guide
Description Release a savepoint. The savepoint-name is an identifier specified on a
SAVEPOINT statement within the current transaction. If savepoint-name is
omitted, the most recent savepoint is released.
Releasing a savepoint does not do any type of COMMIT. It simply removes
the savepoint from the list of currently active savepoints.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise. A similar
feature is available in an Adaptive Server Enterprise-compatible manner
using nested transactions.

574
Chapter 9 SQL Statements

REMOVE statement
Function Use this statement to remove a class or a jar file from a database. When a
class is removed it is no longer available for use as a column or variable
type.
The class or jar must already be installed.
Syntax REMOVE JAVA classes_to_remove
classes_to_remove:
CLASS java_class_name [, java_class_name, …]
| JAR jar_name [, jar_name, …]
Permissions Must have DBA authority.
Not supported on Windows CE.
Description Removes a class or jar file from the database.
Parameters CLASS The java_class_name parameter is the name of one or more Java
class to be removed. These classes must be installed classes in the current
database.
JAR The jar_name is a character string value of maximum length 255.
Each jar_name must be equal to the jar_name of a retained jar in the current
database. Equality of jar_name is determined by the character string
comparison rules of the SQL system.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise. A similar
feature is available in an Adaptive Server Enterprise-compatible manner
using nested transactions.
Examples ♦ The following statement removes a Java class named Demo from the
current database.
REMOVE JAVA CLASS Demo

575
RESIGNAL statement

RESIGNAL statement
Function Use this statement to resignal an exception condition.
Syntax RESIGNAL [ exception-name ]
Permissions None.
Side effects None.
See also "SIGNAL statement" on page 603
"BEGIN statement" on page 392
"Using exception handlers in procedures and triggers" on page 466 of the
book ASA User’s Guide
"RAISERROR statement" on page 570
Description Within an exception handler, RESIGNAL allows you to quit the compound
statement with the exception still active, or to quit reporting another named
exception. The exception will be handled by another exception handler or
returned to the application. Any actions by the exception handler before the
RESIGNAL are undone.
Standards and ♦ SQL/92 Persistent stored module feature.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise. Signaling of
errors in Transact-SQL procedures is carried out using the RAISERROR
statement.
Example ♦ The following fragment returns all exceptions except Column Not
Found to the application.
...
DECLARE COLUMN_NOT_FOUND EXCEPTION
FOR SQLSTATE ’52003’;
...
EXCEPTION
WHEN COLUMN_NOT_FOUND THEN
SET message=’Column not found’;
WHEN OTHERS THEN
RESIGNAL;

576
Chapter 9 SQL Statements

RESTORE statement
Function Use this statement to restore a backed up database from an archive.
Syntax RESTORE DATABASE database_location
FROM archive_root
CATALOG ONLY
[ [ RENAME dbspace_name TO new_dbspace_path ] …]
Permissions Must be connected to the utility database.
Side effects None.
See also "BACKUP statement" on page 389
"Backup and Data Recovery" on page 627 of the book ASA User’s Guide
Description Each RESTORE operation updates a history file called backup.syb, which is
a text file held in the same directory as your database server executable file.
The RENAME clause provides a way to change the restore location for each
dbspace. The dbspace name in a RENAME clause cannot be SYSTEM or
TRANSLOG.
RESTORE DATABASE replaces the database that is being restored. If you
need incremental backups, use the image format of the BACKUP command
and save only the transaction log; however, image backups to tape are not
supported.
Archive backups are only supported on Windows NT and Unix platforms.
Parameters database_location Specifies the location for the main database file.

CATALOG ONLY clause Retrieve information about the named archive,


and place it in the backup history file (backup.syb), but do not restore any
data from the archive.

RENAME clause Specifies a new location to restore each dbspace to.


Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise.
Examples ♦ Restore a database from a Windows NT tape drive:
RESTORE DATABASE ’d:\\dbhome\\cust.db’
FROM ’\\.\tape0’

577
RESUME statement

RESUME statement
Function Use this statement to resume execution of a cursor that returns result sets.
Syntax 1 RESUME cursor-name
cursor-name: identifier
cursor-name: identifier or host-variable
Permissions The cursor must have been previously opened.
Side effects None.
See also "DECLARE CURSOR statement" on page 475
"Returning results from procedures" on page 453 of the book ASA User’s
Guide
Description This statement resumes execution of a procedure that returns result sets. The
procedure executes until the next result set (SELECT statement with no
INTO clause) is encountered. If the procedure completes and no result set is
found, the SQLSTATE_PROCEDURE_COMPLETE warning is set. This
warning is also set when you RESUME a cursor for a SELECT statement.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Adaptive Server Enterprise.
Examples ♦ Embedded SQL example
1. EXEC SQL RESUME cur_employee;
2. EXEC SQL RESUME :cursor_var;
♦ Interactive SQL examples
CALL sample_proc();
RESUME ALL;

578
Chapter 9 SQL Statements

RETURN statement
Function Use this statement to exit from a function or procedure unconditionally,
optionally providing a return value.
Syntax RETURN [ expression ]
Permissions None.
Side effects None.
See also "CREATE FUNCTION statement" on page 432
"CREATE PROCEDURE statement" on page 440
"BEGIN statement" on page 392
Description A RETURN statement causes an immediate exit from a function or
procedure. If expression is supplied, the value of expression is returned as
the value of the function or procedure.
Statements following a RETURN statement are not executed.
Within a function, the expression should be of the same data type as the
function’s RETURNS data type.
Within a procedure, RETURN is used for Transact-SQL-compatibility, and
is used to return an integer error code.
Standards and ♦ SQL/92 Persistent stored module feature.
compatibility
♦ Sybase Transact-SQL procedures use the RETURN statement to
return an integer error code.
Example ♦ The following function returns the product of three numbers:
CREATE FUNCTION product (
a numeric,
b numeric,
c numeric )
RETURNS numeric
BEGIN
RETURN ( a * b * c );
END
♦ Calculate the product of three numbers:
SELECT product (2, 3, 4)

product(2, 3, 4)
24

579
RETURN statement

♦ The following procedure uses the RETURN statement to avoid


executing a complex query if it is meaningless:
CREATE PROCEDURE customer_products
( in customer_id integer DEFAULT NULL)
RESULT ( id integer, quantity_ordered integer )
BEGIN
IF customer_id NOT IN (SELECT id FROM customer)
OR customer_id IS NULL THEN
RETURN
ELSE
SELECT product.id,sum(
sales_order_items.quantity )
FROM product,
sales_order_items,
sales_order
WHERE sales_order.cust_id=customer_id
AND sales_order.id=sales_order_items.id
AND sales_order_items.prod_id=product.id
GROUP BY product.id
END IF
END

580
Chapter 9 SQL Statements

REVOKE statement
Function Use this statement to remove permissions for the specified users.
Syntax 1 REVOKE {
CONNECT,
DBA,
INTEGRATED LOGIN,
GROUP,
MEMBERSHIP IN GROUP userid, …
RESOURCE,
}
..FROM userid, …
Syntax 2 REVOKE {
ALL [PRIVILEGES]
ALTER,
DELETE,
INSERT,
REFERENCES [ ( column-name, …) ],
SELECT [ ( column-name, …) ],
UPDATE [ ( column-name, …) ],
}
… ON [ owner.]table-name FROM userid, …
Syntax 3 REVOKE EXECUTE ON [ owner.]procedure-name FROM userid, …
Permissions Must be the grantor of the permissions that are being revoked or have DBA
authority.
If you are revoking CONNECT permissions or table permissions from
another user, the other user must not be connected to the database.
Side effects Automatic commit.
See also "GRANT statement" on page 526
Description The REVOKE statement removes permissions given using the GRANT
statement. Form 1 revokes special user permissions. Form 2 revokes table
permissions. Form 3 revokes permission to execute a procedure.
REVOKE CONNECT removes a user ID from a database, and also destroys
any objects (tables, views, procedures, etc.) owned by that user and any
permissions granted by that user. REVOKE GROUP automatically
REVOKES MEMBERSHIP from all members of the group.
If you give a user GRANT option permission, then later revoke that
permission, you also revoke any permissions that user granted to others
while they had the GRANT option.

581
REVOKE statement

Standards and ♦ SQL/92 Syntax 1 is a vendor extension. Syntax 2 is an entry-level


compatibility feature. Syntax 3 is a Persistent Stored Module feature.
♦ Sybase Syntax 2 and 3 are supported by Adaptive Server Enterprise.
Syntax 1 is not supported by Adaptive Server Enterprise. User
management and security models are different for Adaptive Server
Anywhere and Adaptive Server Enterprise.
Examples ♦ Prevent user Dave from updating the employee table.
REVOKE UPDATE ON employee FROM dave;
♦ Revoke resource permissions from user Jim.
REVOKE RESOURCE FROM Jim;
♦ Revoke integrated login mapping from user profile name Administrator
REVOKE INTEGRATED LOGIN FROM Administrator;
♦ Disallow the Finance group from executing the procedure
sp_customer_list.
REVOKE EXECUTE ON sp_customer_list
FROM finance;
♦ Drop user ID FranW from the database.
REVOKE CONNECT FROM FranW

582
Chapter 9 SQL Statements

ROLLBACK statement
Function Use this statement to end a transaction and undo any changes made since the
last COMMIT or ROLLBACK.
Syntax ROLLBACK [ WORK ]
Permissions None.
Side effects Closes all cursors not opened WITH HOLD.
See also "COMMIT statement" on page 408
"ROLLBACK TO SAVEPOINT statement" on page 584
Description A transaction is the logical unit of work done on one database connection to
a database between COMMIT or ROLLBACK statements. The ROLLBACK
statement ends the current transaction and undoes all changes made to the
database since the previous COMMIT or ROLLBACK.
Standards and ♦ SQL/92 Entry level feature.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.

583
ROLLBACK TO SAVEPOINT statement

ROLLBACK TO SAVEPOINT statement


Function To cancel any changes made since a SAVEPOINT.
Syntax ROLLBACK TO SAVEPOINT [savepoint-name]
Permissions There must have been a corresponding SAVEPOINT within the current
transaction.
Side effects None.
See also "BEGIN TRANSACTION statement" on page 395
"COMMIT statement" on page 408
"RELEASE SAVEPOINT statement" on page 574
"ROLLBACK statement" on page 583
"SAVEPOINT statement" on page 586
"Savepoints within transactions" on page 373 of the book ASA User’s Guide
Description The ROLLBACK TO SAVEPOINT statement will undo any changes that
have been made since the SAVEPOINT was established. Changes made
prior to the SAVEPOINT are not undone; they are still pending.
The savepoint-name is an identifier that was specified on a SAVEPOINT
statement within the current transaction. If savepoint-name is omitted, the
most recent savepoint is used. Any savepoints since the named savepoint are
automatically released.
Standards and ♦ SQL/92 Vendor extension. Included in the SQL/3 draft specification.
compatibility
♦ Sybase Savepoints are not supported by Adaptive Server Enterprise.
To implement similar features in an Adaptive Server Enterprise-
compatible manner, you can use nested transactions.
$ For more information on nested transactions, see "BEGIN
TRANSACTION statement" on page 395.

584
Chapter 9 SQL Statements

ROLLBACK TRIGGER statement


Function Use this statement to undo any changes made in a trigger.
Syntax ROLLBACK TRIGGER [ WITH raiserror-statement ]
Permissions None.
Side effects None
See also "CREATE TRIGGER statement" on page 464
"ROLLBACK statement" on page 583
"ROLLBACK TO SAVEPOINT statement" on page 584
"RAISERROR statement" on page 570
Description The ROLLBACK TRIGGER statement rolls back the work done in a trigger,
including the data modification that caused the trigger to fire.
Optionally, a RAISERROR statement can be issued. If a RAISERROR
statement is issued, an error is returned to the application. If no
RAISERROR statement is issued, no error is returned.
If a ROLLBACK TRIGGER statement is used within a nested trigger and
without a RAISERROR statement, only the innermost trigger and the
statement which caused it to fire are undone.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.

585
SAVEPOINT statement

SAVEPOINT statement
Function Use this statement to establish a savepoint within the current transaction.
Syntax SAVEPOINT [ savepoint-name ]
Permissions None.
Side effects None.
See also "RELEASE SAVEPOINT statement" on page 574
"ROLLBACK TO SAVEPOINT statement" on page 584
Description Establish a savepoint within the current transaction. The savepoint-name is
an identifier that can be used in a RELEASE SAVEPOINT or ROLLBACK
TO SAVEPOINT statement. All savepoints are automatically released when
a transaction ends. See "Savepoints within transactions" on page 373 of the
book ASA User’s Guide.
Savepoints that are established while a trigger or atomic compound statement
is executing are automatically released when the atomic operation ends.
Standards and ♦ SQL/92 Vendor extension. Included in the SQL/3 draft specification.
compatibility
♦ Sybase Not supported in Adaptive Server Enterprise. To implement
similar features in an Adaptive Server Enterprise-compatible manner,
you can use the SAVE TRANSACTION statement.

586
Chapter 9 SQL Statements

SELECT statement
Function Use this statement to retrieve information from the database.
Syntax SELECT [ ALL | DISTINCT ] [ FIRST | TOP n ] select-list
…[ INTO { host-variable-list | variable-list } ]
…[ FROM table-expression ]
…[ WHERE search-condition ]
…[ GROUP BY group-by-list ]
…[ HAVING search-condition ]
…[ ORDER BY { expression | integer } [ ASC | DESC ], … ]
select-list:
{ column-name | expression } [ [ AS ] alias-name ], …| *
group-by-list:
{ column-name | alias-name | function | expression }, …
Permissions Must have SELECT permission on the named tables and views.
Side effects None.
"Expressions" on page 218
See also
"FROM clause" on page 518
"Search conditions" on page 226
"UNION operation" on page 617
"Joins: Retrieving Data from Several Tables" on page 189 of the book ASA
User’s Guide
Description The SELECT statement is used for retrieving results from the database.
A SELECT statement can be used in Interactive SQL to browse data in the
database, or to export data from the database to an external file.
A SELECT statement can also be used in procedures and triggers or in
embedded SQL. The SELECT statement with an INTO clause is used for
retrieving results from the database when the SELECT statement only
returns one row. For multiple row queries, you must use cursors.
A SELECT statement can also be used to return a result set from a
procedure.
Parameters ALL or DISTINCT All (the default) returns all rows that satisfy the clauses
of the SELECT statement. If DISTINCT is specified, duplicate output rows
are eliminated. Many statements take significantly longer to execute when
DISTINCT is specified, so you should reserve DISTINCT for cases where it
is necessary.

FIRST or TOP These keywords are principally for use with ORDER BY
queries. You can explicitly retrieve only the first row of a query or the first n
rows of a query.

587
SELECT statement

The FIRST and TOP keywords cannot be used in a derived table query. You
should not use the keywords in view definitions.

select list The select list is a list of expressions, separated by commas,


specifying what will be retrieved from the database. An asterisk (*) means to
select all columns of all tables in the FROM clause.

Aggregate functions are allowed in the select list (see "SQL Functions" on
page 291). Subqueries are also allowed in the select list (see "Expressions"
on page 218). Each subquery must be within parentheses.
Alias-names can be used throughout the query to represent the aliased
expression.
Alias names are also displayed by Interactive SQL at the top of each column
of output from the SELECT statement. If the optional alias name is not
specified after an expression, Interactive SQL will display the expression
itself.

INTO host-variable-list This clause is used in Embedded SQL only. It


specifies where the results of the SELECT statement will go. There must be
one host-variable item for each item in the select list. Select list items are put
into the host variables in order. An indicator host variable is also allowed
with each host-variable, so the program can tell if the select list item was
NULL.

INTO variable-list This clause is used in procedures and triggers only. It


specifies where the results of the SELECT statement will go. There must be
one variable for each item in the select list. Select list items are put into the
variables in order.

FROM clause Rows are retrieved from the tables and views specified in
the table expression. Joins can be specified using join operators. A SELECT
statement with no FROM clause can be used to display the values of
expressions not derived from tables. For example:
SELECT @@version
displays the value of the global variable @@version. This is equivalent to:
SELECT @@version
FROM DUMMY
$ For more information, see "FROM clause" on page 518.

588
Chapter 9 SQL Statements

WHERE clause This clause specifies which rows will be selected from
the tables named in the FROM clause. It is also used to do joins between
multiple tables. This is accomplished by putting a condition in the WHERE
clause that relates a column or group of columns from one table with a
column or group of columns from another table. Both tables must be listed in
the FROM clause.
$ For more information, see "Search conditions" on page 226.
GROUP BY clause You can group by columns, alias names, or functions.
The result of the query contains one row for each distinct set of values in the
named columns, aliases, or functions. All NULL-containing rows are treated
as a single set. The resulting rows are often referred to as groups since there
is one row in the result for each group of rows from the table list. Aggregate
functions can then be applied to these groups to get meaningful results.
When GROUP BY is used, the select-list, HAVING clause, and ORDER BY
clause must not reference any identifier that is not named in the GROUP BY
clause. The exception is that the select-list and HAVING clause may contain
aggregate functions.

HAVING clause This clause selects rows based on the group values and
not on the individual row values. The HAVING clause can only be used if
either the statement has a GROUP BY clause or the select list consists solely
of aggregate functions. Any column names referenced in the HAVING
clause must either be in the GROUP BY clause or be used as a parameter to
an aggregate function in the HAVING clause.

ORDER BY clause This clause sorts the results of a query. Each item in
the ORDER BY list can be labeled as ASC for ascending order (the default)
or DESC for descending order. If the expression is an integer n, then the
query results will be sorted by the n’th item in the select list.
In embedded SQL, the SELECT statement is used for retrieving results from
the database and placing the values into host variables via the INTO clause.
The SELECT statement must return only one row. For multiple row queries,
you must use cursors.
Standards and ♦ SQL/92 Entry level feature. The complexity of the SELECT statement
compatibility means that you should check individual clauses against the standard.
♦ Sybase Supported by Adaptive Server Enterprise, with some
differences in syntax.
Examples ♦ How many employees are there?
SELECT count(*)
FROM Employee;
♦ List all customers and the total value of their orders.

589
SELECT statement

SELECT company_name,
CAST( sum(sales_order_items.quantity *
product.unit_price) AS INTEGER) VALUE
FROM customer
JOIN sales_order
JOIN sales_order_items
JOIN product
GROUP BY company_name
ORDER BY VALUE DESC
♦ The following statement shows an Embedded SQL SELECT statement:
SELECT count(*) INTO :size
FROM employee

590
Chapter 9 SQL Statements

SET statement
Function Use this statement to assign a value to a SQL variable.
Syntax SET identifier = expression
Permissions None.
Side effects None.
See also "CREATE VARIABLE statement" on page 468
"DECLARE statement" on page 474
"DROP VARIABLE statement" on page 499
"Expressions" on page 218
Description The SET statement assigns a new value to a variable. The variable must have
been previously created using a CREATE VARIABLE statement or
DECLARE statement, or it must be an OUPUT parameter for a procedure.
A variable can be used in a SQL statement anywhere a column name is
allowed. If a column name exists with the same name as the variable, the
variable value is used.
Variables are local to the current connection, and disappear when you
disconnect from the database or use the DROP VARIABLE statement. They
are not affected by COMMIT or ROLLBACK statements.
Variables are necessary for creating large text or binary objects for INSERT
or UPDATE statements from embedded SQL programs, because
embedded SQL host variables are limited to 32,767 bytes.
Standards and ♦ SQL/92 Persistent stored module feature.
compatibility
♦ Sybase Not supported. In Adaptive Server Enterprise, variables are
assigned using the SELECT statement with no table, a Transact-SQL
syntax that is also supported by Adaptive Server Anywhere. The SET
statement is used to set database options in Adaptive Server Enterprise.
Example ♦ The following code fragment could be used to insert a large text value
into the database.

591
SET statement

EXEC SQL BEGIN DECLARE SECTION;


DECL_LONGVARCHAR( 500 ) buffer;
EXEC SQL END DECLARE SECTION;

EXEC SQL CREATE VARIABLE hold_blob LONG VARCHAR;


EXEC SQL SET hold_blob = ’’;
for(;;) {
/* read some data into buffer ... */
size = fread( buffer, 1, 5000, fp );
if( size <= 0 ) break;
/* Does not work if data contains null chars */
EXEC SQL SET hold_blob = hold_blob || :buffer;
}
EXEC SQL INSERT INTO some_table VALUES( 1, hold_blob
);
EXEC SQL DROP VARIABLE hold_blob;
♦ The following code fragment could be used to insert a large binary value
into the database.
EXEC SQL BEGIN DECLARE SECTION;
DECL_BINARY( 5000 ) buffer;
EXEC SQL END DECLARE SECTION;

EXEC SQL CREATE VARIABLE hold_blob LONG BINARY;


EXEC SQL SET hold_blob = ’’;
for(;;) {
/* read some data into buffer ... */
size = fread( &(buffer.array), 1, 5000, fp );
if( size <= 0 ) break;
buffer.len = size;
/* add data to blob using concatenation */
EXEC SQL SET hold_blob = hold_blob || :buffer;
}
EXEC SQL INSERT INTO some_table VALUES ( 1,
hold_blob );
EXEC SQL DROP VARIABLE hold_blob;

592
Chapter 9 SQL Statements

SET statement [T-SQL]


Function Use this statement to set database options for the current connection in an
Adaptive Server Enterprise-compatible manner.
Syntax SET option-name option-value
Permissions None.
Side effects None.
See also "SET OPTION statement" on page 596
"Setting options for Transact-SQL compatibility" on page 943 of the book
ASA User’s Guide
"Transact-SQL and SQL/92 compatibility options" on page 151
Description The available options are as follows:

Option name Option value


ANSINULL ON | OFF
ANSI_PERMISSIONS ON | OFF
CLOSE ON ENDTRAN ON | OFF
QUOTED_IDENTIFIER ON | OFF
ROWCOUNT integer
SELF_RECURSION ON | OFF
STRING_RTRUNCATION ON | OFF
TEXTSIZE integer
TRANSACTION ISOLATION LEVEL 0|1|2|3

Database options in Adaptive Server Anywhere are set using the SET
OPTION statement. However, Adaptive Server Anywhere also provides
support for the Adaptive Server Enterprise SET statement for options that are
particularly useful for compatibility.
In addition, the SET statement is allowed by Adaptive Server Anywhere for
the PREFETCH option, for compatibility, but has no effect:
Standards and ♦ SQL/92 Transact-SQL extension
compatibility
♦ Sybase Adaptive Server Anywhere supports a subset of the Adaptive
Server Enterprise database options.

593
SET CONNECTION statement [Interactive SQL][ESQL]

SET CONNECTION statement


[Interactive SQL][ESQL]
Function Use this statement to change the active database connection.
Syntax SET CONNECTION [connection-name]
connection-name:
identifier, string, or host-variable
Permissions None.
Side effects None.
See also "CONNECT statement" on page 411
"DISCONNECT statement" on page 490
Description The SET CONNECTION statement changes the active database connection
to connection-name. The current connection state is saved, and will be
resumed when it again becomes the active connection. If connection-name
is omitted and there is a connection that was not named, that connection
becomes the active connection.
When cursors are opened in embedded SQL, they are associated with the
current connection. When the connection is changed, the cursor names of the
previously active connection become inaccessible. These cursors remain
active and in position, and become accessible when the associated
connection becomes active again.

Standards and ♦ SQL/92 Interactive SQL use is a vendor extension. Embedded SQL is
compatibility a Full level feature.
♦ Sybase Supported by Open Client/Open Server.
Example ♦ The following example is in Embedded SQL.
EXEC SQL SET CONNECTION :conn_name;
♦ From Interactive SQL, set the current connection to the connection
named conn1.
SET CONNECTION conn1;

594
Chapter 9 SQL Statements

SET DESCRIPTOR statement [ESQL]


Function Use this statement to describe the variables in a SQL descriptor area and to
place data into the descriptor area.
Syntax SET DESCRIPTOR descriptor-name
…{ COUNT = { integer | hostvar } | VALUE n assignment [, …] }
assignment:
{ TYPE | SCALE | PRECISION | LENGTH | INDICATOR }
… = { integer | hostvar }
| DATA = hostvar
Permissions None.
Side effects None.
See also "ALLOCATE DESCRIPTOR statement" on page 369
"DEALLOCATE DESCRIPTOR statement" on page 472
"The SQL descriptor area (SQLDA)" on page 44 of the book ASA
Programming Interfaces Guide
Description The SET DESCRIPTOR statement is used to describe the variables in a
descriptor area, and to place data into the descriptor area.
The SET … COUNT statement sets the number of described variables within
the descriptor area. The value for count must not exceed the number of
variables specified when the descriptor area was allocated.
The value n specifies the variable in the descriptor area upon which the
assignment(s) will be performed.
Type checking is performed when doing SET … DATA, to ensure that the
variable in the descriptor area has the same type as the host variable.
If an error occurs, the code is returned in the SQLCA.
Standards and ♦ SQL/92 Intermediate level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Example ♦ For an example, see "ALLOCATE DESCRIPTOR statement" on
page 369.

595
SET OPTION statement

SET OPTION statement


Function Use this statement to change the values of database options.
Syntax SET [ EXISTING ] [ TEMPORARY ] OPTION
… [ userid.| PUBLIC.]option-name = [ option-value ]
userid: { identifier | string | host-variable }
option-name: { identifier | string | host-variable }
option-value: { host-variable (indicator allowed)
| string
| identifier
| number }
Permissions None required to set your own options.
DBA authority is required to set database options for another user or
PUBLIC.
Side effects If TEMPORARY is not specified, an automatic commit is performed.
See also "General database options" on page 149
"Transact-SQL and SQL/92 compatibility options" on page 151
"Replication options" on page 154
"SET OPTION statement " on page 599
Description The SET OPTION statement is used to change options that affect the
behavior of the database server. Setting the value of an option can change the
behavior for all users or only for an individual user. The scope of the change
can be either temporary or permanent.
The classes of options are:
♦ General database options
♦ Transact-SQL compatibility
♦ Replication database options

$ For a listing and description of all available options, see "Database


Options" on page 143.
You can set options at three levels of scope: public, user, and temporary. A
temporary option takes precedence over other options, and user options take
precedence over public options. If you set a user level option for the current
user, the corresponding temporary option gets set as well.
If you use the EXISTING keyword, option values cannot be set for an
individual user ID unless there is already a PUBLIC user ID setting for that
option.

596
Chapter 9 SQL Statements

If you specify a user ID, the option value applies to that user (or, for a group
user ID, the members of that group). If you specify PUBLIC, the option
value applies to all users who don’t have an individual setting for the option.
By default, the option value applies to the currently logged on user ID that
issued the SET OPTION statement..
For example, the following statement applies an option change to the user
DBA, if DBA is the user issuing the SQL statement:
SET OPTION login_mode = mixed
However the following statement applies the change to the PUBLIC user ID,
a user group to which all users belong.
SET OPTION Public.login_mode = standard
Only users with DBA privileges have the authority to set an option for the
PUBLIC user ID.
In embedded SQL, database options can be set only temporarily.
Users can use the SET OPTION statement to change the values for their own
user ID. Setting the value of an option for a user id other then your own is
permitted only if you have DBA authority.
Adding the TEMPORARY keyword to the SET OPTION statement changes
the duration that the change takes effect. By default, the option value is
permanent: it will not change until it is explicitly changed using the SET
OPTION statement.
When the SET TEMPORARY OPTION statement is not qualified with a
user ID, the new option value is in effect only for the current connection.
When SET TEMPORARY OPTION is used for the PUBLIC user ID, the
change is in place for as long as the database is running. When the database
is shut down, TEMPORARY options for the PUBLIC group revert back to
their permanent value.
Setting temporary options for the PUBLIC user ID offers a security benefit.
For example, when the LOGIN_MODE option is enabled, the database relies
on the login security of the system on which it is running. Enabling it
temporarily means that a database relying on the security of a Windows NT
domain will not be compromised if the database is shut down and copied to a
local machine. In that case, the temporary enabling of the LOGIN_MODE
option reverts to its permanent value, which could be Standard, a mode
where integrated logins are not permitted.
If option-value is omitted, the specified option setting will be deleted from
the database. If it was a personal option setting, the value will revert back to
the PUBLIC setting. If a TEMPORARY option is deleted, the option setting
will revert back to the permanent setting.

597
SET OPTION statement

Caution
Changing option settings while fetching rows from a cursor is not
supported, as it can lead to ill-defined behavior. For example, changing
the DATE_FORMAT setting while fetching from a cursor would lead to
different date formats among the rows in the result set. Do not change
option settings while fetching rows.

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Not supported by Adaptive Server Enterprise. Adaptive
Server Anywhere does support some Adaptive Server Enterprise options
using the SET statement.
Examples ♦ Set the date format option.
SET OPTION public.date_format = ’Mmm dd yyyy’;
♦ Set the ’wait for commit’ option to on.
SET OPTION waitefor_commit = ’on’;
Embedded SQL 1. EXEC SQL SET OPTION :user.:option_name = :value;
Examples
2. EXEC SQL SET TEMPORARY OPTION Date_format =
’mm/dd/yyyy’;

598
Chapter 9 SQL Statements

SET OPTION statement [Interactive SQL]


Function Use this statement to change the values of Interactive SQL options.
Syntax 1 SET [ TEMPORARY ] OPTION
… [ userid. | PUBLIC. ]option-name = [ option-value ]
userid: identifier, string or host-variable
option-name: identifier, string or host-variable
option-value: host-variable (indicator allowed), string, identifier, or
number
Syntax 2 SET PERMANENT
Syntax 3 SET
See Also "Interactive SQL options" on page 155
Description SET PERMANENT (syntax 2) stores all current Interactive SQL options in
the SYSOPTIONS system table. These settings are automatically established
every time Interactive SQL is started for the current user ID.
Syntax 3 displays all of the current option settings. If there are temporary
options set for Interactive SQL or the database server, these will be
displayed; otherwise, the permanent option settings are displayed.

599
SET SQLCA statement [ESQL]

SET SQLCA statement [ESQL]


Function Use this statement to tell the SQL preprocessor to use a SQLCA other than
the default, global sqlca.
Syntax SET SQLCA sqlca
sqlca: identifier or string
Permissions None.
Side effects None.
See also "SQLCA management for multi-threaded or reentrant code" on page 29 of
the book ASA Programming Interfaces Guide
Description The SET SQLCA statement tells the SQL preprocessor to use a SQLCA
other than the default global sqlca. The sqlca must be an identifier or string
that is a C language reference to a SQLCA pointer.
The current SQLCA pointer is implicitly passed to the database interface
library on every embedded SQL statement. All embedded SQL statements
that follow this statement in the C source file will use the new SQLCA.
This statement is necessary only when you are writing code that is reentrant
(see "SQLCA management for multi-threaded or reentrant code" on page 29
of the book ASA Programming Interfaces Guide). The sqlca should reference
a local variable. Any global or module static variable is subject to being
modified by another thread.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not supported by Open Client/Open Server.
Example ♦ The owning function could be found in a Windows DLL. Each
application that uses the DLL has its own SQLCA.
an_sql_code FAR PASCAL ExecuteSQL( an_application
*app, char *com )
{
EXEC SQL BEGIN DECLARE SECTION;
char *sqlcommand;
EXEC SQL END DECLARE SECTION;
EXEC SQL SET SQLCA "&app->.sqlca";
sqlcommand = com;
EXEC SQL WHENEVER SQLERROR CONTINUE;
EXEC SQL EXECUTE IMMEDIATE :sqlcommand;
return( SQLCODE );
}

600
Chapter 9 SQL Statements

SETUSER statement
Function Use this statement to allow a database administrator to impersonate another
user, and to enable connection pooling.
Syntax { SET SESSION AUTHORIZATION | SETUSER }
[ [ WITH OPTIONS ] userid ]
Permissions Must have DBA authority.
See also "EXECUTE IMMEDIATE statement" on page 504
"GRANT statement" on page 526
"REVOKE statement" on page 581
"SET OPTION statement" on page 596
Description The SETUSER statement is provided to make database administration easier.
It enables a user with DBA authority to impersonate another user of the
database.
SETUSER can also be used from an application server to take advantage of
connection pooling. Connection pooling cuts down the number of distinct
connections that need to be made, which can improve performance.
SETUSER with no user ID undoes all earlier SETUSER statements.
There are several uses for the SETUSER statement, including the following:
♦ Creating objects You can use SETUSER to create a database object
that is to be owned by another user.
♦ Permissions checking By acting as another user, with their
permissions and group memberships, a DBA can test the permissions
and name resolution of queries, procedures, views, and so on.
♦ Providing a safer environment for administrators The DBA has
permission to carry out any action in the database. If you wish to ensure
that you do not accidentally carry out an unintended action, you can use
SETUSER to switch to a different user ID with fewer permissions.
Parameters WITH OPTIONS By default, only permissions (including group
membership) are altered. If WITH OPTIONS is specified, the database
options in effect are changed to the current database options of userid.
Standards and ♦ SQL/92 SET SESSION AUTHORIZATION is SQL 92 compliant.
compatibility SETUSER is a vendor extension.
♦ Sybase Adaptive Server Enterprise supports SETUSER, but not the
WITH OPTIONS keywords.
Examples ♦ The following statements, executed by a user named DBA, change the
user ID to be Joe, then Jane, and then back to DBA

601
SETUSER statement

SETUSER ’Joe’
// ... operations...
SETUSER WITH OPTIONS ’Jane’
// ... operations...
SETUSER

602
Chapter 9 SQL Statements

SIGNAL statement
Function Use this statement to signal an exception condition.
Syntax SIGNAL exception-name
Permissions None.
Side effects None.
See also "DECLARE statement" on page 474
"RESIGNAL statement" on page 576
"BEGIN statement" on page 392
"Using exception handlers in procedures and triggers" on page 466 of the
book ASA User’s Guide
Description SIGNAL allows you to raise an exception. See "Using exception handlers in
procedures and triggers" on page 466 of the book ASA User’s Guide for a
description of how exceptions are handled.

exception-name The name of an exception declared using a DECLARE


statement at the beginning of the current compound statement. The exception
must correspond to a system-defined SQLSTATE or a user-defined
SQLSTATE. User-defined SQLSTATE values must be in the range 99000 to
99999.
Standards and ♦ SQL/92 Persistent Stored Module feature.
compatibility
♦ Sybase SIGNAL is not supported by Adaptive Server Enterprise.
Examples The following compound statement declares and signals a user-defined
exception. If you execute this example from Interactive SQL, the message is
displayed in the Message window.
BEGIN
DECLARE myexception EXCEPTION
FOR SQLSTATE ’99001’;
SIGNAL myexception;
EXCEPTION
WHEN myexception THEN
MESSAGE ’My exception signaled’
TO CLIENT;
END

603
START DATABASE statement

START DATABASE statement


Function Use this statement to start a database on the current database server.
Syntax START DATABASE database-file
… [ AS database-name ]
… [ ON engine-name ]
… [ AUTOSTOP { ON | OFF } ]
Permissions The required permissions are specified by the database server -gd command-
line option. This option defaults to all on the personal database server, and
dba on the network server.
Side effects None
See also "STOP DATABASE statement" on page 609
"CONNECT statement" on page 411
"–gd command-line option" on page 25
Description Starts a specified database on the current database server.
The START DATABASE statement does not connect the current application
to the specified database: an explicit connection is still needed.
Interactive SQL supports the ON clause, which allows the database to be
started on a database server other than the current.
Parameters START DATABASE clause The database-file parameter is a string. If a
relative path is supplied in database-file, it is relative to the database server
starting directory.
If you use this statement in Interactive SQL, database-file is interpreted
relative to the Interactive SQL current directory.

AS clause If database-name is not specified, a default name is assigned to


the database. This default name is the root of the database file. For example,
a database in file c:\asa6\asademo.db would be given the default name of
asademo.

ON clause This clause is supported from Interactive SQL only. In


Interactive SQL, if engine-name is not specified, the default database is the
first started server among those currently running.

AUTOSTOP clause The default setting for the AUTOSTOP clause is ON.
With AUTOSTOP set to ON, the database is unloaded when the last
connection to it is dropped. If AUTOSTOP is set to OFF, the database is not
unloaded.

In Interactive SQL, you can use YES or NO as alternatives to ON and OFF.

604
Chapter 9 SQL Statements

Standards and ♦ SQL/92 Vendor extension.


compatibility
♦ Sybase Not applicable.
Example ♦ Start the database file c:\asa6\sample_2.db on the current server.
START DATABASE ’c:\asa6\sample_2.db’
♦ From Interactive SQL, start the database file c:\asa6\sample_2.db as
sam2 on the server named sample.
START DATABASE ’c:\asa6\sample_2.db’
AS sam2
ON sample

605
START ENGINE statement [Interactive SQL]

START ENGINE statement [Interactive SQL]


Function Use this statement to start a database server.
Syntax START ENGINE AS engine-name [ STARTLINE command-string ]
Permissions None
Side effects None
See also "STOP ENGINE statement" on page 610
"The database server" on page 14
Description The START ENGINE statement starts a database server. If you wish to
specify a set of options for the server, use the STARTLINE keyword
together with a command string. Valid command strings are those that
conform to the database server command-line description in "The database
server" on page 14.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not applicable.
Example ♦ Start a database server, named sample, without starting any databases on
it.
START ENGINE AS sample
♦ The following example shows the use of a STARTLINE clause.
START ENGINE AS eng1 STARTLINE ’dbeng7 -c 8M’

606
Chapter 9 SQL Statements

START JAVA statement


Function Use this statement to start the Java VM.
Syntax START JAVA
Permissions None
Side effects None
See also "STOP JAVA statement" on page 611
Description The START JAVA statement starts the Java VM. The main use is to load the
Java VM at a convenient time so that when the user starts to use Java
functionality there is no initial pause while the Java VM is loaded.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not applicable.
Example ♦ Start the Java VM.
START JAVA

607
START LOGGING statement [Interactive SQL]

START LOGGING statement [Interactive SQL]


Function Use this statement to start logging executed SQL statements to a log file.
Syntax START LOGGING ’filename’’
Permissions None.
Side effects None.
See also "STOP LOGGING statement" on page 612
Description The START LOGGING statement starts copying all subsequent executed
SQL statements to the log file that you specify. If the file does not exist,
Interactive SQL creates it. Logging continues until you explicitly stop the
logging process with the STOP LOGGING statement, or until you end the
current Interactive SQL session. You can also start and stop logging by
clicking SQL➤Start Logging and SQL➤Stop Logging.
Example ♦ Start logging to a file called filename.sql, located in the c: directory.
START LOGGING ’c:\filename.sql’

608
Chapter 9 SQL Statements

STOP DATABASE statement


Function Use this statement to stop a database on the current database server.
Syntax STOP DATABASE database-name
… [ ON engine-name ]
… [ UNCONDITIONALLY ]
Permissions The required permissions are specified by the database server -gd command-
line option. This option defaults to all on the personal database server, and
dba on the network server.
You cannot use STOP DATABASE on the database to which you are
currently connected.
Side effects None
See also "START DATABASE statement" on page 604
"DISCONNECT statement" on page 490
"–gd command-line option" on page 25
Description The STOP DATABASE statement stops a specified database on the current
database server.
Parameters STOP DATABASE clause The database-name is the name of a database
running on the current server.

ON clause This clause is supported in Interactive SQL only. If engine-


name is not specified in Interactive SQL, all running engines will be
searched for a database of the specified name.
When not using this statement in Interactive SQL, the database is stopped
only if it is started on the current database server.

UNCONDITIONALLY keyword Stop the database even if there are


connections to the database. By default, the database is not stopped if there
are connections to it.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not applicable.
Examples ♦ Stop the database named sample on the current server.
STOP DATABASE sample

609
STOP ENGINE statement

STOP ENGINE statement


Function Use this statement to stop a database server.
Syntax STOP ENGINE [ engine-name ]
… [ UNCONDITIONALLY ]
Permissions The permissions to shut down a server depend on the -gd command-line
setting on the database server command line. The default setting is all for the
personal server, and dba for the network server.
Side effects None
See also "START ENGINE statement" on page 606
"–gd command-line option" on page 25
Description The STOP ENGINE statement stops the specified database server. If the
UNCONDITIONALLY keyword is supplied, the database server is stopped
even if there are connections to the server. By default, the database server
will not be stopped if there are connections to it.
Parameters STOP ENGINE clause The engine-name can be used in Interactive SQL
only. If you are not running this statement in Interactive SQL, the current
database is stopped.

UNCONDITIONALLY keyword If you are the only connection to the


database server, you do not need to use UNCONDITIONALLY. If there are
other connections, the database server stops only if you use the
UNCONDITIONALLY keyword.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not applicable.
Example ♦ Stop the current database server, as long as there are no other
connections.
STOP ENGINE

610
Chapter 9 SQL Statements

STOP JAVA statement


Function Use this statement to stop the Java VM.
Syntax STOP JAVA
Permissions None
Side effects None
See also "START JAVA statement" on page 607
Description The STOP JAVA statement unloads the Java VM when it is not in use. The
main use is to economize on the use of system resources.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not applicable.
Example ♦ Stop the Java VM.
STOP JAVA

611
STOP LOGGING statement [Interactive SQL]

STOP LOGGING statement [Interactive SQL]


Function Use this statement to stop logging of SQL statements in the current session.
Syntax STOP LOGGING
Permissions None.
Side effects None.
See also "START LOGGING statement" on page 608
Description The STOP LOGGING statement stops the database server from writing each
SQL statement you execute to a log file. You can start logging with the
START LOGGING statement. You can also start and stop logging by
clicking SQL➤Start Logging and SQL➤Stop Logging.
Example ♦ Stops the current logging session.
STOP LOGGING

612
Chapter 9 SQL Statements

SYSTEM statement [Interactive SQL]


Function Use this statement to execute an operating system command from within
Interactive SQL.
Syntax SYSTEM [ operating-system-command ]
Permissions None.
Not supported on Windows operating systems.
Side effects None.
See also "COMMIT statement" on page 408
"CONNECT statement" on page 411
Description Executes the specified operating system command. If no command is
specified, a shell is started. You can return to Interactive SQL by using the
system exit command or by pressing CTRL+D in UNIX.
♦ The SYSTEM statement must be entirely contained on one line.
♦ Comments are not allowed at the end of a SYSTEM statement.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase Not applicable.
Example ♦ The following statement executes the system command date.
SYSTEM date

613
TRIGGER EVENT statement

TRIGGER EVENT statement


Function Use this statement to trigger a named event. The event may be defined for
event triggers or be a scheduled event.
Syntax TRIGGER EVENT event-name [ ( parm = value, … ) ]
Permissions Must have DBA authority.
Side effects None.
See also "ALTER EVENT statement" on page 375
"CREATE EVENT statement" on page 423
Description Actions are tied to particular trigger conditions or schedules by a CREATE
EVENT statement. You can use the TRIGGER EVENT statement to force
the event handler to execute, even when the scheduled time or trigger
condition has not occurred. TRIGGER EVENT does not execute disabled
event handlers.
Parameters parm = value When a triggering condition causes an event handler to
execute, the database server can provide context information to the event
handler using the event_parameter function. The TRIGGER EVENT
statement allows you to explicitly supply these parameters, in order to
simulate a context for the event handler.

614
Chapter 9 SQL Statements

TRUNCATE TABLE statement


Function Use this statement to delete all rows from a table, without deleting the table
definition.
Syntax TRUNCATE TABLE [ owner.]table-name
Permissions Must be the table owner, or have DBA authority, or have ALTER
permissions on the table.
For base tables, the TRUNCATE TABLE statement requires exclusive
access to the table, as the operation is atomic (either all rows are deleted, or
none are).
For temporary tables, each user has their own copy of the data, and exclusive
access is not required.
Side effects Delete triggers are not fired by the TRUNCATE TABLE statement.
If TRUNCATE_WITH_AUTO_COMMIT is set to ON, then a COMMIT is
performed before and after the table is truncated.
Individual deletions of rows are not entered into the transaction log, so the
TRUNCATE TABLE operation is not replicated. Do not use this statement
in SQL Remote replication or on a MobiLink client database.
If the table contains a column defined as DEFAULT AUTOINCREMENT or
DEFAULT GLOBAL AUTOINCREMENT, TRUNCATE TABLE resets the
next available value for the column.
See also "DELETE statement" on page 482
"TRUNCATE_WITH_AUTO_COMMIT option" on page 202
Description The TRUNCATE TABLE statement deletes all rows from a table. It is
equivalent to a DELETE statement without a WHERE clause, except that no
triggers are fired as a result of the TRUNCATE TABLE statement and each
individual row deletion is not entered into the transaction log.
After a TRUNCATE TABLE statement, the table structure and all of the
indexes continue to exist until you issue a DROP TABLE statement. The
column definitions and constraints remain intact, and triggers and
permissions remain in effect.
The TRUNCATE TABLE statement is entered into the transaction log as a
single statement, like data definition statements. Each deleted row is not
entered into the transaction log.
If the TRUNCATE_WITH_AUTO_COMMIT option is set to ON, and all
the following criteria are satisfied, a fast form of table truncation is executed:
♦ There are no foreign keys either to or from the table.

615
TRUNCATE TABLE statement

♦ The TRUNCATE TABLE statement is not executed within a trigger.


♦ The TRUNCATE TABLE statement is not executed within an atomic
statement.
If a fast truncation is carried out, then a COMMIT is carried out before and
after the operation.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Example ♦ Delete all rows from the department table.
TRUNCATE TABLE department

616
Chapter 9 SQL Statements

UNION operation
Function Use this statement to combine the results of two or more select statements.
Syntax select-without-order-by
… UNION [ALL] select-without-order-by
… [ UNION [ALL] select-without-order-by ] …
… [ ORDER BY integer [ ASC | DESC ], … ]
Permissions Must have SELECT permission for each of the component SELECT
statements.
Side effects None.
See also "SELECT statement" on page 587
Description The results of several SELECT statements can be combined into a larger
result using UNION. The component SELECT statements must each have
the same number of items in the select list, and cannot contain an
ORDER BY clause.
The results of UNION ALL are the combined results of the component
SELECT statements. The results of UNION are the same as UNION ALL,
except that duplicate rows are eliminated. Eliminating duplicates requires
extra processing, so UNION ALL should be used instead of UNION where
possible.
If corresponding items in two select lists have different data types, Adaptive
Server Anywhere will choose a data type for the corresponding column in
the result and automatically convert the columns in each component
SELECT statement appropriately.
If ORDER BY is used, only integers are allowed in the order by list. These
integers specify the position of the columns to be sorted.
The column names displayed are the same column names that are displayed
for the first SELECT statement.
Standards and ♦ SQL/92 Entry level.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise, which also supports
a COMPUTE clause.
Examples ♦ List all distinct surnames of employees and customers.
SELECT emp_lname
FROM Employee
UNION
SELECT lname
FROM Customer

617
UNLOAD statement

UNLOAD statement
Function Use this statement to export data from a database into an external ASCII-
format file.
Syntax UNLOAD select-statement
… TO 'filename-string'
[ unload-option … ]
unload-option:
DELIMITED BY string
| ESCAPE CHARACTER character
| ESCAPES {ON | OFF}
| FORMAT {ASCII | BCP}
| HEXADECIMAL {ON | OFF}
| ORDER {ON | OFF}
| QUOTES {ON | OFF}
Permissions The permissions required to execute an UNLOAD statement are set on the
database server command line, using the –gl command-line option.
$ For more information, see "–gl command-line option" on page 27.
Side effects None. The query is executed at the current isolation level.
See also "UNLOAD TABLE statement" on page 619
"OUTPUT statement" on page 559
Description The UNLOAD statement allows the result set of a query to be exported to a
comma-delimited file. The result set is not ordered unless the query itself
contains an ORDER BY clause.
When unloading result set columns with binary data types, UNLOAD writes
hexadecimal strings, of the form \xnnnn where n is a hexadecimal digit.
$ For a description of the unload-option parameters, see "UNLOAD
TABLE statement" on page 619.
Parameters filename-string The filename to which the data is to be unloaded.
Because it is the database server that executes the statements, filenames
specify files on the database server machine. Relative filenames specify files
relative to the database server's starting directory. To unload data onto a
client machine, see "OUTPUT statement" on page 559.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase UNLOAD is not supported by Adaptive Server Enterprise.

618
Chapter 9 SQL Statements

UNLOAD TABLE statement


Function Use this statement to export data from a database table into an external
ASCII-format file.
Syntax UNLOAD [ FROM ] TABLE [ owner. ]table-name
… TO 'filename-string'
[ unload-option … ]
unload-option:
DELIMITED BY string
| ESCAPE CHARACTER character
| ESCAPES {ON | OFF}
| FORMAT {ASCII | BCP}
| HEXADECIMAL {ON | OFF}
| ORDER {ON | OFF}
| QUOTES {ON | OFF}
Permissions The permissions required to execute an UNLOAD statement are set on the
database server command line, using the –gl command-line option.
$ For more information, see "–gl command-line option" on page 27.
Side effects None.
See also "LOAD TABLE statement" on page 546
"OUTPUT statement" on page 559
"UNLOAD statement" on page 618
Description The UNLOAD TABLE statement allows efficient mass exporting from a
database table into an ASCII file. UNLOAD TABLE is more efficient than
the Interactive SQL statement OUTPUT, and can be called from any client
application.
UNLOAD TABLE places an exclusive lock on the whole table.
When unloading columns with binary data types, UNLOAD TABLE writes
hexadecimal strings, of the form \xnnnn where n is a hexadecimal digit.
For descriptions of the FORMAT, DELIMITED BY, and ESCAPE
CHARACTER options, see "LOAD TABLE statement" on page 546.
Parameters filename-string The filename to which the data is to be unloaded.
Because it is the database server that executes the statements, filenames
specify files on the database server machine. Relative filenames specify files
relative to the database server's starting directory. To unload data onto a
client machine, see "OUTPUT statement" on page 559.

ESCAPES option With ESCAPES on (the default), backslash-character


combinations are used to identify special characters where necessary on
export.

619
UNLOAD TABLE statement

FORMAT option Outputs data in either ASCII format or in BCP out


format.

HEXADECIMAL option By default, HEXADECIMAL is ON. Binary


column values are written as 0xnnnnnn…, where each n is a hexadecimal
digit. It is important to use HEXADECIMAL ON when dealing with multi-
byte character sets.

ORDER option With ORDER on (the default), the exported data is


ordered by primary key values. With ORDER off, the data is exported in the
same order you see when selecting from the table without an ORDER BY
clause.
Exporting is slower with ORDER on. However, reloading using the LOAD
TABLE statement is quicker because of the simplicity of the indexing step.

QUOTES option With QUOTES turned on (the default), single quotes are
placed around all exported strings.
Standards and ♦ SQL/92 Vendor extension.
compatibility
♦ Sybase UNLOAD TABLE is not supported by Adaptive Server
Enterprise. Similar functionality is provided by the Adaptive Server
Enterprise bulk copy utility (bcp).

620
Chapter 9 SQL Statements

UPDATE statement
Function Use this statement to modify existing rows in database tables.
Syntax 1 UPDATE [ FIRST | TOP n ] table-list
… SET set-item, …
… [ FROM table-list ]
… [ WHERE search-condition ]
… [ ORDER BY expression [ ASC | DESC ], … ]
Syntax 2 UPDATE table-list
… SET set-item, …
… [ VERIFY ( column-name, … ) VALUES ( expression, … ) ]
… [ WHERE search-condition ]
… [ ORDER BY expression [ ASC | DESC ], … ]
Syntax 3 UPDATE table
…PUBLICATION publication
…{ SUBSCRIBE BY expression
| OLD SUBSCRIBE BY expression
NEW SUBSCRIBE BY expression
}
…WHERE search-condition
set-item:
column-name [.field-name…] = expression
| column-name[.field-name…].method-name( [ expression ] )
Permissions Must have UPDATE permission for the columns being modified.
Side effects None.
See also "DELETE statement" on page 482
"INSERT statement" on page 540
"FROM clause" on page 518
"Joins: Retrieving Data from Several Tables" on page 189 of the book ASA
User’s Guide
Description Syntax 1 of the UPDATE statement modifies values in rows of one or more
tables. Syntax 2 and 3 are applicable only to SQL Remote.
Syntax 2 is intended for use with SQL Remote only, in single-row updates
executed by the Message Agent. The VERIFY clause contains a set of values
that are expected to be present in the row being updated. If the values do not
match, any RESOLVE UPDATE triggers are fired before the UPDATE
proceeds. The UPDATE does not fail simply because the VERIFY clause
fails to match.
Syntax 3 of the UPDATE statement is used to implement a specific
SQL Remote feature, and is to be used inside a BEFORE trigger.

621
UPDATE statement

It provides a full list of SUBSCRIBE BY values any time the list changes. It
is placed in SQL Remote triggers so that the database server can compute the
current list of SUBSCRIBE BY values. Both lists are placed in the
transaction log.
The Message Agent uses the two lists to make sure that the row moves to any
remote database that did not have the row and now needs it. The Message
Agent also removes the row from any remote database that has the row and
no longer needs it. A remote database that has the row and still needs it is not
be affected by the UPDATE statement.
For publications created using a subquery in a SUBSCRIBE BY clause, you
must write a trigger containing syntax 3 of the UPDATE statement in order
to ensure that the rows are kept in their proper subscriptions.
Syntax 3 of the UPDATE statement allows the old SUBSCRIBE BY list and
the new SUBSCRIBE BY list to be explicitly specified, which can make
SQL Remote triggers more efficient. In the absence of these lists, the
database server computes the old SUBSCRIBE BY list from the publication
definition. Since the new SUBSCRIBE BY list is commonly only slightly
different from the old SUBSCRIBE BY list, the work to compute the old list
may be done twice. By specifying both the old and new lists, you can avoid
this extra work.
The SUBSCRIBE BY expression is either a value or a subquery.
Syntax 3 of the UPDATE statement makes an entry in the transaction log,
but does not change the database table.
Parameters UPDATE clause The table is either a base table, a temporary table, or a
view. Views can be updated unless the SELECT statement defining the view
contains a GROUP BY clause or aggregate function, or involves a UNION
operation.

FIRST or TOP clause Primarily for use with the ORDER BY clause, this
clause allows you to update only a certain subset of the rows that satisfy the
WHERE clause.

SET clause If you are updating non-Java columns, the SET clause is of
the following form:
SET column-name = expression, ...
Each named column is set to the value of the expression on the right hand
side of the equal sign. There are no restrictions on the expression. If the
expression is a column-name, the old value is used.
If you are updating Java columns, you can use field-name to update the value
of a public field in the column. Alternatively, you can use a method to set the
value. The following clause updates name field of the JProd column using a
method:

622
Chapter 9 SQL Statements

SET JProd.setName( ’Tank Top’ )

FROM clause The optional FROM clause allows tables to be updated


based on joins. If the FROM clause is present, the WHERE clause qualifies
the rows of the FROM clause. Data is updated only in the table list of the
UPDATE clause.
If a FROM clause is used, it is important to qualify the table name the same
way in both parts of the statement. If a correlation name is used in one place,
the same correlation name must be used elsewhere. Otherwise, an error is
generated.
This clause is allowed only if ANSI_UPDATE_CONSTRAINTS is set to
OFF. See "ANSI_UPDATE_CONSTRAINTS option" on page 159.
$ For a full description of joins, see "Joins: Retrieving Data from Several
Tables" on page 189 of the book ASA User’s Guide.
$ For more information, see "FROM clause" on page 518.
WHERE clause If a WHERE clause is specified, only rows satisfying the
search condition are updated. If no WHERE clause is specified, every row is
updated.

ORDER BY clause Normally, the order in which rows are updated does
not matter. However, in conjunction with the FIRST or TOP clause the order
can be significant.
You must not update columns that appear in the ORDER BY clause unless
you set the ANSI_UPDATE_CONSTRAINTS option to OFF. See
"ANSI_UPDATE_CONSTRAINTS option" on page 159.

Case sensitivity Character strings inserted into tables are always stored in
the same case as they are entered, regardless of whether the database is case
sensitive or not. A CHAR data type column updated with a string Value is
always held in the database with an upper case V and the remainder of the
letters lower case. SELECT statements return the string as Value. If the
database is not case sensitive, however, all comparisons make Value the
same as value, VALUE, and so on. Further, if a single-column primary key
already contains an entry Value, an INSERT of value is rejected, as it would
make the primary key not unique.

Updates that leave a row unchanged If the new value does not differ
from the old value, no change is made to the data. However, BEFORE
UPDATE triggers fire any time an UPDATE occurs on a row, whether or not
the new value differs from the old value. AFTER UPDATE triggers fire only
if the new value is different from the old value.

623
UPDATE statement

Standards and ♦ SQL/92 Syntax 1 is an entry-level feature, except for the FROM and
compatibility ORDER BY clauses, which are vendor extensions. Syntax 2 and 3 are
vendor extensions for use only with SQL Remote.
To enforce SQL/92 compatibility, ensure that the
ANSI_UPDATE_CONSTRAINTS option is set to STRICT.
$ For more information, see "ANSI_UPDATE_CONSTRAINTS
option" on page 159.
♦ Sybase Subject to the expressions being compatible, the syntax of the
UPDATE statement (syntax 1) is compatible between Adaptive Server
Enterprise and Adaptive Server Anywhere. Syntax 2 and 3 are not
supported.
Examples ♦ Transfer employee Philip Chin (employee 129) from the sales
department to the marketing department.
UPDATE employee
SET dept_id = 400
WHERE emp_id = 129;
♦ Sales orders currently start at ID 2001. Renumber all existing sales
orders by subtracting 2000 from the ID.
UPDATE sales_order AS orders
SET orders.id = orders.id - 2000
ORDER BY items.id ASC
This update is possible only if the foreign key of the sales_order_items
table (referencing the primary key sales_order.id) is defined with the
action ON UPDATE CASCADE. The sales_order_items table is then
updated as well.
$ For more information on foreign key properties, see "ALTER
TABLE statement" on page 380 and "CREATE TABLE statement" on
page 453.

624
Chapter 9 SQL Statements

UPDATE (positioned) statement


Function Use this statement to modify the data at the current location of a cursor.
Syntax 1 UPDATE WHERE CURRENT OF cursor-name
… { USING DESCRIPTOR sqlda-name | FROM host-variable-list }
Syntax 2 UPDATE table-list
… SET set-item, …
… WHERE CURRENT OF cursor-name
host-variable-list:
indicator variables allowed
set-item:
column-name [.field-name…] = expression
| column-name[.field-name…].method-name( [ expression ] )
sqlda-name:
identifier
Permissions Must have UPDATE permission on the columns being modified.
Side effects None.
See also "DELETE statement" on page 482
"DELETE (positioned) statement" on page 484
"UPDATE statement" on page 621
Description This form of the UPDATE statement updates the current row of the specified
cursor. The current row is defined to be the last row successfully fetched
from the cursor, and the last operation on the cursor must not have been a
positioned DELETE statement.
For syntax 1, columns from the SQLDA or values from the host variable list
correspond one-to-one with the columns returned from the specified cursor.
If the sqldata pointer in the SQLDA is the null pointer, the corresponding
select list item is not updated.
In syntax 2, the requested columns are set to the specified values for the row
at the current row of the specified query. The columns do not need to be in
the select list of the specified open cursor. This format can be prepared.
The USING DESCRIPTOR, FROM host-variable-list, and host-variable
formats are for embedded SQL only.
Standards and ♦ SQL/92 Entry level feature. The range of cursors that can be updated
compatibility may contain vendor extensions if the ANSI_UPDATE_CONSTRAINTS
option is set to OFF.

625
UPDATE (positioned) statement

♦ Sybase Embedded SQL use is supported by Open Client/Open Server,


and procedure and trigger use is supported in Adaptive Server
Anywhere.
Example ♦ The following is an example of an UPDATE statement
WHERE CURRENT OF cursor:
UPDATE Employee
SET emp_lname = ’Jones’
WHERE CURRENT OF emp_cursor;

626
Chapter 9 SQL Statements

VALIDATE INDEX statement


Function Use this statement to validate an index.
Syntax VALIDATE INDEX [ [ owner.]table-name.]{index-name | table-name }
Permissions Must be the owner of the table on which the index is created, have DBA
authority, or have REMOTE DBA authority (SQL Remote).
Side effects None.
See also "CREATE INDEX statement" on page 435
"VALIDATE TABLE statement" on page 628
"The Validation utility" on page 136
Description Ensures that every row referenced in the index actually exists in the table.
For foreign key indexes, it also ensures that the corresponding row exists in
the primary table, and that their hash values match. This check complements
the validity checking carried out by the VALIDATE TABLE statement.

index-name | table-name If you supply a table-name instead of an index-


name, the primary key index is validated.

627
VALIDATE TABLE statement

VALIDATE TABLE statement


Function Use this statement to validate a table in the database.
Syntax VALIDATE TABLE [ owner.]table-name
[ WITH { DATA | FULL | INDEX } CHECK ]
Permissions Must be the owner of the table, have DBA authority, or have REMOTE DBA
authority (SQL Remote).
Side effects None.
See also "The Validation utility" on page 136
"VALIDATE INDEX statement" on page 627
"sa_validate system procedure" on page 945
Description With no additional options, VALIDATE TABLE scans every row of a table.
For each entry that is in an index, it checks the validity of the database page
that the entry starts on, and checks that an entry for the row exists in the
proper index. The VALIDATE TABLE statement also ensures, for each
index in the table, that the number of rows referenced by the index is not
greater than the number of rows in the table.
This default validation is sufficient for most purposes. Options are provided
for additional validation, which may be helpful in unusual circumstances.
Depending on the contents of your database, these additional checks may
significantly extend the time required to validate.
If the table is corrupt, an error is reported. If you do have errors reported, you
can drop all of the indexes and keys on a table and recreate them. Any
foreign keys to the table will also need to be recreated. Another solution to
errors reported by VALIDATE TABLE is to unload and reload your entire
database. You should use the -u option of DBUNLOAD so that it will not
try to use a possibly corrupt index to order the data.
Parameters WITH DATA CHECK If you have LONG BINARY, LONG VARCHAR,
TEXT, or IMAGE entries, they may span more than one database page. In
addition to the default checks, this option instructs the database server to
check all pages used by each entry.

WITH FULL CHECK In addition to the default checks, carry out a DATA
CHECK and an INDEX CHECK.

WITH INDEX CHECK In addition to the default checks, validate each


index on the table. For information on index validation, see "VALIDATE
INDEX statement" on page 627.
Standards and ♦ SQL/92 Vendor extension
compatibility

628
Chapter 9 SQL Statements

♦ Sybase VALIDATE TABLE is not supported in Adaptive Server


Enterprise. The procedure dbcc checktable provides a similar function.

629
WHENEVER statement [ESQL]

WHENEVER statement [ESQL]


Function Use this statement to specify error handling in embedded SQL programs.
Syntax WHENEVER { SQLERROR | SQLWARNING | NOTFOUND }
… GOTO label | STOP | CONTINUE | { C code; }
label: identifier
Permissions None.
Side effects None.
Description The WHENEVER statement is used to trap errors, warnings and exceptional
conditions encountered by the database when processing SQL statements.
The statement can be put anywhere in an embedded SQL program and does
not generate any code. The preprocessor will generate code following each
successive SQL statement. The error action remains in effect for all
embedded SQL statements from the source line of the WHENEVER
statement until the next WHENEVER statement with the same error
condition, or the end of the source file.

Errors based on source position


The error conditions are in effect based on positioning in the C language
source file, not based on when the statements are executed.

The default action is CONTINUE.


Note that this statement is provided for convenience in simple programs.
Most of the time, checking the sqlcode field of the SQLCA (SQLCODE)
directly is the easiest way to check error conditions. In this case, the
WHENEVER statement would not be used. If fact, all the WHENEVER
statement does is cause the preprocessor to generate an if ( SQLCODE ) test
after each statement.
Standards and ♦ SQL/92 Entry-level feature.
compatibility
♦ Sybase Supported by Open Client/Open Server.
Examples ♦ The following are examples of the WHENEVER statement:
EXEC SQL WHENEVER NOTFOUND GOTO done;
EXEC SQL WHENEVER SQLERROR
{
PrintError( &sqlca );
return( FALSE );
};

630
Chapter 9 SQL Statements

WHILE statement [T-SQL]


Function Use this statement to provide repeated execution of a statement or compound
statement.
Syntax WHILE search-condition
… statement
Permissions None.
Side effects None.
See also "LOOP statement" on page 553
Description The WHILE conditional affects the execution of only a single SQL
statement, unless statements are grouped into a compound statement between
the keywords BEGIN and END.
The BREAK statement and CONTINUE statement can be used to control
execution of the statements in the compound statement. The BREAK
statement terminates the loop, and execution resumes after the END keyword
marking the end of the loop. The CONTINUE statement causes the WHILE
loop to restart, skipping any statements after the CONTINUE.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Example ♦ The following code illustrates the use of WHILE:
WHILE (SELECT AVG(unit_price) FROM product) < $30
BEGIN
UPDATE product
SET unit_price = unit_price + 2
IF ( SELECT MAX(unit_price) FROM product ) > $50
BREAK
END
The BREAK statement breaks the WHILE loop if the most expensive
product has a price above $50. Otherwise, the loop continues until the
average price is greater than or equal to $30.

631
WRITETEXT statement [T-SQL]

WRITETEXT statement [T-SQL]


Function Permits non-logged, interactive updating of an existing text or image
column.
Syntax WRITETEXT table-name.column-name
…text_pointer [ WITH LOG ] data
Permissions None.
Side effects WRITETEXT does not fire triggers, and by default WRITETEXT operations
are not recorded in the transaction log.
See also "READTEXT statement" on page 573
"TEXTPTR function" on page 359
Description Updates an existing text or image value. The update is not recorded in the
transaction log, unless the WITH LOG option is supplied. You cannot carry
out WRITETEXT operations on views.
Standards and ♦ SQL/92 Transact-SQL extension.
compatibility
♦ Sybase Supported by Adaptive Server Enterprise.
Example ♦ The following code fragment illustrates the use of the WRITETEXT
statement. The SELECT statement in this example returns a single row.
The example replaces the contents of the column_name column on the
specified row with the value newdata.
EXEC SQL create variable textpointer binary(16);
EXEC SQL set textpointer =
( SELECT textptr(column_name)
SELECT table_name SELECT id = 5 );
EXEC SQL writetext table_name.column_name
textpointer ’newdata’;

632
C H A P T E R 1 0

Database Error Messages

About this chapter This chapter lists all database error messages reported by Adaptive Server
Anywhere. Many of the errors contain the characters %1, %2 and so on.
These are replaced by the parameters to the error message.
Each error has a numeric error code, called the SQLCODE. Negative codes
are considered errors; positive codes are warnings. The SQLCODE 0
indicates successful completion.
The full listing of the error messages is ordered by SQLCODE value. To find
an error message description if you do not have the SQLCODE value, look
up the SQLCODE in the alphabetic or SQLSTATE listing.
Contents
Topic Page
Error messages indexed by Adaptive Server Anywhere SQLCODE 634
Error messages indexed by SQLSTATE 652
Error messages indexed by Sybase error code 670
Alphabetic list of error messages 693
Internal errors (assertion failed) 904

633
Error messages indexed by Adaptive Server Anywhere SQLCODE

Error messages indexed by Adaptive Server


Anywhere SQLCODE
Adaptive Error message
Server
Anywhere
SQLCODE
-823 "OMNI cannot handle expressions involving remote tables
inside stored procedures" on page 818
-822 "Table %1 is already included" on page 856
-821 "Dbspace for table ’%1’ not found" on page 758
-820 "Invalid scroll position ’%1’" on page 794
-819 "Table ’%1’ is part of a synchronization definition" on page 858
-818 "The external function call is incompatible" on page 865
-817 "too many temporary tables in connection" on page 877
-816 "Specified database file already in use." on page 844
-815 "Cannot update column ’%1’ since it does not appear in the
SELECT clause." on page 730
-814 "Cannot update column ’%1’ since it appears in the ORDER BY
clause." on page 730
-813 "FOR UPDATE has been incorrectly specified for a READ
ONLY cursor." on page 769
-812 "The Select list for the derived table ’%1’ has no expression to
match %2" on page 870
-811 "Jar %1 not found" on page 801
-810 "Java classes %1 not found" on page 801
-809 "Synchronization option is too long" on page 853
-808 "An internal error was generated by the test harness" on
page 703
-807 "Host variables may not be used within a batch" on page 772
-806 "System event type ’%1’ not found" on page 855
-805 "Synchronization option ’%1’ not found" on page 852
-804 "Unable to reenlist transaction; DTC may be down" on page 883
-803 "Unable to enlist transaction; DTC may be down" on page 882
-802 "Cannot enlist in a transaction with uncommitted data pending"
on page 717

634
CHAPTER 10 Database Error Messages

Adaptive Error message


Server
Anywhere
SQLCODE
-801 "Cannot enlist in a transaction while already enlisted in a
transaction" on page 717
-800 "Cannot commit or rollback while enlisted in a transaction" on
page 710
-799 "DTC transactions are not supported on this platform" on
page 761
-797 "Synchronization option ’%1’ contains semi-colon or equal sign"
on page 852
-796 "Synchronization site ’%1’ is already defined" on page 854
-795 "Undefined synchronization template ’%1’" on page 885
-794 "Synchronization server failed to commit the upload" on
page 853
-793 "Invalid start date/time for event ’%1’" on page 796
-792 "Invalid time ’%1’ for event ’%2’" on page 797
-791 "Invalid day of week or month ’%1’ for event ’%2’" on page 785
-790 "Cannot register connection to ’%1’ since automatic label
exhausted" on page 725
-789 "Cannot register ’%1’ since registration cookie exhausted" on
page 723
-788 "Another connection has already registered as ’%1’" on page 703
-787 "Current connection is already registered to ’%1’ as ’%2’" on
page 747
-786 "Cannot deregister ’%1’ since active registered connection
exists" on page 713
-785 "Cannot deregister application because of invalid cookie" on
page 714
-784 "Cannot register connection because of invalid application
cookie" on page 724
-783 "Cannot register another ’%1’ as an exclusive application" on
page 724
-782 "Cannot register %1’ since another exclusive instance is
running" on page 723
-781 "Cannot update primary key for table ’%1’ involved in
replication" on page 732
-780 "Cannot update primary key for table ’%1’ involved in

635
Error messages indexed by Adaptive Server Anywhere SQLCODE

Adaptive Error message


Server
Anywhere
SQLCODE
synchronization" on page 732
-779 "Cannot create synchronization entry for table ’%1’ with BLOB
primary key" on page 712
-778 "Must include primary key for table ’%1’ in the synchronization"
on page 809
-777 "Cannot synchronize table ’%1’ since it does not have a primary
key" on page 728
-774 "Schedule ’%1’ for event ’%2’ already exists" on page 839
-773 "Schedule ’%1’ for event ’%2’ not found" on page 840
-772 "Event ’%1’ already exists" on page 766
-771 "Event ’%1’ not found" on page 766
-770 "Cannot modify publication entry using ALTER
SYNCHRONIZATION" on page 721
-769 "Cannot modify synchronization entry using ALTER
PUBLICATION" on page 721
-768 "Cannot subscribe to ’%1’" on page 727
-767 "Cannot not find synchronization %1 with name equal ’%2’" on
page 722
-766 "View references ’%1’, which is a temporary object. Views can
only refer to permanent objects." on page 900
-765 "Synchronization message type ’%1’ not found" on page 851
-764 "Server not found and unable to autostart" on page 843
-763 "’%1’ is not a public java reference, and cannot be referenced
from SQL" on page 697
-762 "’%1’ is not a public java class, and cannot be referenced from
SQL" on page 697
-761 "Server capability name %1 could not be found in the
SYSCAPABILITYNAME table." on page 842
-760 "Invalid SQL identifier" on page 795
-759 "SQLDA data type invalid" on page 845
-758 "The database does not support the Java virtual machine" on
page 864
-757 "Modifications not permitted for read-only database" on
page 807

636
CHAPTER 10 Database Error Messages

Adaptive Error message


Server
Anywhere
SQLCODE
-756 "Cannot uniquely identify column ’%2’ of table ’%1’ in the
current jdbc resultset" on page 728
-755 "You cannot synchronize with uncommitted transactions" on
page 903
-754 "Parse error: %1 ’%2’" on page 821
-753 "The JDBC resultset must be positioned on an insert row in
order to use the ’%1’ function" on page 866
-752 "Cannot call the ’%1’ function on a JDBC resultset when it is
positioned on an insert row" on page 710
-751 "User owns tables in use" on page 895
-750 "User owns procedures in use" on page 895
-749 "Feature not available with UltraLite" on page 768
-748 "Invalid JDBC resultset concurrency" on page 789
-747 "Invalid JDBC resultset type" on page 789
-746 "Cannot allocate System V resources" on page 709
-745 "Cannot initialize IQ memory manager: %1" on page 718
-744 "Invalid IQ database command line option or parameter value:
%1" on page 788
-743 "Seek absolute 0 was attempted on a JDBC SAResultSet" on
page 840
-742 "JDBC SAStatement batch execute abandoned" on page 803
-741 "’%1’ is not a write file for ’%2’" on page 698
-740 "The streams environment could not be created" on page 873
-739 "db_init has not been called or the call to db_init failed" on
page 757
-738 "Password must be at least %1 characters" on page 822
-737 "Signature ’%1’ does not match procedure parameters" on
page 843
-736 "The data type of column ’%1’ is not supported" on page 863
-735 "Invalid parameter" on page 792
-734 "Cannot update or delete an all-NULL row from table ’%1’" on
page 731
-733 "Number of columns allowing NULLs exceeds limit" on

637
Error messages indexed by Adaptive Server Anywhere SQLCODE

Adaptive Error message


Server
Anywhere
SQLCODE
page 817
-732 "Creating remote tables with computed columns is not
supported" on page 746
-731 "Cannot drop a user that owns objects involved in replication"
on page 715
-730 "Invalid jar file" on page 789
-729 "The specified foreign key (%1) can not be enforced" on
page 872
-728 "Update operation attempted on non-updatable remote query"
on page 890
-727 "The optimizer was unable to construct a valid access plan" on
page 867
-726 "The table specification ’%1’ identifies more than one remote
table" on page 873
-725 "Identity attribute mismatch for column ’%1’" on page 773
-724 "Null attribute mismatch for column ’%1’" on page 815
-723 "The length specified for column ’%1’ is different than the actual
length" on page 866
-722 "The column ’%1’ does not exist in the remote table" on
page 862
-721 "The data type specified for column ’%1’ is not compatible with
the actual data type" on page 864
-720 "VALIDATE TABLE statement must refer to a base table" on
page 897
-719 "RESTORE unable to start database ’%1’" on page 833
-718 "RESTORE unable to write to file ’%1’" on page 833
-717 "RESTORE unable to open file ’%1’" on page 832
-716 "Backup file format is invalid" on page 706
-715 "Contents of backup files are inconsistent" on page 741
-714 "Invalid operation on a closed ’%1’" on page 791
-713 "An internal error occurred in a ’%1’" on page 702
-712 "External login for server %1 could not be found" on page 767
-711 "Incorrect store DLL (%1) version." on page 775

638
CHAPTER 10 Database Error Messages

Adaptive Error message


Server
Anywhere
SQLCODE
-710 "Invalid comparison" on page 782
-709 "Computed columns are not supported in this database" on
page 739
-708 "READTEXT or WRITETEXT statement cannot refer to a
view" on page 828
-707 "Statement is not allowed in passthrough mode" on page 848
-706 "Remote server does not have the ability to support this
statement" on page 830
-705 "Return type of void from procedure ’%1’ cannot be used in any
expression" on page 834
-704 "Cannot create an index on Java class ’%1’" on page 711
-703 "Cannot insert or update computed column ’%1’" on page 719
-702 "TRUNCATE TABLE statement cannot refer to a view" on
page 880
-701 "Cannot access instance member through a class" on page 708
-700 "SQLDA fields inconsistent for a multi-row SQLDA" on
page 846
-699 "Cannot update member fields qualified with "final" modifier"
on page 731
-698 "The remote server does not support an auto-incrementing data
type" on page 869
-697 "Error during backup: %1" on page 763
-696 "Invalid operation on a closed ’%1’" on page 791
-695 "An internal error occurred in a ’%1’" on page 702
-694 "Could not change an opened prepared statement or callable
statement" on page 743
-693 "JDBC feature ’%1’ not supported" on page 803
-692 "Could not execute backup/restore DLL (%1) entry point." on
page 744
-691 "Could not load the backup/restore DLL %1" on page 746
-690 "Return value cannot be set" on page 835
-689 "Input parameter index out of range" on page 778
-687 "Syntax error, cannot specify IQ specific options without

639
Error messages indexed by Adaptive Server Anywhere SQLCODE

Adaptive Error message


Server
Anywhere
SQLCODE
specifying IQ PATH" on page 855
-686 "Cannot make a static reference to nonstatic variable ’%1’ in
class ’%2’" on page 719
-685 "Resource governor for %1 exceeded" on page 832
-684 "Rollback occurred due to deadlock during prefetch" on
page 835
-683 "The cursor name ’%1’ already exists" on page 863
-682 "%1" on page 695
-681 "Invalid join type used with Transact-SQL outer join" on
page 790
-680 "Invalid expression in WHERE clause of Transact-SQL outer
join" on page 787
-679 "Not enough memory is allocated to the Java virtual machine
for remote access" on page 814
-678 "Index name ’%1’ is ambiguous" on page 776
-677 "Table ’%1’ has a foreign key with a referential action" on
page 856
-676 "The specified transaction isolation is invalid" on page 872
-675 "Java virtual machine could not be started" on page 802
-674 "statement’s size limit is invalid." on page 849
-673 "Database upgrade not possible" on page 757
-672 "Database upgrade failed" on page 756
-671 "Parameter not registered as output parameter" on page 821
-670 "Invalid class byte code" on page 781
-669 "Method ’%1’ cannot be called at this time" on page 806
-668 "Cursor is restricted to FETCH NEXT operations" on page 748
-667 "Could not access column information for the table ’%1’" on
page 742
-666 "The remote table ’%1’ could not be found" on page 870
-665 "Database %1 needs recovery" on page 750
-664 "Database is active" on page 752
-663 "Cannot deserialize Java object" on page 714

640
CHAPTER 10 Database Error Messages

Adaptive Error message


Server
Anywhere
SQLCODE
-662 "Cannot serialize Java object with class %1" on page 726
-661 "Backwards scrolling cursors are not supported for remote
objects" on page 706
-660 "Server %1: %2" on page 842
-659 "Remote server %1 could not be found; Add the server using
CREATE SERVER" on page 829
-658 "Remote server %1 is currently configured as read only" on
page 829
-656 "Unable to connect to server ’%1’: %2" on page 881
-655 "Error parsing connection parameter string" on page 765
-654 "The connection parameters file could not be found" on
page 862
-653 "Cannot remove class ’%1’: member of Jar" on page 725
-652 "Could not decompress class ’%1’ from Jar." on page 743
-651 "An attempt to delete database ’%1’ failed" on page 701
-650 "Index type specification of ’%1’ is invalid" on page 777
-649 "Field ’%1’ of class ’%2’ cannot be null" on page 769
-648 "Cannot create item (%1) in the specified dbspace." on page 712
-647 "Could not execute store DLL (%1) entry point." on page 744
-646 "Could not load the store DLL %1" on page 746
-645 "Database creation failed" on page 752
-644 "Invalid database page size" on page 784
-643 "UNLOAD TABLE cannot be used to unload a view" on
page 886
-642 "Invalid SQL descriptor name" on page 795
-641 "Error in assignment" on page 763
-640 "Invalid descriptor index" on page 785
-639 "Parameter name missing in call to procedure ’%1’" on page 820
-638 "Right truncation of string data" on page 835
-637 "Duplicate insert column" on page 761
-636 "Duplicate referencing column" on page 762

641
Error messages indexed by Adaptive Server Anywhere SQLCODE

Adaptive Error message


Server
Anywhere
SQLCODE
-635 "GRANT of column permission on view not allowed" on
page 772
-634 "Unterminated C string" on page 888
-633 "Update operation attempted on a read-only cursor" on page 889
-632 "WITH CHECK OPTION violated for insert/update on base
table ’%1’" on page 901
-631 "RAISERROR executed: %1" on page 827
-630 "Invalid escape sequence ’%1’" on page 786
-629 "Invalid escape character ’%1’" on page 786
-628 "Division by zero" on page 761
-627 "Disallowed language extension detected in syntax near ’%1’"
on page 760
-626 "A thread used internally could not be started" on page 700
-625 "Too many parameters to this external procedure call" on
page 876
-624 "Expression has unsupported data type" on page 767
-623 "Data definition statements not allowed in procedures or
triggers" on page 750
-622 "Could not allocate resources to call external function" on
page 742
-621 "Could not find ’%1’ in dynamic library ’%2’" on page 745
-620 "Could not load dynamic library ’%1’" on page 745
-619 "Need a dynamic library name" on page 810
-618 "Mismatch between external function platform specifier and
current operating system" on page 806
-617 "Calling functions outside the database server is not supported"
on page 707
-616 "Too many columns in table" on page 876
-615 "Parameter ’%1’ not found in procedure ’%2’" on page 820
-614 "Cannot drop a user that owns messages or data types" on
page 715
-613 "User-defined type %1 not found" on page 896
-612 "User message %1 not found" on page 894

642
CHAPTER 10 Database Error Messages

Adaptive Error message


Server
Anywhere
SQLCODE
-611 "Transact-SQL feature not supported" on page 877
-610 "User message %1 already exists" on page 894
-609 "Invalid data type for column in WRITETEXT or READTEXT"
on page 783
-608 "Invalid TEXTPTR value used with WRITETEXT or
READTEXT" on page 797
-607 "Cannot stop the database server" on page 727
-606 "The pattern is too long" on page 869
-605 "The server attempted to access a page beyond the end of the
maximum allowable dbspace file size" on page 871
-604 "A dbspace has reached its maximum file size" on page 699
-602 "Cannot access file ’%1’ -- %2" on page 708
-601 "’%1’ is not a known file format for loading or unloading tables"
on page 696
-504 "(no message)" on page 694
-503 "(no message)" on page 693
-313 "The login ID ’%1’ has not been mapped to any database user
ID" on page 867
-312 "User ’%1’ already has membership in group ’%2’" on page 891
-311 "Internal rollback log corrupted" on page 781
-310 "Attempt to read beyond end-of-file in a compressed database"
on page 704
-309 "Memory error -- transaction rolled back" on page 805
-308 "Connection was terminated" on page 740
-307 "All threads are blocked" on page 700
-306 "Deadlock detected" on page 759
-305 "I/O error %1 -- transaction rolled back" on page 772
-304 "Disk full ’%1’ -- transaction rolled back" on page 760
-302 "Terminated by user -- transaction rolled back" on page 861
-301 "Internal database error %1 -- transaction rolled back" on
page 780
-300 "Run time SQL error -- %1" on page 838

643
Error messages indexed by Adaptive Server Anywhere SQLCODE

Adaptive Error message


Server
Anywhere
SQLCODE
-299 "Statement interrupted by user" on page 848
-298 "Attempted two active database requests" on page 705
-297 "User-defined exception signaled" on page 896
-296 "Error number %1 for RAISERROR is less than 17000" on
page 764
-295 "Cannot uniquely identify rows in cursor" on page 729
-294 "Format string argument number %1 is invalid" on page 771
-289 "A consolidated user already exists" on page 699
-288 "Remote statement failed" on page 830
-287 "Passthrough statement inconsistent with current passthrough"
on page 822
-286 "Remote message type ’%1’ not found" on page 828
-285 "User ’%1’ is not a remote user for this database" on page 892
-284 "User ’%1’ is already the publisher for this database" on
page 892
-283 "Subscription to ’%1’ for ’%2’ not found" on page 851
-282 "Subscription to ’%1’ for ’%2’ already exists" on page 850
-281 "Table ’%1’ has publications" on page 857
-280 "Publication ’%1’ not found" on page 827
-275 "Triggers and procedures not supported in runtime server" on
page 880
-274 "Procedure or trigger calls have nested too deeply" on page 826
-273 "COMMIT/ROLLBACK not allowed within trigger actions" on
page 738
-272 "Invalid REFERENCES clause in trigger definition" on
page 793
-271 "Trigger definition conflicts with existing triggers" on page 879
-270 "Cannot drop a user that owns procedures in runtime server" on
page 716
-269 "Cannot delete a column referenced in a trigger definition" on
page 713
-268 "Trigger ’%1’ not found" on page 879

644
CHAPTER 10 Database Error Messages

Adaptive Error message


Server
Anywhere
SQLCODE
-267 "COMMIT/ROLLBACK not allowed within atomic operation"
on page 737
-266 "%1" on page 695
-265 "Procedure ’%1’ not found" on page 824
-264 "Wrong number of variables in FETCH" on page 902
-263 "Invalid absolute or relative offset in FETCH" on page 781
-262 "Label ’%1’ not found" on page 804
-261 "There is already a variable named ’%1’" on page 874
-260 "Variable ’%1’ not found" on page 899
-251 "Foreign key ’%1’ for table ’%2’ duplicates an existing foreign
key" on page 770
-250 "Identifier ’%1’ too long" on page 773
-249 "The login ID ’%1’ is already mapped to user ID ’%2’" on
page 867
-248 "Cannot map a login ID to the sys or public user ID" on
page 720
-247 "The integrated login ID guest can only be mapped to the guest
database user ID" on page 865
-246 "Integrated logins are not supported for this database" on
page 780
-245 "Integrated login failed" on page 779
-244 "Transaction log was truncated" on page 878
-243 "Unable to delete database file" on page 881
-242 "Incomplete transactions prevent transaction log renaming" on
page 775
-241 "Database backup not started" on page 751
-240 "Unknown backup operation" on page 885
-231 "Client/database server version mismatch" on page 734
-230 "Sqlpp/dblib version mismatch" on page 846
-222 "Result set not allowed from within an atomic compound
statement" on page 834
-221 "ROLLBACK TO SAVEPOINT not allowed" on page 836

645
Error messages indexed by Adaptive Server Anywhere SQLCODE

Adaptive Error message


Server
Anywhere
SQLCODE
-220 "Savepoint ’%1’ not found" on page 838
-218 "Authentication failed" on page 705
-217 "The option %1 cannot be set from within a procedure" on
page 868
-216 "The option %1 can only be set as a temporary option" on
page 868
-215 "Procedure in use" on page 826
-214 "Table in use" on page 860
-213 "Savepoints require a rollback log" on page 839
-212 "CHECKPOINT statement requires a rollback log" on page 733
-211 "Not allowed while %1 is using the database" on page 812
-210 "User ’%1’ has the row in ’%2’ locked" on page 891
-209 "Invalid value for column ’%1’ in table ’%2’" on page 800
-208 "Row has changed since last read -- operation cancelled" on
page 837
-207 "Wrong number of values for INSERT" on page 902
-206 "Standard logons are not permitted" on page 847
-205 "Integrated logins are not permitted" on page 779
-204 "Only the DBA can set the option %1" on page 819
-203 "Cannot set a temporary option for user ’%1’" on page 726
-202 "Only PUBLIC settings are allowed for option ’%1’" on
page 818
-201 "Invalid setting for option ’%1’" on page 794
-200 "Invalid option ’%1’ -- no PUBLIC setting exists" on page 792
-199 "INSERT/DELETE on cursor can modify only one table" on
page 778
-198 "Primary key for row in table ’%1’ is referenced in another
table" on page 823
-197 "No current row of cursor" on page 810
-196 "Index ’%1’ for table ’%2’ would not be unique" on page 776
-195 "Column ’%1’ in table ’%2’ cannot be NULL" on page 736
-194 "No primary key value for foreign key ’%1’ in table ’%2’" on

646
CHAPTER 10 Database Error Messages

Adaptive Error message


Server
Anywhere
SQLCODE
page 812
-193 "Primary key for table ’%1’ is not unique" on page 824
-192 "Update operation attempted on non-updatable query" on
page 889
-191 "Cannot modify column ’%1’ in table ’%2’" on page 720
-190 "Cannot update an expression" on page 729
-189 "Unable to find in index ’%1’ for table ’%2’" on page 882
-188 "Not enough values for host variables" on page 815
-187 "Illegal cursor operation attempt" on page 774
-186 "Subquery cannot return more than one row" on page 850
-185 "SELECT returns more than one row" on page 841
-183 "Cannot find index named ’%1’" on page 718
-182 "Not enough fields allocated in SQLDA" on page 813
-181 "No indicator variable provided for NULL result" on page 811
-180 "Cursor not open" on page 749
-172 "Cursor already open" on page 747
-171 "Error opening cursor" on page 764
-170 "Cursor has not been declared" on page 748
-165 "Java VM Heap Exhausted at Internal fn: %1" on page 802
-164 "Namespace Heap Exhausted at Internal fn: %1" on page 809
-163 "Derived table ’%1’ has no name for column %2" on page 759
-161 "Invalid type on DESCRIBE statement" on page 798
-160 "Can only describe a SELECT statement" on page 707
-159 "Invalid column number" on page 782
-158 "Value %1 out of range for destination" on page 898
-157 "Cannot convert %1 to a %2" on page 711
-156 "Invalid expression near ’%1’" on page 787
-155 "Invalid host variable" on page 788
-154 "Wrong number of parameters to function ’%1’" on page 901
-153 "SELECT lists in UNION do not match in length" on page 841

647
Error messages indexed by Adaptive Server Anywhere SQLCODE

Adaptive Error message


Server
Anywhere
SQLCODE
-152 "Number in ORDER BY is too large" on page 816
-151 "Subquery allowed only one select list item" on page 849
-150 "Aggregate functions not allowed on this statement" on
page 700
-149 "Function or column reference to ’%1’ in the select list must also
appear in a GROUP BY" on page 771
-148 "Unknown function ’%1’" on page 886
-147 "There is more than one way to join ’%1’ to ’%2’" on page 875
-146 "There is no way to join ’%1’ to ’%2’" on page 875
-145 "Foreign key name ’%1’ not found" on page 770
-144 "Column ’%1’ found in more than one table -- need a correlation
name" on page 736
-143 "Column ’%1’ not found" on page 737
-142 "Correlation name ’%1’ not found" on page 741
-141 "Table ’%1’ not found" on page 859
-140 "User ID ’%1’ does not exist" on page 893
-139 "More than one table is identified as ’%1’" on page 808
-138 "Dbspace ’%1’ not found" on page 758
-137 "Table ’%1’ requires a unique correlation name" on page 859
-136 "Table ’%1’ is in an outer join cycle" on page 858
-135 "Language extension" on page 804
-134 "Feature ’%1’ not implemented" on page 768
-133 "Invalid prepared statement type" on page 793
-132 "SQL statement error" on page 845
-131 "Syntax error near ’%1’" on page 854
-130 "Invalid statement" on page 796
-128 "Cannot drop a user that owns tables in runtime system" on
page 716
-127 "Cannot alter a column in an index" on page 709
-126 "Table cannot have two primary keys" on page 860
-125 "ALTER clause conflict" on page 701

648
CHAPTER 10 Database Error Messages

Adaptive Error message


Server
Anywhere
SQLCODE
-124 "More columns are being dropped from table %1 than are
defined" on page 807
-123 "User ’%1’ is not a user group" on page 893
-122 "Operation would cause a group cycle" on page 819
-121 "%1" on page 694
-120 "User ’%1’ already has GRANT permission" on page 890
-119 "Primary key column ’%1’ already defined" on page 823
-118 "Table ’%1’ has no primary key" on page 857
-116 "Table must be empty" on page 861
-114 "Number of columns defined for the view does not match
SELECT statement" on page 817
-113 "Column %1 in foreign key has a different definition than
primary key" on page 735
-112 "Table already has a primary key" on page 860
-111 "Index name ’%1’ not unique" on page 777
-110 "Item ’%1’ already exists" on page 800
-109 "There are still active database connections" on page 874
-108 "Connection not found" on page 739
-107 "Error writing to transaction log file" on page 765
-106 "Cannot open transaction log file -- %1" on page 722
-105 "Database cannot be started -- %1" on page 751
-104 "Invalid user ID or password on preprocessed module" on
page 799
-103 "Invalid user ID or password" on page 799
-103 "Invalid user ID or password" on page 799
-102 "Database server connection limit exceeded" on page 755
-101 "Not connected to a database" on page 813
-100 "Database server not running" on page 755
-99 "Connections to database have been disabled" on page 740
-98 "Authentication violation" on page 706
-97 "Database page size too big" on page 754

649
Error messages indexed by Adaptive Server Anywhere SQLCODE

Adaptive Error message


Server
Anywhere
SQLCODE
-96 "Database server already running" on page 754
-95 "Parse error: %1 near ’%2’" on page 821
-94 "Invalid type for field reference" on page 798
-93 "Class ’%1’ has no public field ’%2’" on page 734
-92 "’%1’ is not a valid class file" on page 698
-91 "Procedure ’%1’ terminated with unhandled exception ’%2’" on
page 825
-90 "Argument %1 of procedure ’%2’ cannot be null" on page 704
-89 "Database server not running in multi-user mode" on page 756
-88 "Client/server communications protocol version mismatch" on
page 735
-87 "Database name required to start server" on page 753
-86 "Not enough memory to start" on page 814
-85 "Communication error" on page 738
-84 "Specified database is invalid" on page 844
-83 "Specified database not found" on page 844
-82 "Unable to start specified database" on page 884
-81 "Invalid database server command line" on page 784
-80 "Unable to start database server" on page 884
-79 "Invalid local database switch" on page 790
-78 "Dynamic memory exhausted" on page 762
-77 "Database name not unique" on page 752
-76 "Request denied -- no active databases" on page 831
-75 "Request to start/stop database denied" on page 831
-74 "The selected database is currently inactive" on page 871
-72 "No database file specified" on page 811
0 "(no message)" on page 693
100 "Row not found" on page 837
101 "Value truncated" on page 899
102 "Using temporary table" on page 897

650
CHAPTER 10 Database Error Messages

Adaptive Error message


Server
Anywhere
SQLCODE
103 "Invalid data conversion" on page 783
104 "Row has been updated since last time read" on page 836
105 "Procedure has completed" on page 825
106 "Value for column ’%1’ in table ’%2’ has changed" on page 898
107 "Language extension detected in syntax" on page 805
108 "Cursor operation conflict" on page 749
109 "Null value eliminated in aggregate function" on page 816
110 "Transaction log backup page only partially full" on page 878
111 "Statement cannot be executed" on page 847
112 "More information required" on page 808
113 "Database option ’%1’ for user ’%2’ has an invalid setting" on
page 753
114 "Character set translation to ’%1’ cannot be performed; ’%2’ is
used instead" on page 733
115 "Unsupported character set ’%1’" on page 887
116 "Unsupported language; language used is ’%1’ instead" on
page 888
117 "Unsupported character set ’%1’ and unsupported language;
language used is ’%2’ instead" on page 887
118 "Illegal user selectivity estimate specified" on page 774
119 "Unable to open backup log ’%1’" on page 883
200 "Warning" on page 900
738 "’%1’ is an unknown option" on page 696

651
Error messages indexed by SQLSTATE

Error messages indexed by SQLSTATE


Adaptive Server Anywhere supports the SQLSTATE error code defined by
SQL/92. Each SQLSTATE value is a 5- character string containing a 2-
character class followed by a 3-character subclass. Each character can be one
of the uppercase letters A through Z or the digits 0 through 9. A class that
begins with A through H or 0 through 4 has been defined by the ANSI
standard; other classes are implementation defined. Similarly, subclasses of
standard classes that start with the same characters (A-H, 0-4) are standard.
The subclass 000 always means that no subclass code is defined. The most
common SQLSTATE value is 00000, which indicates successful completion.

SQLSTATE Error message


00000 "(no message)" on page 693
01000 "Warning" on page 900
01001 "Cursor operation conflict" on page 749
01003 "Null value eliminated in aggregate function" on page 816
01004 "Value truncated" on page 899
01W02 "Using temporary table" on page 897
01W03 "Invalid data conversion" on page 783
01W04 "Row has been updated since last time read" on page 836
01W05 "Procedure has completed" on page 825
01W06 "Value for column ’%1’ in table ’%2’ has changed" on page 898
01W07 "Language extension detected in syntax" on page 805
01W08 "Statement cannot be executed" on page 847
01W09 "More information required" on page 808
01W10 "Transaction log backup page only partially full" on page 878
01W11 "Database option ’%1’ for user ’%2’ has an invalid setting" on
page 753
01W12 "Character set translation to ’%1’ cannot be performed; ’%2’ is
used instead" on page 733
01W13 "Unsupported character set ’%1’" on page 887
01W14 "Unsupported language; language used is ’%1’ instead" on
page 888
01W15 "Unsupported character set ’%1’ and unsupported language;
language used is ’%2’ instead" on page 887
01W16 "Illegal user selectivity estimate specified" on page 774

652
CHAPTER 10 Database Error Messages

SQLSTATE Error message


01W17 "’%1’ is an unknown option" on page 696
02000 "Row not found" on page 837
04W07 "A dbspace has reached its maximum file size" on page 699
04W08 "The server attempted to access a page beyond the end of the
maximum allowable dbspace file size" on page 871
07001 "Not enough values for host variables" on page 815
07002 "Not enough fields allocated in SQLDA" on page 813
07003 "Error opening cursor" on page 764
07005 "Can only describe a SELECT statement" on page 707
07009 "Invalid descriptor index" on page 785
07W01 "Invalid type on DESCRIBE statement" on page 798
07W02 "Invalid statement" on page 796
07W03 "Invalid prepared statement type" on page 793
07W04 "SQLDA fields inconsistent for a multi-row SQLDA" on
page 846
07W05 "SQLDA data type invalid" on page 845
07W06 "Invalid SQL identifier" on page 795
07W07 "Host variables may not be used within a batch" on page 772
08001 "Database cannot be started -- %1" on page 751
08003 "Not connected to a database" on page 813
08004 "User ID ’%1’ does not exist" on page 893
08W01 "Database server not running" on page 755
08W02 "Connection not found" on page 739
08W03 "Database server connection limit exceeded" on page 755
08W04 "Connections to database have been disabled" on page 740
08W05 "Cannot open transaction log file -- %1" on page 722
08W06 "There are still active database connections" on page 874
08W07 "Unable to start database server" on page 884
08W08 "Invalid database server command line" on page 784
08W09 "Unable to start specified database" on page 884
08W10 "Specified database not found" on page 844
08W11 "Specified database is invalid" on page 844

653
Error messages indexed by SQLSTATE

SQLSTATE Error message


08W12 "Communication error" on page 738
08W13 "Not enough memory to start" on page 814
08W14 "Database name required to start server" on page 753
08W15 "Client/server communications protocol version mismatch" on
page 735
08W16 "Database server not running in multi-user mode" on page 756
08W17 "Error writing to transaction log file" on page 765
08W18 "Sqlpp/dblib version mismatch" on page 846
08W19 "Client/database server version mismatch" on page 734
08W21 "Authentication violation" on page 706
08W22 "Database page size too big" on page 754
08W23 "Database server already running" on page 754
08W24 "Invalid parameter" on page 792
08W25 "Invalid local database switch" on page 790
08W26 "Dynamic memory exhausted" on page 762
08W27 "Database name not unique" on page 752
08W28 "Request denied -- no active databases" on page 831
08W29 "Request to start/stop database denied" on page 831
08W30 "The selected database is currently inactive" on page 871
08W32 "Invalid database page size" on page 784
08W33 "Database creation failed" on page 752
08W34 "Could not load the store DLL %1" on page 746
08W35 "Could not execute store DLL (%1) entry point." on page 744
08W36 "Cannot create item (%1) in the specified dbspace." on
page 712
08W37 "The connection parameters file could not be found" on
page 862
08W38 "Error parsing connection parameter string" on page 765
08W39 "No database file specified" on page 811
08W40 "Database is active" on page 752
08W41 "Database %1 needs recovery" on page 750
08W42 "Database upgrade failed" on page 756

654
CHAPTER 10 Database Error Messages

SQLSTATE Error message


08W43 "Database upgrade not possible" on page 757
08W44 "Could not load the backup/restore DLL %1" on page 746
08W45 "Could not execute backup/restore DLL (%1) entry point." on
page 744
08W46 "Error during backup: %1" on page 763
08W47 "Incorrect store DLL (%1) version." on page 775
08W48 "Authentication failed" on page 705
08W49 "Parse error: %1 near ’%2’" on page 821
08W50 "’%1’ is not a write file for ’%2’" on page 698
08W51 "Invalid IQ database command line option or parameter value:
%1" on page 788
08W52 "Cannot initialize IQ memory manager: %1" on page 718
08W53 "Cannot allocate System V resources" on page 709
08W54 "Parse error: %1 ’%2’" on page 821
08W55 "Server not found and unable to autostart" on page 843
08W56 "Specified database file already in use." on page 844
09W02 "Illegal cursor operation attempt" on page 774
09W04 "INSERT/DELETE on cursor can modify only one table" on
page 778
09W05 "Cannot uniquely identify rows in cursor" on page 729
09W06 "Cursor is restricted to FETCH NEXT operations" on page 748
09W07 "statement’s size limit is invalid." on page 849
09W08 "Cannot update or delete an all-NULL row from table ’%1’" on
page 731
0A000 "Feature ’%1’ not implemented" on page 768
0AW01 "Language extension" on page 804
0AW02 "Transact-SQL feature not supported" on page 877
0AW03 "Disallowed language extension detected in syntax near ’%1’"
on page 760
0AW04 "Triggers and procedures not supported in runtime server" on
page 880
0AW05 "Statement is not allowed in passthrough mode" on page 848
0AW06 "Computed columns are not supported in this database" on
page 739

655
Error messages indexed by SQLSTATE

SQLSTATE Error message


0AW07 "Feature not available with UltraLite" on page 768
0AW08 "You cannot synchronize with uncommitted transactions" on
page 903
0AW09 "Synchronization server failed to commit the upload" on
page 853
0AW10 "DTC transactions are not supported on this platform" on
page 761
21000 "SELECT returns more than one row" on page 841
21W01 "Subquery cannot return more than one row" on page 850
22001 "Right truncation of string data" on page 835
22002 "No indicator variable provided for NULL result" on page 811
22003 "Value %1 out of range for destination" on page 898
22005 "Error in assignment" on page 763
22012 "Division by zero" on page 761
22019 "Invalid escape character ’%1’" on page 786
22024 "Unterminated C string" on page 888
22025 "Invalid escape sequence ’%1’" on page 786
22W02 "Row has changed since last read -- operation cancelled" on
page 837
22W03 "Invalid TEXTPTR value used with WRITETEXT or
READTEXT" on page 797
23502 "Column ’%1’ in table ’%2’ cannot be NULL" on page 736
23503 "No primary key value for foreign key ’%1’ in table ’%2’" on
page 812
23504 "Number of columns allowing NULLs exceeds limit" on
page 817
23505 "Index ’%1’ for table ’%2’ would not be unique" on page 776
23506 "Invalid value for column ’%1’ in table ’%2’" on page 800
23507 "The specified foreign key (%1) can not be enforced" on
page 872
23W01 "Primary key for table ’%1’ is not unique" on page 824
23W05 "Primary key for row in table ’%1’ is referenced in another
table" on page 823
24501 "Cursor not open" on page 749
24502 "Cursor already open" on page 747

656
CHAPTER 10 Database Error Messages

SQLSTATE Error message


24503 "No current row of cursor" on page 810
24504 "Invalid scroll position ’%1’" on page 794
24W01 "Cursor has not been declared" on page 748
26501 "SQL statement error" on page 845
28000 "Password must be at least %1 characters" on page 822
28000 "Invalid user ID or password" on page 799
28000 "Invalid user ID or password" on page 799
28W01 "Invalid user ID or password on preprocessed module" on
page 799
28W02 "Integrated logins are not permitted" on page 779
28W03 "Standard logons are not permitted" on page 847
28W04 "Integrated login failed" on page 779
28W05 "Integrated logins are not supported for this database" on
page 780
28W06 "The integrated login ID guest can only be mapped to the guest
database user ID" on page 865
28W07 "Cannot map a login ID to the sys or public user ID" on
page 720
28W08 "The login ID ’%1’ is already mapped to user ID ’%2’" on
page 867
28W09 "The login ID ’%1’ has not been mapped to any database user
ID" on page 867
2D501 "COMMIT/ROLLBACK not allowed within trigger actions"
on page 738
33000 "Invalid SQL descriptor name" on page 795
37505 "Wrong number of parameters to function ’%1’" on page 901
3B001 "Savepoint ’%1’ not found" on page 838
3B002 "ROLLBACK TO SAVEPOINT not allowed" on page 836
3BW01 "Savepoints require a rollback log" on page 839
3BW02 "Result set not allowed from within an atomic compound
statement" on page 834
40000 "Run time SQL error -- %1" on page 838
40001 "Deadlock detected" on page 759
40W01 "Internal database error %1 -- transaction rolled back" on
page 780

657
Error messages indexed by SQLSTATE

SQLSTATE Error message


40W02 "Terminated by user -- transaction rolled back" on page 861
40W03 "Disk full ’%1’ -- transaction rolled back" on page 760
40W04 "I/O error %1 -- transaction rolled back" on page 772
40W06 "All threads are blocked" on page 700
40W07 "Connection was terminated" on page 740
40W08 "Memory error -- transaction rolled back" on page 805
42501 "%1" on page 694
42U00 "View references ’%1’, which is a temporary object. Views can
only refer to permanent objects." on page 900
42W01 "User ’%1’ already has GRANT permission" on page 890
42W02 "Operation would cause a group cycle" on page 819
42W03 "User ’%1’ is not a user group" on page 893
42W04 "Syntax error near ’%1’" on page 854
42W05 "Unknown function ’%1’" on page 886
42W06 "Aggregate functions not allowed on this statement" on
page 700
42W07 "Invalid host variable" on page 788
42W08 "Invalid expression near ’%1’" on page 787
42W13 "Invalid column number" on page 782
42W14 "Variable ’%1’ not found" on page 899
42W15 "There is already a variable named ’%1’" on page 874
42W16 "Invalid option ’%1’ -- no PUBLIC setting exists" on page 792
42W17 "Invalid setting for option ’%1’" on page 794
42W18 "User ’%1’ has the row in ’%2’ locked" on page 891
42W19 "Not allowed while %1 is using the database" on page 812
42W20 "CHECKPOINT statement requires a rollback log" on
page 733
42W21 "Table in use" on page 860
42W22 "Attempted two active database requests" on page 705
42W23 "Procedure in use" on page 826
42W24 "Label ’%1’ not found" on page 804
42W25 "Invalid absolute or relative offset in FETCH" on page 781

658
CHAPTER 10 Database Error Messages

SQLSTATE Error message


42W26 "Wrong number of variables in FETCH" on page 902
42W27 "%1" on page 695
42W28 "COMMIT/ROLLBACK not allowed within atomic operation"
on page 737
42W29 "Procedure or trigger calls have nested too deeply" on
page 826
42W30 "Update operation attempted on a read-only cursor" on
page 889
42W31 "Update operation attempted on non-updatable query" on
page 889
42W32 "Cannot modify column ’%1’ in table ’%2’" on page 720
42W33 "Table ’%1’ not found" on page 859
42W34 "User ’%1’ already has membership in group ’%2’" on page 891
42W35 "Update operation attempted on non-updatable remote query"
on page 890
42W36 "FOR UPDATE has been incorrectly specified for a READ
ONLY cursor." on page 769
42W37 "Cannot update column ’%1’ since it appears in the ORDER
BY clause." on page 730
42W38 "Cannot update column ’%1’ since it does not appear in the
SELECT clause." on page 730
42W40 "Duplicate referencing column" on page 762
42W41 "Duplicate insert column" on page 761
42W42 "Parameter name missing in call to procedure ’%1’" on
page 820
42W43 "Only PUBLIC settings are allowed for option ’%1’" on
page 818
42W44 "More columns are being dropped from table %1 than are
defined" on page 807
42W45 "Cannot set a temporary option for user ’%1’" on page 726
42W46 "Only the DBA can set the option %1" on page 819
42W47 "Parameter ’%1’ not found in procedure ’%2’" on page 820
42W48 "Syntax error, cannot specify IQ specific options without
specifying IQ PATH" on page 855
42W49 "TRUNCATE TABLE statement cannot refer to a view" on
page 880

659
Error messages indexed by SQLSTATE

SQLSTATE Error message


42W50 "READTEXT or WRITETEXT statement cannot refer to a
view" on page 828
42W51 "VALIDATE TABLE statement must refer to a base table" on
page 897
42W52 "The option %1 can only be set as a temporary option" on
page 868
42W53 "The option %1 cannot be set from within a procedure" on
page 868
42W54 "Signature ’%1’ does not match procedure parameters" on
page 843
42W55 "User owns procedures in use" on page 895
42W56 "User owns tables in use" on page 895
42W57 "Java classes %1 not found" on page 801
42W58 "Jar %1 not found" on page 801
42W59 "The Select list for the derived table ’%1’ has no expression to
match %2" on page 870
44000 "WITH CHECK OPTION violated for insert/update on base
table ’%1’" on page 901
52002 "Column ’%1’ found in more than one table -- need a
correlation name" on page 736
52003 "Column ’%1’ not found" on page 737
52004 "Derived table ’%1’ has no name for column %2" on page 759
52009 "Primary key column ’%1’ already defined" on page 823
52010 "Item ’%1’ already exists" on page 800
52012 "More than one table is identified as ’%1’" on page 808
52W02 "Correlation name ’%1’ not found" on page 741
52W03 "Cannot find index named ’%1’" on page 718
52W04 "Index name ’%1’ not unique" on page 777
52W05 "Table cannot have two primary keys" on page 860
52W06 "Foreign key ’%1’ for table ’%2’ duplicates an existing foreign
key" on page 770
52W07 "Foreign key name ’%1’ not found" on page 770
52W08 "There is more than one way to join ’%1’ to ’%2’" on page 875
52W09 "Procedure ’%1’ not found" on page 824
52W10 "Trigger ’%1’ not found" on page 879

660
CHAPTER 10 Database Error Messages

SQLSTATE Error message


52W11 "Trigger definition conflicts with existing triggers" on
page 879
52W12 "Invalid REFERENCES clause in trigger definition" on
page 793
52W13 "Dbspace ’%1’ not found" on page 758
52W14 "Table ’%1’ is in an outer join cycle" on page 858
52W15 "Table ’%1’ requires a unique correlation name" on page 859
52W16 "User message %1 already exists" on page 894
52W17 "User message %1 not found" on page 894
52W18 "User-defined type %1 not found" on page 896
52W19 "Dbspace for table ’%1’ not found" on page 758
52W20 "Too many columns in table" on page 876
52W21 "Data definition statements not allowed in procedures or
triggers" on page 750
52W22 "GRANT of column permission on view not allowed" on
page 772
52W23 "Invalid expression in WHERE clause of Transact-SQL outer
join" on page 787
52W24 "Invalid join type used with Transact-SQL outer join" on
page 790
52W25 "Invalid comparison" on page 782
52W40 "Index name ’%1’ is ambiguous" on page 776
52W41 "too many temporary tables in connection" on page 877
53002 "Wrong number of values for INSERT" on page 902
53003 "Function or column reference to ’%1’ in the select list must
also appear in a GROUP BY" on page 771
53005 "Number in ORDER BY is too large" on page 816
53011 "Number of columns defined for the view does not match
SELECT statement" on page 817
53018 "Cannot convert %1 to a %2" on page 711
53019 "Return type of void from procedure ’%1’ cannot be used in
any expression" on page 834
53023 "Subquery allowed only one select list item" on page 849
53026 "SELECT lists in UNION do not match in length" on page 841
53030 "Column %1 in foreign key has a different definition than

661
Error messages indexed by SQLSTATE

SQLSTATE Error message


primary key" on page 735
53W01 "ALTER clause conflict" on page 701
53W02 "Cannot update an expression" on page 729
53W04 "There is no way to join ’%1’ to ’%2’" on page 875
53W05 "Cannot alter a column in an index" on page 709
53W06 "Cannot delete a column referenced in a trigger definition" on
page 713
53W07 "Error number %1 for RAISERROR is less than 17000" on
page 764
53W08 "Format string argument number %1 is invalid" on page 771
53W09 "Invalid data type for column in WRITETEXT or
READTEXT" on page 783
54003 "Identifier ’%1’ too long" on page 773
55008 "Table ’%1’ has no primary key" on page 857
55013 "Table already has a primary key" on page 860
55W02 "Table must be empty" on page 861
55W03 "Cannot drop a user that owns tables in runtime system" on
page 716
55W04 "Cannot drop a user that owns procedures in runtime server"
on page 716
55W05 "Cannot drop a user that owns messages or data types" on
page 715
55W06 "Cannot drop a user that owns objects involved in replication"
on page 715
55W07 "db_init has not been called or the call to db_init failed" on
page 757
55W08 "Modifications not permitted for read-only database" on
page 807
55W09 "Cannot commit or rollback while enlisted in a transaction" on
page 710
55W10 "Cannot enlist in a transaction while already enlisted in a
transaction" on page 717
55W11 "Cannot enlist in a transaction with uncommitted data
pending" on page 717
56001 "Table ’%1’ has a foreign key with a referential action" on
page 856

662
CHAPTER 10 Database Error Messages

SQLSTATE Error message


57014 "Statement interrupted by user" on page 848
5RW01 "Publication ’%1’ not found" on page 827
5RW02 "Table ’%1’ has publications" on page 857
5RW03 "Subscription to ’%1’ for ’%2’ already exists" on page 850
5RW04 "Subscription to ’%1’ for ’%2’ not found" on page 851
5RW05 "User ’%1’ is already the publisher for this database" on
page 892
5RW06 "User ’%1’ is not a remote user for this database" on page 892
5RW07 "Remote message type ’%1’ not found" on page 828
5RW08 "Passthrough statement inconsistent with current passthrough"
on page 822
5RW09 "Remote statement failed" on page 830
5RW10 "A consolidated user already exists" on page 699
5RW11 "Synchronization message type ’%1’ not found" on page 851
5RW12 "Cannot not find synchronization %1 with name equal ’%2’" on
page 722
5RW13 "Cannot subscribe to ’%1’" on page 727
5RW14 "Cannot modify synchronization entry using ALTER
PUBLICATION" on page 721
5RW15 "Cannot modify publication entry using ALTER
SYNCHRONIZATION" on page 721
5RW16 "Cannot synchronize table ’%1’ since it does not have a
primary key" on page 728
5RW17 "Must include primary key for table ’%1’ in the
synchronization" on page 809
5RW18 "Cannot create synchronization entry for table ’%1’ with BLOB
primary key" on page 712
5RW19 "Cannot update primary key for table ’%1’ involved in
synchronization" on page 732
5RW20 "Cannot update primary key for table ’%1’ involved in
replication" on page 732
5RW21 "Cannot register %1’ since another exclusive instance is
running" on page 723
5RW22 "Cannot register another ’%1’ as an exclusive application" on
page 724
5RW23 "Cannot register connection because of invalid application

663
Error messages indexed by SQLSTATE

SQLSTATE Error message


cookie" on page 724
5RW24 "Cannot deregister application because of invalid cookie" on
page 714
5RW25 "Cannot deregister ’%1’ since active registered connection
exists" on page 713
5RW26 "Current connection is already registered to ’%1’ as ’%2’" on
page 747
5RW27 "Another connection has already registered as ’%1’" on
page 703
5RW28 "Cannot register ’%1’ since registration cookie exhausted" on
page 723
5RW29 "Cannot register connection to ’%1’ since automatic label
exhausted" on page 725
5RW30 "Undefined synchronization template ’%1’" on page 885
5RW31 "Synchronization site ’%1’ is already defined" on page 854
5RW32 "Synchronization option ’%1’ contains semi-colon or equal
sign" on page 852
5RW33 "Synchronization option ’%1’ not found" on page 852
5RW34 "Synchronization option is too long" on page 853
5RW35 "Table ’%1’ is part of a synchronization definition" on
page 858
5RW36 "Table %1 is already included" on page 856
99999 "User-defined exception signaled" on page 896
WB001 "Unknown backup operation" on page 885
WB002 "Database backup not started" on page 751
WB003 "Incomplete transactions prevent transaction log renaming" on
page 775
WB004 "Unable to delete database file" on page 881
WB005 "Transaction log was truncated" on page 878
WB006 "Contents of backup files are inconsistent" on page 741
WB007 "Backup file format is invalid" on page 706
WB008 "RESTORE unable to open file ’%1’" on page 832
WB009 "RESTORE unable to write to file ’%1’" on page 833
WB010 "RESTORE unable to start database ’%1’" on page 833
WB011 "Unable to open backup log ’%1’" on page 883

664
CHAPTER 10 Database Error Messages

SQLSTATE Error message


WE001 "Event ’%1’ not found" on page 766
WE002 "Event ’%1’ already exists" on page 766
WE003 "Schedule ’%1’ for event ’%2’ not found" on page 840
WE004 "Schedule ’%1’ for event ’%2’ already exists" on page 839
WE005 "Invalid day of week or month ’%1’ for event ’%2’" on
page 785
WE006 "Invalid time ’%1’ for event ’%2’" on page 797
WE007 "Invalid start date/time for event ’%1’" on page 796
WE008 "System event type ’%1’ not found" on page 855
WI001 "Attempt to read beyond end-of-file in a compressed database"
on page 704
WI004 "Internal rollback log corrupted" on page 781
WI005 "Unable to find in index ’%1’ for table ’%2’" on page 882
WI006 "(no message)" on page 693
WI008 "(no message)" on page 694
WI009 "Cannot serialize Java object with class %1" on page 726
WI010 "The optimizer was unable to construct a valid access plan" on
page 867
WJ001 "Method ’%1’ cannot be called at this time" on page 806
WJ002 "Parameter not registered as output parameter" on page 821
WJ003 "The specified transaction isolation is invalid" on page 872
WJ004 "The cursor name ’%1’ already exists" on page 863
WJ005 "Input parameter index out of range" on page 778
WJ006 "Return value cannot be set" on page 835
WJ007 "JDBC feature ’%1’ not supported" on page 803
WJ008 "Could not change an opened prepared statement or callable
statement" on page 743
WJ009 "An internal error occurred in a ’%1’" on page 702
WJ010 "Invalid operation on a closed ’%1’" on page 791
WJ011 "Cannot access instance member through a class" on page 708
WJ012 "Cannot update member fields qualified with "final" modifier"
on page 731
WJ013 "An internal error occurred in a ’%1’" on page 702

665
Error messages indexed by SQLSTATE

SQLSTATE Error message


WJ014 "Invalid operation on a closed ’%1’" on page 791
WJ015 "JDBC SAStatement batch execute abandoned" on page 803
WJ016 "Seek absolute 0 was attempted on a JDBC SAResultSet" on
page 840
WJ017 "Invalid JDBC resultset type" on page 789
WJ018 "Invalid JDBC resultset concurrency" on page 789
WJ019 "Cannot call the ’%1’ function on a JDBC resultset when it is
positioned on an insert row" on page 710
WJ020 "The JDBC resultset must be positioned on an insert row in
order to use the ’%1’ function" on page 866
WJ021 "Cannot uniquely identify column ’%2’ of table ’%1’ in the
current jdbc resultset" on page 728
WJ022 "The database does not support the Java virtual machine" on
page 864
WJ023 "’%1’ is not a public java class, and cannot be referenced from
SQL" on page 697
WJ024 "’%1’ is not a public java reference, and cannot be referenced
from SQL" on page 697
WL001 "’%1’ is not a known file format for loading or unloading
tables" on page 696
WL002 "Cannot access file ’%1’ -- %2" on page 708
WL004 "UNLOAD TABLE cannot be used to unload a view" on
page 886
WL005 "Unable to enlist transaction; DTC may be down" on page 882
WL006 "Unable to reenlist transaction; DTC may be down" on
page 883
WO001 "Unable to connect to server ’%1’: %2" on page 881
WO003 "Remote server %1 is currently configured as read only" on
page 829
WO004 "Remote server %1 could not be found; Add the server using
CREATE SERVER" on page 829
WO005 "Server %1: %2" on page 842
WO006 "Backwards scrolling cursors are not supported for remote
objects" on page 706
WO007 "The remote table ’%1’ could not be found" on page 870
WO008 "Could not access column information for the table ’%1’" on

666
CHAPTER 10 Database Error Messages

SQLSTATE Error message


page 742
WO009 "Not enough memory is allocated to the Java virtual machine
for remote access" on page 814
WO010 "%1" on page 695
WO011 "The remote server does not support an auto-incrementing data
type" on page 869
WO012 "Remote server does not have the ability to support this
statement" on page 830
WO013 "External login for server %1 could not be found" on page 767
WO014 "Server capability name %1 could not be found in the
SYSCAPABILITYNAME table." on page 842
WO015 "The data type specified for column ’%1’ is not compatible
with the actual data type" on page 864
WO016 "The column ’%1’ does not exist in the remote table" on
page 862
WO017 "The length specified for column ’%1’ is different than the
actual length" on page 866
WO018 "Null attribute mismatch for column ’%1’" on page 815
WO019 "Identity attribute mismatch for column ’%1’" on page 773
WO020 "The table specification ’%1’ identifies more than one remote
table" on page 873
WO021 "Creating remote tables with computed columns is not
supported" on page 746
WO022 "The data type of column ’%1’ is not supported" on page 863
WO023 "OMNI cannot handle expressions involving remote tables
inside stored procedures" on page 818
WP000 "Argument %1 of procedure ’%2’ cannot be null" on page 704
WP001 "Procedure ’%1’ terminated with unhandled exception ’%2’" on
page 825
WP002 "’%1’ is not a valid class file" on page 698
WP003 "Could not decompress class ’%1’ from Jar." on page 743
WP004 "Cannot remove class ’%1’: member of Jar" on page 725
WP005 "Invalid class byte code" on page 781
WP006 "Java virtual machine could not be started" on page 802
WP007 "Namespace Heap Exhausted at Internal fn: %1" on page 809
WP008 "Java VM Heap Exhausted at Internal fn: %1" on page 802

667
Error messages indexed by SQLSTATE

SQLSTATE Error message


WP009 "Resource governor for %1 exceeded" on page 832
WP010 "Invalid jar file" on page 789
WW001 "The pattern is too long" on page 869
WW002 "Cannot stop the database server" on page 727
WW003 "Calling functions outside the database server is not supported"
on page 707
WW004 "Mismatch between external function platform specifier and
current operating system" on page 806
WW005 "Need a dynamic library name" on page 810
WW006 "Could not load dynamic library ’%1’" on page 745
WW007 "Could not find ’%1’ in dynamic library ’%2’" on page 745
WW008 "Could not allocate resources to call external function" on
page 742
WW009 "Expression has unsupported data type" on page 767
WW010 "Too many parameters to this external procedure call" on
page 876
WW011 "A thread used internally could not be started" on page 700
WW012 "RAISERROR executed: %1" on page 827
WW013 "Class ’%1’ has no public field ’%2’" on page 734
WW014 "Invalid type for field reference" on page 798
WW015 "Field ’%1’ of class ’%2’ cannot be null" on page 769
WW016 "Index type specification of ’%1’ is invalid" on page 777
WW017 "An attempt to delete database ’%1’ failed" on page 701
WW018 "Cannot deserialize Java object" on page 714
WW019 "Rollback occurred due to deadlock during prefetch" on
page 835
WW020 "Cannot make a static reference to nonstatic variable ’%1’ in
class ’%2’" on page 719
WW022 "Cannot create an index on Java class ’%1’" on page 711
WW023 "Cannot insert or update computed column ’%1’" on page 719
WW024 "The streams environment could not be created" on page 873
WW025 "An internal error was generated by the test harness" on
page 703
WW026 "The external function call is incompatible" on page 865

668
CHAPTER 10 Database Error Messages

669
Error messages indexed by Sybase error code

Error messages indexed by Sybase error code


Sybase error codes are a set of error codes for use by all Sybase products,
including Adaptive Server Enterprise. For every Sybase error code returned
by Adaptive Server Anywhere, there is a matching Adaptive Server
Anywhere error code. In many cases Adaptive Server Anywhere error codes
offer a finer level of granularity than their Sybase error code counterparts,
thus some Sybase error codes in the following table are non-unique.

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
0 -631 "RAISERROR executed: %1" on page 827
102 -171 "Error opening cursor" on page 764
102 -199 "INSERT/DELETE on cursor can modify
only one table" on page 778
102 -275 "Triggers and procedures not supported in
runtime server" on page 880
102 -273 "COMMIT/ROLLBACK not allowed
within trigger actions" on page 738
102 -131 "Syntax error near ’%1’" on page 854
102 -687 "Syntax error, cannot specify IQ specific
options without specifying IQ PATH" on
page 855
102 -145 "Foreign key name ’%1’ not found" on
page 770
102 -271 "Trigger definition conflicts with existing
triggers" on page 879
102 -272 "Invalid REFERENCES clause in trigger
definition" on page 793
102 -635 "GRANT of column permission on view
not allowed" on page 772
102 -151 "Subquery allowed only one select list
item" on page 849
102 -269 "Cannot delete a column referenced in a
trigger definition" on page 713
103 -250 "Identifier ’%1’ too long" on page 773
104 -152 "Number in ORDER BY is too large" on
page 816
133 -262 "Label ’%1’ not found" on page 804

670
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
134 -261 "There is already a variable named ’%1’"
on page 874
137 -260 "Variable ’%1’ not found" on page 899
154 -623 "Data definition statements not allowed in
procedures or triggers" on page 750
155 -200 "Invalid option ’%1’ -- no PUBLIC setting
exists" on page 792
174 -154 "Wrong number of parameters to function
’%1’" on page 901
176 -611 "Transact-SQL feature not supported" on
page 877
176 -148 "Unknown function ’%1’" on page 886
182 -159 "Invalid column number" on page 782
201 -639 "Parameter name missing in call to
procedure ’%1’" on page 820
201 -615 "Parameter ’%1’ not found in procedure
’%2’" on page 820
201 -737 "Signature ’%1’ does not match procedure
parameters" on page 843
205 -153 "SELECT lists in UNION do not match in
length" on page 841
207 -124 "More columns are being dropped from
table %1 than are defined" on page 807
207 -143 "Column ’%1’ not found" on page 737
208 -142 "Correlation name ’%1’ not found" on
page 741
209 -144 "Column ’%1’ found in more than one
table -- need a correlation name" on
page 736
209 -163 "Derived table ’%1’ has no name for
column %2" on page 759
213 -207 "Wrong number of values for INSERT" on
page 902
217 -274 "Procedure or trigger calls have nested too
deeply" on page 826

671
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
220 -158 "Value %1 out of range for destination" on
page 898
230 -191 "Cannot modify column ’%1’ in table ’%2’"
on page 720
230 -190 "Cannot update an expression" on
page 729
233 -195 "Column ’%1’ in table ’%2’ cannot be
NULL" on page 736
233 -733 "Number of columns allowing NULLs
exceeds limit" on page 817
257 -157 "Cannot convert %1 to a %2" on page 711
257 -705 "Return type of void from procedure ’%1’
cannot be used in any expression" on
page 834
262 -121 "%1" on page 694
264 -637 "Duplicate insert column" on page 761
285 -708 "READTEXT or WRITETEXT statement
cannot refer to a view" on page 828
301 -147 "There is more than one way to join ’%1’
to ’%2’" on page 875
301 -680 "Invalid expression in WHERE clause of
Transact-SQL outer join" on page 787
301 -146 "There is no way to join ’%1’ to ’%2’" on
page 875
305 -681 "Invalid join type used with Transact-SQL
outer join" on page 790
311 -295 "Cannot uniquely identify rows in cursor"
on page 729
314 -122 "Operation would cause a group cycle" on
page 819
315 -136 "Table ’%1’ is in an outer join cycle" on
page 858
315 -137 "Table ’%1’ requires a unique correlation
name" on page 859
401 -134 "Feature ’%1’ not implemented" on
page 768

672
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
401 -135 "Language extension" on page 804
401 -156 "Invalid expression near ’%1’" on page 787
409 109 "Null value eliminated in aggregate
function" on page 816
409 -90 "Argument %1 of procedure ’%2’ cannot
be null" on page 704
504 -265 "Procedure ’%1’ not found" on page 824
509 -140 "User ID ’%1’ does not exist" on page 893
512 -186 "Subquery cannot return more than one
row" on page 850
518 103 "Invalid data conversion" on page 783
532 104 "Row has been updated since last time
read" on page 836
532 106 "Value for column ’%1’ in table ’%2’ has
changed" on page 898
538 -627 "Disallowed language extension detected
in syntax near ’%1’" on page 760
546 -194 "No primary key value for foreign key
’%1’ in table ’%2’" on page 812
547 -198 "Primary key for row in table ’%1’ is
referenced in another table" on page 823
547 -677 "Table ’%1’ has a foreign key with a
referential action" on page 856
548 -196 "Index ’%1’ for table ’%2’ would not be
unique" on page 776
548 -209 "Invalid value for column ’%1’ in table
’%2’" on page 800
549 -729 "The specified foreign key (%1) can not be
enforced" on page 872
550 -632 "WITH CHECK OPTION violated for
insert/update on base table ’%1’" on
page 901
553 -264 "Wrong number of variables in FETCH"
on page 902
554 108 "Cursor operation conflict" on page 749

673
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
554 -208 "Row has changed since last read --
operation cancelled" on page 837
557 -170 "Cursor has not been declared" on
page 748
558 -172 "Cursor already open" on page 747
559 -180 "Cursor not open" on page 749
560 100 "Row not found" on page 837
560 -197 "No current row of cursor" on page 810
573 -738 "Password must be at least %1 characters"
on page 822
590 111 "Statement cannot be executed" on
page 847
601 -642 "Invalid SQL descriptor name" on
page 795
708 -80 "Unable to start database server" on
page 884
708 -86 "Not enough memory to start" on page 814
708 -679 "Not enough memory is allocated to the
Java virtual machine for remote access" on
page 814
840 -82 "Unable to start specified database" on
page 884
840 -87 "Database name required to start server"
on page 753
911 -83 "Specified database not found" on
page 844
924 -816 "Specified database file already in use." on
page 844
927 -97 "Database page size too big" on page 754
927 -644 "Invalid database page size" on page 784
928 -645 "Database creation failed" on page 752
932 -311 "Internal rollback log corrupted" on
page 781
950 -76 "Request denied -- no active databases" on
page 831

674
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
950 -74 "The selected database is currently
inactive" on page 871
1205 -306 "Deadlock detected" on page 759
1205 -307 "All threads are blocked" on page 700
1205 -684 "Rollback occurred due to deadlock during
prefetch" on page 835
1601 -102 "Database server connection limit
exceeded" on page 755
1602 -85 "Communication error" on page 738
1602 -88 "Client/server communications protocol
version mismatch" on page 735
1702 -616 "Too many columns in table" on page 876
1719 -118 "Table ’%1’ has no primary key" on
page 857
1721 -113 "Column %1 in foreign key has a different
definition than primary key" on page 735
1801 -77 "Database name not unique" on page 752
1802 -138 "Dbspace ’%1’ not found" on page 758
1909 -636 "Duplicate referencing column" on
page 762
1909 -119 "Primary key column ’%1’ already
defined" on page 823
1909 -251 "Foreign key ’%1’ for table ’%2’ duplicates
an existing foreign key" on page 770
1921 -111 "Index name ’%1’ not unique" on page 777
1921 -678 "Index name ’%1’ is ambiguous" on
page 776
1923 -126 "Table cannot have two primary keys" on
page 860
1923 -112 "Table already has a primary key" on
page 860
2561 -106 "Cannot open transaction log file -- %1"
on page 722
2601 -193 "Primary key for table ’%1’ is not unique"
on page 824

675
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
2706 -141 "Table ’%1’ not found" on page 859
2715 -613 "User-defined type %1 not found" on
page 896
2727 -189 "Unable to find in index ’%1’ for table
’%2’" on page 882
2732 -296 "Error number %1 for RAISERROR is
less than 17000" on page 764
2748 -612 "User message %1 not found" on page 894
2749 -294 "Format string argument number %1 is
invalid" on page 771
3013 -305 "I/O error %1 -- transaction rolled back"
on page 772
3013 -309 "Memory error -- transaction rolled back"
on page 805
3206 -240 "Unknown backup operation" on page 885
3206 -241 "Database backup not started" on page 751
3206 -242 "Incomplete transactions prevent
transaction log renaming" on page 775
3451 -672 "Database upgrade failed" on page 756
3451 -673 "Database upgrade not possible" on
page 757
3618 -302 "Terminated by user -- transaction rolled
back" on page 861
3618 -304 "Disk full ’%1’ -- transaction rolled back"
on page 760
3619 -107 "Error writing to transaction log file" on
page 765
3621 -299 "Statement interrupted by user" on
page 848
3702 -214 "Table in use" on page 860
3702 -215 "Procedure in use" on page 826
3702 -750 "User owns procedures in use" on
page 895
3702 -751 "User owns tables in use" on page 895

676
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
3819 -160 "Can only describe a SELECT statement"
on page 707
4001 -105 "Database cannot be started -- %1" on
page 751
4001 -84 "Specified database is invalid" on
page 844
4001 -72 "No database file specified" on page 811
4002 -103 "Invalid user ID or password" on page 799
4002 -103 "Invalid user ID or password" on page 799
4002 -104 "Invalid user ID or password on
preprocessed module" on page 799
4224 -108 "Connection not found" on page 739
4224 -99 "Connections to database have been
disabled" on page 740
4224 -308 "Connection was terminated" on page 740
4406 -703 "Cannot insert or update computed column
’%1’" on page 719
4409 -114 "Number of columns defined for the view
does not match SELECT statement" on
page 817
4412 -766 "View references ’%1’, which is a
temporary object. Views can only refer to
permanent objects." on page 900
4708 -702 "TRUNCATE TABLE statement cannot
refer to a view" on page 880
4901 -116 "Table must be empty" on page 861
4939 -127 "Cannot alter a column in an index" on
page 709
5006 -604 "A dbspace has reached its maximum file
size" on page 699
5006 -605 "The server attempted to access a page
beyond the end of the maximum allowable
dbspace file size" on page 871
5703 107 "Language extension detected in syntax"
on page 805

677
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
5849 -201 "Invalid setting for option ’%1’" on
page 794
5864 -81 "Invalid database server command line" on
page 784
5864 -735 "Invalid parameter" on page 792
5864 -79 "Invalid local database switch" on
page 790
5864 -95 "Parse error: %1 near ’%2’" on page 821
5864 -754 "Parse error: %1 ’%2’" on page 821
5878 -204 "Only the DBA can set the option %1" on
page 819
5878 -216 "The option %1 can only be set as a
temporary option" on page 868
5878 -217 "The option %1 cannot be set from within
a procedure" on page 868
6001 -109 "There are still active database
connections" on page 874
6004 -75 "Request to start/stop database denied" on
page 831
6226 -183 "Cannot find index named ’%1’" on
page 718
6259 -263 "Invalid absolute or relative offset in
FETCH" on page 781
6267 -814 "Cannot update column ’%1’ since it
appears in the ORDER BY clause." on
page 730
6401 -220 "Savepoint ’%1’ not found" on page 838
7123 -608 "Invalid TEXTPTR value used with
WRITETEXT or READTEXT" on
page 797
7139 -609 "Invalid data type for column in
WRITETEXT or READTEXT" on
page 783
7201 -155 "Invalid host variable" on page 788
7203 -89 "Database server not running in multi-user
mode" on page 756

678
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
7301 -192 "Update operation attempted on non-
updatable query" on page 889
7301 -813 "FOR UPDATE has been incorrectly
specified for a READ ONLY cursor." on
page 769
7321 -149 "Function or column reference to ’%1’ in
the select list must also appear in a
GROUP BY" on page 771
7337 101 "Value truncated" on page 899
7338 -728 "Update operation attempted on non-
updatable remote query" on page 890
7364 -139 "More than one table is identified as ’%1’"
on page 808
7374 -676 "The specified transaction isolation is
invalid" on page 872
7705 -630 "Invalid escape sequence ’%1’" on
page 786
7706 -606 "The pattern is too long" on page 869
7707 -629 "Invalid escape character ’%1’" on
page 786
7732 -633 "Update operation attempted on a read-
only cursor" on page 889
7740 -815 "Cannot update column ’%1’ since it does
not appear in the SELECT clause." on
page 730
7950 -100 "Database server not running" on page 755
7950 -96 "Database server already running" on
page 754
8201 -640 "Invalid descriptor index" on page 785
8205 -641 "Error in assignment" on page 763
8405 -210 "User ’%1’ has the row in ’%2’ locked" on
page 891
9119 -78 "Dynamic memory exhausted" on
page 762
9502 -638 "Right truncation of string data" on
page 835

679
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
9526 -187 "Illegal cursor operation attempt" on
page 774
9819 -268 "Trigger ’%1’ not found" on page 879
10356 -624 "Expression has unsupported data type" on
page 767
11205 -698 "The remote server does not support an
auto-incrementing data type" on page 869
11205 -732 "Creating remote tables with computed
columns is not supported" on page 746
11205 -736 "The data type of column ’%1’ is not
supported" on page 863
11206 -656 "Unable to connect to server ’%1’: %2" on
page 881
11207 -667 "Could not access column information for
the table ’%1’" on page 742
11208 -722 "The column ’%1’ does not exist in the
remote table" on page 862
11209 -721 "The data type specified for column ’%1’ is
not compatible with the actual data type"
on page 864
11210 -723 "The length specified for column ’%1’ is
different than the actual length" on
page 866
11211 -724 "Null attribute mismatch for column ’%1’"
on page 815
11212 -725 "Identity attribute mismatch for column
’%1’" on page 773
11214 -659 "Remote server %1 could not be found;
Add the server using CREATE SERVER"
on page 829
11214 -666 "The remote table ’%1’ could not be
found" on page 870
11215 -726 "The table specification ’%1’ identifies
more than one remote table" on page 873
11221 -712 "External login for server %1 could not be
found" on page 767

680
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
11227 -706 "Remote server does not have the ability to
support this statement" on page 830
11248 -658 "Remote server %1 is currently configured
as read only" on page 829
12006 -110 "Item ’%1’ already exists" on page 800
13075 102 "Using temporary table" on page 897
13204 -150 "Aggregate functions not allowed on this
statement" on page 700
13600 0 "(no message)" on page 693
13601 -690 "Return value cannot be set" on page 835
13602 -693 "JDBC feature ’%1’ not supported" on
page 803
13603 -694 "Could not change an opened prepared
statement or callable statement" on
page 743
13604 -695 "An internal error occurred in a ’%1’" on
page 702
13605 -696 "Invalid operation on a closed ’%1’" on
page 791
13606 -699 "Cannot update member fields qualified
with "final" modifier" on page 731
13607 -701 "Cannot access instance member through a
class" on page 708
13608 -713 "An internal error occurred in a ’%1’" on
page 702
13609 -714 "Invalid operation on a closed ’%1’" on
page 791
13613 114 "Character set translation to ’%1’ cannot be
performed; ’%2’ is used instead" on
page 733
13614 115 "Unsupported character set ’%1’" on
page 887
13615 116 "Unsupported language; language used is
’%1’ instead" on page 888
13616 117 "Unsupported character set ’%1’ and
unsupported language; language used is
’%2’ instead" on page 887

681
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13617 118 "Illegal user selectivity estimate specified"
on page 774
13618 105 "Procedure has completed" on page 825
13619 200 "Warning" on page 900
13620 -98 "Authentication violation" on page 706
13621 -218 "Authentication failed" on page 705
13622 -101 "Not connected to a database" on page 813
13623 -125 "ALTER clause conflict" on page 701
13624 -610 "User message %1 already exists" on
page 894
13625 -120 "User ’%1’ already has GRANT
permission" on page 890
13626 -123 "User ’%1’ is not a user group" on
page 893
13627 -312 "User ’%1’ already has membership in
group ’%2’" on page 891
13628 -130 "Invalid statement" on page 796
13629 -132 "SQL statement error" on page 845
13630 -133 "Invalid prepared statement type" on
page 793
13631 -707 "Statement is not allowed in passthrough
mode" on page 848
13632 -614 "Cannot drop a user that owns messages or
data types" on page 715
13633 -731 "Cannot drop a user that owns objects
involved in replication" on page 715
13634 -161 "Invalid type on DESCRIBE statement" on
page 798
13635 -181 "No indicator variable provided for NULL
result" on page 811
13636 -182 "Not enough fields allocated in SQLDA"
on page 813
13637 -185 "SELECT returns more than one row" on
page 841

682
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13638 -188 "Not enough values for host variables" on
page 815
13639 -266 "%1" on page 695
13640 -267 "COMMIT/ROLLBACK not allowed
within atomic operation" on page 737
13641 -270 "Cannot drop a user that owns procedures
in runtime server" on page 716
13642 -280 "Publication ’%1’ not found" on page 827
13643 -281 "Table ’%1’ has publications" on page 857
13644 -282 "Subscription to ’%1’ for ’%2’ already
exists" on page 850
13645 -283 "Subscription to ’%1’ for ’%2’ not found"
on page 851
13646 -284 "User ’%1’ is already the publisher for this
database" on page 892
13647 -285 "User ’%1’ is not a remote user for this
database" on page 892
13648 -286 "Remote message type ’%1’ not found" on
page 828
13649 -287 "Passthrough statement inconsistent with
current passthrough" on page 822
13650 -288 "Remote statement failed" on page 830
13652 -211 "Not allowed while %1 is using the
database" on page 812
13653 -212 "CHECKPOINT statement requires a
rollback log" on page 733
13654 -221 "ROLLBACK TO SAVEPOINT not
allowed" on page 836
13655 -222 "Result set not allowed from within an
atomic compound statement" on page 834
13656 -213 "Savepoints require a rollback log" on
page 839
13657 -230 "Sqlpp/dblib version mismatch" on
page 846
13658 -231 "Client/database server version mismatch"
on page 734

683
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13660 -243 "Unable to delete database file" on
page 881
13661 -244 "Transaction log was truncated" on
page 878
13662 -297 "User-defined exception signaled" on
page 896
13663 -298 "Attempted two active database requests"
on page 705
13664 -300 "Run time SQL error -- %1" on page 838
13665 -301 "Internal database error %1 -- transaction
rolled back" on page 780
13666 -310 "Attempt to read beyond end-of-file in a
compressed database" on page 704
13669 -601 "’%1’ is not a known file format for
loading or unloading tables" on page 696
13670 -602 "Cannot access file ’%1’ -- %2" on
page 708
13672 -643 "UNLOAD TABLE cannot be used to
unload a view" on page 886
13673 -607 "Cannot stop the database server" on
page 727
13674 -617 "Calling functions outside the database
server is not supported" on page 707
13675 -618 "Mismatch between external function
platform specifier and current operating
system" on page 806
13676 -619 "Need a dynamic library name" on
page 810
13677 -620 "Could not load dynamic library ’%1’" on
page 745
13678 -621 "Could not find ’%1’ in dynamic library
’%2’" on page 745
13679 -622 "Could not allocate resources to call
external function" on page 742
13680 -625 "Too many parameters to this external
procedure call" on page 876

684
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13681 -626 "A thread used internally could not be
started" on page 700
13682 -634 "Unterminated C string" on page 888
13683 110 "Transaction log backup page only
partially full" on page 878
13685 -202 "Only PUBLIC settings are allowed for
option ’%1’" on page 818
13686 112 "More information required" on page 808
13687 -203 "Cannot set a temporary option for user
’%1’" on page 726
13688 113 "Database option ’%1’ for user ’%2’ has an
invalid setting" on page 753
13689 -205 "Integrated logins are not permitted" on
page 779
13690 -206 "Standard logons are not permitted" on
page 847
13691 -245 "Integrated login failed" on page 779
13692 -503 "(no message)" on page 693
13693 -504 "(no message)" on page 694
13694 -246 "Integrated logins are not supported for
this database" on page 780
13695 -247 "The integrated login ID guest can only be
mapped to the guest database user ID" on
page 865
13696 -248 "Cannot map a login ID to the sys or
public user ID" on page 720
13697 -249 "The login ID ’%1’ is already mapped to
user ID ’%2’" on page 867
13698 -313 "The login ID ’%1’ has not been mapped to
any database user ID" on page 867
13699 -646 "Could not load the store DLL %1" on
page 746
13700 -647 "Could not execute store DLL (%1) entry
point." on page 744
13701 -711 "Incorrect store DLL (%1) version." on
page 775

685
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13702 -648 "Cannot create item (%1) in the specified
dbspace." on page 712
13703 -93 "Class ’%1’ has no public field ’%2’" on
page 734
13704 -650 "Index type specification of ’%1’ is
invalid" on page 777
13705 -651 "An attempt to delete database ’%1’ failed"
on page 701
13706 -654 "The connection parameters file could not
be found" on page 862
13707 -655 "Error parsing connection parameter
string" on page 765
13708 -664 "Database is active" on page 752
13709 -665 "Database %1 needs recovery" on
page 750
13710 -668 "Cursor is restricted to FETCH NEXT
operations" on page 748
13711 -669 "Method ’%1’ cannot be called at this
time" on page 806
13712 -671 "Parameter not registered as output
parameter" on page 821
13713 -674 "statement’s size limit is invalid." on
page 849
13714 -683 "The cursor name ’%1’ already exists" on
page 863
13715 -685 "Resource governor for %1 exceeded" on
page 832
13716 -686 "Cannot make a static reference to
nonstatic variable ’%1’ in class ’%2’" on
page 719
13717 -689 "Input parameter index out of range" on
page 778
13718 -691 "Could not load the backup/restore DLL
%1" on page 746
13719 -692 "Could not execute backup/restore DLL
(%1) entry point." on page 744
13720 -697 "Error during backup: %1" on page 763

686
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13721 -700 "SQLDA fields inconsistent for a multi-
row SQLDA" on page 846
13722 -709 "Computed columns are not supported in
this database" on page 739
13723 -761 "Server capability name %1 could not be
found in the SYSCAPABILITYNAME
table." on page 842
13724 -715 "Contents of backup files are inconsistent"
on page 741
13725 -716 "Backup file format is invalid" on
page 706
13726 -717 "RESTORE unable to open file ’%1’" on
page 832
13727 -718 "RESTORE unable to write to file ’%1’"
on page 833
13728 -719 "RESTORE unable to start database ’%1’"
on page 833
13729 -720 "VALIDATE TABLE statement must
refer to a base table" on page 897
13730 -727 "The optimizer was unable to construct a
valid access plan" on page 867
13731 -128 "Cannot drop a user that owns tables in
runtime system" on page 716
13732 -660 "Server %1: %2" on page 842
13733 -661 "Backwards scrolling cursors are not
supported for remote objects" on page 706
13734 -682 "%1" on page 695
13735 -91 "Procedure ’%1’ terminated with
unhandled exception ’%2’" on page 825
13736 -92 "’%1’ is not a valid class file" on page 698
13737 -730 "Invalid jar file" on page 789
13738 -94 "Invalid type for field reference" on
page 798
13739 -164 "Namespace Heap Exhausted at Internal
fn: %1" on page 809

687
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13740 -165 "Java VM Heap Exhausted at Internal fn:
%1" on page 802
13741 -649 "Field ’%1’ of class ’%2’ cannot be null" on
page 769
13742 -652 "Could not decompress class ’%1’ from
Jar." on page 743
13743 -653 "Cannot remove class ’%1’: member of
Jar" on page 725
13744 -662 "Cannot serialize Java object with class
%1" on page 726
13745 -663 "Cannot deserialize Java object" on
page 714
13746 -670 "Invalid class byte code" on page 781
13747 -675 "Java virtual machine could not be started"
on page 802
13748 -704 "Cannot create an index on Java class
’%1’" on page 711
13749 -710 "Invalid comparison" on page 782
13750 -734 "Cannot update or delete an all-NULL row
from table ’%1’" on page 731
13751 738 "’%1’ is an unknown option" on page 696
13752 -739 "db_init has not been called or the call to
db_init failed" on page 757
13753 -740 "The streams environment could not be
created" on page 873
13754 -741 "’%1’ is not a write file for ’%2’" on
page 698
13755 -742 "JDBC SAStatement batch execute
abandoned" on page 803
13756 -743 "Seek absolute 0 was attempted on a
JDBC SAResultSet" on page 840
13757 -744 "Invalid IQ database command line option
or parameter value: %1" on page 788
13758 -745 "Cannot initialize IQ memory manager:
%1" on page 718

688
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13759 -746 "Cannot allocate System V resources" on
page 709
13760 -747 "Invalid JDBC resultset type" on page 789
13761 -748 "Invalid JDBC resultset concurrency" on
page 789
13762 -749 "Feature not available with UltraLite" on
page 768
13763 -752 "Cannot call the ’%1’ function on a JDBC
resultset when it is positioned on an insert
row" on page 710
13764 -753 "The JDBC resultset must be positioned on
an insert row in order to use the ’%1’
function" on page 866
13765 -755 "You cannot synchronize with
uncommitted transactions" on page 903
13766 -756 "Cannot uniquely identify column ’%2’ of
table ’%1’ in the current jdbc resultset" on
page 728
13767 -289 "A consolidated user already exists" on
page 699
13768 -757 "Modifications not permitted for read-only
database" on page 807
13769 -758 "The database does not support the Java
virtual machine" on page 864
13770 -759 "SQLDA data type invalid" on page 845
13771 -760 "Invalid SQL identifier" on page 795
13772 -762 "’%1’ is not a public java class, and cannot
be referenced from SQL" on page 697
13773 -763 "’%1’ is not a public java reference, and
cannot be referenced from SQL" on
page 697
13774 -764 "Server not found and unable to autostart"
on page 843
13775 -765 "Synchronization message type ’%1’ not
found" on page 851
13776 119 "Unable to open backup log ’%1’" on
page 883

689
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13777 -767 "Cannot not find synchronization %1 with
name equal ’%2’" on page 722
13778 -768 "Cannot subscribe to ’%1’" on page 727
13779 -769 "Cannot modify synchronization entry
using ALTER PUBLICATION" on
page 721
13780 -770 "Cannot modify publication entry using
ALTER SYNCHRONIZATION" on
page 721
13781 -771 "Event ’%1’ not found" on page 766
13782 -772 "Event ’%1’ already exists" on page 766
13783 -773 "Schedule ’%1’ for event ’%2’ not found"
on page 840
13784 -774 "Schedule ’%1’ for event ’%2’ already
exists" on page 839
13787 -777 "Cannot synchronize table ’%1’ since it
does not have a primary key" on page 728
13788 -778 "Must include primary key for table ’%1’
in the synchronization" on page 809
13789 -779 "Cannot create synchronization entry for
table ’%1’ with BLOB primary key" on
page 712
13790 -780 "Cannot update primary key for table ’%1’
involved in synchronization" on page 732
13791 -781 "Cannot update primary key for table ’%1’
involved in replication" on page 732
13792 -782 "Cannot register %1’ since another
exclusive instance is running" on page 723
13793 -783 "Cannot register another ’%1’ as an
exclusive application" on page 724
13794 -784 "Cannot register connection because of
invalid application cookie" on page 724
13795 -785 "Cannot deregister application because of
invalid cookie" on page 714
13796 -786 "Cannot deregister ’%1’ since active
registered connection exists" on page 713

690
CHAPTER 10 Database Error Messages

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13797 -787 "Current connection is already registered
to ’%1’ as ’%2’" on page 747
13798 -788 "Another connection has already registered
as ’%1’" on page 703
13799 -789 "Cannot register ’%1’ since registration
cookie exhausted" on page 723
13800 -790 "Cannot register connection to ’%1’ since
automatic label exhausted" on page 725
13801 -791 "Invalid day of week or month ’%1’ for
event ’%2’" on page 785
13802 -792 "Invalid time ’%1’ for event ’%2’" on
page 797
13803 -793 "Invalid start date/time for event ’%1’" on
page 796
13804 -794 "Synchronization server failed to commit
the upload" on page 853
13805 -795 "Undefined synchronization template
’%1’" on page 885
13806 -796 "Synchronization site ’%1’ is already
defined" on page 854
13807 -797 "Synchronization option ’%1’ contains
semi-colon or equal sign" on page 852
13809 -799 "DTC transactions are not supported on
this platform" on page 761
13810 -800 "Cannot commit or rollback while enlisted
in a transaction" on page 710
13811 -801 "Cannot enlist in a transaction while
already enlisted in a transaction" on
page 717
13812 -802 "Cannot enlist in a transaction with
uncommitted data pending" on page 717
13813 -803 "Unable to enlist transaction; DTC may be
down" on page 882
13814 -804 "Unable to reenlist transaction; DTC may
be down" on page 883
13815 -805 "Synchronization option ’%1’ not found"
on page 852

691
Error messages indexed by Sybase error code

Sybase Adaptive Server Error message


error code Anywhere
SQLCODE
13816 -806 "System event type ’%1’ not found" on
page 855
13817 -807 "Host variables may not be used within a
batch" on page 772
13818 -808 "An internal error was generated by the
test harness" on page 703
13819 -809 "Synchronization option is too long" on
page 853
13820 -810 "Java classes %1 not found" on page 801
13821 -811 "Jar %1 not found" on page 801
13822 -812 "The Select list for the derived table ’%1’
has no expression to match %2" on
page 870
13823 -817 "too many temporary tables in connection"
on page 877
13824 -818 "The external function call is
incompatible" on page 865
13825 -819 "Table ’%1’ is part of a synchronization
definition" on page 858
13826 -820 "Invalid scroll position ’%1’" on page 794
13827 -821 "Dbspace for table ’%1’ not found" on
page 758
13828 -822 "Table %1 is already included" on
page 856
13829 -823 "OMNI cannot handle expressions
involving remote tables inside stored
procedures" on page 818
36007 -628 "Division by zero" on page 761

692
CHAPTER 10 Database Error Messages

Alphabetic list of error messages


This section provides a full listing of error messages and descriptions.
Errors with an ODBC state marked "handled by ODBC driver" are not
returned to ODBC applications, as the ODBC driver carries out the required
actions.

(no message)
Item Value
SQLCODE 0
Constant SQLE_NOERROR
SQLSTATE 00000
Sybase error code 13600
ODBC 2 State 00000
ODBC 3 State 00000

Probable cause This code indicates that there was no error or warning.

(no message)
Item Value
SQLCODE -503
Constant SQLE_PREEMPTED
SQLSTATE WI006
Sybase error code 13692
ODBC 2 State ERROR
ODBC 3 State ERROR

693
Alphabetic list of error messages

(no message)
Item Value
SQLCODE -504
Constant SQLE_RETRY
SQLSTATE WI008
Sybase error code 13693
ODBC 2 State ERROR
ODBC 3 State ERROR

%1
Item Value
SQLCODE -121
Constant SQLE_PERMISSION_DENIED
SQLSTATE 42501
Sybase error code 262
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Description of the type of permission lacking.

Probable cause You do not have the required permission to do the specified action. The
message specifies the actual permission required and the object being acted
upon.

694
CHAPTER 10 Database Error Messages

%1
Item Value
SQLCODE -266
Constant SQLE_OLD_DBINIT
SQLSTATE 42W27
Sybase error code 13639
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The database is missing some system table definitions required for this
statement. These system table definitions are normally created when a
database is initialized. The database should be unloaded and reloaded into a
database that has been initialized with a newer version of Adaptive Server
Anywhere or use DBUPGRADE to upgrade the database to the most recent
version.

%1
Item Value
SQLCODE -682
Constant SQLE_OMNI_DEBUG
SQLSTATE WO010
Sybase error code 13734
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 The debug message for the console

Probable cause This message is used for displaying component integration services debug
mesages on the console.

695
Alphabetic list of error messages

’%1’ is an unknown option


Item Value
SQLCODE 738
Constant SQLE_UNKNOWN_OPTION
SQLSTATE 01W17
Sybase error code 13751
ODBC 2 State 01004
ODBC 3 State 01004

Probable cause You attempted to set the value of an option which is not known to the server.
You should make sure that you did intend to set the specified option as
opposed to having make a typographical error.

’%1’ is not a known file format for loading or unloading tables


Item Value
SQLCODE -601
Constant SQLE_UNSUPPORTED_LOAD_FORMAT
SQLSTATE WL001
Sybase error code 13669
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The specified format

Probable cause An unsupported file format was specifed for LOAD TABLE or UNLOAD
TABLE.

696
CHAPTER 10 Database Error Messages

’%1’ is not a public java class, and cannot be referenced from SQL
Item Value
SQLCODE -762
Constant SQLE_NON_PUBLIC_JAVA_CLASS
SQLSTATE WJ023
Sybase error code 13772
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Java class name

Probable cause Only public java classes installed into the database are accessible from SQL.

’%1’ is not a public java reference, and cannot be referenced from


SQL
Item Value
SQLCODE -763
Constant SQLE_UNKNOWN_JAVA_REF
SQLSTATE WJ024
Sybase error code 13773
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 a dotted expression

Probable cause The dotted expression is neither a public java class nor a java variable.

697
Alphabetic list of error messages

’%1’ is not a valid class file


Item Value
SQLCODE -92
Constant SQLE_BAD_CLASS_FILE
SQLSTATE WP002
Sybase error code 13736
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the invalid file.

Probable cause A file passed to the INSTALL JAVA statement was not a valid Java class
file.

’%1’ is not a write file for ’%2’


Item Value
SQLCODE -741
Constant SQLE_NOTA_WRITE_FILE
SQLSTATE 08W50
Sybase error code 13754
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The write file specified in the ALTER WRITEFILE statement is not a
writefile for the database specified.

698
CHAPTER 10 Database Error Messages

A consolidated user already exists


Item Value
SQLCODE -289
Constant SQLE_CONSOLIDATED_USER_ALREADY_EXIST
S
SQLSTATE 5RW10
Sybase error code 13767
ODBC 2 State S0002
ODBC 3 State 42S02

Probable cause You attempted to grant consolidated permissions when your database already
has a consolidated user.

A dbspace has reached its maximum file size


Item Value
SQLCODE -604
Constant SQLE_DBSPACE_FULL
SQLSTATE 04W07
Sybase error code 5006
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause A dbspace has grown to its maximum number of disk pages, which is usually
limited by the maximum operating system file size. This is a fatal error.

699
Alphabetic list of error messages

A thread used internally could not be started


Item Value
SQLCODE -626
Constant SQLE_THREAD_START_FAILURE
SQLSTATE WW011
Sybase error code 13681
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause This is a Windows95 specific error. An operating system thread could not be
started that is required to execute external functions.

Aggregate functions not allowed on this statement


Item Value
SQLCODE -150
Constant SQLE_AGGREGATES_NOT_ALLOWED
SQLSTATE 42W06
Sybase error code 13204
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You used an UPDATE statement with an aggregate function.

All threads are blocked


Item Value
SQLCODE -307
Constant SQLE_THREAD_DEADLOCK
SQLSTATE 40W06
Sybase error code 1205
ODBC 2 State 40001
ODBC 3 State 40001

700
CHAPTER 10 Database Error Messages

Probable cause You attempted to read or write a row and it is locked by another user. Also,
all other threads (see database option THREAD_COUNT) are blocked
waiting for a lock to be released. This is a deadlock situation and your
transaction has been chosen as the one to rollback.

ALTER clause conflict


Item Value
SQLCODE -125
Constant SQLE_ALTER_CLAUSE_CONFLICT
SQLSTATE 53W01
Sybase error code 13623
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause A primary key clause, foreign key clause, or a uniqueness clause must be the
only clause of an ALTER TABLE statement.

An attempt to delete database ’%1’ failed


Item Value
SQLCODE -651
Constant SQLE_DROP_DATABASE_FAILED
SQLSTATE WW017
Sybase error code 13705
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause Your attempt to delete a database file failed. You may have attempted to
delete a running database. Some parts of the database may have been deleted
before failure.

701
Alphabetic list of error messages

An internal error occurred in a ’%1’


Item Value
SQLCODE -695
Constant SQLE_JDBC_OBJ_INTERNAL_ERR
SQLSTATE WJ009
Sybase error code 13604
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Java class of the object in error

Probable cause This is an internal JDBC object error. If it can be reproduced, it should be
reported to Sybase.

An internal error occurred in a ’%1’


Item Value
SQLCODE -713
Constant SQLE_JNAT_OBJ_INTERNAL_ERR
SQLSTATE WJ013
Sybase error code 13608
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Java class of the object in error

Probable cause This is an internal native Java object error. If it can be reproduced, it should
be reported to Sybase.

702
CHAPTER 10 Database Error Messages

An internal error was generated by the test harness


Item Value
SQLCODE -808
Constant SQLE_TEST_HARNESS
SQLSTATE WW025
Sybase error code 13818
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An internal error was generated by the test harness.

Another connection has already registered as ’%1’


Item Value
SQLCODE -788
Constant SQLE_NOT_UNIQUE_CONN_REG_LABEL
SQLSTATE 5RW27
Sybase error code 13798
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Registered connection label

Probable cause You attempted to register a connection with a label already in use for the
same application.

703
Alphabetic list of error messages

Argument %1 of procedure ’%2’ cannot be null


Item Value
SQLCODE -90
Constant SQLE_ARGUMENT_CANNOT_BE_NULL
SQLSTATE WP000
Sybase error code 409
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The argument number which cannot be null.
Parameter 2 The name of the procedure which cannot receive the null
parameter.

Probable cause You passed a null value to a procedure expecting a scalar argument. For
example, a Java procedure which has an ’int’ argument cannot receive a null
value.

Attempt to read beyond end-of-file in a compressed database


Item Value
SQLCODE -310
Constant SQLE_BEYOND_EOF
SQLSTATE WI001
Sybase error code 13666
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause While reading the database file, an attempt was made to read beyond the end
of the file. This is a fatal internal error.

704
CHAPTER 10 Database Error Messages

Attempted two active database requests


Item Value
SQLCODE -298
Constant SQLE_DOUBLE_REQUEST
SQLSTATE 42W22
Sybase error code 13663
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause In Embedded SQL, you attempted to submit a database request while you
have another request in process. This often occurs in Windows when
processing the WM_PAINT message causes a database request, and you get
a second WM_PAINT before the database request has completed.

Authentication failed
Item Value
SQLCODE -218
Constant SQLE_AUTHENTICATION_FAILED
SQLSTATE 08W48
Sybase error code 13621
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause You set the database_authentication or connection_authentication option


incorrectly.

705
Alphabetic list of error messages

Authentication violation
Item Value
SQLCODE -98
Constant SQLE_AUTHENTICATION_VIOLATION
SQLSTATE 08W21
Sybase error code 13620
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause You attempted to connect to a server which has been authenticated for
exclusive use with a specific application.

Backup file format is invalid


Item Value
SQLCODE -716
Constant SQLE_RESTORE_INVALID_FORMAT
SQLSTATE WB007
Sybase error code 13725
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The format of an archive file to be used during a RESTORE is invalid.

Backwards scrolling cursors are not supported for remote objects


Item Value
SQLCODE -661
Constant SQLE_OMNI_BACKWARDS_CURSOR
SQLSTATE WO006
Sybase error code 13733
ODBC 2 State ERROR
ODBC 3 State ERROR

706
CHAPTER 10 Database Error Messages

Probable cause Backwards scrolling cursors are not supported for remote objects. Change
the client program to use forward scrolling cursors only.

Calling functions outside the database server is not supported


Item Value
SQLCODE -617
Constant SQLE_EXTERNAL_CALLS_NOT_SUPPORTED
SQLSTATE WW003
Sybase error code 13674
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to call a stored procedure that, in turn, calls a function in a
dynamically loaded module. The operating system on which this stored
procedure was called does not support such an action.

Can only describe a SELECT statement


Item Value
SQLCODE -160
Constant SQLE_DESCRIBE_NONSELECT
SQLSTATE 07005
Sybase error code 3819
ODBC 2 State OK
ODBC 3 State OK

Probable cause In the C language interface, you attempted to describe the select list of a
statement other than a SELECT statement.

707
Alphabetic list of error messages

Cannot access file ’%1’ -- %2


Item Value
SQLCODE -602
Constant SQLE_CANNOT_ACCESS_FILE
SQLSTATE WL002
Sybase error code 13670
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The filename
Parameter 2 The cause of the error

Probable cause A file cannot be accessed. For example, a file referenced by LOAD TABLE
does not exist or cannot be read. The message will contain the reason for the
error.

Cannot access instance member through a class


Item Value
SQLCODE -701
Constant SQLE_CANNOT_ACCESS_INSTANCE_MEMBER
SQLSTATE WJ011
Sybase error code 13607
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause Non-static fields or methods must be accessed through an object instance.

708
CHAPTER 10 Database Error Messages

Cannot allocate System V resources


Item Value
SQLCODE -746
Constant SQLE_IQ_SYSTEM_V_FAILURE
SQLSTATE 08W53
Sybase error code 13759
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause IQ was unable to allocate System V resources. Please delete unused System
V semaphores and shared memory segments or increase OS configuration
values for these resources.

Cannot alter a column in an index


Item Value
SQLCODE -127
Constant SQLE_COLUMN_IN_INDEX
SQLSTATE 53W05
Sybase error code 4939
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You may have attempted to delete or modify the definition of a column that
is part of a primary or foreign key. You may have attempted to delete a
column that has an index on it. In this case, DROP the index or key, perform
the ALTER statement, and then add the index or key again.

709
Alphabetic list of error messages

Cannot call the ’%1’ function on a JDBC resultset when it is


positioned on an insert row
Item Value
SQLCODE -752
Constant SQLE_JDBC_INVALID_OPER_ON_INSERT_ROW
SQLSTATE WJ019
Sybase error code 13763
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the resultset function being called

Probable cause Some resultset function such as ’updateRow’ and ’deleteRow’ are invalid
when the cursor of the resultset is positioned at the insert row.

Cannot commit or rollback while enlisted in a transaction


Item Value
SQLCODE -800
Constant SQLE_CANNOT_COMMIT_OR_ROLLBACK_WHIL
E_ENLISTED
SQLSTATE 55W09
Sybase error code 13810
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You tried to explicitly commit or rollback on a connection that is enlisted in
a transaction. You must use the Commit/Abort protocol of the transaction
instead.

710
CHAPTER 10 Database Error Messages

Cannot convert %1 to a %2
Item Value
SQLCODE -157
Constant SQLE_CONVERSION_ERROR
SQLSTATE 53018
Sybase error code 257
ODBC 2 State 07006
ODBC 3 State 07006
Parameter 1 The value that could not be converted.
Parameter 2 The name of the type for the conversion.

Probable cause You supplied to or fetched from the database an invalid value. For example,
the value 12X might have been supplied where a number was required.

Cannot create an index on Java class ’%1’


Item Value
SQLCODE -704
Constant SQLE_CANNOT_INDEX_ON_JAVA_CLASS
SQLSTATE WW022
Sybase error code 13748
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the class.

Probable cause An operation requiring an index was attempted in which at attempt was made
to create an index on a Java class type.

711
Alphabetic list of error messages

Cannot create item (%1) in the specified dbspace.


Item Value
SQLCODE -648
Constant SQLE_INVALID_DBSPACE_FOR_CREATE
SQLSTATE 08W36
Sybase error code 13702
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The dbspace specified is invalid. For example, an index must be created in a
dbspace of the same type as the underlying table.

Cannot create synchronization entry for table ’%1’ with BLOB


primary key
Item Value
SQLCODE -779
Constant SQLE_BLOB_IN_SYNC_TABLE_PK
SQLSTATE 5RW18
Sybase error code 13789
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the table

Probable cause You attempted to create a synchronization on a table with BLOB primary
key.

712
CHAPTER 10 Database Error Messages

Cannot delete a column referenced in a trigger definition


Item Value
SQLCODE -269
Constant SQLE_COLUMN_IN_TRIGGER
SQLSTATE 53W06
Sybase error code 102
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to delete a column referenced in a trigger definition. DROP
the trigger before performing the ALTER statement.

Cannot deregister ’%1’ since active registered connection exists


Item Value
SQLCODE -786
Constant SQLE_DEREG_APP_IN_USE
SQLSTATE 5RW25
Sybase error code 13796
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the application

Probable cause You attempted to deregister an application while there are still active
connection registered to that application.

713
Alphabetic list of error messages

Cannot deregister application because of invalid cookie


Item Value
SQLCODE -785
Constant SQLE_DEREG_APP_NOT_FOUND
SQLSTATE 5RW24
Sybase error code 13795
ODBC 2 State 42000
ODBC 3 State 42S02

Probable cause Application has not been registered successfully or it has already been
deregistered previously.

Cannot deserialize Java object


Item Value
SQLCODE -663
Constant SQLE_JAVA_DESERIALIZATION_ERROR
SQLSTATE WW018
Sybase error code 13745
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The persisted Java object cannot be read from the database column. Possibly,
the class of the object has been removed or modified.

714
CHAPTER 10 Database Error Messages

Cannot drop a user that owns messages or data types


Item Value
SQLCODE -614
Constant SQLE_USER_OWNS_MESSAGES_OR_DATATYPE
S
SQLSTATE 55W05
Sybase error code 13632
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted to drop a user who is the creator of a message or user-defined
data type. The message or user-defined data type must be dropped first.

Cannot drop a user that owns objects involved in replication


Item Value
SQLCODE -731
Constant SQLE_USER_OWNS_REPLICATED_OBJECTS
SQLSTATE 55W06
Sybase error code 13633
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted to drop a user who is the creator of a database object involved
in replication. For example. the user may own a table that is part of a
publication.

715
Alphabetic list of error messages

Cannot drop a user that owns procedures in runtime server


Item Value
SQLCODE -270
Constant SQLE_USER_OWNS_PROCEDURES
SQLSTATE 55W04
Sybase error code 13641
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted to drop a user who owns procedures whil using the runtime
server. This operation would result in dropping procedures, and the runtime
server cannot drop procedures. Use the full server.

Cannot drop a user that owns tables in runtime system


Item Value
SQLCODE -128
Constant SQLE_USER_OWNS_TABLES
SQLSTATE 55W03
Sybase error code 13731
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted to drop a user who owns tables, while running the runtime
server. This operation would result in dropping tables, which is not permitted
in the runtime server. Use the full server.

716
CHAPTER 10 Database Error Messages

Cannot enlist in a transaction while already enlisted in a


transaction
Item Value
SQLCODE -801
Constant SQLE_CANNOT_ENLIST_WHILE_ALREADY_ENLI
STED
SQLSTATE 55W10
Sybase error code 13811
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You tried to enlist a second transaction on a connection that is already
enlisted in a transaction.

Cannot enlist in a transaction with uncommitted data pending


Item Value
SQLCODE -802
Constant SQLE_CANNOT_ENLIST_WITH_UNCOMMITTED_
DATA
SQLSTATE 55W11
Sybase error code 13812
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You tried to enlist a transaction on a connection that has pending
uncommitted data.

717
Alphabetic list of error messages

Cannot find index named ’%1’


Item Value
SQLCODE -183
Constant SQLE_INDEX_NOT_FOUND
SQLSTATE 52W03
Sybase error code 6226
ODBC 2 State S0012
ODBC 3 State 42S12
Parameter 1 Name of the index that cannot be found.

Probable cause You attempted to drop an index that does not exist. Check for spelling errors.
Check whether the index name must be qualified by a user ID.

Cannot initialize IQ memory manager: %1


Item Value
SQLCODE -745
Constant SQLE_IQ_MEMORY_MANAGER_FAILED
SQLSTATE 08W52
Sybase error code 13758
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause System V shared memory was requested but could not be allocated.

718
CHAPTER 10 Database Error Messages

Cannot insert or update computed column ’%1’


Item Value
SQLCODE -703
Constant SQLE_COMPUTED_COLUMN_WRITE_ATTEMPTE
D
SQLSTATE WW023
Sybase error code 4406
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the column.

Probable cause Computed column values cannot be modified explicitly. Their value is
determined implicitly from the computed expression value.

Cannot make a static reference to nonstatic variable ’%1’ in class


’%2’
Item Value
SQLCODE -686
Constant SQLE_STATIC_REF_TO_NONSTATIC_VAR
SQLSTATE WW020
Sybase error code 13716
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the nonstatic variable.
Parameter 2 The name of the class.

Probable cause A static reference was attempted on nonstatic variable of a class.

719
Alphabetic list of error messages

Cannot map a login ID to the sys or public user ID


Item Value
SQLCODE -248
Constant SQLE_INTEGRATED_LOGON_SYSMAP
SQLSTATE 28W07
Sybase error code 13696
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause You attempted to map a login ID to either sys or public

Cannot modify column ’%1’ in table ’%2’


Item Value
SQLCODE -191
Constant SQLE_CANNOT_MODIFY
SQLSTATE 42W32
Sybase error code 230
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the column that cannot be changed.
Parameter 2 Name of the table containing the column.

Probable cause You may have tried to modify a column that you do not have permission to
modify. You may have tried to modify a column defined as an expression
(such as column1+column2) in a view.

720
CHAPTER 10 Database Error Messages

Cannot modify publication entry using ALTER SYNCHRONIZATION


Item Value
SQLCODE -770
Constant SQLE_CANNOT_MODIFY_PUB_AS_SYNC
SQLSTATE 5RW15
Sybase error code 13780
ODBC 2 State 42000
ODBC 3 State 42S02

Probable cause You attempted to modify a publication entry using an alter synchronization
statement.

Cannot modify synchronization entry using ALTER PUBLICATION


Item Value
SQLCODE -769
Constant SQLE_CANNOT_MODIFY_SYNC_AS_PUB
SQLSTATE 5RW14
Sybase error code 13779
ODBC 2 State 42000
ODBC 3 State 42S02

Probable cause You attempted to modify a synchronization entry using an alter publication
statement.

721
Alphabetic list of error messages

Cannot not find synchronization %1 with name equal ’%2’


Item Value
SQLCODE -767
Constant SQLE_SYNCHRONIZATION_NOT_FOUND
SQLSTATE 5RW12
Sybase error code 13777
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Definition, template or site
Parameter 2 Name of the synchronization

Probable cause You misspelled the name of a synchronization publication, or you did not
qualify a publication name with a user name.

Cannot open transaction log file -- %1


Item Value
SQLCODE -106
Constant SQLE_CANNOT_OPEN_LOG
SQLSTATE 08W05
Sybase error code 2561
ODBC 2 State 08003
ODBC 3 State 08003
Parameter 1 Reason why transaction log file cannot be opened.

Probable cause The database server was unable to open the named transaction log file. The
log file name may include an invalid device or directory. If this is the case,
you can use the DBLOG utility to find out where the transaction log should
be and perhaps change it.

722
CHAPTER 10 Database Error Messages

Cannot register %1’ since another exclusive instance is running


Item Value
SQLCODE -782
Constant SQLE_SAME_EXCLUSIVE_APP_RUNNING
SQLSTATE 5RW21
Sybase error code 13792
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the application

Probable cause You attempted to start an application but another exclusive instance of the
same application is already registered.

Cannot register ’%1’ since registration cookie exhausted


Item Value
SQLCODE -789
Constant SQLE_APP_REG_COOKIE_EXHAUSTED
SQLSTATE 5RW28
Sybase error code 13799
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the application

Probable cause Cannot register until someone deregistered.

723
Alphabetic list of error messages

Cannot register another ’%1’ as an exclusive application


Item Value
SQLCODE -783
Constant SQLE_SAME_APP_RUNNING
SQLSTATE 5RW22
Sybase error code 13793
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the application

Probable cause You attempted to register an exclusive application but another instance of the
same application is already registered.

Cannot register connection because of invalid application cookie


Item Value
SQLCODE -784
Constant SQLE_CANNOT_REG_CONN
SQLSTATE 5RW23
Sybase error code 13794
ODBC 2 State 42000
ODBC 3 State 42S02

Probable cause Application registration cannot be found for the given cookie.

724
CHAPTER 10 Database Error Messages

Cannot register connection to ’%1’ since automatic label exhausted


Item Value
SQLCODE -790
Constant SQLE_CONN_REG_AUTO_LABEL_EXHAUSTED
SQLSTATE 5RW29
Sybase error code 13800
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the application

Probable cause You may register using a specified label instead.

Cannot remove class ’%1’: member of Jar


Item Value
SQLCODE -653
Constant SQLE_CLASS_MEMBER_OF_JAR
SQLSTATE WP004
Sybase error code 13743
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the class file that can’t be removed

Probable cause You attempted to remove a class file which is still part of a Jar. (It must be
removed with the Jar)

725
Alphabetic list of error messages

Cannot serialize Java object with class %1


Item Value
SQLCODE -662
Constant SQLE_JAVA_SERIALIZATION_ERROR
SQLSTATE WI009
Sybase error code 13744
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The class of the value that cannot be serialized.

Probable cause The Java object cannot be serialized as a persistent database column.

Cannot set a temporary option for user ’%1’


Item Value
SQLCODE -203
Constant SQLE_TEMPORARY_NOT_ALLOWED
SQLSTATE 42W45
Sybase error code 13687
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 user ID whose option was to be changed.

Probable cause TEMPORARY options are set on a connection basis. To change an option
for another user, do not specify TEMPORARY in the SET OPTION
statement.

726
CHAPTER 10 Database Error Messages

Cannot stop the database server


Item Value
SQLCODE -607
Constant SQLE_CANNOT_STOP_SERVER
SQLSTATE WW002
Sybase error code 13673
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The server has determined that it cannot be shut down at this time. Normally,
this error should not occur.

Cannot subscribe to ’%1’


Item Value
SQLCODE -768
Constant SQLE_CANNOT_SUBSCRIBE
SQLSTATE 5RW13
Sybase error code 13778
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the publication.

Probable cause Some publications are not subscribable such as a synchronization


publication.

727
Alphabetic list of error messages

Cannot synchronize table ’%1’ since it does not have a primary key
Item Value
SQLCODE -777
Constant SQLE_CANNOT_SYNC_TABLE_WITHOUT_PK
SQLSTATE 5RW16
Sybase error code 13787
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the table

Probable cause Table for synchronization must contain a primary key.

Cannot uniquely identify column ’%2’ of table ’%1’ in the current


jdbc resultset
Item Value
SQLCODE -756
Constant SQLE_JDBC_TBL_COL_NOT_FOUND_IN_RESULT
SET
SQLSTATE WJ021
Sybase error code 13766
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Table name
Parameter 2 Column name

Probable cause Failed to identify a column in a JDBC resultset with the given table name
and column name. This can happen either the given names are not found or
they are ambiguous.

728
CHAPTER 10 Database Error Messages

Cannot uniquely identify rows in cursor


Item Value
SQLCODE -295
Constant SQLE_CANNOT_UNIQUELY_IDENTIFY_ROWS
SQLSTATE 09W05
Sybase error code 311
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You opened a UNIQUE cursor on a SELECT statement for which a set of
columns uniquely identifying each row cannot be generated. One of the
tables may not be defined with a primary key or uniqueness constraint, or the
SELECT statement may involve a UNION or GROUP BY.

Cannot update an expression


Item Value
SQLCODE -190
Constant SQLE_NON_UPDATEABLE_COLUMN
SQLSTATE 53W02
Sybase error code 230
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You tried to update a column in a query that is a database expression rather
than a column in a table.

729
Alphabetic list of error messages

Cannot update column ’%1’ since it appears in the ORDER BY


clause.
Item Value
SQLCODE -814
Constant SQLE_CANNOT_UPDATE_ORDER_BY_COLUMN
SQLSTATE 42W37
Sybase error code 6267
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the column that appears in the ORDER BY
clause.

Probable cause You attempted to update a column that appears in the ORDER BY clause.
The ANSI_UPDATE_CONSTRAINTS option controls whether this update
is allowed.

Cannot update column ’%1’ since it does not appear in the SELECT
clause.
Item Value
SQLCODE -815
Constant SQLE_UPDATE_NOT_IN_SELECT
SQLSTATE 42W38
Sybase error code 7740
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the column that does not appear in the SELECT
clause.

Probable cause You attempted to update a column that does not explicitly appear in the
SELECT list. The ANSI_UPDATE_CONSTRAINTS option controls
whether this update is allowed.

730
CHAPTER 10 Database Error Messages

Cannot update member fields qualified with "final" modifier


Item Value
SQLCODE -699
Constant SQLE_CANNOT_UPDATE_FINAL_FIELD
SQLSTATE WJ012
Sybase error code 13606
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An attempt was made to modify a Java member that was qualified with the
"final" modifier. Such members are constant and cannot be modified.

Cannot update or delete an all-NULL row from table ’%1’


Item Value
SQLCODE -734
Constant SQLE_CANNOT_UPDATE_NULL_ROW
SQLSTATE 09W08
Sybase error code 13750
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 The name of the table which cannot be modified.

Probable cause You attempted to modify or delete a row in the specified table, which is part
of the null-supplying side of an outer join. However, the cursor is currently
positioned on a derived row that contains an all-NULL row for this table,
which is the result of the failure of one or more ON conditions to evaluate to
TRUE. Verify that the UPDATE or DELETE statement is correct.

731
Alphabetic list of error messages

Cannot update primary key for table ’%1’ involved in replication


Item Value
SQLCODE -781
Constant SQLE_REPL_ARTICLE_PK_CANNOT_BE_UPDATE
D
SQLSTATE 5RW20
Sybase error code 13791
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the table.

Probable cause The primary key of a table involved in replication cannot be updated. The
database option "Allow_replication_pkey_update" can be set to "OFF" to
allow updates to the primary key of table involved in replication.

Cannot update primary key for table ’%1’ involved in


synchronization
Item Value
SQLCODE -780
Constant SQLE_SYNC_ARTICLE_PK_CANNOT_BE_UPDAT
ED
SQLSTATE 5RW19
Sybase error code 13790
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the table.

Probable cause The primary key of a table involved in a synchronization publication cannot
be updated. The database option "Allow_sync_pkey_update" can be set to
"OFF" to allow updates to the primary key of table involved in a
synchronization publication.

732
CHAPTER 10 Database Error Messages

Character set translation to ’%1’ cannot be performed; ’%2’ is used


instead
Item Value
SQLCODE 114
Constant SQLE_CANNOT_PERFORM_CHAR_TRANSLATIO
N
SQLSTATE 01W12
Sybase error code 13613
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 Name of character set the application requested.
Parameter 2 Name of character set the database will be using.

Probable cause The server is unable to do a character translation from the character set the
database is using to the character set the application requested.

CHECKPOINT statement requires a rollback log


Item Value
SQLCODE -212
Constant SQLE_CHECKPOINT_REQUIRES_UNDO
SQLSTATE 42W20
Sybase error code 13653
ODBC 2 State 40001
ODBC 3 State 40001

Probable cause You cannot use a CHECKPOINT statement when the database server is
running in bulk mode without a rollback log.

733
Alphabetic list of error messages

Class ’%1’ has no public field ’%2’


Item Value
SQLCODE -93
Constant SQLE_FIELD_NOT_FOUND
SQLSTATE WW013
Sybase error code 13703
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the class in which the named field could not
be found.
Parameter 2 The name of the field which could not be found.

Probable cause An expression referenced a field which either does not exist or is not public.

Client/database server version mismatch


Item Value
SQLCODE -231
Constant SQLE_DBLIB_ENGINE_MISMATCH
SQLSTATE 08W19
Sybase error code 13658
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause Your executable uses a database interface library that does not match the
version number of the database server.

734
CHAPTER 10 Database Error Messages

Client/server communications protocol version mismatch


Item Value
SQLCODE -88
Constant SQLE_PROTOCOL_MISMATCH
SQLSTATE 08W15
Sybase error code 1602
ODBC 2 State 08S01
ODBC 3 State 08S01

Probable cause The connection failed because the protocol versions of the client and the
server do not match. Make sure the client and server software are the same
version.

Column %1 in foreign key has a different definition than primary


key
Item Value
SQLCODE -113
Constant SQLE_INVALID_FOREIGN_KEY_DEF
SQLSTATE 53030
Sybase error code 1721
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the problem column.

Probable cause The data type of the column in the foreign key is not the same as the data
type of the column in the primary key. Change the definition of one of the
columns using ALTER TABLE.

735
Alphabetic list of error messages

Column ’%1’ found in more than one table -- need a correlation


name
Item Value
SQLCODE -144
Constant SQLE_COLUMN_AMBIGUOUS
SQLSTATE 52002
Sybase error code 209
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the ambiguous column.

Probable cause You have not put a correlation name on a column that is found in more than
one of the tables referenced in a query. You need to add a correlation name
to the reference.

Column ’%1’ in table ’%2’ cannot be NULL


Item Value
SQLCODE -195
Constant SQLE_COLUMN_CANNOT_BE_NULL
SQLSTATE 23502
Sybase error code 233
ODBC 2 State 23000
ODBC 3 State 23000
Parameter 1 Name of the column that cannot be NULL.
Parameter 2 Name of the table containing the column.

Probable cause You have not supplied a value where a value is required. The column
definition prohibits NULL values or the column is part of a NOT NULL
foreign key.

736
CHAPTER 10 Database Error Messages

Column ’%1’ not found


Item Value
SQLCODE -143
Constant SQLE_COLUMN_NOT_FOUND
SQLSTATE 52003
Sybase error code 207
ODBC 2 State S0002
ODBC 3 State 42S22
Parameter 1 Name of the column that could not be found.

Probable cause You misspelled the name of a column, or the column you are looking for is
in a different table.

COMMIT/ROLLBACK not allowed within atomic operation


Item Value
SQLCODE -267
Constant SQLE_ATOMIC_OPERATION
SQLSTATE 42W28
Sybase error code 13640
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted a COMMIT or ROLLBACK statement while executing


within an atomic operation.

737
Alphabetic list of error messages

COMMIT/ROLLBACK not allowed within trigger actions


Item Value
SQLCODE -273
Constant SQLE_INVALID_TRIGGER_STATEMENT
SQLSTATE 2D501
Sybase error code 102
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to execute a statement that is not allowed while performing a
trigger action. COMMIT and ROLLBACK statements cannot be executed
from a trigger.

Communication error
Item Value
SQLCODE -85
Constant SQLE_COMMUNICATIONS_ERROR
SQLSTATE 08W12
Sybase error code 1602
ODBC 2 State 08S01
ODBC 3 State 08S01

Probable cause There is a client/server communication problem. The client may have been
unable to start because a communication error occurred while trying to locate
the server.

738
CHAPTER 10 Database Error Messages

Computed columns are not supported in this database


Item Value
SQLCODE -709
Constant SQLE_COMPUTED_COLUMNS_NOT_SUPPORTED
SQLSTATE 0AW06
Sybase error code 13722
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause The current database is an older database and does not have catalog support
for computed (materialized) columns. To use this feature, upgrade your
database to the most recent version.

Connection not found


Item Value
SQLCODE -108
Constant SQLE_CONNECTION_NOT_FOUND
SQLSTATE 08W02
Sybase error code 4224
ODBC 2 State 08003
ODBC 3 State 08003

Probable cause The specified connection name on a DISCONNECT or SET CONNECTION


statement is invalid.

739
Alphabetic list of error messages

Connection was terminated


Item Value
SQLCODE -308
Constant SQLE_CONNECTION_TERMINATED
SQLSTATE 40W07
Sybase error code 4224
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause Your database connection has been terminated and your transaction has been
rolled back. The connection may have been terminated because a DBA
executed a DROP CONNECTION statement, or because the database server
was shut down, or because your network connection to the database server
was interrupted.

Connections to database have been disabled


Item Value
SQLCODE -99
Constant SQLE_CONNECTIONS_DISABLED
SQLSTATE 08W04
Sybase error code 4224
ODBC 2 State 08005
ODBC 3 State 08005

Probable cause Connections to the network database server have been disabled. You will
receive this error until they have been re-enabled on the server console.

740
CHAPTER 10 Database Error Messages

Contents of backup files are inconsistent


Item Value
SQLCODE -715
Constant SQLE_RESTORE_INCONSISTENT
SQLSTATE WB006
Sybase error code 13724
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause During a RESTORE, the contents of a backup that was done to two or more
disk or tape devices were found to be inconsistent.

Correlation name ’%1’ not found


Item Value
SQLCODE -142
Constant SQLE_CORRELATION_NAME_NOT_FOUND
SQLSTATE 52W02
Sybase error code 208
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the invalid correlation name.

Probable cause You misspelled a correlation name, or you used a table name instead of the
correlation name.

741
Alphabetic list of error messages

Could not access column information for the table ’%1’


Item Value
SQLCODE -667
Constant SQLE_OMNI_RMT_COLUMNS_NOTFOUND
SQLSTATE WO008
Sybase error code 11207
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The complete name of the remote table

Probable cause Column information for the table could not be accessed. Check privileges for
the table.

Could not allocate resources to call external function


Item Value
SQLCODE -622
Constant SQLE_ERROR_CALLING_FUNCTION
SQLSTATE WW008
Sybase error code 13679
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The external function could not be called due to a shortage of operating
system resources. If the operating system supports threads, the maximum
thread count should be increased.

742
CHAPTER 10 Database Error Messages

Could not change an opened prepared statement or callable


statement
Item Value
SQLCODE -694
Constant SQLE_CANNOT_CHANGE_OPENED_STATEMENT
SQLSTATE WJ008
Sybase error code 13603
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to change the SQL statement of an opened prepared statement
or callable statement. Prepared statement and callable statement must be
closed before attempting such changes.

Could not decompress class ’%1’ from Jar.


Item Value
SQLCODE -652
Constant SQLE_CANNOT_DECOMPRESS_CLASS
SQLSTATE WP003
Sybase error code 13742
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the class file in the Jar

Probable cause The Java runtime library must be installed to extract class files from .ZIPs or
.JARs

743
Alphabetic list of error messages

Could not execute backup/restore DLL (%1) entry point.


Item Value
SQLCODE -692
Constant SQLE_BACKUP_ENTRY_NOT_FOUND
SQLSTATE 08W45
Sybase error code 13719
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An attempt to locate or execute the backup/restore DLL entry point failed.

Could not execute store DLL (%1) entry point.


Item Value
SQLCODE -647
Constant SQLE_STORE_ENTRY_NOT_FOUND
SQLSTATE 08W35
Sybase error code 13700
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An attempt to locate or execute the store DLL entry point failed.

744
CHAPTER 10 Database Error Messages

Could not find ’%1’ in dynamic library ’%2’


Item Value
SQLCODE -621
Constant SQLE_COULD_NOT_FIND_FUNCTION
SQLSTATE WW007
Sybase error code 13678
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the function which could not be found.
Parameter 2 Name of the dynamic library in which the function could
not be found.

Probable cause The external function could not be found in the dynamic library.

Could not load dynamic library ’%1’


Item Value
SQLCODE -620
Constant SQLE_COULD_NOT_LOAD_LIBRARY
SQLSTATE WW006
Sybase error code 13677
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the dynamic library which could not be loaded.

Probable cause This error is usually caused by a failure to load a dynamic library named in
an external function call. This error can also occur if other libraries such as
the Java virtual machine library are missing.

745
Alphabetic list of error messages

Could not load the backup/restore DLL %1


Item Value
SQLCODE -691
Constant SQLE_BACKUP_NOT_LOADED
SQLSTATE 08W44
Sybase error code 13718
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An attempt to load the backup/restore DLL failed.

Could not load the store DLL %1


Item Value
SQLCODE -646
Constant SQLE_STORE_NOT_LOADED
SQLSTATE 08W34
Sybase error code 13699
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An attempt to load the store DLL failed.

Creating remote tables with computed columns is not supported


Item Value
SQLCODE -732
Constant SQLE_OMNI_COMPUTED_NOT_SUPPORTED
SQLSTATE WO021
Sybase error code 11205
ODBC 2 State ERROR
ODBC 3 State ERROR

746
CHAPTER 10 Database Error Messages

Probable cause Computed columns are not supported in ’CREATE TABLE’ statements
which specify a remote location.

Current connection is already registered to ’%1’ as ’%2’


Item Value
SQLCODE -787
Constant SQLE_CONN_ALREADY_REGISTERED
SQLSTATE 5RW26
Sybase error code 13797
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the application
Parameter 2 Registered connection label

Probable cause You attempted to register this connection more than once.

Cursor already open


Item Value
SQLCODE -172
Constant SQLE_CURSOR_ALREADY_OPEN
SQLSTATE 24502
Sybase error code 558
ODBC 2 State 24000
ODBC 3 State 24000

Probable cause You attempted to OPEN a cursor that is already open.

747
Alphabetic list of error messages

Cursor has not been declared


Item Value
SQLCODE -170
Constant SQLE_CURSOR_NOT_DECLARED
SQLSTATE 24W01
Sybase error code 557
ODBC 2 State 24000
ODBC 3 State 24000

Probable cause You attempted to OPEN a cursor that has not been declared.

Cursor is restricted to FETCH NEXT operations


Item Value
SQLCODE -668
Constant SQLE_NO_SCROLL_CURSOR
SQLSTATE 09W06
Sybase error code 13710
ODBC 2 State S1106
ODBC 3 State HY106

Probable cause An illegal FETCH operation has been detected for a NO SCROLL cursor.
For a forward-only cursor the only permitted FETCH operations are FETCH
RELATIVE 0 and FETCH NEXT (FETCH RELATIVE 1).

748
CHAPTER 10 Database Error Messages

Cursor not open


Item Value
SQLCODE -180
Constant SQLE_CURSOR_NOT_OPEN
SQLSTATE 24501
Sybase error code 559
ODBC 2 State 34000
ODBC 3 State 34000

Probable cause You attempted to OPEN a cursor that has not been declared.

Cursor operation conflict


Item Value
SQLCODE 108
Constant SQLE_CURSOR_OPERATION_CONFLICT
SQLSTATE 01001
Sybase error code 554
ODBC 2 State OK
ODBC 3 State OK

Probable cause You attempted to perform an operation on the current row of a cursor, but the
row has been modified by a searched UPDATE or DELETE or by a
positioned UPDATE or DELETE.

749
Alphabetic list of error messages

Data definition statements not allowed in procedures or triggers


Item Value
SQLCODE -623
Constant SQLE_DDL_NOT_ALLOWED_IN_PROCEDURES
SQLSTATE 52W21
Sybase error code 154
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The procedure or trigger definition contains a data definition statement (such
as CREATE, DROP, GRANT, REVOKE, ALTER). These statements are
not allowed within procedures or triggers.

Database %1 needs recovery


Item Value
SQLCODE -665
Constant SQLE_DATABASE_NEEDS_RECOVERY
SQLSTATE 08W41
Sybase error code 13709
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The filename of the database that needs recovery.

Probable cause The database quit abnormally the last time it was used. Database recovery
must be performed before proceeding.

750
CHAPTER 10 Database Error Messages

Database backup not started


Item Value
SQLCODE -241
Constant SQLE_BACKUP_NOT_STARTED
SQLSTATE WB002
Sybase error code 3206
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause A database backup could not be started. Either you do not have DBA
authority, or another backup has started and not completed.

Database cannot be started -- %1


Item Value
SQLCODE -105
Constant SQLE_UNABLE_TO_CONNECT
SQLSTATE 08001
Sybase error code 4001
ODBC 2 State 08001
ODBC 3 State 08001
Parameter 1 Reason that database cannot be started.

Probable cause The specified database cannot be started. Either it does not exist, it is not a
database, it is corrupt, or it is an older format.

751
Alphabetic list of error messages

Database creation failed


Item Value
SQLCODE -645
Constant SQLE_DATABASE_NOT_CREATED
SQLSTATE 08W33
Sybase error code 928
ODBC 2 State 08004
ODBC 3 State 08004

Probable cause Your attempt to initialize a file for a database or for a write file failed.

Database is active
Item Value
SQLCODE -664
Constant SQLE_DATABASE_ACTIVE
SQLSTATE 08W40
Sybase error code 13708
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An attempt was made to create a writefile for a database that is currently
active.

Database name not unique


Item Value
SQLCODE -77
Constant SQLE_ALIAS_CLASH
SQLSTATE 08W27
Sybase error code 1801
ODBC 2 State 08001
ODBC 3 State 08001

752
CHAPTER 10 Database Error Messages

Probable cause The database cannot be started as its name is conflicting with a previously
started database.

Database name required to start server


Item Value
SQLCODE -87
Constant SQLE_DATABASE_NAME_REQUIRED
SQLSTATE 08W14
Sybase error code 840
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause You did not supply a database name. A database name is required to start the
database server.

Database option ’%1’ for user ’%2’ has an invalid setting


Item Value
SQLCODE 113
Constant SQLE_INVALID_OPTION_ON_CONNECT
SQLSTATE 01W11
Sybase error code 13688
ODBC 2 State 42000
ODBC 3 State OK
Parameter 1 Name of the database option that has the invalid value.
Parameter 2 Name of the user attempting to connect.

Probable cause Upon processing a connection request for a specific user, the server
processed a database option from the SYSOPTIONS table which had an
invalid setting. The erroneous option setting is ignored; in its place, the
server will use the default option value for the current database.

753
Alphabetic list of error messages

Database page size too big


Item Value
SQLCODE -97
Constant SQLE_PAGE_SIZE_TOO_BIG
SQLSTATE 08W22
Sybase error code 927
ODBC 2 State 08004
ODBC 3 State 08004

Probable cause You attempted to start a database or create a write file for a database with a
page size that exceeds the maximum page size of the running server. Either
restart the server with this database named on the command line, or restart
the server with a larger page size.

Database server already running


Item Value
SQLCODE -96
Constant SQLE_ENGINE_ALREADY_RUNNING
SQLSTATE 08W23
Sybase error code 7950
ODBC 2 State S1000
ODBC 3 State HY000

Probable cause The database server was not able to start on a db_start_engine call because it
was already running.

754
CHAPTER 10 Database Error Messages

Database server connection limit exceeded


Item Value
SQLCODE -102
Constant SQLE_TOO_MANY_CONNECTIONS
SQLSTATE 08W03
Sybase error code 1601
ODBC 2 State 08004
ODBC 3 State 08004

Probable cause You exceeded the number of computers allowed to connect to the server. If
you are running the network database server, the limit is spelled out in your
license agreement. The server may be running low on cache such that it
cannot accept any more database connections. The personal database server
is restricted to 10 connections.

Database server not running


Item Value
SQLCODE -100
Constant SQLE_ENGINE_NOT_RUNNING
SQLSTATE 08W01
Sybase error code 7950
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause The database server is not running, or the interface library is unable to find it.

755
Alphabetic list of error messages

Database server not running in multi-user mode


Item Value
SQLCODE -89
Constant SQLE_ENGINE_NOT_MULTIUSER
SQLSTATE 08W16
Sybase error code 7203
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause The database server was started for bulk loading (the -b switch) and cannot
be used as a network server. Stop the database server, and start again without
-b.

Database upgrade failed


Item Value
SQLCODE -672
Constant SQLE_DATABASE_UPGRADE_FAILED
SQLSTATE 08W42
Sybase error code 3451
ODBC 2 State 08004
ODBC 3 State 08004

Probable cause Your attempt to upgrade a database failed. This could be caused by a failure
to locate one of the SQL script files used to define the system table changes.

756
CHAPTER 10 Database Error Messages

Database upgrade not possible


Item Value
SQLCODE -673
Constant SQLE_DATABASE_UPGRADE_NOT_POSSIBLE
SQLSTATE 08W43
Sybase error code 3451
ODBC 2 State 08004
ODBC 3 State 08004

Probable cause An attempt to upgrade a database failed. The database is too old to be
upgraded.

db_init has not been called or the call to db_init failed


Item Value
SQLCODE -739
Constant SQLE_DB_INIT_NOT_CALLED
SQLSTATE 55W07
Sybase error code 13752
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The SQLCA passed to a dblib entry point has not been initialized by a call to
db_init or the call to db_init failed.

757
Alphabetic list of error messages

Dbspace ’%1’ not found


Item Value
SQLCODE -138
Constant SQLE_DBSPACE_NOT_FOUND
SQLSTATE 52W13
Sybase error code 1802
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the dbspace that could not be found.

Probable cause You tried to access a dbspace that the database server could not find.

Dbspace for table ’%1’ not found


Item Value
SQLCODE -821
Constant SQLE_DBSPACE_FOR_TABLE_UNAVAILABLE
SQLSTATE 52W19
Sybase error code 13827
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the table whose dbspace could not be found.

Probable cause You tried to access a table in a dbspace that the database server could not
find. You may need to change the filename associated with the dbspace using
the ALTER DBSPACE statement.

758
CHAPTER 10 Database Error Messages

Deadlock detected
Item Value
SQLCODE -306
Constant SQLE_DEADLOCK
SQLSTATE 40001
Sybase error code 1205
ODBC 2 State 40001
ODBC 3 State 40001

Probable cause You attempted to read or write a row and it is locked by another user. Also,
the other user is blocked directly or indirectly on your own transaction. This
is a deadlock situation and your transaction has been chosen as the one to
rollback.

Derived table ’%1’ has no name for column %2


Item Value
SQLCODE -163
Constant SQLE_NO_COLUMN_NAME
SQLSTATE 52004
Sybase error code 209
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the derived table.
Parameter 2 Number of the column for which there is no name.

Probable cause The specified column of the derived table has no column name. Use a select
list alias in the query specification or use a derived columns specifier.

759
Alphabetic list of error messages

Disallowed language extension detected in syntax near ’%1’


Item Value
SQLCODE -627
Constant SQLE_INVALID_SYNTAX_EXTENSION
SQLSTATE 0AW03
Sybase error code 538
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The word or symbol where the syntax has been detected.

Probable cause The statement you are trying to execute contains extensions to ANSI 1992
Entry Level SQL. These extensions are not allowed by the current settings.

Disk full ’%1’ -- transaction rolled back


Item Value
SQLCODE -304
Constant SQLE_DEVICE_FULL
SQLSTATE 40W03
Sybase error code 3618
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause Your hard disk is out of space. A ROLLBACK WORK statement has been
automatically executed.

760
CHAPTER 10 Database Error Messages

Division by zero
Item Value
SQLCODE -628
Constant SQLE_DIV_ZERO_ERROR
SQLSTATE 22012
Sybase error code 36007
ODBC 2 State 22012
ODBC 3 State 22012

Probable cause A division by zero operation was detected.

DTC transactions are not supported on this platform


Item Value
SQLCODE -799
Constant SQLE_DTC_TRANSACTIONS_NOT_SUPPORTED
SQLSTATE 0AW10
Sybase error code 13809
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You tried to enlist a DTC transactions on a platform that does not support
this feature.

Duplicate insert column


Item Value
SQLCODE -637
Constant SQLE_DUPLICATE_INSERT_COLUMN
SQLSTATE 42W41
Sybase error code 264
ODBC 2 State 37000
ODBC 3 State 42000

761
Alphabetic list of error messages

Probable cause You supplied a duplicate column name in the list of insert columns.

Duplicate referencing column


Item Value
SQLCODE -636
Constant SQLE_DUPLICATE_REFERENCING_COLUMN
SQLSTATE 42W40
Sybase error code 1909
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You supplied a duplicate column name in the list of referencing columns.

Dynamic memory exhausted


Item Value
SQLCODE -78
Constant SQLE_DYNAMIC_MEMORY_EXHAUSTED
SQLSTATE 08W26
Sybase error code 9119
ODBC 2 State S1001
ODBC 3 State HY001

Probable cause A failure occurred when trying to allocate dynamic memory.

762
CHAPTER 10 Database Error Messages

Error during backup: %1


Item Value
SQLCODE -697
Constant SQLE_BACKUP_ERROR
SQLSTATE 08W46
Sybase error code 13720
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An error occurred during a BACKUP statement.

Error in assignment
Item Value
SQLCODE -641
Constant SQLE_ERROR_IN_ASSIGNMENT
SQLSTATE 22005
Sybase error code 8205
ODBC 2 State 22005
ODBC 3 State 22018

Probable cause In a GET DESCRIPTOR statement, the data type of the host variable must
correspond to the data type of the descriptor item.

763
Alphabetic list of error messages

Error number %1 for RAISERROR is less than 17000


Item Value
SQLCODE -296
Constant SQLE_ERROR_NUMBER_OUT_OF_RANGE
SQLSTATE 53W07
Sybase error code 2732
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Error number.

Probable cause You supplied an invalid error number in a RAISERROR statement. The
number must be greater than or equal to 17000.

Error opening cursor


Item Value
SQLCODE -171
Constant SQLE_OPEN_CURSOR_ERROR
SQLSTATE 07003
Sybase error code 102
ODBC 2 State 24000
ODBC 3 State 24000

Probable cause You attempted to open a cursor on a statement that is not a SELECT
statement or a CALL or EXEC statement.

764
CHAPTER 10 Database Error Messages

Error parsing connection parameter string


Item Value
SQLCODE -655
Constant SQLE_GEN_PARSE_ERROR
SQLSTATE 08W38
Sybase error code 13707
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause The connection string could not be parsed. The string or connection
parameter file contains a syntax error.

Error writing to transaction log file


Item Value
SQLCODE -107
Constant SQLE_ERROR_WRITING_LOG
SQLSTATE 08W17
Sybase error code 3619
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The database server got an I/O error writing the transaction log file. Perhaps
the disk is full or the log file name is invalid.

765
Alphabetic list of error messages

Event ’%1’ already exists


Item Value
SQLCODE -772
Constant SQLE_EVENT_ALREADY_EXISTS
SQLSTATE WE002
Sybase error code 13782
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the event that already exists.

Probable cause You have attempted to create an event with a name that already exists in
SYS.SYSEVENT.

Event ’%1’ not found


Item Value
SQLCODE -771
Constant SQLE_EVENT_NOT_FOUND
SQLSTATE WE001
Sybase error code 13781
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the event that could not be found.

Probable cause You have attempted to reference an event with a name that does not exist in
SYS.SYSEVENT.

766
CHAPTER 10 Database Error Messages

Expression has unsupported data type


Item Value
SQLCODE -624
Constant SQLE_DATATYPE_NOT_ALLOWED
SQLSTATE WW009
Sybase error code 10356
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause Either an external function or Java method is declared to have a parameter or
result data type which is not supported, or a Java field reference with
unsupported result type was attempted.

External login for server %1 could not be found


Item Value
SQLCODE -712
Constant SQLE_OMNI_EXTLOGIN_NOT_FOUND
SQLSTATE WO013
Sybase error code 11221
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the remote server.

Probable cause An external login for the server and user does not exist.

767
Alphabetic list of error messages

Feature ’%1’ not implemented


Item Value
SQLCODE -134
Constant SQLE_NOT_IMPLEMENTED
SQLSTATE 0A000
Sybase error code 401
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The unimplemented feature.

Probable cause You attempted to carry out an operation or use a feature that is not
implemented in this version of Adaptive Server Anywhere.

Feature not available with UltraLite


Item Value
SQLCODE -749
Constant SQLE_NOT_SUPPORTED_IN_ULTRALITE
SQLSTATE 0AW07
Sybase error code 13762
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to execute a statement or use a feature that is not supported in
an UltraLite database. For example, UltraLite does not support statements
that modify the schema of the database.

768
CHAPTER 10 Database Error Messages

Field ’%1’ of class ’%2’ cannot be null


Item Value
SQLCODE -649
Constant SQLE_FIELD_CANNOT_BE_NULL
SQLSTATE WW015
Sybase error code 13741
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the field which cannot be null.
Parameter 2 The name of the class which has the field.

Probable cause An attempt was made to store a SQL null value in a Java object field which
has a Java type that cannot be null. For example, the Java ’int’ type cannot be
null.

FOR UPDATE has been incorrectly specified for a READ ONLY


cursor.
Item Value
SQLCODE -813
Constant SQLE_NON_UPDATEABLE_CURSOR
SQLSTATE 42W36
Sybase error code 7301
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted to declare a cursor FOR UPDATE on a query that is not
updateable. Queries that contain DISTINCT, GROUP BY, HAVING, or
UNION, or that contain aggregate functions are read only. If the
ANSI_UPDATE_CONSTRAINTS option is on, then queries that contain an
join are read only. If the query references a view then the view may be non-
updateable.

769
Alphabetic list of error messages

Foreign key ’%1’ for table ’%2’ duplicates an existing foreign key
Item Value
SQLCODE -251
Constant SQLE_DUPLICATE_FOREIGN_KEY
SQLSTATE 52W06
Sybase error code 1909
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 The role name of the new foreign key.
Parameter 2 The table containing the foreign key.

Probable cause You attempted to define a foreign key that already exists.

Foreign key name ’%1’ not found


Item Value
SQLCODE -145
Constant SQLE_FOREIGN_KEY_NAME_NOT_FOUND
SQLSTATE 52W07
Sybase error code 102
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the non-existing foreign key.

Probable cause You misspelled the name of a foreign key, or the foreign key does not exist.

770
CHAPTER 10 Database Error Messages

Format string argument number %1 is invalid


Item Value
SQLCODE -294
Constant SQLE_INVALID_FORMAT_STRING_ARG_NUM
SQLSTATE 53W08
Sybase error code 2749
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Argument number.

Probable cause You supplied an invalid argument number in the format string for a PRINT
or RAISERROR statement. The number must be between 1 and 20 and must
not exceed the number of arguments provided.

Function or column reference to ’%1’ in the select list must also


appear in a GROUP BY
Item Value
SQLCODE -149
Constant SQLE_INVALID_GROUP_SELECT
SQLSTATE 53003
Sybase error code 7321
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the column referenced directly, or in an
expression, that must be in the GROUP BY clause.

Probable cause You used a non-aggregate function or column reference in the select list that
does not appear in the GROUP BY clause. In a query using GROUP BY,
select list items that are not aggregate functions must also appear in the
GROUP BY clause. If the select list item is a column reference or an alias,
you may add the column name or alias to the GROUP BY clause. If the
select list item is a scalar function, ensure that the function’s arguments in the
GROUP BY clause match exactly with those in the select list. In some cases,
you may want to use the MAX function on the column name (or another
aggregate function) instead of adding the column to the GROUP BY clause.

771
Alphabetic list of error messages

GRANT of column permission on view not allowed


Item Value
SQLCODE -635
Constant SQLE_NO_COLUMN_PERMS_FOR_VIEWS
SQLSTATE 52W22
Sybase error code 102
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You cannot grant permissions on columns for views.

Host variables may not be used within a batch


Item Value
SQLCODE -807
Constant SQLE_HOSTVARS_IN_BATCH
SQLSTATE 07W07
Sybase error code 13817
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You have attempted to execute a batch which contains host variable
references. Host variables are not supported within a batch.

I/O error %1 -- transaction rolled back


Item Value
SQLCODE -305
Constant SQLE_DEVICE_ERROR
SQLSTATE 40W04
Sybase error code 3013
ODBC 2 State ERROR
ODBC 3 State ERROR

772
CHAPTER 10 Database Error Messages

Probable cause Adaptive Server Anywhere has detected a problem with your hard disk. A
ROLLBACK WORK statement has been automatically executed.

Identifier ’%1’ too long


Item Value
SQLCODE -250
Constant SQLE_IDENTIFIER_TOO_LONG
SQLSTATE 54003
Sybase error code 103
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 The identifier in error.

Probable cause An identifier is longer than 128 characters.

Identity attribute mismatch for column ’%1’


Item Value
SQLCODE -725
Constant SQLE_OMNI_IDENTITY_MISMATCH
SQLSTATE WO019
Sybase error code 11212
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 The name of the column.

Probable cause The identity attribute of the column specified in the ’CREATE EXISTING’
statement differs from the identity attribute of the actual column.

773
Alphabetic list of error messages

Illegal cursor operation attempt


Item Value
SQLCODE -187
Constant SQLE_CURSOROP_NOT_ALLOWED
SQLSTATE 09W02
Sybase error code 9526
ODBC 2 State 07005
ODBC 3 State 07005

Probable cause You attempted an illegal cursor operation. For example, you may be
attempting to OPEN a cursor for a statement that is neither a SELECT nor a
BATCH.

Illegal user selectivity estimate specified


Item Value
SQLCODE 118
Constant SQLE_INVALID_USER_ESTIMATE
SQLSTATE 01W16
Sybase error code 13617
ODBC 2 State OK
ODBC 3 State OK

Probable cause You specified a user selectivity estimate that is either not a literal constant or
is outside the range 0.0 to 100.0 (estimates are specified as percentages). The
estimate has been ignored.

774
CHAPTER 10 Database Error Messages

Incomplete transactions prevent transaction log renaming


Item Value
SQLCODE -242
Constant SQLE_BACKUP_CANNOT_RENAME_LOG_YET
SQLSTATE WB003
Sybase error code 3206
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The last page in the transaction log was read by a call to db_backup. One or
more currently active connections have partially completed transactions,
preventing the transaction log file from being renamed. Reissue the
db_backup call.

Incorrect store DLL (%1) version.


Item Value
SQLCODE -711
Constant SQLE_STORE_VERSION_MISMATCH
SQLSTATE 08W47
Sybase error code 13701
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The store and server DLL versions do not match.

775
Alphabetic list of error messages

Index ’%1’ for table ’%2’ would not be unique


Item Value
SQLCODE -196
Constant SQLE_INDEX_NOT_UNIQUE
SQLSTATE 23505
Sybase error code 548
ODBC 2 State 23000
ODBC 3 State 23000
Parameter 1 Name of the index that would not be unique.
Parameter 2 Name of the table that contains the index.

Probable cause You attempted to insert or update a row that has the same value as another
row in some column, and there is a constraint that does not allow two rows to
have the same value in that column.

Index name ’%1’ is ambiguous


Item Value
SQLCODE -678
Constant SQLE_AMBIGUOUS_INDEX_NAME
SQLSTATE 52W40
Sybase error code 1921
ODBC 2 State S0011
ODBC 3 State 42S11
Parameter 1 Name of the ambiguous index.

Probable cause A statement has referred to an index name which is not unique. Preface the
index name by an owner name.

776
CHAPTER 10 Database Error Messages

Index name ’%1’ not unique


Item Value
SQLCODE -111
Constant SQLE_INDEX_NAME_NOT_UNIQUE
SQLSTATE 52W04
Sybase error code 1921
ODBC 2 State S0011
ODBC 3 State 42S11
Parameter 1 Name of the invalid index.

Probable cause You attempted to create an index with the same name as an existing index.

Index type specification of ’%1’ is invalid


Item Value
SQLCODE -650
Constant SQLE_INVALID_INDEX_TYPE
SQLSTATE WW016
Sybase error code 13704
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause IQ index types can be specified for IQ indexes only.

777
Alphabetic list of error messages

Input parameter index out of range


Item Value
SQLCODE -689
Constant SQLE_BAD_PARAM_INDEX
SQLSTATE WJ005
Sybase error code 13717
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The range for valid parameters is from 1 up to the number of host variables
specified in the prepared/callable statement.

INSERT/DELETE on cursor can modify only one table


Item Value
SQLCODE -199
Constant SQLE_ONLY_ONE_TABLE
SQLSTATE 09W04
Sybase error code 102
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to insert into a cursor and have specified values for more than
one table; or you attempted to delete from a cursor that involves a join. Insert
into one table at a time. For DELETE, use the FROM clause to specify
which table you wish to delete from.

778
CHAPTER 10 Database Error Messages

Integrated login failed


Item Value
SQLCODE -245
Constant SQLE_INTEGRATED_LOGON_FAILED
SQLSTATE 28W04
Sybase error code 13691
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause The integrated login failed. You may not have a system account on the server
machine.

Integrated logins are not permitted


Item Value
SQLCODE -205
Constant SQLE_INVALID_STANDARD_LOGON
SQLSTATE 28W02
Sybase error code 13689
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause The LOGIN_MODE database option is set to STANDARD logon type, and
you attempted an integrated login. Change the option setting or supply an
explicit user ID.

779
Alphabetic list of error messages

Integrated logins are not supported for this database


Item Value
SQLCODE -246
Constant SQLE_INTEGRATED_LOGON_UNSUPPORTED
SQLSTATE 28W05
Sybase error code 13694
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause The current database is an older database and does not have a sys.syslogin
table to map integrated login IDs to database user IDs. You must upgrade
your database to use integrated logins.

Internal database error %1 -- transaction rolled back


Item Value
SQLCODE -301
Constant SQLE_DATABASE_ERROR
SQLSTATE 40W01
Sybase error code 13665
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Identification of the error.

Probable cause An internal database error occurred. If it can be reproduced, it should be


reported to Sybase. A ROLLBACK WORK statement has been
automatically executed.

780
CHAPTER 10 Database Error Messages

Internal rollback log corrupted


Item Value
SQLCODE -311
Constant SQLE_LOG_CORRUPTED
SQLSTATE WI004
Sybase error code 932
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause While processing a COMMIT or ROLLBACK, corruption was found in the
internal rollback log. This is a fatal internal error.

Invalid absolute or relative offset in FETCH


Item Value
SQLCODE -263
Constant SQLE_INVALID_FETCH_POSITION
SQLSTATE 42W25
Sybase error code 6259
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You specified an offset in a FETCH that was invalid or NULL.

Invalid class byte code


Item Value
SQLCODE -670
Constant SQLE_BAD_CLASS_BYTE_CODE
SQLSTATE WP005
Sybase error code 13746
ODBC 2 State ERROR
ODBC 3 State ERROR

781
Alphabetic list of error messages

Probable cause A binary expression passed to the INSTALL JAVA statement was not a
valid Java class.

Invalid column number


Item Value
SQLCODE -159
Constant SQLE_INVALID_COLUMN_NUMBER
SQLSTATE 42W13
Sybase error code 182
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You gave an invalid column number, or the column you are looking for is in
a different table.

Invalid comparison
Item Value
SQLCODE -710
Constant SQLE_INVALID_COMPARISON
SQLSTATE 52W25
Sybase error code 13749
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause An attempt was made to compare two arguments that do not support
comparison. For example, it is not valid to compare a Java object with
another Java object, unless the class of the object supports a valid
compareTo() method.

782
CHAPTER 10 Database Error Messages

Invalid data conversion


Item Value
SQLCODE 103
Constant SQLE_CANNOT_CONVERT
SQLSTATE 01W03
Sybase error code 518
ODBC 2 State 07006
ODBC 3 State 07006

Probable cause The database could not convert a value to the required type. The value being
converted was either supplied to the database on an insert, update or as a host
bind variable, or was a value retrieved from the database into a host variable
or SQLDA.

Invalid data type for column in WRITETEXT or READTEXT


Item Value
SQLCODE -609
Constant SQLE_INVALID_TEXT_IMAGE_DATATYPE
SQLSTATE 53W09
Sybase error code 7139
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You referenced a column in a WRITETEXT or READTEXT statement that


is not defined for storing text or image data.

783
Alphabetic list of error messages

Invalid database page size


Item Value
SQLCODE -644
Constant SQLE_PAGE_SIZE_INVALID
SQLSTATE 08W32
Sybase error code 927
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted to create a database with an invalid page size. The page size
for an Adaptive Server Anywhere database must be either 1024, 2048, or
4096 bytes.

Invalid database server command line


Item Value
SQLCODE -81
Constant SQLE_INVALID_COMMAND_LINE
SQLSTATE 08W08
Sybase error code 5864
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause It was not possible to start the database server because the command line was
invalid.

784
CHAPTER 10 Database Error Messages

Invalid day of week or month ’%1’ for event ’%2’


Item Value
SQLCODE -791
Constant SQLE_INVALID_EVENT_DAY
SQLSTATE WE005
Sybase error code 13801
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Day-of-week name or day-of-month number.
Parameter 2 Name of the event being scheduled.

Probable cause You have attempted to create a schedule with an invalid day-of-week name
or day-of-month number.

Invalid descriptor index


Item Value
SQLCODE -640
Constant SQLE_INVALID_DESCRIPTOR_INDEX
SQLSTATE 07009
Sybase error code 8201
ODBC 2 State S1002
ODBC 3 State 07009

Probable cause The index number used with respect to a descriptor area is out of range.

785
Alphabetic list of error messages

Invalid escape character ’%1’


Item Value
SQLCODE -629
Constant SQLE_INVALID_ESCAPE_CHAR
SQLSTATE 22019
Sybase error code 7707
ODBC 2 State S1000
ODBC 3 State 22019

Probable cause The escape character string length must be exactly one.

Invalid escape sequence ’%1’


Item Value
SQLCODE -630
Constant SQLE_INVALID_ESCAPE_SEQ
SQLSTATE 22025
Sybase error code 7705
ODBC 2 State S1000
ODBC 3 State 22025
Parameter 1 The escaped character

Probable cause A LIKE pattern contains an invalid use of the escape character. The escape
character may only precede the special characters ’%’, ’_’, ’[’, and the escape
character itself.

786
CHAPTER 10 Database Error Messages

Invalid expression in WHERE clause of Transact-SQL outer join


Item Value
SQLCODE -680
Constant SQLE_INVALID_TSQL_OJ_EXPRESSION
SQLSTATE 52W23
Sybase error code 301
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause An expression in the WHERE clause of a query which uses Transact-SQL
syntax contains a comparison of a column from the null-supplying table with
a subquery or an expression which references a column from another table.

Invalid expression near ’%1’


Item Value
SQLCODE -156
Constant SQLE_EXPRESSION_ERROR
SQLSTATE 42W08
Sybase error code 401
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 The invalid expression.

Probable cause You supplied an expression which the database server cannot understand.
For example, you may have tried to add two dates.

787
Alphabetic list of error messages

Invalid host variable


Item Value
SQLCODE -155
Constant SQLE_VARIABLE_INVALID
SQLSTATE 42W07
Sybase error code 7201
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You supplied an invalid host variable to the database using the C language
interface. You may have supplied the variable as a host variable or through a
SQLDA.

Invalid IQ database command line option or parameter value: %1


Item Value
SQLCODE -744
Constant SQLE_IQ_INVALID_COMMAND_LINE
SQLSTATE 08W51
Sybase error code 13757
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause An invalid command line option was used. The option began with ’-iq’, but is
either invalid or contained a bad parameter.

788
CHAPTER 10 Database Error Messages

Invalid jar file


Item Value
SQLCODE -730
Constant SQLE_BAD_JAR_FILE
SQLSTATE WP010
Sybase error code 13737
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause A file passed to the INSTALL JAVA statement was not a valid jar file.

Invalid JDBC resultset concurrency


Item Value
SQLCODE -748
Constant SQLE_JDBC_INVALID_RESULTSET_CONCURREN
CY
SQLSTATE WJ018
Sybase error code 13761
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An invalid resultset concurrency was used when creating a JDBC statement.

Invalid JDBC resultset type


Item Value
SQLCODE -747
Constant SQLE_JDBC_INVALID_RESULTSET_TYPE
SQLSTATE WJ017
Sybase error code 13760
ODBC 2 State ERROR
ODBC 3 State ERROR

789
Alphabetic list of error messages

Probable cause An invalid resultset type was used when creating a JDBC statement.

Invalid join type used with Transact-SQL outer join


Item Value
SQLCODE -681
Constant SQLE_INVALID_TSQL_JOIN_TYPE
SQLSTATE 52W24
Sybase error code 305
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause An invalid join type was used with a query that contains Transact-SQL outer
join comparison operators.

Invalid local database switch


Item Value
SQLCODE -79
Constant SQLE_INVALID_LOCAL_OPTION
SQLSTATE 08W25
Sybase error code 5864
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause An invalid database switch was found in the DBS (DatabaseSwitches)
connection parameter.

790
CHAPTER 10 Database Error Messages

Invalid operation on a closed ’%1’


Item Value
SQLCODE -696
Constant SQLE_JDBC_OBJ_CLOSED
SQLSTATE WJ010
Sybase error code 13605
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Java class of the closed object

Probable cause An illegal attempt was made to access a closed JDBC object.

Invalid operation on a closed ’%1’


Item Value
SQLCODE -714
Constant SQLE_JNAT_OBJ_CLOSED
SQLSTATE WJ014
Sybase error code 13609
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Java class of the closed object

Probable cause An illegal attempt was made to access a closed native Java object.

791
Alphabetic list of error messages

Invalid option ’%1’ -- no PUBLIC setting exists


Item Value
SQLCODE -200
Constant SQLE_INVALID_OPTION
SQLSTATE 42W16
Sybase error code 155
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the invalid option.

Probable cause You may have misspelled the name of an option in the SET OPTION
statement. You can only define an option for a user if the database
administrator has supplied a PUBLIC value for that option.

Invalid parameter
Item Value
SQLCODE -735
Constant SQLE_INVALID_PARAMETER
SQLSTATE 08W24
Sybase error code 5864
ODBC 2 State 08004
ODBC 3 State 08004

Probable cause An error occurred while evaluating a parameter.

792
CHAPTER 10 Database Error Messages

Invalid prepared statement type


Item Value
SQLCODE -133
Constant SQLE_INVALID_STATEMENT_TYPE
SQLSTATE 07W03
Sybase error code 13630
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause This is an internal error. If it can be reproduced, it should be reported to


Sybase.

Invalid REFERENCES clause in trigger definition


Item Value
SQLCODE -272
Constant SQLE_INVALID_TRIGGER_COL_REFS
SQLSTATE 52W12
Sybase error code 102
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You supplied an invalid REFERENCES clause in a trigger definition. You
may have specified an OLD correlation name in a BEFORE INSERT trigger,
or a NEW correlation name in an AFTER DELETE trigger. In both cases,
the values do not exist and cannot be referenced.

793
Alphabetic list of error messages

Invalid scroll position ’%1’


Item Value
SQLCODE -820
Constant SQLE_INVALID_POSITION
SQLSTATE 24504
Sybase error code 13826
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to scroll to a position that is not supported. Scroll positions
must be between -2147483647 and 2147483646.

Invalid setting for option ’%1’


Item Value
SQLCODE -201
Constant SQLE_INVALID_OPTION_SETTING
SQLSTATE 42W17
Sybase error code 5849
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the invalid option.

Probable cause You supplied an invalid value for an option in the SET statement. Some
options only allow numeric values, while other options only allow the values
"on" and "off".

794
CHAPTER 10 Database Error Messages

Invalid SQL descriptor name


Item Value
SQLCODE -642
Constant SQLE_INVALID_DESCRIPTOR_NAME
SQLSTATE 33000
Sybase error code 601
ODBC 2 State 33000
ODBC 3 State 33000

Probable cause You attempted to deallocate a descriptor that has not been allocated.

Invalid SQL identifier


Item Value
SQLCODE -760
Constant SQLE_INVALID_SQL_IDENTIFIER
SQLSTATE 07W06
Sybase error code 13771
ODBC 2 State 07001
ODBC 3 State 07W06

Probable cause An invalid identifier was supplied through the C language interface. For
example, you may have supplied a NULL string for a cursor name.

795
Alphabetic list of error messages

Invalid start date/time for event ’%1’


Item Value
SQLCODE -793
Constant SQLE_INVALID_EVENT_START
SQLSTATE WE007
Sybase error code 13803
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the event being scheduled.

Probable cause You have specified an event starting date or time which has already passed.

Invalid statement
Item Value
SQLCODE -130
Constant SQLE_INVALID_STATEMENT
SQLSTATE 07W02
Sybase error code 13628
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The statement identifier generated by a PREPARE passed to the database for
a further operation is invalid.

796
CHAPTER 10 Database Error Messages

Invalid TEXTPTR value used with WRITETEXT or READTEXT


Item Value
SQLCODE -608
Constant SQLE_INVALID_TEXTPTR_VALUE
SQLSTATE 22W03
Sybase error code 7123
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You supplied an invalid value as the TEXTPTR for a WRITETEXT or
READTEXT statement.

Invalid time ’%1’ for event ’%2’


Item Value
SQLCODE -792
Constant SQLE_INVALID_EVENT_TIME
SQLSTATE WE006
Sybase error code 13802
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Time value.
Parameter 2 Name of the event being scheduled.

Probable cause You have attempted to create a schedule with an invalid start or stop time.

797
Alphabetic list of error messages

Invalid type for field reference


Item Value
SQLCODE -94
Constant SQLE_INVALID_FIELD_REFERENCE
SQLSTATE WW014
Sybase error code 13738
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An expression attempted to reference a field or a method of a non-Java


value. Field references via ’.’ and ’>>’ are only valid when applied to Java
objects.

Invalid type on DESCRIBE statement


Item Value
SQLCODE -161
Constant SQLE_INVALID_DESCRIBE_TYPE
SQLSTATE 07W01
Sybase error code 13634
ODBC 2 State OK
ODBC 3 State OK

Probable cause A Java type specified on a DESCRIBE statement has no corresponding SQL
type.

798
CHAPTER 10 Database Error Messages

Invalid user ID or password


Item Value
SQLCODE -103
Constant SQLE_INVALID_LOGON
SQLSTATE 28000
Sybase error code 4002
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause You supplied an invalid user ID or an incorrect password.

Invalid user ID or password


Item Value
SQLCODE -103
Constant SQLE_INVALID_PASSWORD
SQLSTATE 28000
Sybase error code 4002
ODBC 2 State 28000
ODBC 3 State 28000

Invalid user ID or password on preprocessed module


Item Value
SQLCODE -104
Constant SQLE_INVALID_MODULE_LOGON
SQLSTATE 28W01
Sybase error code 4002
ODBC 2 State 28000
ODBC 3 State 28000

799
Alphabetic list of error messages

Probable cause You specified an invalid user ID or password when a module was
preprocessed.

Invalid value for column ’%1’ in table ’%2’


Item Value
SQLCODE -209
Constant SQLE_INVALID_COLUMN_VALUE
SQLSTATE 23506
Sybase error code 548
ODBC 2 State 42000
ODBC 3 State 23000
Parameter 1 Name of the column that was assigned an invalid value.
Parameter 2 Name of the table containing the column.

Probable cause You attempted an insert or update that violates a CHECK constraint. A
CHECK constraint is violated if it evaluates to FALSE; it is deemed to hold
if the condition evaluates to TRUE or UNKNOWN.

Item ’%1’ already exists


Item Value
SQLCODE -110
Constant SQLE_NAME_NOT_UNIQUE
SQLSTATE 52010
Sybase error code 12006
ODBC 2 State S0001
ODBC 3 State 42S01
Parameter 1 Name of the item that already exists.

Probable cause You attempted to create a file, table, view, column, foreign key, or
publication with the same name as an existing one.

800
CHAPTER 10 Database Error Messages

Jar %1 not found


Item Value
SQLCODE -811
Constant SQLE_JAR_NOT_FOUND
SQLSTATE 42W58
Sybase error code 13821
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the jar.

Probable cause The jar with this name does not exist in SYSJAR.

Java classes %1 not found


Item Value
SQLCODE -810
Constant SQLE_JAVA_CLASS_NOT_FOUND
SQLSTATE 42W57
Sybase error code 13820
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the Java class.

Probable cause The Java class with this name does not exist in SYSJAVACLASS.

801
Alphabetic list of error messages

Java virtual machine could not be started


Item Value
SQLCODE -675
Constant SQLE_JAVA_VM_NOT_STARTED
SQLSTATE WP006
Sybase error code 13747
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause A problem was encountered starting the Java virtual machine. Possible
problems include not enough memory, or incomplete installation of the Java
runtime support classes.

Java VM Heap Exhausted at Internal fn: %1


Item Value
SQLCODE -165
Constant SQLE_JAVA_VM_HEAP_EXHAUSTED
SQLSTATE WP008
Sybase error code 13740
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The internal function is for debugging purposes.

Probable cause The amount of space allocated for the Java VM is insufficient to continue
allocating new objects. Increase the size by using: set option
public.java_heap_size = nnnnnnnn

802
CHAPTER 10 Database Error Messages

JDBC feature ’%1’ not supported


Item Value
SQLCODE -693
Constant SQLE_UNSUPPORTED_JDBC_FEATURE
SQLSTATE WJ007
Sybase error code 13602
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the attempted feature

Probable cause An attempt was made to use a feature of JDBC that is not supported.

JDBC SAStatement batch execute abandoned


Item Value
SQLCODE -742
Constant SQLE_JDBC_BATCH_EXECUTE_ABANDONED
SQLSTATE WJ015
Sybase error code 13755
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An error occurred when executing a statement in the batch. The rest of the
statements in the batch will be abandoned.

803
Alphabetic list of error messages

Label ’%1’ not found


Item Value
SQLCODE -262
Constant SQLE_LABEL_NOT_FOUND
SQLSTATE 42W24
Sybase error code 133
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the label that could not be found.

Probable cause You reference a label in a LEAVE statement, but the label could not be
found.

Language extension
Item Value
SQLCODE -135
Constant SQLE_LANGUAGE_EXTENSION
SQLSTATE 0AW01
Sybase error code 401
ODBC 2 State 37000
ODBC 3 State ERROR

Probable cause You used a SQL statement that may be valid in some versions of SQL, but
not in Adaptive Server Anywhere.

804
CHAPTER 10 Database Error Messages

Language extension detected in syntax


Item Value
SQLCODE 107
Constant SQLE_SYNTAX_EXTENSION_WARNING
SQLSTATE 01W07
Sybase error code 5703
ODBC 2 State OK
ODBC 3 State OK

Probable cause The statement you are executing contains extensions to ANSI 1992 Entry
level SQL.

Memory error -- transaction rolled back


Item Value
SQLCODE -309
Constant SQLE_MEMORY_ERROR
SQLSTATE 40W08
Sybase error code 3013
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The UltraLite runtime has received an unexpected error from the system calls
being used to store the UltraLite database. For example, a write to persistent
memory failed. This is an internal error and indicates faulty or corrupt
persistent storage on the device. A ROLLBACK WORK statement has been
automatically executed.

805
Alphabetic list of error messages

Method ’%1’ cannot be called at this time


Item Value
SQLCODE -669
Constant SQLE_METHOD_CANNOT_BE_CALLED
SQLSTATE WJ001
Sybase error code 13711
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the method

Probable cause The method cannot be called at this time. Check that the method is not being
called out of order.

Mismatch between external function platform specifier and current


operating system
Item Value
SQLCODE -618
Constant SQLE_EXTERNAL_PLATFORM_FAILURE
SQLSTATE WW004
Sybase error code 13675
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause A call to an external entry point in a dynamically loaded module was
qualified by an operating system which was not the operating system on
which the server is currently executing.

806
CHAPTER 10 Database Error Messages

Modifications not permitted for read-only database


Item Value
SQLCODE -757
Constant SQLE_READ_ONLY_DATABASE
SQLSTATE 55W08
Sybase error code 13768
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted an update operation on a database that was declared as read-
only.

More columns are being dropped from table %1 than are defined
Item Value
SQLCODE -124
Constant SQLE_TOO_MANY_COLUMNS_DELETED
SQLSTATE 42W44
Sybase error code 207
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause The number of columns in a table can never fall below one. Your ALTER
TABLE has more drop/delete column clauses than the current number of
columns in the table.

807
Alphabetic list of error messages

More information required


Item Value
SQLCODE 112
Constant SQLE_MORE_INFO
SQLSTATE 01W09
Sybase error code 13686
ODBC 2 State 37000
ODBC 3 State OK

Probable cause More information is required to complete the request. This is used internally
in the database interface library to process a unified logon. It should not be
returned to an application.

More than one table is identified as ’%1’


Item Value
SQLCODE -139
Constant SQLE_CORRELATION_NAME_AMBIGUOUS
SQLSTATE 52012
Sybase error code 7364
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Ambiguous correlation name.

Probable cause You identified two tables in the same FROM clause with the same
correlation name.

808
CHAPTER 10 Database Error Messages

Must include primary key for table ’%1’ in the synchronization


Item Value
SQLCODE -778
Constant SQLE_PK_NOT_IN_SYNC_ARTICLE
SQLSTATE 5RW17
Sybase error code 13788
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 Name of the table

Probable cause The primary key of the table must be included in the synchronization entry.

Namespace Heap Exhausted at Internal fn: %1


Item Value
SQLCODE -164
Constant SQLE_NAMESPACE_HEAP_EXHAUSTED
SQLSTATE WP007
Sybase error code 13739
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The internal function is for debugging purposes.

Probable cause The amount of space allocated for the Java Namespace is insufficient to
continue loading Java classes etc. Increase the size by using: set option
public.java_namespace_size = nnnnnnnn

809
Alphabetic list of error messages

Need a dynamic library name


Item Value
SQLCODE -619
Constant SQLE_REQUIRE_DLL_NAME
SQLSTATE WW005
Sybase error code 13676
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You must provide a library name specifier in the name of the external
function to call.

No current row of cursor


Item Value
SQLCODE -197
Constant SQLE_NO_CURRENT_ROW
SQLSTATE 24503
Sybase error code 560
ODBC 2 State 24000
ODBC 3 State 24000

Probable cause You attempted to perform an operation on the current row of a cursor, but the
cursor is not positioned on a row. The cursor is before the first row of the
cursor, after the last row, or is on a row that has since been deleted.

810
CHAPTER 10 Database Error Messages

No database file specified


Item Value
SQLCODE -72
Constant SQLE_NO_DATABASE_FILE
SQLSTATE 08W39
Sybase error code 4001
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause The database server was started but there was no specified database file. The
server is stopped.

No indicator variable provided for NULL result


Item Value
SQLCODE -181
Constant SQLE_NO_INDICATOR
SQLSTATE 22002
Sybase error code 13635
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You tried to retrieve a value from the database that was NULL, but you did
not provide an indicator variable for that value.

811
Alphabetic list of error messages

No primary key value for foreign key ’%1’ in table ’%2’


Item Value
SQLCODE -194
Constant SQLE_INVALID_FOREIGN_KEY
SQLSTATE 23503
Sybase error code 546
ODBC 2 State 23000
ODBC 3 State 23000
Parameter 1 Name of the foreign key.
Parameter 2 Name of the table with the foreign key.

Probable cause You attempted to insert or update a row that has a foreign key for another
table. The value for the foreign key is not NULL and there is not a
corresponding value in the primary key

Not allowed while %1 is using the database


Item Value
SQLCODE -211
Constant SQLE_MUST_BE_ONLY_CONNECTION
SQLSTATE 42W19
Sybase error code 13652
ODBC 2 State 40001
ODBC 3 State 40001

Probable cause You attempted a data definition language operation that cannot be completed
while another user is connected.

812
CHAPTER 10 Database Error Messages

Not connected to a database


Item Value
SQLCODE -101
Constant SQLE_NOT_CONNECTED
SQLSTATE 08003
Sybase error code 13622
ODBC 2 State 08003
ODBC 3 State 08003

Probable cause You are not connected to a database, or you executed the DISCONNECT
statement and have not connected to a database again.

Not enough fields allocated in SQLDA


Item Value
SQLCODE -182
Constant SQLE_SQLDA_TOO_SMALL
SQLSTATE 07002
Sybase error code 13636
ODBC 2 State 07001
ODBC 3 State 07002

Probable cause There are not enough fields in the SQLDA to retrieve all of the values
requested.

813
Alphabetic list of error messages

Not enough memory is allocated to the Java virtual machine for


remote access
Item Value
SQLCODE -679
Constant SQLE_OMNI_MEMORY_CONFIG
SQLSTATE WO009
Sybase error code 708
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The Java heap size and Java name space configuration values in sysoptions
must be increased to allow the loading of the Java classes used for remote
access.

Not enough memory to start


Item Value
SQLCODE -86
Constant SQLE_NO_MEMORY
SQLSTATE 08W13
Sybase error code 708
ODBC 2 State S1001
ODBC 3 State HY001

Probable cause The database server was started but was unable to start because there is not
enough memory to run properly.

814
CHAPTER 10 Database Error Messages

Not enough values for host variables


Item Value
SQLCODE -188
Constant SQLE_NOT_ENOUGH_HOST_VARS
SQLSTATE 07001
Sybase error code 13638
ODBC 2 State 07002
ODBC 3 State 07002

Probable cause You have not provided enough host variables for either the number of bind
variables, or the statement, or the number of select list items.

Null attribute mismatch for column ’%1’


Item Value
SQLCODE -724
Constant SQLE_OMNI_NULL_MISMATCH
SQLSTATE WO018
Sybase error code 11211
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 The name of the column.

Probable cause The null attribute of the column specified in the ’CREATE EXISTING’
statement differs from the null attribute of the actual column.

815
Alphabetic list of error messages

Null value eliminated in aggregate function


Item Value
SQLCODE 109
Constant SQLE_NULL_VALUE_ELIMINATED
SQLSTATE 01003
Sybase error code 409
ODBC 2 State OK
ODBC 3 State OK

Probable cause The expression argument of the aggregate function evaluated to NULL for
one or more rows.

Number in ORDER BY is too large


Item Value
SQLCODE -152
Constant SQLE_INVALID_ORDER
SQLSTATE 53005
Sybase error code 104
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You used an integer in an ORDER BY list and the integer is larger than the
number of columns in the select list.

816
CHAPTER 10 Database Error Messages

Number of columns allowing NULLs exceeds limit


Item Value
SQLCODE -733
Constant SQLE_TOO_MANY_NULL_COLUMNS
SQLSTATE 23504
Sybase error code 233
ODBC 2 State 23000
ODBC 3 State 23000

Probable cause You attempted to create or modify a table definition such that the number of
columns that allow nulls is now more than the limit on such columns. The
limit is a function of database page size and is approximately 8*(page_size -
30).

Number of columns defined for the view does not match SELECT
statement
Item Value
SQLCODE -114
Constant SQLE_VIEW_DEFINITION_ERROR
SQLSTATE 53011
Sybase error code 4409
ODBC 2 State 21S02
ODBC 3 State 21S02

Probable cause You attempted to create a view, but the column list specified as part of the
CREATE VIEW statement does not correspond to the list of items in the
view’s SELECT statement.

817
Alphabetic list of error messages

OMNI cannot handle expressions involving remote tables inside


stored procedures
Item Value
SQLCODE -823
Constant SQLE_OMNI_EXPRESSION_IN_PROC
SQLSTATE WO023
Sybase error code 13829
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause OMNI encountered a complicated expression involving remote tables inside
a stored procedure. OMNI cannot always deal with such expressions.

Only PUBLIC settings are allowed for option ’%1’


Item Value
SQLCODE -202
Constant SQLE_NOT_PUBLIC_ID
SQLSTATE 42W43
Sybase error code 13685
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the option.

Probable cause The option specified in the SET OPTION statement is PUBLIC only. You
cannot define this option for any other user.

818
CHAPTER 10 Database Error Messages

Only the DBA can set the option %1


Item Value
SQLCODE -204
Constant SQLE_OPTION_REQUIRES_DBA
SQLSTATE 42W46
Sybase error code 5878
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause The option specified in the SET OPTION statement can only be set by a user
having DBA authority.

Operation would cause a group cycle


Item Value
SQLCODE -122
Constant SQLE_GROUP_CYCLE
SQLSTATE 42W02
Sybase error code 314
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to add a member to group that would result in a member
belonging to itself. The membership may be direct or indirect.

819
Alphabetic list of error messages

Parameter ’%1’ not found in procedure ’%2’


Item Value
SQLCODE -615
Constant SQLE_INVALID_PARAMETER_NAME
SQLSTATE 42W47
Sybase error code 201
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You supplied a procedure parameter name that does not match a parameter
for this procedure. Check the spelling of the parameter name.

Parameter name missing in call to procedure ’%1’


Item Value
SQLCODE -639
Constant SQLE_PARAMETER_NAME_MISSING
SQLSTATE 42W42
Sybase error code 201
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 The name of the procedure

Probable cause Positional arguments were specified after keyword arguments in a call to this
procedure.

820
CHAPTER 10 Database Error Messages

Parameter not registered as output parameter


Item Value
SQLCODE -671
Constant SQLE_PARAM_NOT_REGISTERED
SQLSTATE WJ002
Sybase error code 13712
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The parameter must be registered as an output parameter before the value of
the parameter can be obtained.

Parse error: %1 ’%2’


Item Value
SQLCODE -754
Constant SQLE_INVALID_DSN_NAME
SQLSTATE 08W54
Sybase error code 5864
ODBC 2 State 08004
ODBC 3 State 08004

Probable cause An invalid data source name was used in the connection string.

Parse error: %1 near ’%2’


Item Value
SQLCODE -95
Constant SQLE_INVALID_PARSE_PARAMETER
SQLSTATE 08W49
Sybase error code 5864
ODBC 2 State 08004
ODBC 3 State 08004

821
Alphabetic list of error messages

Probable cause An error occurred while parsing a connection string.

Passthrough statement inconsistent with current passthrough


Item Value
SQLCODE -287
Constant SQLE_PASSTHROUGH_INCONSISTENT
SQLSTATE 5RW08
Sybase error code 13649
ODBC 2 State S0002
ODBC 3 State 42S02

Probable cause Passthrough is additive, in that subsequent passthrough statements add to the
list of users receiving passthrough. The passthrough statements must all be
PASSTHROUGH ONLY or none should be PASSTHROUGH ONLY.

Password must be at least %1 characters


Item Value
SQLCODE -738
Constant SQLE_PASSWORD_TOO_SHORT
SQLSTATE 28000
Sybase error code 573
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause The password is shorter than that allowed by the current
MIN_PASSWORD_LENGTH option setting. :EN-

822
CHAPTER 10 Database Error Messages

Primary key column ’%1’ already defined


Item Value
SQLCODE -119
Constant SQLE_PRIMARY_KEY_COLUMN_DEFINED
SQLSTATE 52009
Sybase error code 1909
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the column that is already in the primary key.

Probable cause You listed the same column name twice in the definition of a primary key.

Primary key for row in table ’%1’ is referenced in another table


Item Value
SQLCODE -198
Constant SQLE_PRIMARY_KEY_VALUE_REF
SQLSTATE 23W05
Sybase error code 547
ODBC 2 State 23000
ODBC 3 State 23000
Parameter 1 The name of the table containing the row being
modified.

Probable cause You attempted to delete or modify a row whose primary key value is
referenced elsewhere in the database.

823
Alphabetic list of error messages

Primary key for table ’%1’ is not unique


Item Value
SQLCODE -193
Constant SQLE_PRIMARY_KEY_NOT_UNIQUE
SQLSTATE 23W01
Sybase error code 2601
ODBC 2 State 23000
ODBC 3 State 23000
Parameter 1 Name of the table where the problem was detected.

Probable cause You attempted to add a new row to a table, but the new row has the same
primary key as an existing row. The database has not added the incorrect row
to the database. For example, you might have added a student with student
number 86004 and there is already a row for a student with that number.

Procedure ’%1’ not found


Item Value
SQLCODE -265
Constant SQLE_PROCEDURE_NOT_FOUND
SQLSTATE 52W09
Sybase error code 504
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the procedure that could not be found.

Probable cause You misspelled the name of a procedure, or you did not qualify a procedure
name with a user name.

824
CHAPTER 10 Database Error Messages

Procedure ’%1’ terminated with unhandled exception ’%2’


Item Value
SQLCODE -91
Constant SQLE_UNHANDLED_JAVA_EXCEPTION
SQLSTATE WP001
Sybase error code 13735
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the procedure which returned the
unhandled exception.
Parameter 2 The fully qualified Java class name of the unhandled
exception.

Probable cause A Java procedure terminated with an active exception, and this exception is
reflected in SQL as an error status.

Procedure has completed


Item Value
SQLCODE 105
Constant SQLE_PROCEDURE_COMPLETE
SQLSTATE 01W05
Sybase error code 13618
ODBC 2 State OK
ODBC 3 State OK

Probable cause There are no more result sets available for this procedure. An OPEN or a
RESUME statement may have caused the procedure to execute to
completion. You may have attempted to RESUME a cursor on a SELECT
statement.

825
Alphabetic list of error messages

Procedure in use
Item Value
SQLCODE -215
Constant SQLE_PROCEDURE_IN_USE
SQLSTATE 42W23
Sybase error code 3702
ODBC 2 State 40001
ODBC 3 State 40001

Probable cause You attempted to DROP a procedure that is being used by other active users
of the database.

Procedure or trigger calls have nested too deeply


Item Value
SQLCODE -274
Constant SQLE_NESTING_TOO_DEEP
SQLSTATE 42W29
Sybase error code 217
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You may have defined a procedure or trigger that causes unlimited recursion.

826
CHAPTER 10 Database Error Messages

Publication ’%1’ not found


Item Value
SQLCODE -280
Constant SQLE_PUBLICATION_NOT_FOUND
SQLSTATE 5RW01
Sybase error code 13642
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the publication that could not be found.

Probable cause You misspelled the name of a publication, or you did not qualify a
publication name with a user name.

RAISERROR executed: %1
Item Value
SQLCODE -631
Constant SQLE_RAISERROR_STMT
SQLSTATE WW012
Sybase error code 0
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 RAISERROR message string

Probable cause A RAISERROR statement has been executed.

827
Alphabetic list of error messages

READTEXT or WRITETEXT statement cannot refer to a view


Item Value
SQLCODE -708
Constant SQLE_TEXT_OPERATION_ON_VIEW
SQLSTATE 42W50
Sybase error code 285
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause A Transact-SQL READTEXT or WRITETEXT statement cannot refer to


text columns in a view. Replace the view reference with the name of a base
table.

Remote message type ’%1’ not found


Item Value
SQLCODE -286
Constant SQLE_NOT_REMOTE_TYPE
SQLSTATE 5RW07
Sybase error code 13648
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of remote message type.

Probable cause You referred to a remote message type that is not defined in this database.
Use CREATE REMOTE TYPE to define remote message types.

828
CHAPTER 10 Database Error Messages

Remote server %1 could not be found; Add the server using


CREATE SERVER
Item Value
SQLCODE -659
Constant SQLE_OMNI_SERVER_NOT_FOUND
SQLSTATE WO004
Sybase error code 11214
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the remote server.

Probable cause You attempted to define an object on a server that has not been added. Use
CREATE SERVER to add the remote server definition.

Remote server %1 is currently configured as read only


Item Value
SQLCODE -658
Constant SQLE_OMNI_READONLY
SQLSTATE WO003
Sybase error code 11248
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the remote server.

Probable cause You attempted to perform an update on an object located on a server that is
configured as read only. Use ALTER SERVER to reconfigure the remote
server to be updatable.

829
Alphabetic list of error messages

Remote server does not have the ability to support this statement
Item Value
SQLCODE -706
Constant SQLE_OMNI_SERVER_NOT_CAPABLE
SQLSTATE WO012
Sybase error code 11227
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to execute a statement that requires a capability that is not
supported by a remote server.

Remote statement failed


Item Value
SQLCODE -288
Constant SQLE_REMOTE_STATEMENT_FAILED
SQLSTATE 5RW09
Sybase error code 13650
ODBC 2 State S0002
ODBC 3 State 42S02

Probable cause This SQLSTATE can be signaled within a trigger to prevent DBREMOTE
from displaying an error message in the output. This exception will only
occur when a trigger or procedure SIGNALS it. This is useful for ignoring
replication errors that are permitted by design.

830
CHAPTER 10 Database Error Messages

Request denied -- no active databases


Item Value
SQLCODE -76
Constant SQLE_REQUEST_DENIED_NO_DATABASES
SQLSTATE 08W28
Sybase error code 950
ODBC 2 State 08004
ODBC 3 State 08004

Probable cause The server has denied your request as there are currently no running
databases.

Request to start/stop database denied


Item Value
SQLCODE -75
Constant SQLE_START_STOP_DATABASE_DENIED
SQLSTATE 08W29
Sybase error code 6004
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You do not have permission to start or stop a database. The required
permission is determined on the server command line.

831
Alphabetic list of error messages

Resource governor for %1 exceeded


Item Value
SQLCODE -685
Constant SQLE_RESOURCE_GOVERNOR_EXCEEDED
SQLSTATE WP009
Sybase error code 13715
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The resource whose limit has been exceeded

Probable cause The resource governor for the stated resource has determined that the usage
of the resource has exceeded its limit.

RESTORE unable to open file ’%1’


Item Value
SQLCODE -717
Constant SQLE_RESTORE_UNABLE_TO_OPEN
SQLSTATE WB008
Sybase error code 13726
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 File name of database file.

Probable cause RESTORE was unable to open one of the database files.

832
CHAPTER 10 Database Error Messages

RESTORE unable to start database ’%1’


Item Value
SQLCODE -719
Constant SQLE_RESTORE_UNABLE_TO_START
SQLSTATE WB010
Sybase error code 13728
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 File name of database file.

Probable cause After a RESTORE, the resulting database could not be started.

RESTORE unable to write to file ’%1’


Item Value
SQLCODE -718
Constant SQLE_RESTORE_UNABLE_TO_WRITE
SQLSTATE WB009
Sybase error code 13727
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 File name of database file.

Probable cause RESTORE was unable to write to one of the database files.

833
Alphabetic list of error messages

Result set not allowed from within an atomic compound statement


Item Value
SQLCODE -222
Constant SQLE_RESULT_NOT_ALLOWED
SQLSTATE 3BW02
Sybase error code 13655
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You used a SELECT statement with no INTO clause or a RESULT
CURSOR statement within an atomic compound statement.

Return type of void from procedure ’%1’ cannot be used in any


expression
Item Value
SQLCODE -705
Constant SQLE_PROCEDURE_RETURNS_VOID
SQLSTATE 53019
Sybase error code 257
ODBC 2 State 07006
ODBC 3 State 07006
Parameter 1 Name of the procedure.

Probable cause The Java type void does not map onto any SQL type, hence a procedure
returning void cannot be used in any SQL expression.

834
CHAPTER 10 Database Error Messages

Return value cannot be set


Item Value
SQLCODE -690
Constant SQLE_RETVAL_CANNOT_BE_SET
SQLSTATE WJ006
Sybase error code 13601
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause Setting a value for the return parameter of a callable statement is not
allowed.

Right truncation of string data


Item Value
SQLCODE -638
Constant SQLE_STRING_RIGHT_TRUNCATION
SQLSTATE 22001
Sybase error code 9502
ODBC 2 State 22001
ODBC 3 State 22001

Probable cause Non-space characters were truncated upon the assignment of string data.

Rollback occurred due to deadlock during prefetch


Item Value
SQLCODE -684
Constant SQLE_ROLLBACK_ON_PREFETCH
SQLSTATE WW019
Sybase error code 1205
ODBC 2 State 40001
ODBC 3 State 40001

835
Alphabetic list of error messages

Probable cause One of the cursors that was opened with prefetch enabled was performing
fetch operations, and a deadlock occurred during a prefetch. This is a
deadlock situation and your transaction has been chosen as the one to
rollback.

ROLLBACK TO SAVEPOINT not allowed


Item Value
SQLCODE -221
Constant SQLE_ROLLBACK_NOT_ALLOWED
SQLSTATE 3B002
Sybase error code 13654
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted a ROLLBACK TO SAVEPOINT within an atomic operation


to a savepoint established before the atomic operation.

Row has been updated since last time read


Item Value
SQLCODE 104
Constant SQLE_ROW_UPDATED_WARNING
SQLSTATE 01W04
Sybase error code 532
ODBC 2 State OK
ODBC 3 State OK

Probable cause You fetched a row from a SCROLL cursor. The row was previously fetched
from the same cursor, and one or more columns in the row has been updated
since the previous fetch. The column(s) updated may or may not be fetched
by the cursor; this warning just indicates that the row from the table has been
updated. If the cursor involves more than one table, a row from one or more
of the tables has been updated.

836
CHAPTER 10 Database Error Messages

Row has changed since last read -- operation cancelled


Item Value
SQLCODE -208
Constant SQLE_ROW_UPDATED_SINCE_READ
SQLSTATE 22W02
Sybase error code 554
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted an UPDATE (positioned) or DELETE (positioned) operation


on a cursor declared as a SCROLL cursor, and the row you are changing has
been updated since you read it. This error prevents the ’lost update’ problem.

Row not found


Item Value
SQLCODE 100
Constant SQLE_NOTFOUND
SQLSTATE 02000
Sybase error code 560
ODBC 2 State OK
ODBC 3 State OK

Probable cause You positioned a cursor beyond the beginning or past the end of the query.
There is no row at that position.

837
Alphabetic list of error messages

Run time SQL error -- %1


Item Value
SQLCODE -300
Constant SQLE_ERROR
SQLSTATE 40000
Sybase error code 13664
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Identification of the error.

Probable cause An internal database error occurred. If it can be reproduced, it should be


reported to Sybase.

Savepoint ’%1’ not found


Item Value
SQLCODE -220
Constant SQLE_SAVEPOINT_NOTFOUND
SQLSTATE 3B001
Sybase error code 6401
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of savepoint.

Probable cause You attempted to rollback to a savepoint that does not exist.

838
CHAPTER 10 Database Error Messages

Savepoints require a rollback log


Item Value
SQLCODE -213
Constant SQLE_SAVEPOINTS_REQUIRE_UNDO
SQLSTATE 3BW01
Sybase error code 13656
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You cannot use savepoints when the database server is running in bulk mode
without a rollback log.

Schedule ’%1’ for event ’%2’ already exists


Item Value
SQLCODE -774
Constant SQLE_SCHEDULE_ALREADY_EXISTS
SQLSTATE WE004
Sybase error code 13784
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the schedule that already exists.
Parameter 2 Name of the event being scheduled.

Probable cause You have attempted to create a schedule with a name that already exists in
SYS.SYSSCHEDULE for the named event.

839
Alphabetic list of error messages

Schedule ’%1’ for event ’%2’ not found


Item Value
SQLCODE -773
Constant SQLE_SCHEDULE_NOT_FOUND
SQLSTATE WE003
Sybase error code 13783
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the schedule that could not be found.
Parameter 2 Name of the event being scheduled.

Probable cause You have attempted to reference a schedule with a name that does not exist
in SYS.SYSSCHEDULE for the named event.

Seek absolute 0 was attempted on a JDBC SAResultSet


Item Value
SQLCODE -743
Constant SQLE_JDBC_RESULTSET_SEEK_ABSOLUTE_ZER
O
SQLSTATE WJ016
Sybase error code 13756
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause There is no row zero on JDBC resultSets. The valid row numbers are 1, 2, ...,
-2, -1.

840
CHAPTER 10 Database Error Messages

SELECT lists in UNION do not match in length


Item Value
SQLCODE -153
Constant SQLE_INVALID_UNION
SQLSTATE 53026
Sybase error code 205
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You specified a UNION but the SELECT statements involved in the union
do not have the same number of columns in the select list.

SELECT returns more than one row


Item Value
SQLCODE -185
Constant SQLE_TOO_MANY_RECORDS
SQLSTATE 21000
Sybase error code 13637
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You tried to use a SELECT statement without a cursor, but the statement
cursor returns more than one row. Only a single row SELECT statement can
be used in this context.

841
Alphabetic list of error messages

Server %1: %2
Item Value
SQLCODE -660
Constant SQLE_OMNI_REMOTE_ERROR
SQLSTATE WO005
Sybase error code 13732
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the remote server.
Parameter 2 The message from the remote server.

Probable cause A message was generated by a remote server. The message text is included."

Server capability name %1 could not be found in the


SYSCAPABILITYNAME table.
Item Value
SQLCODE -761
Constant SQLE_CAPABILITY_NOT_FOUND
SQLSTATE WO014
Sybase error code 13723
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of server capability.

Probable cause An ALTER SERVER statement was attempted on a capability that was not
defined.

842
CHAPTER 10 Database Error Messages

Server not found and unable to autostart


Item Value
SQLCODE -764
Constant SQLE_UNABLE_TO_CONNECT_OR_START
SQLSTATE 08W55
Sybase error code 13774
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause Could not connect to a server, and was unable to autostart a server. Autostart
may have failed because no database file was supplied.

Signature ’%1’ does not match procedure parameters


Item Value
SQLCODE -737
Constant SQLE_SIGNATURE_MISMATCH
SQLSTATE 42W54
Sybase error code 201
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 The value of the signature

Probable cause The number of types in the signature must match the number of procedure
parameters. If a ’dynamic result sets’ clause was specified, the number of
dynamic result sets must match the quantity found in the signature.

843
Alphabetic list of error messages

Specified database file already in use.


Item Value
SQLCODE -816
Constant SQLE_FILE_IN_USE
SQLSTATE 08W56
Sybase error code 924
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause The database server could not start the specified database because the file is
already in use.

Specified database is invalid


Item Value
SQLCODE -84
Constant SQLE_INVALID_DATABASE
SQLSTATE 08W11
Sybase error code 4001
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause The database file you specified is invalid. The database server is stopped.

Specified database not found


Item Value
SQLCODE -83
Constant SQLE_DATABASE_NOT_FOUND
SQLSTATE 08W10
Sybase error code 911
ODBC 2 State 08001
ODBC 3 State 08001

844
CHAPTER 10 Database Error Messages

Probable cause The database server was started but was unable to find the specified
database. The database server may be attempting to start a database file that
cannot be opened or that cannot be found on the network. You may be
attempting to connect to a database name that is not running. The database
server is stopped.

SQL statement error


Item Value
SQLCODE -132
Constant SQLE_STATEMENT_ERROR
SQLSTATE 26501
Sybase error code 13629
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The statement identifier (generated by PREPARE) passed to the database for
a further operation is invalid.

SQLDA data type invalid


Item Value
SQLCODE -759
Constant SQLE_SQLDA_INVALID_DATATYPE
SQLSTATE 07W05
Sybase error code 13770
ODBC 2 State 07001
ODBC 3 State 07W05

Probable cause The data type specified for a SQLDA variable is invalid.

845
Alphabetic list of error messages

SQLDA fields inconsistent for a multi-row SQLDA


Item Value
SQLCODE -700
Constant SQLE_SQLDA_INCONSISTENT
SQLSTATE 07W04
Sybase error code 13721
ODBC 2 State 07001
ODBC 3 State 07W04

Probable cause Not all of the rows in a multi-rows SQLDA have been defined identically for
an array operation (insert, fetch, or execute). A given column must be
defined the same (type and length) in each row.

Sqlpp/dblib version mismatch


Item Value
SQLCODE -230
Constant SQLE_PP_DBLIB_MISMATCH
SQLSTATE 08W18
Sybase error code 13657
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause Your executable has source files with Embedded SQL that were
preprocessed with a preprocessor that does not match the database interface
library.

846
CHAPTER 10 Database Error Messages

Standard logons are not permitted


Item Value
SQLCODE -206
Constant SQLE_INVALID_INTEGRATED_LOGON
SQLSTATE 28W03
Sybase error code 13690
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause The LOGIN_MODE database option is set to integrated login type, and you
attempted a standard logon. Change the option setting or use an integrated
login.

Statement cannot be executed


Item Value
SQLCODE 111
Constant SQLE_CANNOT_EXECUTE_STMT
SQLSTATE 01W08
Sybase error code 590
ODBC 2 State OK
ODBC 3 State OK

Probable cause You specified a statement for the PREPARE..WITH EXECUTE statement
that cannot be executed. If you specified an output SQLDA, it may contain a
DESCRIBE of the prepared statement.

847
Alphabetic list of error messages

Statement interrupted by user


Item Value
SQLCODE -299
Constant SQLE_INTERRUPTED
SQLSTATE 57014
Sybase error code 3621
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You canceled a statement during its execution. The database was able to stop
the operation without doing a rollback. If the statement is INSERT,
UPDATE, or DELETE, any changes made by the statement will be canceled.
If the statement is a data definition statement (for example CREATE
TABLE), the statement will be canceled, but the COMMIT that was done as
a side effect will not be canceled.

Statement is not allowed in passthrough mode


Item Value
SQLCODE -707
Constant SQLE_STMT_NOT_ALLOWED_IN_PASSTHROUG
H
SQLSTATE 0AW05
Sybase error code 13631
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You tried to execute a statement that cannot be executed while in
passthrough mode. For example, you may have executed a batch statement.

848
CHAPTER 10 Database Error Messages

statement’s size limit is invalid.


Item Value
SQLCODE -674
Constant SQLE_INVALID_CURSOR_RANGE
SQLSTATE 09W07
Sybase error code 13713
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause FIRST or TOP n are used in a SELECT statement to limit the size of a result.
The size limit ’n’ must be a constant integer greater than 0 and less than
32767.

Subquery allowed only one select list item


Item Value
SQLCODE -151
Constant SQLE_SUBQUERY_SELECT_LIST
SQLSTATE 53023
Sybase error code 102
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You entered a subquery which has more than one column in the select list.
Change the select list to have only one column.

849
Alphabetic list of error messages

Subquery cannot return more than one row


Item Value
SQLCODE -186
Constant SQLE_SUBQUERY_RESULT_NOT_UNIQUE
SQLSTATE 21W01
Sybase error code 512
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You used a subquery that returns more than one row, in a context where only
a single row can be used. If the subquery is in the WHERE clause, you might
be able to use the IN keyword.

Subscription to ’%1’ for ’%2’ already exists


Item Value
SQLCODE -282
Constant SQLE_SUBSCRIPTION_NOT_UNIQUE
SQLSTATE 5RW03
Sybase error code 13644
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the publication.
Parameter 2 Name of the user.

Probable cause You attempted to create a subscription that already exists.

850
CHAPTER 10 Database Error Messages

Subscription to ’%1’ for ’%2’ not found


Item Value
SQLCODE -283
Constant SQLE_SUBSCRIPTION_NOT_FOUND
SQLSTATE 5RW04
Sybase error code 13645
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the publication.
Parameter 2 Name of the user.

Probable cause You attempted to drop, start, or synchronize a subscription that does not
exist.

Synchronization message type ’%1’ not found


Item Value
SQLCODE -765
Constant SQLE_NOT_SYNC_TYPE
SQLSTATE 5RW11
Sybase error code 13775
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of synchronization message type.

Probable cause You referred to a synchronization message type that is not defined in this
database.

851
Alphabetic list of error messages

Synchronization option ’%1’ contains semi-colon or equal sign


Item Value
SQLCODE -797
Constant SQLE_BAD_SYNC_OPTION_VALUE
SQLSTATE 5RW32
Sybase error code 13807
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 The name of the synchronization option

Probable cause You attempted to set a synchronization option with an invalid value.

Synchronization option ’%1’ not found


Item Value
SQLCODE -805
Constant SQLE_SYNC_OPTION_NOT_FOUND
SQLSTATE 5RW33
Sybase error code 13815
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 The name of the synchronization option

Probable cause You attempted to delete a undefined synchronization option.

852
CHAPTER 10 Database Error Messages

Synchronization option is too long


Item Value
SQLCODE -809
Constant SQLE_SYNC_OPTION_TOO_LONG
SQLSTATE 5RW34
Sybase error code 13819
ODBC 2 State 42000
ODBC 3 State 42S02

Probable cause Synchronization option list cannot be longer than database page size.

Synchronization server failed to commit the upload


Item Value
SQLCODE -794
Constant SQLE_UPLOAD_FAILED_AT_SERVER
SQLSTATE 0AW09
Sybase error code 13804
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to synchronize an UltraLite database and during the
synchronization session, a complete upload stream was sent that could not be
commited to the consolidated database. The reason for the upload failure can
be found in the synchronization log file.

853
Alphabetic list of error messages

Synchronization site ’%1’ is already defined


Item Value
SQLCODE -796
Constant SQLE_SYNC_SITE_NOT_UNIQUE
SQLSTATE 5RW31
Sybase error code 13806
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 The name of the synchronization site

Probable cause You attempted to create a synchronization site with a non-unique site name.

Syntax error near ’%1’


Item Value
SQLCODE -131
Constant SQLE_SYNTAX_ERROR
SQLSTATE 42W04
Sybase error code 102
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 The word or symbol where the syntax error has been
detected.

Probable cause The database server cannot understand the statement you are trying to
execute. If you used a keyword (such as DATE) for a column name, try
enclosing the keyword in quotation marks ("DATE").

854
CHAPTER 10 Database Error Messages

Syntax error, cannot specify IQ specific options without specifying


IQ PATH
Item Value
SQLCODE -687
Constant SQLE_IQ_PATH_SYNTAX_ERROR
SQLSTATE 42W48
Sybase error code 102
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause The database server cannot understand the statement you are trying to
execute. If you used a keyword (such as DATE) for a column name, try
enclosing the keyword in quotation marks ("DATE").

System event type ’%1’ not found


Item Value
SQLCODE -806
Constant SQLE_EVENT_TYPE_NOT_FOUND
SQLSTATE WE008
Sybase error code 13816
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the system event type that could not be found.

Probable cause You have attempted to create an event with a system event type name that
does not exist in SYS.SYSEVENTTYPE.

855
Alphabetic list of error messages

Table %1 is already included


Item Value
SQLCODE -822
Constant SQLE_TABLE_ALREADY_INCLUDED
SQLSTATE 5RW36
Sybase error code 13828
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 The name of the table

Probable cause You attempted to add or modify a publication or synchronization definition


such that the same table is included twice.

Table ’%1’ has a foreign key with a referential action


Item Value
SQLCODE -677
Constant SQLE_TABLE_HAS_REFACTION
SQLSTATE 56001
Sybase error code 547
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the table with the referential action

Probable cause The table could not be renamed as it has a foreign key with a referential
action. To rename the table, first drop the foreign key constraints.

856
CHAPTER 10 Database Error Messages

Table ’%1’ has no primary key


Item Value
SQLCODE -118
Constant SQLE_NO_PRIMARY_KEY
SQLSTATE 55008
Sybase error code 1719
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the table that does not have a primary key.

Probable cause You attempted to add a foreign key referring to a table that does not have a
primary key. You must add a primary key to the referenced table.

Table ’%1’ has publications


Item Value
SQLCODE -281
Constant SQLE_TABLE_HAS_PUBLICATIONS
SQLSTATE 5RW02
Sybase error code 13643
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the publication that has publications.

Probable cause You attempted to drop a table that has publications defined.

857
Alphabetic list of error messages

Table ’%1’ is in an outer join cycle


Item Value
SQLCODE -136
Constant SQLE_OUTER_JOIN_CYCLE
SQLSTATE 52W14
Sybase error code 315
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of a table in the cycle.

Probable cause You specified outer joins that create a cycle of tables.

Table ’%1’ is part of a synchronization definition


Item Value
SQLCODE -819
Constant SQLE_SYNC_CONTAINS_TABLE
SQLSTATE 5RW35
Sybase error code 13825
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 The name of the table

Probable cause A table belonging to a synchronization definition cannot be dropped or


altered except using DBMLSync.

858
CHAPTER 10 Database Error Messages

Table ’%1’ not found


Item Value
SQLCODE -141
Constant SQLE_TABLE_NOT_FOUND
SQLSTATE 42W33
Sybase error code 2706
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the table that could not be found.

Probable cause You misspelled the name of a table, or you did not qualify a table name with
a user name. For example, you might have referred to employee instead of
"DBA".employee,

Table ’%1’ requires a unique correlation name


Item Value
SQLCODE -137
Constant SQLE_CORRELATION_NAME_NEEDED
SQLSTATE 52W15
Sybase error code 315
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the table that needs a unique correlation name.

Probable cause You specified a join that joins a table to itself. You need to use unique
correlation names in order to have multiple instances of a table.

859
Alphabetic list of error messages

Table already has a primary key


Item Value
SQLCODE -112
Constant SQLE_EXISTING_PRIMARY_KEY
SQLSTATE 55013
Sybase error code 1923
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted to add a primary key on a table that already has a primary key
defined. You must delete the current primary key before adding a new one.

Table cannot have two primary keys


Item Value
SQLCODE -126
Constant SQLE_PRIMARY_KEY_TWICE
SQLSTATE 52W05
Sybase error code 1923
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You specified the primary key twice in a CREATE TABLE statement.

Table in use
Item Value
SQLCODE -214
Constant SQLE_TABLE_IN_USE
SQLSTATE 42W21
Sybase error code 3702
ODBC 2 State 40001
ODBC 3 State 40001

860
CHAPTER 10 Database Error Messages

Probable cause You attempted to ALTER or DROP a table that is being used by other active
users of the database.

Table must be empty


Item Value
SQLCODE -116
Constant SQLE_TABLE_MUST_BE_EMPTY
SQLSTATE 55W02
Sybase error code 4901
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to modify a table, and the database server can only perform
the change if there are no rows in the table.

Terminated by user -- transaction rolled back


Item Value
SQLCODE -302
Constant SQLE_TERMINATED_BY_USER
SQLSTATE 40W02
Sybase error code 3618
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You canceled a statement while the database was executing. A ROLLBACK
WORK statement has been automatically executed.

861
Alphabetic list of error messages

The column ’%1’ does not exist in the remote table


Item Value
SQLCODE -722
Constant SQLE_OMNI_NOSUCH_COLUMN
SQLSTATE WO016
Sybase error code 11208
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the column.

Probable cause The column specified in the ’CREATE EXISTING’ statement does not exist
in the remote table.

The connection parameters file could not be found


Item Value
SQLCODE -654
Constant SQLE_NO_PROFILE_FILE
SQLSTATE 08W37
Sybase error code 13706
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause An attempt was made to parse a connection string containing a connection
profile but the connection parameters file could not be found.

862
CHAPTER 10 Database Error Messages

The cursor name ’%1’ already exists


Item Value
SQLCODE -683
Constant SQLE_DUPLICATE_CURSOR_NAME
SQLSTATE WJ004
Sybase error code 13714
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the cursor

Probable cause You attempted to declare a cursor with a name that already exists. Cursor
names must be unique within a connection.

The data type of column ’%1’ is not supported


Item Value
SQLCODE -736
Constant SQLE_OMNI_UNSUPPORTED_DATATYPE
SQLSTATE WO022
Sybase error code 11205
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the column.

Probable cause The column is defined with a data type that is not supported for remote
tables.

863
Alphabetic list of error messages

The data type specified for column ’%1’ is not compatible with the
actual data type
Item Value
SQLCODE -721
Constant SQLE_OMNI_DATATYPE_MISMATCH
SQLSTATE WO015
Sybase error code 11209
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the column.

Probable cause The data type of the column specified in the ’CREATE EXISTING’
statement is not compatible with the actual data type of the column in the
remote table.

The database does not support the Java virtual machine


Item Value
SQLCODE -758
Constant SQLE_NO_JAVA_SUPPORT
SQLSTATE WJ022
Sybase error code 13769
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The Java virtual machine could not be started because the database does not
have the proper support. It may be that the database was created with an
older version of the software, or was created with the Java support disabled.
If the database was created with an older version of the software the database
should be upgraded to the most recent version. If the database was created
with Java support disabled, then the instjava.sql script should be run against
the database to enable java support.

864
CHAPTER 10 Database Error Messages

The external function call is incompatible


Item Value
SQLCODE -818
Constant SQLE_INCOMPATIBLE_EXTERNAL_CALL
SQLSTATE WW026
Sybase error code 13824
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to call an external function. An attempt to load the attempted
library failed because of incompatibility with the server. Incompatibility may
arise because the dynamic library is using an external function api that is
either not supported by the server or is newer than the one supported by the
server.

The integrated login ID guest can only be mapped to the guest


database user ID
Item Value
SQLCODE -247
Constant SQLE_INTEGRATED_LOGON_GUESTMAP
SQLSTATE 28W06
Sybase error code 13695
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause You attempted to map the guest login ID to something other than guest

865
Alphabetic list of error messages

The JDBC resultset must be positioned on an insert row in order to


use the ’%1’ function
Item Value
SQLCODE -753
Constant SQLE_JDBC_MUST_OPER_ON_INSERT_ROW
SQLSTATE WJ020
Sybase error code 13764
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of the resultset function being called

Probable cause Resultset functions such as ’insertRow’ can only be called when the resultset
is positioned on the insert row.

The length specified for column ’%1’ is different than the actual
length
Item Value
SQLCODE -723
Constant SQLE_OMNI_LENGTH_MISMATCH
SQLSTATE WO017
Sybase error code 11210
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 The name of the column.

Probable cause The length of the column specified in the ’CREATE EXISTING’ statement is
different than the length of the column in the remote table.

866
CHAPTER 10 Database Error Messages

The login ID ’%1’ has not been mapped to any database user ID
Item Value
SQLCODE -313
Constant SQLE_INTEGRATED_LOGON_UNMAPPED
SQLSTATE 28W09
Sybase error code 13698
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause You attempted to drop a login ID that had not been mapped yet

The login ID ’%1’ is already mapped to user ID ’%2’


Item Value
SQLCODE -249
Constant SQLE_INTEGRATED_LOGON_MAPPED
SQLSTATE 28W08
Sybase error code 13697
ODBC 2 State 28000
ODBC 3 State 28000

Probable cause You attempted to map a login ID twice

The optimizer was unable to construct a valid access plan


Item Value
SQLCODE -727
Constant SQLE_CANNOT_OPTIMIZE_QUERY
SQLSTATE WI010
Sybase error code 13730
ODBC 2 State ERROR
ODBC 3 State ERROR

867
Alphabetic list of error messages

Probable cause The database server was unable to construct a valid access plan for the given
request. This is an Adaptive Server Anywhere internal error. If it can be
reproduced, it should be reported by Sybase. You may be able to work
around this problem by modifying the query statement.

The option %1 can only be set as a temporary option


Item Value
SQLCODE -216
Constant SQLE_OPTION_IS_TEMP_ONLY
SQLSTATE 42W52
Sybase error code 5878
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause The option specified in the SET OPTION statement can only be set as a
temporary option.

The option %1 cannot be set from within a procedure


Item Value
SQLCODE -217
Constant SQLE_OPTION_IN_PROCEDURE
SQLSTATE 42W53
Sybase error code 5878
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause The option specified in the SET OPTION statement can only be set as a
temporary option.

868
CHAPTER 10 Database Error Messages

The pattern is too long


Item Value
SQLCODE -606
Constant SQLE_PATTERN_TOO_LONG
SQLSTATE WW001
Sybase error code 7706
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The pattern for the LIKE operator is too long. All patterns of 126 characters
or less are supported. Some patterns as long as 254 characters are supported,
depending on their contents. Patterns longer than 254 characters are not
supported.

The remote server does not support an auto-incrementing data


type
Item Value
SQLCODE -698
Constant SQLE_OMNI_AUTOINC_NOT_SUPPORTED
SQLSTATE WO011
Sybase error code 11205
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause Auto-incrementing data types can only be supported in a proxy table when
the backend server supports this feature.

869
Alphabetic list of error messages

The remote table ’%1’ could not be found


Item Value
SQLCODE -666
Constant SQLE_OMNI_RMT_TABLE_NOTFOUND
SQLSTATE WO007
Sybase error code 11214
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The complete name of the remote table

Probable cause The table could not be found on the remote server. Check the remote table
name and the user privileges on that table.

The Select list for the derived table ’%1’ has no expression to
match %2
Item Value
SQLCODE -812
Constant SQLE_NO_MATCHING_SELECT_ITEM
SQLSTATE 42W59
Sybase error code 13822
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the derived table.
Parameter 2 Name of the alias for which there is no matching
expression.

Probable cause The specified alias from the derived table’s AS clause has no matching
expression from the Select statement for that derived table. Ensure that each
Select list item has a matching alias in the derived table’s AS clause, and
vice-versa.

870
CHAPTER 10 Database Error Messages

The selected database is currently inactive


Item Value
SQLCODE -74
Constant SQLE_DATABASE_NOT_ACTIVE
SQLSTATE 08W30
Sybase error code 950
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause The selected database is in an inactive state. The database may be in the
process of being started or of being shut down.

The server attempted to access a page beyond the end of the


maximum allowable dbspace file size
Item Value
SQLCODE -605
Constant SQLE_ACCESS_BEYOND_END_OF_MAX_DBSPA
CE
SQLSTATE 04W08
Sybase error code 5006
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The database attempted to access a page whose page number is beyond the
maximum possible number of disk pages. This is a fatal internal error.

871
Alphabetic list of error messages

The specified foreign key (%1) can not be enforced


Item Value
SQLCODE -729
Constant SQLE_UNENFORCEABLE_FOREIGN_KEY
SQLSTATE 23507
Sybase error code 549
ODBC 2 State 23000
ODBC 3 State 23000
Parameter 1 Name of the foreign key.

Probable cause You attempted to create a foreign key that can not be enforced. In order to
enforceable, the primary and foreign table for the specified key must exist on
the same server. You can use the ’unenforced’ keyword to create a foreign
key specification that is not to be enforced.

The specified transaction isolation is invalid


Item Value
SQLCODE -676
Constant SQLE_INVALID_TRANSACTION_ISOLATION
SQLSTATE WJ003
Sybase error code 7374
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The specified transaction isolation is invalid.

872
CHAPTER 10 Database Error Messages

The streams environment could not be created


Item Value
SQLCODE -740
Constant SQLE_FAILED_TO_CREATE_STREAMS_ENV
SQLSTATE WW024
Sybase error code 13753
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause The streams environment could not be created. Either there are insufficient
resources to create the environment or the language resource file cannot be
found.

The table specification ’%1’ identifies more than one remote table
Item Value
SQLCODE -726
Constant SQLE_OMNI_RMT_TABLE_NOTUNIQUE
SQLSTATE WO020
Sybase error code 11215
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The complete name of the remote table

Probable cause More than one table was found on the remote server for the given table
specification. Add a database or owner name to the specification.

873
Alphabetic list of error messages

There are still active database connections


Item Value
SQLCODE -109
Constant SQLE_STILL_ACTIVE_CONNECTIONS
SQLSTATE 08W06
Sybase error code 6001
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to shut down a database which still has active connections.

There is already a variable named ’%1’


Item Value
SQLCODE -261
Constant SQLE_VARIABLE_EXISTS
SQLSTATE 42W15
Sybase error code 134
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to CREATE a variable with the name of another variable that
already exists.

874
CHAPTER 10 Database Error Messages

There is more than one way to join ’%1’ to ’%2’


Item Value
SQLCODE -147
Constant SQLE_AMBIGUOUS_JOIN
SQLSTATE 52W08
Sybase error code 301
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of first table that cannot be joined.
Parameter 2 Name of second table that cannot be joined.

Probable cause You are attempting to KEY JOIN two tables, and there are two or more
foreign keys relating the two tables. There may be two foreign keys from the
first table to the second table It may be that each table has a foreign key to
the other table. You must use a correlation name for the primary key table
which is the same as the role name of the desired foreign key relationship.

There is no way to join ’%1’ to ’%2’


Item Value
SQLCODE -146
Constant SQLE_CANNOT_JOIN
SQLSTATE 53W04
Sybase error code 301
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of first table that cannot be joined.
Parameter 2 Name of second table that cannot be joined.

Probable cause You may have attempted a KEY JOIN between two tables and there is no
foreign key on one of the tables that references the primary key of the other
table. You may have attempted a NATURAL JOIN between two tables that
have no common column names.

875
Alphabetic list of error messages

Too many columns in table


Item Value
SQLCODE -616
Constant SQLE_TOO_MANY_COLUMNS_IN_TABLE
SQLSTATE 52W20
Sybase error code 1702
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You executed a CREATE TABLE or ALTER TABLE statement, which
attempted to add a column to a table. The resulting number of columns in the
table would exceed the limit for the current database page size.

Too many parameters to this external procedure call


Item Value
SQLCODE -625
Constant SQLE_TOO_MANY_PARAMETERS
SQLSTATE WW010
Sybase error code 13680
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause There is a maximum of 256 parameters to an external function call in 32-bit
Windows.

876
CHAPTER 10 Database Error Messages

too many temporary tables in connection


Item Value
SQLCODE -817
Constant SQLE_TOO_MANY_TEMP_TABLES
SQLSTATE 52W41
Sybase error code 13823
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause A CREATE TABLE or DECLARE TABLE statement attempted to create a


temporary table, but the resulting number of distinct table ids used for
temporary tables in the current connection would exceed the limit.

Transact-SQL feature not supported


Item Value
SQLCODE -611
Constant SQLE_TSQL_FEATURE_NOT_SUPPORTED
SQLSTATE 0AW02
Sybase error code 176
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to use a Transact-SQL feature that is not supported in
Adaptive Server Anywhere.

877
Alphabetic list of error messages

Transaction log backup page only partially full


Item Value
SQLCODE 110
Constant SQLE_BACKUP_PAGE_INCOMPLETE
SQLSTATE 01W10
Sybase error code 13683
ODBC 2 State OK
ODBC 3 State OK

Probable cause A DB_LOG_BACKUP_READ_WAIT was issued against the transaction


log and the page returned was not full. The application should reissue the
request for the same page.

Transaction log was truncated


Item Value
SQLCODE -244
Constant SQLE_LOG_TRUNCATED
SQLSTATE WB005
Sybase error code 13661
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause An operation was being performed on the transaction log such as SQL
Remote or Replication Agent processing and the transaction log was
truncated by an independent backup during that operation.

878
CHAPTER 10 Database Error Messages

Trigger ’%1’ not found


Item Value
SQLCODE -268
Constant SQLE_TRIGGER_NOT_FOUND
SQLSTATE 52W10
Sybase error code 9819
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the trigger that could not be found.

Probable cause You misspelled the name of a trigger, or you did not qualify a trigger name
with a user name.

Trigger definition conflicts with existing triggers


Item Value
SQLCODE -271
Constant SQLE_TRIGGER_DEFN_CONFLICT
SQLSTATE 52W11
Sybase error code 102
ODBC 2 State S0002
ODBC 3 State 42S01

Probable cause You attempted to create a trigger, but a trigger with the same name already
exists.

879
Alphabetic list of error messages

Triggers and procedures not supported in runtime server


Item Value
SQLCODE -275
Constant SQLE_PROCEDURES_NOT_IN_DESKTOP
SQLSTATE 0AW04
Sybase error code 102
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to call a stored procedure or have modified a row in a table on
which a trigger is defined and you are using the runtime server. Triggers and
stored procedures are not supported in the runtime server. You must be
running the full server to use these features.

TRUNCATE TABLE statement cannot refer to a view


Item Value
SQLCODE -702
Constant SQLE_CANNOT_TRUNCATE_VIEW
SQLSTATE 42W49
Sybase error code 4708
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to use TRUNCATE TABLE on a view. The TRUNCATE
TABLE statement deletes every row from a table and cannot be used to
delete rows from a view. Replace the view reference with the name of a base
table.

880
CHAPTER 10 Database Error Messages

Unable to connect to server ’%1’: %2


Item Value
SQLCODE -656
Constant SQLE_OMNI_CONNECT_ERROR
SQLSTATE WO001
Sybase error code 11206
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 The name of the server that could not be connected to
Parameter 2 A more specific reason returned from the server class
driver.

Probable cause You attempted to connect to a remote server. Check that the remote server is
running.

Unable to delete database file


Item Value
SQLCODE -243
Constant SQLE_BACKUP_UNABLE_TO_DELETE_FILE
SQLSTATE WB004
Sybase error code 13660
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You attempted to delete a database file, but it could not be deleted. The
filename should not be the same as any database file that is currently in use.

881
Alphabetic list of error messages

Unable to enlist transaction; DTC may be down


Item Value
SQLCODE -803
Constant SQLE_FAILED_TO_ENLIST
SQLSTATE WL005
Sybase error code 13813
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You tried to enlist a transaction but DTC does not seem to be available at this
time.

Unable to find in index ’%1’ for table ’%2’


Item Value
SQLCODE -189
Constant SQLE_NOT_FOUND_IN_INDEX
SQLSTATE WI005
Sybase error code 2727
ODBC 2 State ERROR
ODBC 3 State ERROR
Parameter 1 Name of invalid index.
Parameter 2 Name of table containing the invalid index.

Probable cause This is an internal error. If it can be reproduced, it should be reported to


Sybase. You should be able to work around the error by dropping and
recreating the index.

882
CHAPTER 10 Database Error Messages

Unable to open backup log ’%1’


Item Value
SQLCODE 119
Constant SQLE_UNABLE_TO_OPEN_BACKUP_LOG
SQLSTATE WB011
Sybase error code 13776
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 backup log filename

Probable cause The server was unable to open the backup log to record the execution of a
BACKUP or RESTORE statement. Check the settings of the environment
variables used to locate the backup log file. The directory to contain the log
must already exist.

Unable to reenlist transaction; DTC may be down


Item Value
SQLCODE -804
Constant SQLE_FAILED_TO_REENLIST
SQLSTATE WL006
Sybase error code 13814
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You tried to recover a transaction but DTC does not seem to be available at
this time.

883
Alphabetic list of error messages

Unable to start database server


Item Value
SQLCODE -80
Constant SQLE_UNABLE_TO_START_ENGINE
SQLSTATE 08W07
Sybase error code 708
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause It was not possible to start the database server. There may not be enough
memory to run the database server. It may be that the executable cannot be
found.

Unable to start specified database


Item Value
SQLCODE -82
Constant SQLE_UNABLE_TO_START_DATABASE
SQLSTATE 08W09
Sybase error code 840
ODBC 2 State 08001
ODBC 3 State 08001

Probable cause The database server was started but was unable to find the specified
database. No specific reason is known.

884
CHAPTER 10 Database Error Messages

Undefined synchronization template ’%1’


Item Value
SQLCODE -795
Constant SQLE_SYNC_TEMPLATE_NOT_FOUND
SQLSTATE 5RW30
Sybase error code 13805
ODBC 2 State 42000
ODBC 3 State 42S02
Parameter 1 The name of the synchronization template

Probable cause You attempted to define a remote synchronization site using an undefined
synchronization template.

Unknown backup operation


Item Value
SQLCODE -240
Constant SQLE_UNKNOWN_BACKUP_OPERATION
SQLSTATE WB001
Sybase error code 3206
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause You specified an invalid backup statement operation in a call to db_backup.

885
Alphabetic list of error messages

Unknown function ’%1’


Item Value
SQLCODE -148
Constant SQLE_UNKNOWN_FUNC
SQLSTATE 42W05
Sybase error code 176
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Function name that is not a database function.

Probable cause You misspelled the name of a database function (such as MAXIMUM
instead of MAX) in a query definition or in a query column name.

UNLOAD TABLE cannot be used to unload a view


Item Value
SQLCODE -643
Constant SQLE_CANNOT_UNLOAD_A_VIEW
SQLSTATE WL004
Sybase error code 13672
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause UNLOAD TABLE was specified with the name of a view. UNLOAD
TABLE may only be used to unload tables.

886
CHAPTER 10 Database Error Messages

Unsupported character set ’%1’


Item Value
SQLCODE 115
Constant SQLE_UNSUPPORTED_CHARACTER_SET
SQLSTATE 01W13
Sybase error code 13614
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 Name of the character set that could not be supported.

Probable cause The character set that the application requested is not supported by the server
to which the application was attempting a connection.

Unsupported character set ’%1’ and unsupported language;


language used is ’%2’ instead
Item Value
SQLCODE 117
Constant SQLE_UNSUPPORTED_CHARSET_AND_LANGUA
GE
SQLSTATE 01W15
Sybase error code 13616
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 Name of the character set that could not be supported.
Parameter 2 Name of the language that the server will use to send
language strings.

Probable cause The character set that the application requested is not supported by the server
to which the application is connecting. The language that the application
requested is not supported either. Language strings will be sent in the
language specified.

887
Alphabetic list of error messages

Unsupported language; language used is ’%1’ instead


Item Value
SQLCODE 116
Constant SQLE_UNSUPPORTED_LANGUAGE
SQLSTATE 01W14
Sybase error code 13615
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 Name of the language that the server will use to send
language strings.

Probable cause The language that the application requested is not supported by the server to
which the application is connecting. Language strings will be sent in the
language specified.

Unterminated C string
Item Value
SQLCODE -634
Constant SQLE_UNTERMINATED_C_STR
SQLSTATE 22024
Sybase error code 13682
ODBC 2 State 22024
ODBC 3 State 22024

Probable cause The least significant character of a C string host variable must contain the
null character.

888
CHAPTER 10 Database Error Messages

Update operation attempted on a read-only cursor


Item Value
SQLCODE -633
Constant SQLE_READ_ONLY_CURSOR
SQLSTATE 42W30
Sybase error code 7732
ODBC 2 State S1009
ODBC 3 State HY092

Probable cause You attempted an update operation on a cursor that was explicitly declared
as read-only.

Update operation attempted on non-updatable query


Item Value
SQLCODE -192
Constant SQLE_NON_UPDATEABLE_VIEW
SQLSTATE 42W31
Sybase error code 7301
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted an insert, update, or delete operation on a query that is
implicitly read-only. Queries that contain DISTINCT, GROUP BY,
HAVING, or UNION, or that contain aggregate functions, or that involve a
join, are implicitly read only. If the query references a view then the view
may be non-updatable.

889
Alphabetic list of error messages

Update operation attempted on non-updatable remote query


Item Value
SQLCODE -728
Constant SQLE_NON_UPDATEABLE_EXT_TAB
SQLSTATE 42W35
Sybase error code 7338
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause You attempted an update, or delete operation on a remote table that is
currently not implemented. Examples of such operations include positioned
updates and updates that require building of work tables.

User ’%1’ already has GRANT permission


Item Value
SQLCODE -120
Constant SQLE_ALREADY_HAS_GRANT_PERMS
SQLSTATE 42W01
Sybase error code 13625
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the user ID that already has GRANT
permission.

Probable cause You attempted to give a user GRANT OPTION and that user already has
GRANT OPTION.

890
CHAPTER 10 Database Error Messages

User ’%1’ already has membership in group ’%2’


Item Value
SQLCODE -312
Constant SQLE_ALREADY_HAS_GROUP_MEMBERSHIP
SQLSTATE 42W34
Sybase error code 13627
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the user ID that already has membership.
Parameter 2 Name of the group.

Probable cause You attempted to give a membership in a group to a user that already has
such membership.

User ’%1’ has the row in ’%2’ locked


Item Value
SQLCODE -210
Constant SQLE_LOCKED
SQLSTATE 42W18
Sybase error code 8405
ODBC 2 State 40001
ODBC 3 State 40001
Parameter 1 Name of another user.
Parameter 2 Table which generates the error.

Probable cause You attempted to read or write a row and it is locked by another user, while
the BLOCKING database option is set to OFF.

891
Alphabetic list of error messages

User ’%1’ is already the publisher for this database


Item Value
SQLCODE -284
Constant SQLE_ONLY_ONE_PUBLISHER
SQLSTATE 5RW05
Sybase error code 13646
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of the publisher.

Probable cause You attempted to GRANT PUBLISH to a user ID, when a publisher already
exists.

User ’%1’ is not a remote user for this database


Item Value
SQLCODE -285
Constant SQLE_NOT_REMOTE_USER
SQLSTATE 5RW06
Sybase error code 13647
ODBC 2 State S0002
ODBC 3 State 42S02
Parameter 1 Name of user.

Probable cause You attempted to CREATE a subscription for a user, or PASSTHROUGH


for a user that is not a remote user of this database. You must GRANT
REMOTE or GRANT CONSOLIDATE.

892
CHAPTER 10 Database Error Messages

User ’%1’ is not a user group


Item Value
SQLCODE -123
Constant SQLE_NOT_A_GROUP
SQLSTATE 42W03
Sybase error code 13626
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of user you thought was a group.

Probable cause You attempted to add a member to group, but the user ID specified as a
group has not been granted the GROUP special privilege.

User ID ’%1’ does not exist


Item Value
SQLCODE -140
Constant SQLE_UNKNOWN_USERID
SQLSTATE 08004
Sybase error code 509
ODBC 2 State 28000
ODBC 3 State 28000
Parameter 1 Name of the user ID that could not be found.

Probable cause You used a user ID that does not exist.

893
Alphabetic list of error messages

User message %1 already exists


Item Value
SQLCODE -610
Constant SQLE_MESSAGE_ALREADY_EXISTS
SQLSTATE 52W16
Sybase error code 13624
ODBC 2 State 42000
ODBC 3 State 42000

Probable cause The message with this error number already exists in the
SYSUSERMESSAGES system table.

User message %1 not found


Item Value
SQLCODE -612
Constant SQLE_MESSAGE_NOT_FOUND
SQLSTATE 52W17
Sybase error code 2748
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Message number.

Probable cause The message with this error number does not exist in
SYSUSERMESSAGES.

894
CHAPTER 10 Database Error Messages

User owns procedures in use


Item Value
SQLCODE -750
Constant SQLE_USER_OWNS_PROCEDURES_IN_USE
SQLSTATE 42W55
Sybase error code 3702
ODBC 2 State 40001
ODBC 3 State 40001

Probable cause You attempted to REVOKE CONNECT from a user that owns a procedure
being used by other active users of the database.

User owns tables in use


Item Value
SQLCODE -751
Constant SQLE_USER_OWNS_TABLES_IN_USE
SQLSTATE 42W56
Sybase error code 3702
ODBC 2 State 40001
ODBC 3 State 40001

Probable cause You attempted to REVOKE CONNECT from a user that owns a table being
used by other active users of the database.

895
Alphabetic list of error messages

User-defined exception signaled


Item Value
SQLCODE -297
Constant SQLE_USER_DEFINED_EXCEPTION
SQLSTATE 99999
Sybase error code 13662
ODBC 2 State ERROR
ODBC 3 State ERROR

Probable cause A stored procedure or trigger signaled a user-defined exception. This error
state is reserved for use within stored procedures or triggers which contain
exception handlers, as a way of signaling an exception which can be
guaranteed to not have been caused by the database server. Valid
SQLSTATE values range from 99000 to 99999 and are set by the user when
executing the signal SQL statement.

User-defined type %1 not found


Item Value
SQLCODE -613
Constant SQLE_USER_TYPE_NOT_FOUND
SQLSTATE 52W18
Sybase error code 2715
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Name of the user-defined type.

Probable cause The user-defined type with this name does not exist in SYSUSERTYPE.

896
CHAPTER 10 Database Error Messages

Using temporary table


Item Value
SQLCODE 102
Constant SQLE_TEMPORARY_TABLE
SQLSTATE 01W02
Sybase error code 13075
ODBC 2 State OK
ODBC 3 State OK

Probable cause A temporary table has been created in order to satisfy the query. It can only
occur on an OPEN statement.

VALIDATE TABLE statement must refer to a base table


Item Value
SQLCODE -720
Constant SQLE_CANNOT_VALIDATE_OBJECT
SQLSTATE 42W51
Sybase error code 13729
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause The VALIDATE TABLE statement must refer to a local base table; it cannot
refer to a view, an IQ table, or an object on a remote server.

897
Alphabetic list of error messages

Value %1 out of range for destination


Item Value
SQLCODE -158
Constant SQLE_OVERFLOW_ERROR
SQLSTATE 22003
Sybase error code 220
ODBC 2 State 22003
ODBC 3 State 22003
Parameter 1 The value that caused the overflow.

Probable cause You supplied to or fetched from the database a value that is out of range for
the destination column or host variable. For example, the value 10 may have
been supplied for a DECIMAL(3,2) field.

Value for column ’%1’ in table ’%2’ has changed


Item Value
SQLCODE 106
Constant SQLE_COLUMN_VALUE_CHANGED
SQLSTATE 01W06
Sybase error code 532
ODBC 2 State OK
ODBC 3 State OK
Parameter 1 Name of the column whose value has changed.
Parameter 2 Name of the table containing the column.

Probable cause A replicated UPDATE has found a value in an updated column that does not
match the value when the original UPDATE was made.

898
CHAPTER 10 Database Error Messages

Value truncated
Item Value
SQLCODE 101
Constant SQLE_TRUNCATED
SQLSTATE 01004
Sybase error code 7337
ODBC 2 State 01004
ODBC 3 State 01004

Probable cause You may have tried to insert, update, or select a value in the database that is
too large to fit in the destination. You may have fetched data into a host
variable or SQLDA variable not large enough to receive the value.

Variable ’%1’ not found


Item Value
SQLCODE -260
Constant SQLE_VARIABLE_NOT_FOUND
SQLSTATE 42W14
Sybase error code 137
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to DROP or SET the value of a SQL variable that was not
created or was previously dropped.

899
Alphabetic list of error messages

View references ’%1’, which is a temporary object. Views can only


refer to permanent objects.
Item Value
SQLCODE -766
Constant SQLE_VIEW_OVER_TEMP_OBJECT
SQLSTATE 42U00
Sybase error code 4412
ODBC 2 State 42000
ODBC 3 State 42000
Parameter 1 Temporary object name

Probable cause Views must refer only to permanent objects, not to temporary objects such as
local temporary tables.

Warning
Item Value
SQLCODE 200
Constant SQLE_WARNING
SQLSTATE 01000
Sybase error code 13619
ODBC 2 State OK
ODBC 3 State OK

Probable cause A warning has occurred. The message indicates the condition that caused the
warning.

900
CHAPTER 10 Database Error Messages

WITH CHECK OPTION violated for insert/update on base table ’%1’


Item Value
SQLCODE -632
Constant SQLE_WITH_CHECK_OPTION_VIOLATION
SQLSTATE 44000
Sybase error code 550
ODBC 2 State S1000
ODBC 3 State 44000
Parameter 1 Name of the base table being updated.

Probable cause You attempted an insert or update operation on the indicated base table
through a view (possibly nested). However, one or more values in the
modified row(s) triggered a WITH CHECK OPTION violation. This
violation occurs when a modified value causes one or more rows to fall
outside the range of the view by making the view’s WHERE clause evaluate
to FALSE or UNKNOWN for that row.

Wrong number of parameters to function ’%1’


Item Value
SQLCODE -154
Constant SQLE_WRONG_PARAMETER_COUNT
SQLSTATE 37505
Sybase error code 174
ODBC 2 State 37000
ODBC 3 State 42000
Parameter 1 Name of the function.

Probable cause You supplied an incorrect number of parameters to a database function.

901
Alphabetic list of error messages

Wrong number of values for INSERT


Item Value
SQLCODE -207
Constant SQLE_WRONG_NUM_OF_INSERT_COLS
SQLSTATE 53002
Sybase error code 213
ODBC 2 State 21S01
ODBC 3 State 21S01

Probable cause The number of values you are trying to insert does not match the number of
columns specified in the INSERT statement, or the number of columns in the
table if no columns are specified.

Wrong number of variables in FETCH


Item Value
SQLCODE -264
Constant SQLE_WRONG_NUM_OF_FETCH_VARIABLES
SQLSTATE 42W26
Sybase error code 553
ODBC 2 State S1002
ODBC 3 State 07009

Probable cause You specified a number of variables in a FETCH statement that does not
match the number of select list items.

902
CHAPTER 10 Database Error Messages

You cannot synchronize with uncommitted transactions


Item Value
SQLCODE -755
Constant SQLE_UNCOMMITTED_TRANSACTIONS
SQLSTATE 0AW08
Sybase error code 13765
ODBC 2 State 37000
ODBC 3 State 42000

Probable cause You attempted to synchronize an UltraLite database and there are changes in
the UltraLite database that have not been committed.

903
Internal errors (assertion failed)

Internal errors (assertion failed)


Adaptive Server Anywhere has many internal checks that have been
designed to detect possible database corruption as soon as possible. If the
database server prints an Assertion Failed message, you should not continue
to use it before attempting to determine the cause. You should record the
assertion number displayed on the screen and report the error to Adaptive
Server Anywhere technical support.
The dbvalid utility is useful for determining if your database file is corrupt.
You may find it necessary to reconstruct your data from backups and
transaction logs (see "Backup and Data Recovery" on page 627 of the book
ASA User’s Guide).

904
C H A P T E R 1 1

SQL Preprocessor Error Messages

About this chapter This chapter presents a list of all SQL preprocessor errors and warnings.
Contents
Topic Page
SQL Preprocessor error messages indexed by error message value 906
SQLPP errors 910

905
SQL Preprocessor error messages indexed by error message value

SQL Preprocessor error messages indexed by


error message value
Message value Message
2601 "subscript value %1 too large" on
page 923
2602 "combined pointer and arrays not
supported for hosttypes" on page 915
2603 "only one dimensional arrays
supported for char type" on page 922
2604 "VARCHAR type must have a
length" on page 913
2605 "arrays of VARCHAR not supported"
on page 914
2606 "VARCHAR host variables cannot be
pointers" on page 913
2607 "initializer not allowed on
VARCHAR host variable" on
page 918
2608 "FIXCHAR type must have a length"
on page 911
2609 "arrays of FIXCHAR not supported"
on page 913
2610 "arrays of this type not supported" on
page 914
2611 "precision must be specified for
decimal type" on page 922
2612 "arrays of decimal not allowed" on
page 914
2613 "Unknown hostvar type" on page 913
2614 "invalid integer" on page 919
2615 "’%1’ host variable must be a C string
type" on page 910
2617 "’%1’ symbol already defined" on
page 910
2618 "invalid type for sql statement
variable" on page 920

906
Chapter 11 SQL Preprocessor Error Messages

Message value Message


2619 "Cannot find include file ’%1’" on
page 911
2620 "host variable ’%1’ is unknown" on
page 916
2621 "indicator variable ’%1’ is unknown"
on page 918
2622 "invalid type for indicator variable
’%1’" on page 919
2623 "invalid host variable type on ’%1’"
on page 919
2625 "host variable ’%1’ has two different
definitions" on page 916
2626 "statement ’%1’ not previously
prepared" on page 922
2627 "cursor ’%1’ not previously declared"
on page 915
2628 "unknown statement ’%1’" on
page 924
2629 "host variables not allowed for this
cursor" on page 917
2630 "host variables specified twice - on
declare and open" on page 917
2631 "must specify a host list or using
clause on %1" on page 920
2633 "no INTO clause on SELECT
statement" on page 921
2634 "incorrect SQL language usage -- that
is a ’%1’ extension" on page 918
2635 "incorrect Embedded SQL language
usage -- that is a ’%1’ extension" on
page 917
2636 "incorrect Embedded SQL syntax" on
page 917
2637 "missing ending quote of string" on
page 920
2639 "token too long" on page 923
2640 "’%1’ host variable must be an integer
type" on page 910

907
SQL Preprocessor error messages indexed by error message value

Message value Message


2641 "must specify an SQLDA on a
DESCRIBE" on page 920
2642 "Two SQLDAs specified of the same
type (INTO or USING)" on page 912
2643 "cannot use both DESCRIBE INTO
and FETCH INTO on OPEN" on
page 914
2644 "no statement defined for OPEN" on
page 921
2645 "statements defined for OPEN in both
DECLARE and FROM" on page 922
2646 "cannot describe static cursors" on
page 914
2647 "Macros cannot be redefined" on
page 912
2648 "Invalid array dimension" on
page 912
2649 "invalid descriptor index" on
page 918
2650 "invalid field for SET
DESCRIPTOR" on page 919
2651 "field used more than once in SET
DESCRIPTOR statement" on
page 916
2652 "data value must be a host variable"
on page 915
2660 "Into clause not allowed on declare
cursor - ignored" on page 912
2661 "unrecognized SQL syntax" on
page 924
2662 "unknown sql function ’%1’" on
page 924
2663 "wrong number of parms to sql
function ’%1’" on page 924
2664 "static statement names will not work
properly if used by 2 threads" on
page 922
2665 "host variable ’%1’ has been
redefined" on page 916

908
Chapter 11 SQL Preprocessor Error Messages

Message value Message


2666 "vendor extension" on page 924
2667 "intermediate SQL feature" on
page 918
2668 "full SQL feature" on page 916
2669 "transact SQL extension" on
page 923
2680 "no declare section and no INCLUDE
SQLCA statement" on page 921
2681 "unable to open temporary file" on
page 923
2682 "error reading temporary file" on
page 915
2683 "error writing output file" on
page 915
2690 "Inconsistent number of host
variables for this cursor" on page 912
2691 "Inconsistent host variable types for
this cursor" on page 911
2692 "Inconsistent indicator variables for
this cursor" on page 911
2693 "Feature not available with UltraLite"
on page 911
2694 "no OPEN for cursor ’%1’" on
page 921
2695 "no FETCH or PUT for cursor ’%1’"
on page 920

909
SQLPP errors

SQLPP errors
This section lists messages generated by the SQL preprocessor. The
messages may be errors or warnings, or either depending on which
command-line options are set.
$ For more information about the SQL Preprocessor and its command-
line options, see "The SQL preprocessor" on page 79 of the book ASA
Programming Interfaces Guide.

’%1’ host variable must be a C string type


Message value Message Type
2615 Error

Probable cause A C string was required in an embedded SQL statement (for a cursor name,
option name etc.) and the value supplied was not a C string.

’%1’ host variable must be an integer type


Message value Message Type
2640 Error

Probable cause You have used a host variable that is not of integer type in a statement where
only an integer type host variable is allowed.

’%1’ symbol already defined


Message value Message Type
2617 Error

Probable cause You defined a host variable twice.

910
Chapter 11 SQL Preprocessor Error Messages

Cannot find include file ’%1’


Message value Message Type
2619 Error

Probable cause The specified include file was not found. Note that the preprocessor will use
the INCLUDE environment variable to search for include files.

FIXCHAR type must have a length


Message value Message Type
2608 Error

Probable cause You have used the DECL_FIXCHAR macro to declare a host variable of
type FIXCHAR but have not specified a length.

Feature not available with UltraLite


Message value Message Type
2693 Flag (warning or error)

Inconsistent host variable types for this cursor


Message value Message Type
2691 Error

Inconsistent indicator variables for this cursor


Message value Message Type
2692 Error

911
SQLPP errors

Inconsistent number of host variables for this cursor


Message value Message Type
2690 Error

Into clause not allowed on declare cursor - ignored


Message value Message Type
2660 Warning

Invalid array dimension


Message value Message Type
2648 Error

Probable cause The array dimension of the variable is negative.

Macros cannot be redefined


Message value Message Type
2647 Error

Probable cause A preprocessor macro has been defined twice, possibly in a header file.

Two SQLDAs specified of the same type (INTO or USING)


Message value Message Type
2642 Error

912
Chapter 11 SQL Preprocessor Error Messages

Unknown hostvar type


Message value Message Type
2613 Error

Probable cause You declared a host variable of a type not understood by the SQL
preprocessor.

VARCHAR host variables cannot be pointers


Message value Message Type
2606 Error

Probable cause You have attempted to declare a host variable as a pointer to a VARCHAR
or BINARY. This is not a legal host variable type.

VARCHAR type must have a length


Message value Message Type
2604 Error

Probable cause You have attempted to declare a VARCHAR or BINARY host variable using
the DECL_VARCHAR or DECL_BINARY macro but have not specified a
size for the array.

arrays of FIXCHAR not supported


Message value Message Type
2609 Error

Probable cause You have attempted to declare a host variable as an array of FIXCHAR
arrays. This is not a legal host variable type.

913
SQLPP errors

arrays of VARCHAR not supported


Message value Message Type
2605 Error

Probable cause You have attempted to declare a host variable as an array of VARCHAR or
BINARY. This is not a legal host variable type.

arrays of decimal not allowed


Message value Message Type
2612 Error

Probable cause You have attempted to declare a host variable as an array of DECIMAL. A
decimal array is not a legal host variable type.

arrays of this type not supported


Message value Message Type
2610 Error

Probable cause You have attempted to declare a host variable array of a type that is not
supported.

cannot describe static cursors


Message value Message Type
2646 Error

cannot use both DESCRIBE INTO and FETCH INTO on OPEN


Message value Message Type
2643 Error

914
Chapter 11 SQL Preprocessor Error Messages

combined pointer and arrays not supported for hosttypes


Message value Message Type
2602 Error

Probable cause You have used an array of pointers as a host variable. This is not legal.

cursor ’%1’ not previously declared


Message value Message Type
2627 Error

Probable cause An embedded SQL cursor name has been used (in a FETCH, OPEN, CLOSE
etc.) without first being declared.

data value must be a host variable


Message value Message Type
2652 Error

Probable cause The variable used in the SET DESCRIPTOR statement hasn’t been declared
as a host variable.

error reading temporary file


Message value Message Type
2682 Error

error writing output file


Message value Message Type
2683 Error

915
SQLPP errors

field used more than once in SET DESCRIPTOR statement


Message value Message Type
2651 Error

Probable cause The same keyword has been used more than once inside a single SET
DESCRIPTOR statement.

full SQL feature


Message value Message Type
2668 Flag (warning or error)

host variable ’%1’ has been redefined


Message value Message Type
2665 Warning

host variable ’%1’ has two different definitions


Message value Message Type
2625 Error

Probable cause The same host variable name was defined with two different types within the
same module. Note that host variable names are global to a C module.

host variable ’%1’ is unknown


Message value Message Type
2620 Error

Probable cause You have used a host variable in a statement and that host variable has not
been declared in a declare section.

916
Chapter 11 SQL Preprocessor Error Messages

host variables not allowed for this cursor


Message value Message Type
2629 Error

Probable cause Host variables are not allowed on the declare statement for the specified
cursor. If the cursor name is provided through a host variable, then you
should use full dynamic SQL and prepare the statement. A prepared
statement may have host variables in it.

host variables specified twice - on declare and open


Message value Message Type
2630 Error

Probable cause You have specified host variables for a cursor on both the declare and the
open statements. In the static case, you should specify the host variables on
the declare statement. In the dynamic case, specify them on the open.

incorrect Embedded SQL language usage -- that is a ’%1’ extension


Message value Message Type
2635 Error

incorrect Embedded SQL syntax


Message value Message Type
2636 Error

Probable cause An embedded SQL specific statement (OPEN, DECLARE, FETCH etc.) has
a syntax error.

917
SQLPP errors

incorrect SQL language usage -- that is a ’%1’ extension


Message value Message Type
2634 Error

indicator variable ’%1’ is unknown


Message value Message Type
2621 Error

Probable cause You have used a indicator variable in a statement and that indicator variable
has not been declared in a declare section.

initializer not allowed on VARCHAR host variable


Message value Message Type
2607 Error

Probable cause You can not specify a C variable initializer for a host variable of type
VARCHAR or BINARY. You must initialize this variable in regular C
executable code.

intermediate SQL feature


Message value Message Type
2667 Flag (warning or error)

invalid descriptor index


Message value Message Type
2649 Error

918
Chapter 11 SQL Preprocessor Error Messages

invalid field for SET DESCRIPTOR


Message value Message Type
2650 Error

Probable cause An invalid or unknown keyword is present in a SET DESCRIPTOR


statement. The keywords can only be TYPE, PRECISION, SCALE,
LENGTH, INDICATOR, or DATA.

invalid host variable type on ’%1’


Message value Message Type
2623 Error

Probable cause You have used a host variable that is not a string type in a place where the
preprocessor was expecting a host variable of a string type.

invalid integer
Message value Message Type
2614 Error

Probable cause An integer was required in an embedded SQL statement (for a fetch offset, or
a host variable array index, etc.) and the preprocessor was unable to convert
what was supplied into an integer.

invalid type for indicator variable ’%1’


Message value Message Type
2622 Error

Probable cause Indicator variables must be of type short int. You have used a variable of a
different type as an indicator variable.

919
SQLPP errors

invalid type for sql statement variable


Message value Message Type
2618 Error

Probable cause A host variable used as a statement identifier should be of type


a_sql_statement_number. You attempted to use a host variable of some other
type as a statement identifier.

missing ending quote of string


Message value Message Type
2637 Error

Probable cause You have specified a string constant in an embedded SQL statement, but
there is no ending quote before the end of line or end of file.

must specify a host list or using clause on %1


Message value Message Type
2631 Error

Probable cause The specified statement requires host variables to be specified either in a host
variable list or from an SQLDA.

must specify an SQLDA on a DESCRIBE


Message value Message Type
2641 Error

no FETCH or PUT for cursor ’%1’


Message value Message Type
2695 Error

920
Chapter 11 SQL Preprocessor Error Messages

Probable cause A cursor is declared and opened, but is never used.

no INTO clause on SELECT statement


Message value Message Type
2633 Error

Probable cause You specified an embedded static SELECT statement but you did not specify
an INTO clause for the results.

no OPEN for cursor ’%1’


Message value Message Type
2694 Error

Probable cause A cursor is declared, and possibly used, but is never opened.

no declare section and no INCLUDE SQLCA statement


Message value Message Type
2680 Error

Probable cause The EXEC SQL INCLUDE SQLCA statement is missing from the source
file.

no statement defined for OPEN


Message value Message Type
2644 Error

921
SQLPP errors

only one dimensional arrays supported for char type


Message value Message Type
2603 Error

Probable cause You have attempted to declare a host variable as an array of character arrays.
This is not a legal host variable type.

precision must be specified for decimal type


Message value Message Type
2611 Error

Probable cause You must specify the precision when declaring a packed decimal host
variable using the DECL_DECIMAL macro. The scale is optional.

statement ’%1’ not previously prepared


Message value Message Type
2626 Error

Probable cause An embedded SQL statement name has been used (EXECUTE) without first
being prepared.

statements defined for OPEN in both DECLARE and FROM


Message value Message Type
2645 Error

static statement names will not work properly if used by 2 threads


Message value Message Type
2664 Warning

922
Chapter 11 SQL Preprocessor Error Messages

Probable cause You have used a static statement name and preprocessed with the -r
reentrancy switch. Static statement names cause static variables to be
generated that are filled in by the database. If two threads use the same
statement, contention arises over this variable. Use a local host variable as
the statement identifier instead of a static name.

subscript value %1 too large


Message value Message Type
2601 Error

Probable cause You have attempted to index a host variable that is an array with a value too
large for the array.

token too long


Message value Message Type
2639 Error

Probable cause The SQL preprocessor has a maximum token length of 2K. Any token longer
than 2K will produce this error. For constant strings in embedded SQL
commands (the main place this error shows up) use string concatenation to
make a longer string.

transact SQL extension


Message value Message Type
2669 Flag (warning or error)

unable to open temporary file


Message value Message Type
2681 Error

923
SQLPP errors

unknown sql function ’%1’


Message value Message Type
2662 Warning

Probable cause You have used a SQL function that is unknown to the preprocessor and will
probably cause an error when the statement is sent to the database engine.

unknown statement ’%1’


Message value Message Type
2628 Error

Probable cause You attempted to drop an embedded SQL statement that doesn’t exist.

unrecognized SQL syntax


Message value Message Type
2661 Warning

Probable cause You have used a SQL statement that will probably cause a syntax error when
the statement is sent to the database engine.

vendor extension
Message value Message Type
2666 Flag (warning or error)

wrong number of parms to sql function ’%1’


Message value Message Type
2663 Warning

924
Chapter 11 SQL Preprocessor Error Messages

Probable cause You have used a SQL function with the wrong number of parameters. This
will likely cause an error when the statement is sent to the database engine.

925
SQLPP errors

926
C H A P T E R 1 2

Differences from Other SQL Dialects

About this chapter Adaptive Server Anywhere conforms to the ANSI SQL89 standard but has
many additional features defined in IBM’s DB2 and SAA specification, and
in ANSI SQL/92.
This chapter describes those features of Adaptive Server Anywhere that are
not commonly found in other SQL implementations.
Contents
Topic Page
Adaptive Server Anywhere SQL features 928

927
Adaptive Server Anywhere SQL features

Adaptive Server Anywhere SQL features


The following features of the SQL supported by Adaptive Server Anywhere
are not found in many other SQL implementations.
Type conversions Full type conversion is implemented. Any data type can be compared with or
used in any expression with any other data type.
Dates Adaptive Server Anywhere has date, time and timestamp types that includes
a year, month and day, hour, minutes, seconds and fraction of a second. For
insertions or updates to date fields, or comparisons with date fields, a free
format date is supported.
In addition, the following operations are allowed on dates:
♦ date + integer Add the specified number of days to a date.
♦ date - integer Subtract the specified number of days from a date.
♦ date - date Compute the number of days between two dates.
♦ date + time Make a timestamp out of a date and time.
Also, many functions are provided for manipulating dates and times. See
"SQL Functions" on page 291 for a description of these.
Integrity Adaptive Server Anywhere supports both entity and referential integrity.
This has been implemented via the following two extensions to the CREATE
TABLE and ALTER TABLE commands.
PRIMARY KEY ( column-name, ... )
[NOT NULL] FOREIGN KEY [role-name]
[(column-name, ...)]
REFERENCES table-name [(column-name, ...)]
[ CHECK ON COMMIT ]
The PRIMARY KEY clause declares the primary key for the relation.
Adaptive Server Anywhere will then enforce the uniqueness of the primary
key, and ensure that no column in the primary key contains the NULL value.
The FOREIGN KEY clause defines a relationship between this table and
another table. This relationship is represented by a column (or columns) in
this table which must contain values in the primary key of another table. The
system will then ensure referential integrity for these columns - whenever
these columns are modified or a row is inserted into this table, these columns
will be checked to ensure that either one or more is NULL or the values
match the corresponding columns for some row in the primary key of the
other table. For more information, see "CREATE TABLE statement" on
page 453.

928
Chapter 12 Differences from Other SQL Dialects

Joins Adaptive Server Anywhere allows automatic joins between tables. In


addition to the NATURAL and OUTER join operators supported in other
implementations, Adaptive Server Anywhere allows KEY joins between
tables based on foreign key relationships. This reduces the complexity of the
WHERE clause when performing joins.
Updates Adaptive Server Anywhere allows more than one table to be referenced by
the UPDATE command. Views defined on more than one table can also be
updated. Many SQL implementations will not allow updates on joined tables.
Altering tables The ALTER TABLE command has been extended. In addition to changes
for entity and referential integrity, the following types of alterations are
allowed:
ADD column data-type
MODIFY column data-type
DELETE column
RENAME new-table-name
RENAME old-column TO new-column
The MODIFY can be used to change the maximum length of a character
column as well as converting from one data type to another. For more
information, see "ALTER TABLE statement" on page 380.
Subqueries where Adaptive Server Anywhere allows subqueries to appear wherever
expressions are expressions are allowed. Many SQL implementations only allow subqueries
allowed on the right side of a comparison operator. For example, the following
command is valid in Adaptive Server Anywhere but not valid in most other
SQL implementations.
SELECT emp_lname,
emp_birthdate,
( SELECT skill
FROM department
WHERE emp_id = employee.emp_ID
AND dept_id = 200 )
FROM employee

Additional Adaptive Server Anywhere supports several functions not in the ANSI SQL
functions definition. See "SQL Functions" on page 291 for a full list of available
functions.
Cursors When using Embedded SQL, cursor positions can be moved arbitrarily on
the FETCH statement. Cursors can be moved forward or backward relative
to the current position or a given number of records from the beginning or
end of the cursor.

929
Adaptive Server Anywhere SQL features

930
C H A P T E R 1 3

Physical Limitations

About this chapter This chapter describes the limitations on size and number of objects in
Adaptive Server Anywhere databases.
Contents
Topic Page
Size and number limitations 932

931
Size and number limitations

Size and number limitations


The following table lists the physical limitations on size and number of
objects in Adaptive Server Anywhere database. The memory, CPU, and disk
drive of the computer are more limiting factors in most cases.

Item Limitation
Database size 12 files per database. For each file,
the largest file allowed by operating
system and file system.
Field size 2 GB
File size (FAT 12) 16 MB
File size (FAT 16) 2 GB
File size (FAT 32) 4 GB
File size (NTFS, HP-UX 11.0 and later, 256 GB (for 1K pages)
Solaris 2.6 and later) 512 GB (for 2K pages)
1 TB (for 4K pages)
File size (all other platforms and file 2 GB
systems)
Maximum index entry size No limit
Number of columns per table 999 (using 4K pages)
Number of indexes The maximum number of indexes per
table is based on the database page
size:
♦ 4K or less 2048 indexes
♦ 8K 1024 indexes
♦ 16K 512 indexes
♦ 32K 256 indexes
Number of rows per database Limited by file size
Number of rows per table Limited by file size
Number of tables per database 2^32 – 1 (4294967295)
Number of tables referenced per transaction No limit
Row size Limited by file size
Table size Maximum file size. User-created
indexes for the table can be stored
separately from the table.

932
C H A P T E R 1 4

System Procedures and Functions

About this chapter This chapter documents the system-supplied catalog stored procedures in
Adaptive Server Anywhere databases, used to retrieve system information.
The chapter also documents system-supplied extended procedures, including
procedures for sending e-mail messages on a MAPI e-mail system.
Contents
Topic Page
System procedure overview 934
System and catalog stored procedures 935
System extended stored procedures 950
Adaptive Server Enterprise system and catalog procedures 957

933
System procedure overview

System procedure overview


Adaptive Server Anywhere includes the following kinds of system
procedures:
♦ Catalog stored procedures, for displaying system information in tabular
form.
♦ Extended stored procedures for MAPI e-mail support and other
functions.
♦ Transact-SQL system and catalog procedures.
$ For a list of these system procedures see "Adaptive Server
Enterprise system and catalog procedures" on page 957.
♦ System functions that are implemented as stored procedures.
$ For information see "System functions" on page 298.
This chapter documents the catalog stored procedures and the extended
stored procedures for MAPI e-mail support and other external functions.

934
Chapter 14 System Procedures and Functions

System and catalog stored procedures


System and catalog stored procedures are owned by the user ID dbo. Some
of these procedures are for internal system use. This section documents only
those not intended solely for system and internal use.

sa_audit_string system procedure


Function Adds a string to the audit log.
Syntax sa_audit_string ( string )
Permissions DBA authority required
Side effects None
See also "AUDITING option" on page 160
"Auditing database activity" on page 756 of the book ASA User’s Guide
Description If auditing is turned on, this system procedure adds a comment into the audit
log. The string can be a maximum of 200 bytes long.
Examples The following call adds a comment into the audit log:
call sa_audit_string( ’Auditing test’ )

sa_check_commit system procedure


Function Checks for outstanding referential integrity violations before a commit.
Syntax sa_check_commit ( out tname varchar( 128 ), out keyname varchar( 128 ) )
Permissions None
Side effects None
See also "WAIT_FOR_COMMIT option" on page 205
"CREATE TABLE statement" on page 453
Description If you have the database option WAIT_FOR_COMMIT set to ON, or if a
foreign key is defined using CHECK ON COMMIT in the CREATE TABLE
statement, you can update the database in such a way as to violate referential
integrity, as long as these violations are resolved before the changes are
committed.
You can use the sa_check_commit system procedure to check whether there
are any outstanding referential integrity violations, before attempting to
commit your changes.

935
System and catalog stored procedures

The returned parameters indicate the name of a table containing a row that is
currently violating referential integrity, and the name of the corresponding
foreign key index.
Examples The following set of commands can be executed from Interactive SQL. It
deletes rows from the department table in the sample database, in such a way
as to violate referential integrity. The call to sa_check_commit checks
which tables and keys have outstanding violations, and the rollback cancels
the change:
SET TEMPORARY OPTION WAIT_FOR_COMMIT=’ON’
go
DELETE FROM department
go
CREATE VARIABLE tname VARCHAR( 128 )
CREATE VARIABLE keyname VARCHAR( 128 )
go
CALL sa_check_commit( tname, keyname )
go
SELECT tname, keyname
go
ROLLBACK
go

sa_conn_info system procedure


Function Reports connection property information.
Syntax sa_conn_info ( [ connection-id ] )
Permissions None.
Side effects None
Description Returns a result set consisting of the following connection properties for the
supplied connection. If no connection-id is supplied, information for all
current connections to databases on the server is returned.
♦ Number
♦ Name
♦ Userid
♦ DBNumber
♦ LastReqTime
♦ ProcessTime
♦ Port
936
Chapter 14 System Procedures and Functions

♦ ReqType
♦ CommLink
♦ NodeAddr
♦ LastIdle
♦ CurrTaskSwitch
♦ BlockedOn
♦ UncmtOps.
♦ LockName
In a deadlock situation, the BlockedOn value returned by this procedure
allows you to check which users are blocked, and who they are blocked on.
The sa_locks procedure can be used to display the locks held by the blocking
connection; and if A holds locks on several tables you can match the
LockName value between sa_locks and sa_conn_info.
$ For information on these properties, see "Connection-level properties"
on page 1060.

sa_conn_properties system procedure


Function Reports connection property information
Syntax sa_conn_properties ( [ connection-id ] )
Permissions None.
Side effects None
See also "sa_conn_properties_by_conn system procedure" on page 937
"sa_conn_properties_by_name system procedure" on page 938
"System functions" on page 298
"Connection-level properties" on page 1060
Description Returns the connection id as Number, and the PropNum, PropName,
PropDescription, and Value for each available connection property.
If no connection-id is supplied, properties for all current connections to the
server are returned.

sa_conn_properties_by_conn system procedure


Function Reports connection property information
Syntax sa_conn_properties_by_conn ( [property-name ] )

937
System and catalog stored procedures

Permissions None.
Side effects None
See also "sa_conn_properties system procedure" on page 937
"Connection-level properties" on page 1060
Description This is a variant on the sa_conn_properties system procedure, and returns the
same result columns.It returns results only for connection properties that
match the property-name string. You can use wild cards in property-name, as
the comparison uses a LIKE operator. The result set is sorted by connection
number and property name.
$ For a listing of available connection properties, see "Connection-level
properties" on page 1060.
Example ♦ The following statement returns the AnsiNull option setting for all
connections:
call sa_conn_properties_by_conn( ’ansinull’ )
♦ The following statement returns the Ansi-related option settings for all
connections:
call sa_conn_properties_by_conn( ’ansi%’ )

sa_conn_properties_by_name system procedure


Function Reports connection property information
Syntax sa_conn_properties_by_name ( [connection-id ] )
Permissions None.
Side effects None
See also "sa_conn_properties system procedure" on page 937
"Connection-level properties" on page 1060
Description This is a variant on the sa_conn_properties system procedure, and returns the
same result columns. The information is sorted by property name and
connection number.

$ For a listing of available connection properties, see "System


functions" on page 298sa_db_info system procedure
Function Reports database property information
Syntax sa_db_info ( [ database-id ] )

938
Chapter 14 System Procedures and Functions

Permissions None.
Side effects None
See also "sa_db_properties system procedure" on page 939
"Database-level properties" on page 1070
Description Returns a single row containing the Number, Alias, File, ConnCount,
PageSize, and LogName for the specified database.
Examples ♦ The following statement returns a single row describing the current
database:
call sa_db_info
Sample values are as follows:

Property Value
Number 0
Alias asademo
File c:\asa6\asademo.db
ConnCount 1
PageSize 1024
LogName c:\asa6\asademo.log

sa_db_properties system procedure


Function Reports database property information
Syntax sa_db_properties ( [ database-id ] )
Permissions None.
Side effects None
See also "" on page 298sa_db_info system procedure" on page 938
"Database-level properties" on page 1070
Description Returns the database ID number and the Number, PropNum, PropName,
PropDescription, and Value, for each available database property.

sa_eng_properties system procedure


Function Reports database server property information

939
System and catalog stored procedures

Syntax sa_eng_properties
Permissions None.
Side effects None
See also "Server-level properties" on page 1065
Description Returns the PropNum, PropName, PropDescription, and Value for each
available server property.
$ For a listing of available engine properties, see "System functions" on
page 298.
Example ♦ The following statement returns a set of available server properties
call sa_eng_properties()

PropNum PropName ...


1 IdleWrite ...
2 IdleChkPt ...
... ... ...

sa_flush_cache system procedure


Function Empties all pages in the database server cache.
Syntax sa_flush_cache ( )
Permissions DBA authority required.
Side effects None
Description Database administrators can use this procedure to empty the contents of the
database server cache. This is of use in performance measurement to ensure
repeatable results.

sa_index_levels system procedure


Function To assist in performance tuning by reporting the number of levels in an
index.
Syntax sa_index_levels ( [ ’table_name’ [, ’owner_name’ ] )
Permissions DBA authority required.

940
Chapter 14 System Procedures and Functions

Side effects None


See also "CREATE INDEX statement" on page 435
"How indexes work" on page 795 of the book ASA User’s Guide
Description The number of levels in the index tree determines the number of I/O
operations needed to access a row using the index. Indexes with a small
number of levels are more efficient than indexes with a large number of
levels. You can influence the number of levels in an index using the WITH
HASH SIZE option in the CREATE INDEX statement.
The procedure returns a result set containing the table name, the index name,
and the number of levels in the index.
If no arguments are supplied, levels are returned for all indexes in the
database. If only table_name is supplied, levels for all indexes on that table
are supplied. If table_name is NULL and an owner_name is given, only
levels for indexes on tables owner by that user are returned.

sa_locks system procedure


Function Displays all locks in the database.
Syntax sa_locks ( [ connection, ][ [owner.]table_name, ][max_locks ] )
Permissions DBA authority required.
Side effects None
See also "How locking works" on page 401 of the book ASA User’s Guide
Description The sa_locks procedure returns a result set containing information about all
the locks in the database.
The input parameters are as follows:

connection An integer representing a connection ID. The procedure


returns lock information only about the specified connection. The default
value is zero, in which case information is returned about all connections.

table_name A char(128) parameter representing a table name. The


procedure returns information only about the specified tables. The default
value is NULL, in which case information is returned about all tables.
If you do not include owner, it is assumed that the table is owned by the
caller of the procedure.

941
System and catalog stored procedures

max_locks An integer parameter representing the maximum number of


locks for which to return information. The default value is 1000. The value -
1 means return all lock information.
The information returned for each lock includes the following:

connection ID The connection ID that has the lock.

user name The user connected through connection ID.

table name The table on which the lock is held.

lock_name The LockName value identifying the lock. This value can be
matched with sa_conn_info output to determine the responsible locks in a
blocking situation.
$ For more information, see "Connection-level properties" on page 1060,
and "sa_conn_info system procedure" on page 936.

lock type The lock type is a string of characters indicating the type of
lock. These characters are:
♦ S Shared
♦ E Exclusive
♦ P Phantom
♦ A Anti-phantom
All locks listed have exactly one of S or E specified, and may also have P, A,
or both. If a lock is a phantom or anti-phantom lock, a qualifier is added to
the lock type. The qualifier is as follows:
♦ T The lock is with respect to a sequential scan
♦ * The lock is with respect to all scans.
♦ nnn An index number. The lock is with respect to a particular index.

sa_server_option system procedure


Function Overrides a database server command-line option while the database server
is running.
Syntax sa_server_option ( option_name, option_value )
Permissions DBA authority required.
Side effects None

942
Chapter 14 System Procedures and Functions

Description Database administrators can use this procedure to override some database
server command-line options without restarting the database server.
The options that can be reset are as follows:

Option name Values


disable_connections ON or OFF
liveness_timeout integer, in seconds
quitting_time valid date and time
request_level_log_file filename
request_level_logging ALL, SQL, NONE

disable_connections When set to ON, no other connections are allowed


to any databases on the database server.

liveness_timeout A liveness packet is sent periodically across a


client/server TCP/IP or SPX communications protocol to confirm that a
connection is intact. If the network server runs for a liveness_timeout period
(default 120 seconds) without detecting a liveness packet, the
communication is severed.
$ For more information, see "–tl command-line option" on page 35.
quitting_time Instruct the database server to shut down at the specified
time.
$ For more information, see "–tq time command-line option" on page 36.
request-level_log_file The name of the file used to record logging
information. A name of NULL stops logging to file.
Any backslash characters in the filename must be doubled, as this is a SQL
string.
$ For more information, see "–z command-line option" on page 39, and
"–o command-line option" on page 32.

request_level_logging Can be ALL, SQL, or NONE. ON is a synonym


for ALL and OFF is a synonym for NONE. NONE is the default. This call
turns on logging of individual SQL statements sent to the database server, for
use in troubleshooting, in conjunction with the database server -z and -o
command-line options. You can use request_level_debugging as a synonym
for request_level_logging.
If you select SQL, the following types of request only are recorded:
♦ START DATABASE

943
System and catalog stored procedures

♦ STOP ENGINE
♦ STOP DATABASE
♦ Statement preparation
♦ Statement execution
♦ EXECUTE IMMEDIATE statements
♦ Option settings
♦ COMMIT statements
♦ ROLLBACK statements
♦ PREPARE TO COMMIT operations.
♦ Connections
♦ Disconnections
♦ Beginnings of transactions
♦ DROP STATEMENT statement.
♦ Cursor explanations
♦ Cursor closings
♦ Cursor resume
♦ Errors
You can find the current value of this setting using the RequestLogging
property function.
$ For more information, see "–zr command-line option" on page 40, and
"Server-level properties" on page 1065.
Example The following statement disallows new connections to the database server.
call sa_server_option( ’disable_connections’, ’ON’)

sa_table_page_usage system procedure


Function Reports information about the page usage of database tables.
Syntax sa_table_page_usage
Permissions DBA authority required.
Side effects None
See also "The Information utility" on page 90

944
Chapter 14 System Procedures and Functions

Description The results include the same information provided by the Information utility.
$ For information on the Information utility, see "The Information utility"
on page 90.

sa_validate system procedure


Function Validates all tables in a database.
Syntax sa_validate [ tbl_name, ] [ owner_name, ] [ check_type ]
Permissions DBA authority required.
Side effects None
Description This procedure is equivalent to calling the VALIDATE TABLE statement
for each table in the database.
$ For information, see "VALIDATE TABLE statement" on page 628.
tbl-name Validate only the specified table. When NULL (the default),
validate all tables.

owner_name Validate only the tables owned by the specified user. When
NULL (the default), validate tables for all users.

check_type When NULL (the default), each table is checked using a


VALIDATE TABLE statement with no additional checks. The check_type
value can be one of the following:
♦ data Validate tables using WITH DATA CHECK.
♦ index Validate tables using WITH INDEX CHECK.
♦ full Validate tables using WITH FULL CHECK.
The procedure returns a single column, named msg. If all tables are valid, the
column contains No errors detected.

sp_login_environment system procedure


Function Sets connection options when users log in.
Syntax sp_login_environment
Permissions None
Side effects None
See also "LOGIN_PROCEDURE option" on page 184.
945
System and catalog stored procedures

Description Sp_login_environment is the default procedure called by the


LOGIN_PROCEDURE database option.
It is recommended that you not edit this procedure. Instead, to change the
login environment, set the LOGIN_PROCEDURE option to point to a
different procedure.
Here is the text of the sp_login_environment procedure:
CREATE PROCEDURE dbo.sp_login_environment()
BEGIN
IF connection_property(’CommProtocol’)=’TDS’ THEN
CALL dbo.sp_tsql_environment()
END IF
END

sp_remote_columns system procedure


Function Produces a list of the columns on a remote table and a description of their
data types.
The server must be defined with the CREATE SERVER statement to use this
system procedure.
Syntax sp_remote_columns servername [,tablename] [, owner ] [, database]
Permissions None
Side effects None
See also "Accessing Remote Data" on page 867 of the book ASA User’s Guide
"Server Classes for Remote Data Access" on page 899 of the book ASA
User’s Guide
"CREATE SERVER statement" on page 451
Description If you are entering a CREATE EXISTING statement and you are specifiying
a column list, it may be helpful to get a list of the columns that are available
on a remote table. sp_remote_columns produces a list of the columns on a
remote table and a description of their data types.
Standards and ♦ Sybase Supported by Open Client/Open Server.
compatibility
Example ♦ To get a list of the columns in the sysobjects table in the production
database in an ASE named "asetest".
sp_remote_columns asetest, sysobjects,
null, production

946
Chapter 14 System Procedures and Functions

sp_remote_tables system procedure


Function Returns a list of the tables on a server.
The server must be defined with the CREATE SERVER statement to use this
system procedure.
Syntax sp_remote_tables servername [,tablename] [, owner ] [, database ]
Permissions None
Side effects None
See also "Accessing Remote Data" on page 867 of the book ASA User’s Guide
"Server Classes for Remote Data Access" on page 899 of the book ASA
User’s Guide
"CREATE SERVER statement" on page 451
Description It may be helpful when you are configuring your database server to get a list
of the remote tables available on a particular server. This procedure returns a
list of the tables on a server.
If a tablename, owner, or database name is given, the list of tables will be
limited to only those that match.
Standards and ♦ Sybase Supported by Open Client/Open Server.
compatibility
Examples ♦ To get a list of all of the Microsoft Excel worksheets available from an
ODBC datasource named ’excel’:
sp_remote_tables excel
♦ To get a list of all of the tables in the ’production’ database in an
Adaptive Server Enterprise server named "asetest", owned by fred:
sp_remote_tables asetest, null, fred, production

sp_servercaps system procedure


Function Displays information about a remote server’s capabilities.
The server must be defined with the CREATE SERVER statement to use this
system procedure.
Syntax sp_servercaps servername
Permissions None
Side effects None
See also "Accessing Remote Data" on page 867 of the book ASA User’s Guide

947
System and catalog stored procedures

"Server Classes for Remote Data Access" on page 899 of the book ASA
User’s Guide
"CREATE SERVER statement" on page 451
Description This procedure displays information about a remote server’s capabilities.
Adaptive Server Anywhere uses this capability information to determine how
much of a SQL statement can be forwarded to a remote server. The system
tables which contain server capabilities are not populated until after Adaptive
Server Anywhere first connects to the remote server. This information
comes from SYSCAPABILITY and SYSCAPABILITYNAME. The
servername specified must be the same servername used in the CREATE
SERVER statement.
Standards and ♦ Sybase Supported by Open Client/Open Server.
compatibility
Example ♦ To display information about the remote server testasa issue the
following stored procedure:
sp_servercaps testasa

sp_tsql_environment system procedure


Function Sets connection options when users connect from jConnect or Open Client
applications.
Syntax sp_tsql_environment
Permissions None
Side effects None
See also "sp_login_environment system procedure" on page 945
"LOGIN_PROCEDURE option" on page 184.
Description At startup, sp_login_environment is the default procedure called by the
LOGIN_PROCEDURE database option. If the connection uses the TDS
communications protocol (that is, if it is an Open Client or jConnect
connection), then sp_login_environment in turn calls sp_tsql_environment.
This procedure sets database options so that they are compatible with default
Sybase Adaptive Server Enterprise behavior.
If you wish to change the default behavior, it is recommended that you create
new procedures and alter your LOGIN_PROCEDURE option to point to
these new procedures.
Example ♦ Here is the text of the sp_tsql_environment procedure:
create procedure dbo.sp_tsql_environment()
begin
if db_property(’IQStore’)=’OFF’ then

948
Chapter 14 System Procedures and Functions

-- ASA datastore
set temporary option AUTOMATIC_TIMESTAMP=’ON’
end if;
set temporary option ANSINULL=’OFF’;
set temporary option TSQL_VARIABLES=’ON’;
set temporary option ANSI_BLANKS=’ON’;
set temporary option TSQL_HEX_CONSTANT=’ON’;
set temporary option CHAINED=’OFF’;
set temporary option QUOTED_IDENTIFIER=’OFF’;
set temporary option ALLOW_NULLS_BY_DEFAULT=’OFF’;
set temporary option FLOAT_AS_DOUBLE=’ON’;
set temporary option ON_TSQL_ERROR=’CONTINUE’;
set temporary option ISOLATION_LEVEL=’1’;
set temporary option DATE_FORMAT=’YYYY-MM-DD’;
set temporary option TIMESTAMP_FORMAT=’YYYY-MM-DD
HH:NN:SS.SSS’;
set temporary option TIME_FORMAT=’HH:NN:SS.SSS’;
set temporary option DATE_ORDER=’MDY’;
set temporary option ESCAPE_CHARACTER=’OFF’
end

949
System extended stored procedures

System extended stored procedures


A set of system extended procedures are included in Adaptive Server
Anywhere databases. These procedures are owned by the dbo user ID.
The following sections describe each of the stored procedures.

MAPI system extended stored procedures


Adaptive Server Anywhere includes three system procedures for sending
electronic mail using Microsoft’s Messaging API standard (MAPI). These
system procedures are implemented as extended stored procedures: each
procedure calls a function in an external DLL.
In order to use the MAPI stored procedures, a MAPI e-mail system must be
accessible from the database server machine.
The MAPI stored procedures are:
♦ xp_startmail Starts a mail session in a specified mail account by
logging on the MAPI message system
♦ xp_sendmail Sends a mail message to specified users
♦ xp_stopmail Closes the mail session
The following procedure notifies a set of people that a backup has been
completed.
CREATE PROCEDURE notify_backup()
BEGIN
CALL xp_startmail( mail_user=’ServerAccount’,
mail_password=’ServerPassword’
);
CALL xp_sendmail( recipient=’IS Group’,
subject=’Backup’,
"message"=’Backup completed’
);
CALL xp_stopmail( )
END
The MAPI system procedures are discussed in the following sections.

xp_startmail system procedure


Function Starts an e-mail session.
Syntax [ [ variable = ] CALL ] xp_startmail (
... [ mail_user = mail-login-name ]

950
Chapter 14 System Procedures and Functions

... [, mail_password = mail-password ]


... )
Permissions None.
Description xp_startmail is a system stored procedure that starts an e-mail session.
The mail-login-name and mail-password values are strings containing the
MAPI login name and password to be used in the mail session.
If you are using Microsoft Exchange, the mail_login_name argument is an
Exchange profile name, and you should not include a password in the
procedure call.
Return codes The xp_startmail system procedure issues one of the following return codes:

Return code Meaning


0 Success
2 Failure

xp_sendmail system procedure


Function To send an e-mail message.
Syntax [ [ variable = ] CALL ] xp_sendmail (
... [ recipient = mail-address ]
... [, subject = subject ]
... [, cc_recipient = mail-address ]
... [, bcc_recipient = mail-address ]
... [, "message" = message-body ]
... [, include_file = file-name ]
... )
Permissions Must have executed xp_startmail to start an e-mail session.
Description xp_sendmail is a system stored procedure that sends an e-mail message once
a session has been started to xp_startmail.
The argument values are strings. The message parameter name requires
double quotes around it, because MESSAGE is a keyword.
Return codes The xp_sendmail system procedure issues one of the following return codes:

951
System extended stored procedures

Return code Meaning


0 Success
5 Failure (general)
11 Ambiguous recipient
12 Attachment not found
13 Disk full
14 Insufficient memory
15 Invalid session
16 Text too large
17 Too many files
18 Too many recipients
19 Unknown recipient

Example The following call sends a message to the user ID Sales Group containing
the file prices.doc as a mail attachment:
CALL xp_sendmail(recipient=’Sales Group’,
subject=’New Pricing’,
include_file = ’C:\\DOCS\\PRICES.DOC’
)

xp_stopmail system procedure


Function Closes an e-mail session.
Syntax [ variable = ] [ CALL ] xp_stopmail ()
Permissions None.
Description xp_stopmail is a system stored procedure that ends an e-mail session.
Return codes The xp_stopmail system procedure issues one of the following return codes:

Return code Meaning


0 Success
3 Failure

952
Chapter 14 System Procedures and Functions

Other system extended stored procedures


The other system extended stored procedures included are:
♦ xp_cmdshell Executes a system command.
♦ xp_msver Returns a string containing version information.
♦ xp_sprintf Builds a string from a format string and a set of input
strings.
♦ xp_scanf Extracts substrings from an input string and a format string.
The following sections provide more detail on each of these procedures.

xp_cmdshell system procedure


Function Carries out an operating system command from a procedure.
Syntax [ variable = CALL ] xp_cmdshell ( string )
Permissions None.
Description xp_cmdshell executes a system command and then returns control to the
calling environment.
Example The following statement lists the files in the current directory in the file
c:\temp.txt
xp_cmdshell(’dir > c:\\temp.txt’)

xp_msver system function


Function Retrieves version and name information about the database server.
Syntax xp_msver ( string )
The string must be one of the following, enclosed in string delimiters.

953
System extended stored procedures

Argument Description
ProductName The name of the product (Sybase Adaptive Server
Anywhere)
ProductVersion The version number, followed by the build number. The
format is as follows:
6.5.02 (1200)
CompanyName Returns the following string:
Sybase Inc.
FileDescription Returns the name of the product, followed by the name of
the operating system.
LegalCopyright Returns a copyright string for the software
LegalTrademarks Returns trademark information for the software

Permissions None.
See also "System functions" on page 298
Description xp_msver returns product, company, version, and other information.
Example ♦ The following statement requests the version and operating system
description:
select xp_msver( ’ProductVersion’) Version,
xp_msver(’FileDescription’) Description
Sample output is as follows:

Version Description
6.5.02 (1438) Sybase Adaptive Server Anywhere Windows
NT

xp_read_file system procedure


Function Returns the contents of a file as a LONG BINARY variable.
Syntax [ variable = CALL ] xp_read_file ( filename)
Permissions DBA authority required.
See also "xp_write_file system procedure" on page 956
Description The function reads the contents of the named file, and returns the result as a
LONG BINARY value.

954
Chapter 14 System Procedures and Functions

The filename is relative to the starting directory of the database server.


The function can be useful for inserting entire documents or images stored in
files into tables. If the file cannot be read, the function returns NULL.
Example The following statement inserts an image into a column named picture of the
table t1 (assuming all other columns can accept NULL):
INSERT INTO t1 ( picture)
SELECT xp_read_file( ’portrait.gif’ )

xp_sprintf system procedure


Function Builds up a string from a format string and a set of input strings.
Syntax [ variable = CALL ] xp_sprintf ( out-string,
... format-string
... [ input-string, ... ] )
Permissions None.
Description xp_sprintf builds up a string from a format string and a set of input strings.
The format-string can contain up to fifty string placeholders (%s). These
placeholders are filled in by the input-string arguments.
All arguments must be strings of less than 254 characters.
Example The following statements put the string Hello World! into the variable
mystring.
CREATE VARIABLE mystring CHAR(254) ;
xp_sprintf( mystring, ’Hello %s’, ’World!’ )

xp_scanf system procedure


Function Extracts substrings from an input string and a format string.
Syntax [ variable = CALL ] xp_scanf ( in-string,
... format-string
... [ output-string, ... ] )
Permissions None.
Description xp_scanf extracts substrings from an input string and a format string. The
format-string can contain up to fifty string placeholders (%s). The values of
these placeholders are placed in the output-string variables.
All arguments must be strings of less than 254 characters.
Example ♦ The following statements put the string World! into the variable
mystring.

955
System extended stored procedures

CREATE VARIABLE mystring CHAR(254) ;


xp_scanf( ’Hello World!’, ’Hello %s’, mystring )

xp_write_file system procedure


Function Writes data to a file from a SQL statement.
Syntax [ variable = CALL ] xp_write_file ( filename, file_contents)
Permissions DBA authority required.
See also "xp_read_file system procedure" on page 954
Description The function writes file_contents to the file filename. It returns 0 if
successful, and non-zero if it fails.
The filename is relative to the current working directory of the database
server. If the file already exists, its contents are overwritten.
This function can be useful for unloading long binary data into files.
Example Consider a table t1 that has the following columns:
♦ filename A filename relative to the server.
♦ picture A LONG BINARY column holding an image.
The following statement unloads the pictures into the named files:
SELECT xp_write_file( filename, picture)
FROM t1

956
Chapter 14 System Procedures and Functions

Adaptive Server Enterprise system and catalog


procedures
Adaptive Server Enterprise provides system and catalog procedures to carry
out many administrative functions and to obtain system information.
Adaptive Server Anywhere has implemented support for some of these
procedures.
System procedures are built-in stored procedures used for getting reports
from and updating system tables. Catalog stored procedures retrieve
information from the system tables in tabular form.

Adaptive Server Enterprise system procedures


The following list describes the Adaptive Server Enterprise system
procedures that are provided in Adaptive Server Anywhere.
While these procedures perform the same functions as they do in Adaptive
Server Enterprise and pre-Version 12 Adaptive Server IQ, they are not
identical. If you have preexisting scripts that use these procedures, you may
want to examine the procedures. To see the text of a stored procedure, you
can open it in Sybase Central or, in Interactive SQL, run the following
command.
sp_helptext procedure_name

You may need to reset the width of your Interactive SQL output to see the
full text, by selecting Command➤Options and entering a new Limit Display
Columns value.

System procedure Description


sp_addgroup group-name Adds a group to a database
sp_addlogin userid, Adds a new user account to a database
password[, defdb [,
deflanguage [, fullname]]]
sp_addmessage message- Adds a user-defined message to
num, message_text [, SYSUSERMESSAGES, for use by stored
language] procedure PRINT and RAISERROR calls
sp_addtype typename, data- Creates a user-defined data type
type [, "identity" | nulltype]
sp_adduser login_name [, Adds a new user to a database
name_in_db [, grpname]]
sp_changegroup new-group- Changes a user’s group or adds a user to a group
name, userid

957
Adaptive Server Enterprise system and catalog procedures

System procedure Description


sp_dboption [dbname, Displays or changes a database option
optname, {true | false}]
sp_dropgroup group-name Drops a group from a database
sp_droplogin userid Drops a user from a database
sp_dropmessage message- Drops a user-defined message
number [, language]
sp_droptype typename Drops a user-defined data type
sp_dropuser userid Drops a user from a database
sp_getmessage message- Retrieves a stored message string from
num, @msg-var output [, SYSUSERMESSAGES, for PRINT and
language] RAISERROR statements.
sp_helptext object-name Displays the text of a system procedure, trigger,
or view
sp_password caller_passwd, Adds or changes a password for a user ID
new_passwd [, userid]

Adaptive Server Enterprise catalog procedures


Adaptive Server Anywhere implements a subset of the Adaptive Server
Enterprise catalog procedures. The implemented catalog procedures are
described in the following table.

Catalog procedure Description


sp_column_privileges Unsupported
sp_columns table-name [, Returns the data types of the specified columns
table-owner ] [, table-
qualifier] [, column-name]
sp_databases Unsupported
sp_datatype_info Unsupported
sp_fkeys pktable_name [, Returns foreign key information about the
pktable-owner][, pktable- specified table
qualifier] [, fktable-name] [,
fktable_owner] [, fktable-
qualifier]
sp_pkeys table-name [, Returns primary key information about the
table_owner] [, specified table
table_qualifier]
sp_server_info Unsupported

958
Chapter 14 System Procedures and Functions

Catalog procedure Description


sp_special_columns Returns the optimal set of columns that uniquely
table_name [, table-owner] identify a row in the specified table
[, table-qualifier] [, col-type]
sp_sproc_columns proc- Returns information about a stored procedure’s
name [, proc_owner] [, input and return parameters
proc-qualifier] [, column-
name]
sp_stored_procedures [sp- Returns information about one or more stored
name] [, sp-owner] [, sp- procedures
qualifier]
sp_statistics [table_name] [, Returns information about tables and their indexes
table_owner] [,
table_qualities] [,
index_name] [, is_unique]
sp_tables table-name [, table- Returns a list of objects that can appear in a
owner] [, table-qualifier] [, FROM clause for the specified table
table-type]

959
Adaptive Server Enterprise system and catalog procedures

960
C H A P T E R 1 5

System Tables

About this chapter The structure of every database is described in a number of system tables.
The Entity-Relationship diagram on the next page shows all the system
tables and the foreign keys that connect them.
The system tables are owned by the SYS user ID. The contents of these
tables can be changed only by the database system. The UPDATE, DELETE,
and INSERT commands cannot be used to modify the contents of these
tables. Further, the structure of these tables cannot be changed using the
ALTER TABLE and DROP commands.
Contents
Topic Page
System tables diagram 963
System table descriptions 965
DUMMY system table 966
SYSARTICLE system table 967
SYSARTICLECOL system table 968
SYSCAPABILITY system table 969
SYSCAPABILITYNAME system table 970
SYSCOLLATION system table 971
SYSCOLLATIONMAPPINGS system table 972
SYSCOLPERM system table 973
SYSCOLUMN system table 974
SYSDOMAIN system table 976
SYSEXTENT system table 977
SYSEXTERNLOGINS system table 978
SYSFILE system table 979
SYSFKCOL system table 980
SYSFOREIGNKEY system table 981
SYSGROUP system table 983
961
System tables diagram

SYSINDEX system table 984


SYSINFO system table 986
SYSIXCOL system table 988
SYSJAR system table 989
SYSJARCOMPONENT system table 990
SYSJAVACLASS system table 991
SYSLOGIN system table 993
SYSOPTION system table 994
SYSPROCEDURE system table 995
SYSPROCPARM system table 996
SYSPROCPERM system table 998
SYSPUBLICATION system table 999
SYSREMOTEOPTION system table 1000
SYSREMOTEOPTIONTYPE system table 1001
SYSREMOTETYPE system table 1002
SYSREMOTEUSER system table 1003
SYSSERVERS system table 1005
SYSSQLSERVERTYPE system table 1006
SYSSUBSCRIPTION system table 1007
SYSTABLE system table 1008
SYSTABLEPERM system table 1010
SYSTRIGGER system table 1012
SYSTYPEMAP system table 1014
SYSUSERMESSAGES system table 1015
SYSUSERPERM system table 1016
SYSUSERTYPE system table 1018

962
Chapter 15 System Tables

System tables diagram


The Adaptive Server Anywhere system tables are shown in the following
diagrams. Arrows indicate foreign key relations between tables: the arrow
leads from the foreign table to the primary table.
The first diagram shows the core set of system tables.
SYSDOMAIN SYSPROCPARM SYSUSERMESSAGES
DOMAIN_ID PROC_ID ERROR
DOMAIN_NAME PARM_ID UID
SYSEXTENT TYPE_ID DESCRIPTION
SYSTYPEMAP PARM_TYPE
FILE_ID PRECISION PARM_MODE_IN LANGID
SS_USER_TYPE
EXTENT_ID PARM_MODE_OUT
SA_DOMAIN_ID
FIRST_PAGE DOMAIN_ID
SA_USER_TYPE SYSCOLLATION
LAST_PAGE WIDTH
NULLABLE COLLATION_ID
FILE_NAME SCALE
SYSPROCPERM COLLATION_LABEL
PARM_NAME
PROC_ID COLLATION_NAME
REMARKS
SYSCOLPERM GRANTEE COLLATION_ORDER
DEFAULT
TABLE_ID USER_TYPE
SYSFILE GRANTEE
FILE_ID GRANTOR SYSOPTION
FILE_NAME COLUMN_ID USER_ID
DBSPACE_NAME PRIVILEGE_TYPE OPTION SYSSQLSERVERTYPE
IS_GRANTABLE SETTING SYSPROCEDURE SS_USER_TYPE
PROC_ID SS_DOMAIN_ID
CREATOR SS_TYPE_NAME
PROC_NAME PRIMARY_SA_DOMAIN_ID
PROC_DEFN PRIMARY_SA_USER_TYPE
SYSUSERPERM REMARKS
SYSCOLUMN
USER_ID REPLICATE
TABLE_ID
SYSTABLE USER_NAME
COLUMN_ID
TABLE_ID PASSWORD
PKEY
FILE_ID RESOURCEAUTH SYSGROUP
DOMAIN_ID
COUNT DBAAUTH GROUP_ID
NULLS
FIRST_PAGE SCHEDULEAUTH GROUP_MEMBER SYSEXTERNLOGINS
WIDTH
LAST_PAGE PUBLISHAUTH USER_ID
SCALE
PRIMARY_ROOT REMOTEDBAAUTH SRVID
ESTIMATE
CREATOR USER_GROUP
COLUMN_NAME REMOTE_LOGIN
TABLE_NAME REMARKS REMOTE_PASSWORD
REMARKS
TABLE_TYPE SYSSERVERS
DEFAULT
VIEW_DEF SRVID
CHECK
REMARKS SRVNAME
USER_TYPE
REPLICATE SRVCLASS
FORMAT_STR
EXISTING_OBJ SRVINFO
COLUMN_TYPE
REMOTE_LOCATION SRVREADONLY
REMOTE_NAME SYSTABLEPERM
REMOTE_OBJTYPE
REMOTE_TYPE STABLE_ID
SRVID
GRANTEE SYSTRIGGER
GRANTOR TRIGGER_ID SYSINFO
TTABLE_ID PAGE_SIZE
TABLE_ID
SYSIXCOL SELECTAUTH
EVENT ENCRYPTION
TABLE_ID INSERTAUTH
TRIGGER_TIME BLANK_PADDING
INDEX_ID DELETEAUTH
TRIGGER_ORDER CASE_SENSITIVITY
SEQUENCE UPDATEAUTH
FOREIGN_TABLE_ID DEFAULT_COLLATION
COLUMN_ID UPDATECOLS
FOREIGN_KEY_ID DATABASE_VERSION
ORDER ALTERAUTH
REFERENTIAL_ACTION CLASSES_VERSION
REFERENCEAUTH
TRIGGER_NAME
TRIGGER_DEFN
REMARKS
SYSINDEX
TABLE_ID
SYSUSERTYPE INDEX_ID
DUMMY
TYPE_ID ROOT
DUMMY_COL SYSLOGIN
CREATOR FILE_ID INTEGRATED_LOGIN_ID
DOMAIN_ID UNIQUE LOGIN_UID
NULLS CREATOR REMARKS
WIDTH INDEX_NAME SYSFOREIGNKEY
SCALE REMARKS FOREIGN_TABLE_ID
TYPE_NAME
FOREIGN_KEY_ID SYSCOLLATIONMAPPINGS
DEFAULT
PRIMARY_TABLE_ID COLLATION_LABEL
CHECK
SYSFKCOL ROOT COLLATION_NAME
FORMAT_STR
FOREIGN_TABLE_ID CHECK_ON_COMMIT CS_LABEL
SUPER_TYPE_ID
FOREIGN_KEY_ID NULLS SO_CASE_LABEL
FOREIGN_COLUMN_ID ROLE SO_CASELESS_LABEL
REMARKS JDK_LABEL
PRIMARY_COLUMN_ID

963
System tables diagram

Java system tables


Those system tables that are used for Java in the database are listed below.
Foreign key relations between tables are indicated by arrows: the arrow leads
from the foreign table to the primary table.

CLASS_ID = REPLACED_BY

SYSJAVACLASS
CLASS_ID <pk> smallint
REPLACED_BY <fk> smallint
JAR_ID smallint
CLASS_NAME long varchar
PUBLIC char(1)
COMPONENT_ID <fk> smallint
CREATE_TIME timestamp
UPDATE_TIME timestamp
CLASS_DESCRIPTOR long binary
REMARKS long varchar

COMPONENT_ID = COMPONENT_ID

SYSJARCOMPONENT
COMPONENT_ID <pk> smallint
JAR_ID <fk> smallint
COMPONENT_NAME long varchar
COMPONENT_TYPE char(1)
CREATE_TIME timestamp
CONTENTS long binary
REMARKS long varchar

JAR_ID = JAR_ID

SYSJAR
JAR_ID <pk> smallint
CREATOR smallint
JAR_NAME long varchar
JAR_FILE long varchar
CREATE_TIME timestamp
UPDATE_TIME timestamp
REMARKS long varchar

Other system tables


$ For information about the SQL Remote system tables, see
"SQL Remote system tables" on page 548 of the book Replication and
Synchronization Guide.

964
Chapter 15 System Tables

System table descriptions


This chapter contains descriptions of each of the system tables. Several of the
columns have only two possible values. Usually these values are "Y" and
"N" for "yes" and "no" respectively. These columns are designated by
"(Y/N)".

965
DUMMY system table

DUMMY system table


Column name Column type Column Table
constraint constraints
dummy_col INTEGER NOT NULL

The DUMMY table is provided as a read-only table that always has exactly
one row. This can be useful for extracting information from the database, as
in the following example that gets the current user ID and the current date
from the database.
SELECT USER, today(*) FROM SYS.DUMMY
Use of FROM SYS.DUMMY in the FROM clause is optional. If no table is
specified in the FROM clause, the table is assumed to be SYS.DUMMY. The
above example could be written as follows:
SELECT USER, today(*)

dummy_col This column is not used. It is present because a table cannot


be created with no columns.

966
Chapter 15 System Tables

SYSARTICLE system table


Column name Column type Column Table constraints
constraint
publication_id UNSIGNED NOT NULL Primary key, foreign key
INT references
SYSPUBLICATION
table_id UNSIGNED NOT NULL Primary key, foreign key
INT references SYSTABLE
where_expr LONG
VARCHAR
subscribe_by_expr LONG
VARCHAR
query CHAR(1) NOT NULL

Each row of SYSARTICLE describes an article in a SQL Remote


publication.

publication_id The publication of which this article is a part.

table_id Each article consists of columns and rows from a single table.
This column contains the table ID for this table.

where_expr For articles that contain a subset of rows defined by a


WHERE clause, this column contains the search condition.

subscribe_by_expr For articles that contain a subset of rows defined by


a SUBSCRIBE BY expression, this column contains the expression.

967
SYSARTICLECOL system table

SYSARTICLECOL system table


Column name Column Column Table constraints
type constraint
publication_id UNSIGNED NOT NULL Primary Key, foreign key
INT references SYSARTICLE
table_id UNSIGNED NOT NULL Primary Key, foreign key
INT references SYSARTICLE,
SYSCOLUMN
column_id UNSIGNED NOT NULL Primary Key, foreign key
INT references SYSCOLUMN

Each row identifies a column in an article.

publication_id A unique identifier for the publication of which the


column is a part.

table_id The table to which the column belongs.

column_id The column identifier, from the SYSCOLUMN system table.

968
Chapter 15 System Tables

SYSCAPABILITY system table


Column name Column Column Table constraints
type constraint
capid INTEGER Primary key. Foreign key
references
SYSCAPABILITYNAME
capvalue CHAR(128)
srvid INTEGER Primary key. Foreign key
references SYSSERVERS

Each row identifies a capability of a remote server.

capid The capability, as listed in SYSCAPABILITYNAME.

capvalue The value of the capability.

srvidThe server to which the capability applies, as listed in


SYSSERVERS.

969
SYSCAPABILITYNAME system table

SYSCAPABILITYNAME system table


Column name Column Column Table constraints
type constraint
capid INTEGER Primary key.
capname CHAR(128)

Each row identifies a capability.

capid The capability, as listed in SYSCAPABILITYNAME.

capname The name of the capability.

970
Chapter 15 System Tables

SYSCOLLATION system table


Column name Column type Column Table
constraint constraint
collation_id SMALLINT NOT NULL Primary key
collation_label CHAR(10) NOT NULL
collation_name CHAR(128) NOT NULL
collation_order BINARY(1280) NOT NULL

This table contains the collation sequences available to Adaptive Server


Anywhere. There is no way to modify the contents of this table.

collation_id A unique number identifying the collation sequence. The


collation sequence with collation_id 2 is the sequence used in previous
versions of Adaptive Server Anywhere, and is the default when a database is
created.

collation_label A string identifying the collation sequence. The collation


sequence to be used is selected when the database is created, by specifying
the collation label with the -z option.

collation_name The name of the collation sequence.

collation_order An array of bytes defining how each of the 256 character


codes are treated for comparison purposes. All string comparisons translate
each character according to the collation order table before comparing the
characters. For the different ASCII code pages, the only difference is how
accented characters are sorted. In general, an accented character is sorted as
if it were the same as the nonaccented character.

971
SYSCOLLATIONMAPPINGS system table

SYSCOLLATIONMAPPINGS system table


Column name Column type Column Table
constraint Constraints
collation_label char(10) NOT NULL Primary key
collation_name char(128) NOT NULL
cs_label char(128)
so_case_label char(128)
so_caseless_label char(128)
jdk_label char(128)

collation_label A string identifying the collation sequence. The collation


sequence to be used is selected when the database is created, by specifying
the collation label with the -z option.

collation_name The collation name used to describe the character set


encoding.

cs_label The GPG character set mapping label.

so_case_label The collation sort order for case-sensitive GPG character


set mapping.

so_caseless_label The collation sort order for case-insensitive GPG


character set mapping.

jdk_label The JDK character set label.

972
Chapter 15 System Tables

SYSCOLPERM system table


Column name Column type Column Table constraint
constraint
table_id UNSIGNED INT NOT NULL Primary key, foreign
key references
SYSCOLUMN
grantee UNSIGNED INT NOT NULL Primary key, foreign
key references
SYSUSERPERM.user_
id
grantor UNSIGNED INT NOT NULL Primary key, foreign
key references
SYSUSERPERM.user_
id
column_id UNSIGNED INT NOT NULL Primary key, foreign
key references
SYSCOLUMN
privilege_type SMALLINT NOT NULL Primary key
is_grantable CHAR(1) NOT NULL

The GRANT command can give UPDATE permission to individual columns


in a table. Each column with UPDATE permission is recorded in one row of
SYSCOLPERM.

table_id The table number for the table containing the column.

grantee The user number of the user ID that is given UPDATE permission
on the column. If the grantee is the user number for the special PUBLIC
user ID, the UPDATE permission is given to all user IDs.

grantor The user number of the user ID that grants the permission.

column_id This column number, together with the table_id, identifies the
column for which UPDATE permission has been granted.

privilege_type The number in this column indicates the kind of column


permission (REFERENCES, SELECT or UPDATE).

is_grantable (Y/N)
Indicates if the permission on the column was granted
WITH GRANT OPTION.

973
SYSCOLUMN system table

SYSCOLUMN system table


Column Column type Column Table constraints
name constraint
table_id UNSIGNED INT NOT NULL Primary key, foreign key
references
SYSTABLE.table_id
column_id UNSIGNED INT NOT NULL Primary key.
pkey CHAR(1) NOT NULL
domain_id SMALLINT NOT NULL foreign key references
SYSDOMAIN.domain_id
nulls CHAR(1) NOT NULL
width SMALLINT NOT NULL
scale SMALLINT NOT NULL
estimate INTEGER NOT NULL
max_identity BIGINT NOT NULL
column_name CHAR(128) NOT NULL
remarks LONG
VARCHAR
"default" LONG
VARCHAR
"check" LONG
VARCHAR
user_type SMALLINT Foreign key references
SYSUSERTYPE.type_id
format_str CHAR(128)
column_type CHAR(1) NOT NULL
remote_name VARCHAR(128)
remote_type UNSIGNED INT

Each column in every table or view is described by one row in


SYSCOLUMN.

table_id A number that uniquely identifies the table or view to which this
column belongs.

column_id Each table starts numbering columns at 1. The order of column


numbers determines the order that columns are displayed in the command

974
Chapter 15 System Tables

SELECT * FROM TABLE

pkey (Y/N) Indicate whether this column is part of the primary key for the
table.

domain_id The data type for the column, indicated by a data type number
listed in the SYSDOMAIN table.

nulls (Y/N) Indicates whether the NULL value is allowed in this column.

width The length of a string column, the precision of numeric columns or


the number of bytes of storage for any other data type.

scale The number of digits after the decimal point for numeric data type
columns, and zero for all other data types.

estimate A self-tuning parameter for the optimizer. Adaptive Server


Anywhere will learn from previous queries by adjusting guesses that are
made by the optimizer.

max_identity
The largest value of the column, if it is an
AUTOINCREMENT, IDENTITY, or GLOBAL AUTOINCREMENT
column.

column_name The name of the column.

remarks A comment string.

default The default value for the column. This value is only used when an
INSERT statement does not specify a value for the column.

check. Any CHECK condition defined on the column.

user_type If the column is defined on a user-defined data type, the data


type is held here.

format_str Currently unused.

column_type The type of column. Contains C for a computed column and


R for other columns.

remote_name The name of the remote column.

remote_type The type of the remote column. This value is defined by the
remote server or interface.

975
SYSDOMAIN system table

SYSDOMAIN system table


Column name Column type Column Table
constraint constraints
domain_id SMALLINT NOT NULL Primary key
domain_name CHAR(128) NOT NULL
type_id SMALLINT NOT NULL
precision SMALLINT

Each of the predefined data types (sometimes called domains) is assigned a


unique number. The SYSDOMAIN table is provided for informational
purposes, to show the association between these numbers and the appropriate
data types. This table is never changed.

domain_id The unique number assigned to each data type. These numbers
cannot be changed.

domain_name A string containing the data type normally found in the


CREATE TABLE command, such as char or integer.

type_id The ODBC data type. This corresponds to "data_type" in the


Transact-SQL-compatibility DBO.SYSTYPES table.

precision The number of significant digits that can be stored using this
data type. The column value is NULL for non-numeric data types.

976
Chapter 15 System Tables

SYSEXTENT system table


Column name Column type Column Table
constraint constraint
file_id SMALLINT NOT NULL Primary key,
foreign key
references
SYSFILE
extent_id SMALLINT NOT NULL Primary key
first_page INTEGER NOT NULL
last_page INTEGER NOT NULL
file_name LONG NOT NULL
VARCHAR

This table is not used by Adaptive Server Anywhere 6.0.

977
SYSEXTERNLOGINS system table

SYSEXTERNLOGINS system table


Column name Column type Column Table
constraint constraints
user_id UNSIGNED INT NOT NULL Primary key.
Foreign key to
SYSUSERPERM
srvid INTEGER NOT NULL Primary key.
Foreign key to
SYSSERVERS
remote_login VARCHAR(128)
remote_password VARBINARY(128)

Each row describes an external login for remote data access.

user_id The user ID on the local database.

srvid The remote server, as listed in SYSSERVERS.

remote_login The login name for this user, for the remote server.

remote_password The password for this user, for the remote server.

978
Chapter 15 System Tables

SYSFILE system table


Column name Column type Column Table
constraint constraint
file_id SMALLINT NOT NULL Primary key
file_name LONG NOT NULL Unique index
VARCHAR
dbspace_name CHAR(128) NOT NULL

Every database consists of one or more operating system files. Each file is
recorded in SYSFILE.

file_id Each file in a database is assigned a unique number. This file


identifier is the primary key for SYSFILE. All system tables are stored in
file_id 0.

file_name The database name is stored when a database is created. This


name is for informational purposes only.

dbspace_name Every file has a dbspace name that is unique. It is used in


the CREATE TABLE command.

979
SYSFKCOL system table

SYSFKCOL system table


Column name Column Column Table constraints
type constraint
foreign_table_id UNSIGNED NOT NULL Primary key. Foreign key
INT references
SYSCOLUMN.table_id.
Foreign key references
SYSFOREIGNKEY.
foreign_key_id SMALLINT NOT NULL Primary key, foreign key
references
SYSFOREIGNKEY.
foregin_key_id
foreign_column_id UNSIGNED NOT NULL Primary key, Foreign key
INT references SYSCOLUMN
column_id
primary_column_id UNSIGNED NOT NULL
INT

Each row of SYSFKCOL describes the association between a foreign


column in the foreign table of a relationship and the primary column in the
primary table.

foreign_table_id The table number of the foreign table.

foreign_key_id The key number of the FOREIGN KEY for the foreign
table. Together, foreign_table_id and foreign_key_id uniquely identify one
row in SYSFOREIGNKEY. The table number for the primary table can be
obtained from that row (using the SYSFOREIGNKEY table).

foreign_column_id This column number, and the foreign_table_id


identify the foreign column description in SYSCOLUMN.

primary_column_id This column number and the primary_table_id


obtained from SYSFOREIGNKEY identify the primary column description
in SYSCOLUMN.

980
Chapter 15 System Tables

SYSFOREIGNKEY system table


Column name Column type Column Table constraints
constraint
foreign_table_id UNSIGNED INT NOT NULL Primary key, foreign
key references
SYSTABLE.table_id.
Unique index.
foreign_key_id SMALLINT NOT NULL Primary key
primary_table_id UNSIGNED INT NOT NULL foreign key
references
SYSTABLE.table_id.
root INTEGER NOT NULL
check_on_commit CHAR(1) NOT NULL
nulls CHAR(1) NOT NULL
role CHAR(128) NOT NULL Unique index
remarks LONG
VARCHAR

A foreign key is a relationship between two tables—the foreign table and


the primary table. Every foreign key is defined by one row in
SYSFOREIGNKEY and one or more rows in SYSFKCOL.
SYSFOREIGNKEY contains general information about the foreign key
while SYSFKCOL identifies the columns in the foreign key and associates
each column in the foreign key with a column in the primary key of the
primary table.

foreign_table_id The table number of the foreign table.

foreign_key_id Each foreign key has a foreign key number that is


unique with respect to:
♦ The key number of all other foreign keys for the foreign table
♦ The key number of all foreign keys for the primary table
♦ The index number of all indexes for the foreign table

primary_table_id The table number of the primary table.

root Foreign keys are stored in the database as B-trees. The root identifies
the location of the root of the B-tree in the database file.

981
SYSFOREIGNKEY system table

check_on_commit (Y/N) Indicates whether INSERT and UPDATE


commands should wait until the next COMMIT command to check if foreign
keys are valid. A foreign key is valid if, for each row in the foreign table, the
values in the columns of the foreign key either contain the NULL value or
match the primary key values in some row of the primary table.

nulls (Y/N) Indicates whether the columns in the foreign key are allowed
to contain the NULL value. Note that this setting is independent of the nulls
setting in the columns contained in the foreign key.

role The name of the relationship between the foreign table and the
primary table. Unless otherwise specified, the role name will be the same as
the name of the primary table. The foreign table cannot have two foreign
keys with the same role name.

remarks A comment string.

982
Chapter 15 System Tables

SYSGROUP system table


Column name Column type Column Table constraints
constraint
group_id UNSIGNED NOT NULL Primary key, foreign
INT key references
SYSUSERPERM.user_
id
group_member UNSIGNED NOT NULL Primary key, foreign
INT key references
SYSUSERPERM.user_
id

There is one row in SYSGROUP for every member of every group. This
table describes a many-to-many relationship between groups and members.
A group may have many members, and a user may be a member of many
groups.

group_id The user number of group.

group_member The user number of a member.

983
SYSINDEX system table

SYSINDEX system table


Column name Column type Column Table constraints
constraint
table_id UNSIGNED NOT NULL Primary key, Unique
INT index. Foreign key
references
SYSTABLE.
index_id UNSIGNED NOT NULL Primary key
INT
root INTEGER NOT NULL
file_id SMALLINT NOT NULL
"unique" CHAR(1) NOT NULL
creator UNSIGNED NOT NULL Foreign key
INT references
SYSUSERPERM.use
r_id
index_name CHAR(128) NOT NULL Unique index
remarks LONG,
VARCHAR

Each index in the database is described by one row in SYSINDEX. Each


column in the index is described by one row in SYSIXCOL.

table_id Uniquely identifies the table to which this index applies.

index_id Each index for one particular table is assigned a unique index
number.

root Indexes are stored in the database as B-trees. The root identifies the
location of the root of the B-tree in the database file.

file_id
The index is completely contained in the file with this file_id (see
SYSFILE).

unique Indicate whether the index is a unique index ("Y"), a non-unique


index ("N"), or a unique constraint ("U"). A unique index prevents two rows
in the indexed table from having the same values in the index columns.

creator The user number of the creator of the index. This user is always
the same as the creator of the table identified by table_id.

984
Chapter 15 System Tables

index_name The name of the index. A user ID cannot have two indexes
with the same name in tables that it owns..

remarks A comment string.

985
SYSINFO system table

SYSINFO system table


Column name Column type Column Table
constraint constraints
page_size INTEGER NOT NULL
encryption CHAR(1) NOT NULL
blank_padding CHAR(1) NOT NULL
case_sensitivity CHAR(1) NOT NULL
default_collation CHAR(10)
database_version SMALLINT NOT NULL
classes_version CHAR(10)

This table indicates the database characteristics, as defined when the


database was created. It always contains only one row.

page_size The page size specified, in bytes. The default value is 1024.

encryption (Y/N) Indicates whether the -e switch was used with DBINIT.

blank_padding (Y/N) Indicates whether the database was created to use


blank padding for string comparisons in the database ( -b switch was used
with dbinit).

case_sensitivity (Y/N) Indicates whether the database is created as case


sensitive. Case sensitivity affects value comparisons, but not table and
column name comparisons. For example, if a database is case sensitive, table
names such as SYSCATALOG can be specified in either case, but in a case-
sensitive database ’abc’ = ’ABC’ is not true.

default_collation A string corresponding to the collation_label in


SYSCOLLATE, which also corresponds to the collation sequence specified
with DBINIT. The default value corresponds to the multilingual collation
sequence (code page 850), which was the default prior to Watcom SQL 3.2.
The collation sequence is used for all string comparisons, including searches
for character strings as well as column and table name comparison.

database_version A small integer value indicating the database format.


As newer versions become available, new features may require that the
format of the database file change. The version number Adaptive Server
Anywhere software to determine if this database was created with a newer
version of the software and thus, cannot be understood by the software in
use.

986
Chapter 15 System Tables

classes_version A small string describing the current version of the


SYS.JAVA.CLASSES library that is currently installed on your computer.

987
SYSIXCOL system table

SYSIXCOL system table


Column name Column type Column Table constraints
constraint
table_id UNSIGNED NOT NULL Primary key. Foreign
INT key references
SYSCOLUMN. Foreign
key references
SYSINDEX.
index_id UNSIGNED NOT NULL Primary key. Foreign
INT key references
SYSINDEX
sequence SMALLINT NOT NULL Primary key
column_id UNSIGNED NOT NULL Foreign key references
INT SYSCOLUMN
"order" CHAR(1) NOT NULL

Every index has one row in SYSIXCOL for each column in the index.

table_id Identifies the table to which the index applies.

index_id Identifies in which index this column is used. Together, table_id


and index_id identify one index described in SYSINDEX.

sequence Each column in an index is assigned a unique number starting


at 0. The order of these numbers determines the relative significance of the
columns in the index. The most important column has sequence number 0.

column_id The column number identifies which column is indexed.


Together, table_id and column_id identify one column in SYSCOLUMN.

order (A/D) Indicate whether this column in the index is kept in ascending
or descending order.

988
Chapter 15 System Tables

SYSJAR system table


Column name Column type Column Table
constraint constraints
jar_id INTEGER NOT NULL Primary key
creator UNSIGNED INT NOT NULL
jar_name LONG NOT NULL Unique index
VARCHAR
jar_file LONG
VARCHAR
create_time TIMESTAMP NOT NULL
update_time TIMESTAMP NOT NULL
remarks LONG
VARCHAR

jar_id A field containing the id of the jar file. This field also references
the SYSJAR system table.

creator The is of the creator of the jar file.

jar_name The name of the jar file.

jar_file The file name of the jar file.

create_time The time the jar file was created.

update_time The time the jar file was last updated.

remarks A comment field.

989
SYSJARCOMPONENT system table

SYSJARCOMPONENT system table


Column name Column type Column Table
constraint constraints
component_id INTEGER NOT NULL Primary key
jar_id INTEGER Foreign key
references
SYSJAR
component_name LONG
VARCHAR
Component_type CHAR(1)
Create_time TIMESTAMP NOT NULL
Contents LONG BINARY
Remarks LONG
VARCHAR

component_id The primary key containing the id of the component.

jar_id A field containing the ID number of the jar. This field also
references the SYSJAR system table.

component_name The name of the component.

component_type The type of the component.

create_time A field containing the creation time of the component.

contents The byte code of the jar file.

remarks A comment field.

990
Chapter 15 System Tables

SYSJAVACLASS system table


Column name Column type Column Table
constraint constraints
class_id INTEGER NOT NULL Primary key
replaced_by INTEGER Foreign key
references
SYSJAVACLAS
SES. class_id
creator UNSIGNED INT NOT NULL Foreign key
references
SYSUSERPER
M.user_id
jar_id INTEGER
type_id UNSIGNED INT Foreign key
references
SYSUSERTYPE
class_name LONG NOT NULL
VARCHAR
public CHAR(1) NOT NULL
component_id INTEGER Foreign key
references
SYSJARCOMP
ONENT
create_time TIMESTAMP NOT NULL
update_time TIMESTAMP NOT NULL
class_descriptor LONG BINARY
remarks LONG
VARCHAR

The SYSJAVACLASS system table contains all information related to Java


classes.

class_id This field contains the id of the java class. Also the primary key
for the table.

replaced_by A field that references the primary key field, class_id.

creator This field contains the user_id of the creator of the class. This
field references the user_id field in the SYSUSERPERM system table to
obtain the name of the user.

991
SYSJAVACLASS system table

jar_id This field contains the id of the jar file from which the class came.

type_id This field contains the id of the user type. This field references
the SYSUSERTYPE system table to obtain the id of the user.

class_name This field contains the name of the Java class.

public This field determines whether or not the class is public or private.

component_id This field, which references the SYSJARCOMPONENT


system table contains the id of the component.

create_time Contains the creation time of the component.

update_time Contains the last update time of the component.

class_descriptor The byte code of the jar file.

remarks Contains a comment string.

992
Chapter 15 System Tables

SYSLOGIN system table


Column name Column type Column Table
constraint constraints
integrated_login_id CHAR(128) NOT NULL Primary key,
login_uid UNSIGNED NOT NULL Foreign key
INT references
SYSUSERPERM.
user_id.
remarks LONG,
VARCHAR

This table contains all the User Profile names that can be used to connect to
the database using an integrated logon. As a security measure, only users
with DBA authority can view the contents of this table.

integrated_login_id A string value containing the User Profile name that


is used to map to a user ID in the database. When a user successfully logs on
using this User Profile name, and the database is enabled to accept integrated
logons, the user can connect to the database without providing a user ID or
password.

login_uid A foreign key to the system table SYSUSERPERM.

remarks A comment string

993
SYSOPTION system table

SYSOPTION system table


Column name Column type Column Table
constraint constraints
user_id UNSIGNED INT NOT NULL Primary key,
foreign key
references
SYSUSERPER
M
"option" CHAR(128) NOT NULL Primary key
"setting" LONG NOT NULL
VARCHAR

Options settings are stored in the SYSOPTION table by the SET command.
Each user can have their own setting for each option. In addition, settings for
the PUBLIC user ID define the default settings to be used for user IDs that
do not have their own setting.

user_id The user number to whom this option setting applies.

option The name of the option.

setting The current setting for the named option.

994
Chapter 15 System Tables

SYSPROCEDURE system table


Column name Column type Column Table constraints
constraint
proc_id UNSIGNED INT NOT NULL Primary key
creator UNSIGNED INT NOT NULL Unique index. Foreign
key references
SYSUSERPERM.user
_id
proc_name CHAR(128) NOT NULL
proc_defn LONG
VARCHAR
remarks LONG
VARCHAR
replicate CHAR(1) NOT NULL
srvid INTEGER Foreign key references
SYSSERVERS

Each procedure in the database is described by one row in


SYSPROCEDURE.

proc_id Each procedure is assigned a unique number (the procedure


number), which is the primary key for SYSPROCEDURE.

creator This user number identifies the owner of the procedure. The name
of the user can be found by looking in SYSUSERPERM.

proc_name The name of the procedure. One creator cannot have two
procedures with the same name.

proc_defn The command that was used to create the procedure.

remarks A comment string.

replicate (Y/N) Indicates whether the procedure is a primary data source


in a Replication Server installation.

srvid If a procedure on a remote database server, indicates the remote


server.

995
SYSPROCPARM system table

SYSPROCPARM system table


Column name Column type Column Table constraint
constraint
proc_id UNSIGNED INT NOT NULL Primary key, foreign
key references
SYSPROCEDURE
parm_id UNSIGNED INT NOT NULL Primary key
parm_type UNSIGNED INT NOT NULL
parm_mode_in CHAR(1) NOT NULL
parm_mode_out CHAR(1) NOT NULL
domain_id UNSIGNED INT NOT NULL Foreign key
references
SYSDOMAIN
width UNSIGNED INT NOT NULL
scale UNSIGNED INT NOT NULL
parm_name CHAR(128) NOT NULL
remarks LONG
VARCHAR
"default" LONG
VARCHAR
user_type INTEGER

Each parameter to a procedure in the database is described by one row in


SYSPROCEDURE.

proc_id Uniquely identifies the procedure to which this parameter


belongs.

parm_id Each procedure starts numbering parameters at 1. The order of


parameter numbers corresponds to the order in which they were defined.

parm_type The type of parameter will be one of the following:


♦ Normal parameter (variable)
♦ Result variable - used with a procedure that return result sets
♦ SQLSTATE error value
♦ SQLCODE error value

996
Chapter 15 System Tables

parm_mode_in (Y/N) Indicates whether this parameter supplies a value to


the procedure (IN or INOUT parameters).

parm_mode_out (Y/N) Indicates whether this parameter returns a value


from the procedure (OUT or INOUT parameters).

domain_id Identifies the data type for the parameter, by the data type
number listed in the SYSDOMAIN table.

width Contains the length of a string parameter, the precision of a numeric


parameter, or the number of bytes of storage for any other data types.

scale The number of digits after the decimal point for numeric data type
parameters, and zero for all other data type.

parm_name The name of the procedure parameter.

remarks A comment string.

default Unused.

user_type The user type of the parameter.

997
SYSPROCPERM system table

SYSPROCPERM system table


Column name Column type Column Table constraints
constraint
proc_id UNSIGNED NOT NULL Primary key. Foreign
INT key references
SYSPROCEDURE
grantee UNSIGNED NOT NULL Primary key. Foreign
INT key references
SYSUSERPERM.user
_id

Only users who have been granted permission can call a procedure. Each row
of the SYSPROCPERM table corresponds to one user granted permission to
call one procedure.

proc_id The procedure number uniquely identifies the procedure for


which permission has been granted.

grantee The user number of the user ID receiving the permission.

998
Chapter 15 System Tables

SYSPUBLICATION system table


Column name Column type Column Table constraints
constraint
publication_id UNSIGNED NOT NULL Primary key
INT
creator UNSIGNED NOT NULL Unique index. Foreign
INT key references
SYSUSERPERM.user_
id
publication_name CHAR(128) NOT NULL Unique index
remarks LONG
VARCHAR

Each row describes a SQL Remote publication.

publication_id A unique identifying number for the publication.

creator The owner of the publication.

publication_name The name of the publication, which must be a valid


identifier.

remarks Descriptive comments.

999
SYSREMOTEOPTION system table

SYSREMOTEOPTION system table


Function Each row describes the values of a SQL Remote message link parameter.
Columns Column Data type Description
option_id UNSIGNED INT An identification number for the
message link parameter.
user_id UNSIGNED INT The user ID for which the parameter is
set.
"setting" VARCHAR(255) The value of the message link
parameter.

1000
Chapter 15 System Tables

SYSREMOTEOPTIONTYPE system table


Function Each row describes one of the SQL Remote message link parameters.
Columns Column Data type Description
option_id UNSIGNED INT An identification number for the
message link parameter.
type_id UNSIGNED INT An identification number for the
message type that uses this parameter

"option" VARCHAR(128) The name of the message link


parameter.

1001
SYSREMOTETYPE system table

SYSREMOTETYPE system table


Column name Column type Column Table
constraint constraints
type_id UNSIGNED INT NOT NULL Primary key
type_name CHAR(128) NOT NULL Unique index
publisher_address LONG NOT NULL
VARCHAR
remarks LONG
VARCHAR

The SYSREMOTETYPE system table contains information about SQL


Remote.

type_id Identifies which of the of the message systems supported by SQL


Remote is to be used to send messages to this user.

type_name The name of the message system supported by SQL Remote.

publisher_address The address of the remote database publisher.

remarks Descriptive comments.

1002
Chapter 15 System Tables

SYSREMOTEUSER system table


Column name Column type Column Table constraints
constraint
user_id UNSIGNED INT NOT NULL Primary key, foreign
key references
SYSUSERPERM
consolidate CHAR(1) NOT NULL
type_id UNSIGNED INT NOT NULL Foreign key references
SYSREMOTETYPE
address LONG, NOT NULL
VARCHAR
frequency CHAR(1) NOT NULL Unique index
send_time TIME Unique index
log_send NUMERIC(20,0) NOT NULL
time_sent TIMESTAMP
log_sent NUMERIC(20,0) NOT NULL
confirm_sent NUMERIC(20,0) NOT NULL
send_count INTEGER NOT NULL
resend_count INTEGER NOT NULL
time_received TIMESTAMP
log_received NUMERIC(20,0) NOT NULL
confirm_received NUMERIC(20,0)
receive_count INTEGER NOT NULL
rereceive_count INTEGER NOT NULL

Each row describes a userid with REMOTE permissions (a subscriber),


together with the status of SQL Remote messages that were sent to and from
that user.

user_id The user number of the user with REMOTE permissions.

consolidate
(Y/N) Indicates whether the user was granted
CONSOLIDATE permissions (Y) or REMOTE permissions (N).

type_id Identifies which of the of the message systems supported by SQL


Remote is used to send messages to this user.

1003
SYSREMOTEUSER system table

address The address to which SQL Remote messages are to be sent. The
address must be appropriate for the address_type.

frequency How frequently SQL Remote messages are sent.

send_time The next time messages are to be sent to this user.

log_send Messages are sent only to subscribers for whom log_send is


greater than log_sent.

time_sent The time the most recent message was sent to this subscriber.

log_sent The log offset for the most recently sent operation.

confirm_sent The log offset for the most recently confirmed operation
from this subscriber.

send_count How many SQL Remote messages have been sent.

resend_count Counter to ensure that messages are applied only once at


the subscriber database.

time_received The time when the most recent message was received from
this subscriber.

log_received The log offset in the subscriber’s database for the operation
that was most recently received at the current database.

confirm_received The log offset in the subscriber’s database for the most
recent operation for which a confirmation message has been sent.

receive_count How many messages have been received.

rereceive_count Counter to ensure that messages are applied only once at


the current database.

1004
Chapter 15 System Tables

SYSSERVERS system table


Column name Column type Column Table
constraint Constraints
srvid INTEGER NOT NULL Primary key
srvname VARCHAR(128) NOT NULL
srvclass LONG NOT NULL
VARCHAR
srvinfo LONG
VARCHAR
srvreadonly CHAR(1) NOT NULL

Each row describes a remote server.

srvid An identifier for the remote server.

srvname The name of the remote server.

srvclass The server class, as specified in the CREATE SERVER


statement.

srvinfo Server information.

srvreadonly Y if the server is read only, and N otherwise.

1005
SYSSQLSERVERTYPE system table

SYSSQLSERVERTYPE system table


Column name Column Column Table constraints
type constraint
ss_user_type UNSIGNED NOT NULL Primary key
INT
ss_domain_id UNSIGNED NOT NULL
INT
ss_type_name VARCHAR NOT NULL
(30)
primary_sa_domain_id UNSIGNED NOT NULL
INT
primary_sa_user_type UNSIGNED NULL
INT

This table contains information relating to compatibility with Adaptive


Server Enterprise.

ss_user_type A UNSIGNED INT field describing the Adaptive Server


Enterprise user type

ss_domain_id A UNSIGNED INT field describing the Adaptive Server


Enterprise domain id.

ss_type_name Contains the Adaptive Server Enterprise type name.

primary_sa_domain_id A UNSIGNED INT field containing the


Adaptive Server Anywhere primary domain id.

primary_sa_user_type A UNSIGNED INT field containing the Adaptive


Server Anywhere primary user type.

1006
Chapter 15 System Tables

SYSSUBSCRIPTION system table


Column name Column type Column Table constraints
constraint
publication_id UNSIGNED INT NOT NULL Primary key, foreign
key references
SYSPUBLICATION
user_id UNSIGNED INT NOT NULL Primary key, foreign
key references
SYSREMOTEUSER
subscribe_by CHAR(128) NOT NULL Primary key
created NUMERIC(20,0) NOT NULL
started NUMERIC(20,0)

Each row describes a subscription from one user ID (which must have
REMOTE permissions) to one publication.

publication_id The identifier for the publication to which the user ID is


subscribed.

user_id The user number that is subscribed to the publication.

subscribe_by The value of the SUBSCRIBE BY expression, if any, for


the subscription.

created The offset in the transaction log at which the subscription was
created.

started The offset in the transaction log at which the subscription was
started.

1007
SYSTABLE system table

SYSTABLE system table


Column name Column Column Table constraints
type constraint
table_id UNSIGNED NOT NULL Primary key
INT
file_id UNSIGNED NOT NULL Foreign key references
INT SYSFILE
count INTEGER NOT NULL
first_page INTEGER NOT NULL
last_page INTEGER NOT NULL
primary_root INTEGER NOT NULL
creator UNSIGNED NOT NULL Unique index.
INT
Foreign key references
SYSUSERPERM.user_id
table_name CHAR(128) NOT NULL Unique index
table_type CHAR(10) NOT NULL
view_def LONG
VARCHAR
remarks LONG
VARCHAR
replicate CHAR(1) NOT NULL
existing_obj CHAR(1)
remote_location LONG
VARCHAR
remote_objtype CHAR(1)
srvid INTEGER Foreign key references
SYSSERVERS

Each row of SYSTABLE describes one table or view in the database.

table_id Each table or view is assigned a unique number (the table


number) which is the primary key for SYSTABLE.

file_id
Indicates which database file contains the table. The file_id is a
FOREIGN KEY for SYSFILE.

1008
Chapter 15 System Tables

count The number of rows in the table is updated during each successful
CHECKPOINT. This number is used by Adaptive Server Anywhere when
optimizing database access. The count is always 0 for a view.

first_page Each database is divided into a number of fixed-size pages.


This value identifies the first page that contains information for this table,
and is used internally to find the start of this table. The first_page is always
0 for a view.

last_page The last page that contains information for this table. The
last_page is always 0 for a view.

primary_root Primary keys are stored in the database as B-trees. The


primary_root locates the root of the B-tree for the primary key for the table.
It will be 0 for a view and, for a table with no primary key.

creator The user number of the owner of the table or view. The name of
the user can be found by looking in SYSUSERPERM.

table_name The name of the table or view. One creator cannot have two
tables or views with the same name.

table_type This column is BASE for base tables, VIEW for views, and be
GBL TEMP for global temporary tables. No entry is created for local
temporary tables.

view_def For a view, this column contains the CREATE VIEW command
that was used to create the view. For a table, this column contains any
CHECK constraints for the table.

remarks A comment string.

replicate (Y/N) Indicates whether the table is a primary data source in a


Replication Server installation.

existing_obj (Y/N) Indicates whether the table previously existed or not.

remote_location Indicates the storage location of the remote object.

remote_objtype Indicates the type of remote object: ’T’ if table; ’V’ if


view; ’R’ if rpc; ’B’ if JavaBean.

srvid The unique ID for the server.

1009
SYSTABLEPERM system table

SYSTABLEPERM system table


Column name Column type Column Table
constraint constraints
stable_id UNSIGNED INT NOT NULL Primary key,
foreign key
references
SYSTABLE
table_id
grantee UNSIGNED INT NOT NULL Primary key,
foreign key
references
SYSUSERPERM
.user_id
grantor UNSIGNED INT NOT NULL Primary key,
foreign key
references
SYSUSERPERM
.user_id
ttable_id UNSIGNED INT NOT NULL Foreign key
references
SYSTABLE
table_id
selectauth CHAR(1) NOT NULL
insertauth CHAR(1) NOT NULL
deleteauth CHAR(1) NOT NULL
updateauth CHAR(1) NOT NULL
updatecols CHAR(1) NOT NULL
alterauth CHAR(1) NOT NULL
referenceauth CHAR(1) NOT NULL

Permissions given by the GRANT command are stored in


SYSTABLEPERM. Each row in this table corresponds to one table, one
user ID granting the permission (grantor) and one user ID granted the
permission (grantee).
There are several types of permission that can be granted. Each permission
can have one of the following three values.
♦ N No, the grantee has not been granted this permission by the grantor.
♦ Y Yes, the grantee has been given this permission by the grantor.

1010
Chapter 15 System Tables

♦ G The grantee has been given this permission and can grant the same
permission to another user (with grant options).

Permissions
The grantee might have been given permission for the same table by
another grantor. If so, this information would be recorded in a different
row of SYSTABLEPERM.

stable_id The table number of the table or view to which the permissions
apply.

grantor The user number of the user ID granting the permission.

grantee The user number of the user ID receiving the permission.

ttable_id In the current version of Adaptive Server Anywhere, this table


number is always the same as stable_id.

selectauth (Y/N/G) Indicates whether SELECT permission has been


granted.

insertauth (Y/N/G) Indicates whether INSERT permission has been


granted.

deleteauth (Y/N/G) Indicates whether DELETE permission has been


granted.

updateauth (Y/N/G) Indicates whether UPDATE permission has been


granted for all columns in the table. (Only UPDATE permission can be given
on individual columns. All other permissions are for all columns in a table.)

updatecols (Y/N) Indicates whether UPDATE permission has only been


granted for some of the columns in the table. If updatecols has the value Y,
there will be one or more rows in SYSCOLPERM granting update
permission for the columns in this table.

alterauth (Y/N/G) Indicates whether ALTER permission has been granted.

referenceauth (Y/N/G) Indicates whether REFERENCE permission has


been granted.

1011
SYSTRIGGER system table

SYSTRIGGER system table


Column name Column type Column Table constraints
constraint
trigger_id UNSIGNED INT NOT NULL Primary key
table_id UNSIGNED INT NOT NULL Foreign key
references
SYSTABLE.table_id
event CHAR(1) NOT NULL Unique
trigger_time CHAR(1) NOT NULL Unique
trigger_order UNSIGNED INT Unique
foreign_table_id UNSIGNED INT Unique. Foreign key
references
SYSFOREIGNKEY
foreign_key_id UNSIGNED INT Unique. Foreign key
references
SYSFOREIGNKEY
referential_action CHAR(1)
trigger_name CHAR(128) Unique.
trigger_defn LONG NOT NULL
VARCHAR
remarks LONG
VARCHAR

Each trigger in the database is described by one row in SYSTRIGGER. The


table also contains triggers that are automatically created by the database for
foreign key definitions which have a referential triggered action (such as ON
DELETE CASCADE).

trigger_id Each trigger is assigned a unique number (the trigger


number), which is the primary key for SYSTRIGGER.

table_id The table number uniquely identifies the table to which this
trigger belongs.

event The event or events that cause the trigger to fire. This single-
character value corresponds to the trigger event that was specified when the
trigger was created.

1012
Chapter 15 System Tables

trigger_time The time at which the trigger will fire. This single-character
value corresponds to the trigger time that was specified when the trigger was
created.
♦ A AFTER
♦ B BEFORE

trigger_order The order in which the trigger will fire. This determines the
order that triggers are fired when there are triggers of the same type (insert,
update, or delete) that fire at the same time (before or after).

foreign_table_id The table number of the table containing a foreign key


definition which has a referential triggered action (such as ON DELETE
CASCADE).

foreign_key_id The foreign key number of the foreign key for the table
referenced by foreign_table_id.

referential_action The action defined by a foreign key. This single-


character value corresponds to the action that was specified when the foreign
key was created.
♦ C CASCADE
♦ D SET DEFAULT
♦ N SET NULL
♦ R RESTRICT

trigger_name The name of the trigger. One table cannot have two triggers
with the same name.

trigger_defn The command that was used to create the trigger.

remarks A comment string.

1013
SYSTYPEMAP system table

SYSTYPEMAP system table


Column name Column type Column Table constraints
constraint
ss_user_type UNSIGNED INT NOT NULL
sa_domain_id UNSIGNED INT NOT NULL Foreign key references
SYSDOMAIN
sa_user_type UNSIGNED INT NULL
nullable CHAR(1) NULL

The SYSTYPEMAP system table contains the compatibility mapping values


for the SYSSQLSERVERTYPE system table.

ss_user_type Contains the Adaptive Server Enterprise user type.

sa_domain_id Contains the Adaptive Server Anywhere 6.0 domain_id.

sa_user_type Contains the Adaptive Server Anywhere 6.0 user type.

nullable This field describes whether or not the type can or cannot be null.

1014
Chapter 15 System Tables

SYSUSERMESSAGES system table


Column name Column type Column Table
constraint constraints
error INTEGER NOT NULL Unique index
uid UNSIGNED INT NOT NULL
description VARCHAR(255) NOT NULL
langid UNSIGNED INT NOT NULL Unique index

Each row holds a user-defined message for an error condition.

error A unique identifying number for the error condition.

uid The user number that defined the message.

description The message corresponding to the error condition.

langid Reserved.

1015
SYSUSERPERM system table

SYSUSERPERM system table


Column name Column type Column Table
constraint constraints
user_id UNSIGNED INT NOT NULL Primary key
user_name CHAR(128) NOT NULL
password BINARY(36)
resourceauth CHAR(1) NOT NULL
dbaauth CHAR(1) NOT NULL
scheduleauth CHAR(1) NOT NULL
publishauth CHAR(1) NOT NULL
remotedbaauth CHAR(1) NOT NULL
user_group CHAR(1) NOT NULL
remarks LONG
VARCHAR

DBA permissions required


SYSUSERPERM contains passwords, so DBA permissions are required
to SELECT from it.

Each row of SYSUSERPERM describes one user ID.

user_id Each new user ID is assigned a unique number (the user


number), which is the primary key for SYSUSERPERM.

user_name A string containing a unique name for the user ID.

password The password for the user ID. The password contains the
NULL value for the special user IDs SYS and PUBLIC. This prevents
anyone from connecting to these user IDs.

resourceauth (Y/N) Indicates whether the user has RESOURCE


authority. Resource authority is required to create tables.

dbaauth (Y/N) Indicates whether the user has DBA (database


administrator) authority. DBA authority is very powerful, and should be
restricted to as few user IDs as possible for security purposes.

scheduleauth (Y/N) Indicates whether the user has SCHEDULE


authority. This is currently not used.

1016
Chapter 15 System Tables

publishauth (Y/N) Indicates whether the user has the SQL Remote
publisher authority.

remotedbaauth (Y/N) Indicates whether the user has the SQL Remote
remote DBA authority.

user_group (Y/N) Indicates whether the user is a group.

remarks A comment string.


When a database is initialized, the following user IDs are created:
♦ SYS The creator of all the system tables.
♦ PUBLIC A special user ID used to record PUBLIC permissions.
♦ DBA The database administrator user ID is the only usable user ID in
an initialized system. The initial password is SQL.

There is no way to connect to the SYS or PUBLIC user IDs.

1017
SYSUSERTYPE system table

SYSUSERTYPE system table


Column name Column Column Table constraints
type constraint
type_id UNSIGNED NOT NULL Primary key
INT
creator UNSIGNED NOT NULL Foreign key references
INT SYSUSERPERM.user_id
domain_id UNSIGNED NOT NULL Foreign key references
INT SYSDOMAIN
nulls CHAR(1) NOT NULL
width UNSIGNED NOT NULL
INT
scale UNSIGNED NOT NULL
INT
type_name CHAR(128) NOT NULL Unique
"default" LONG NULL
VARCHAR
"check" LONG NULL
VARCHAR
format_str CHAR(128)
super_type_id UNSIGNED NULL Foreign key references
INT SYSUSERTYPE.type_id.

Each row holds a description of a user-defined data type.

type_id A unique identifying number for the user-defined data type.

creator The user number of the owner of the data type.

domain_id The data type on which this user defined data type is based,
indicated by a data type number listed in the SYSDOMAIN table.

nulls (Y/N) Indicates whether the user-defined data type allows nulls.

width The length of a string column, the precision of a numeric column, or


the number of bytes of storage for any other data type.

scale The number of digits after the decimal point for numeric data type
columns, and zero for all other data types.

type_name The name for the data type, which must be a valid identifier.

1018
Chapter 15 System Tables

default The default value for the data type.

check The CHECK condition for the data type.

format_str Currently unused.

1019
SYSUSERTYPE system table

1020
C H A P T E R 1 6

System Views

About this chapter This chapter lists predefined views for the system tables.
The system tables described in "System Tables" on page 961 use numbers to
identify tables, user IDs, and so forth. While this is efficient for internal use,
it makes these tables difficult for people to interpret. A number of predefined
system views are provided that present the information in the system tables
in a more readable format.
The definitions for the system views are included with their descriptions.
Some of these definitions are complicated, but need not be understood to use
the views. They serve as good examples of what can be accomplished using
the SELECT command and views.
Contents
Topic Page
SYSARTICLECOLS system view 1023
SYSARTICLES system view 1024
SYSCAPABILITIES system view 1025
SYSCATALOG system view 1026
SYSCOLAUTH system view 1027
SYSCOLUMNS system view 1028
SYSFOREIGNKEYS system view 1029
SYSGROUPS system view 1030
SYSINDEXES system view 1031
SYSOPTIONS system view 1032
SYSPROCAUTH system view 1033
SYSPROCPARMS system view 1034
SYSPUBLICATIONS system view 1035
SYSREMOTEOPTIONS system view 1036
SYSREMOTETYPES system views 1037
SYSREMOTEUSERS system view 1038

1021
SYSARTICLECOLS system view

SYSSUBSCRIPTIONS system view 1039


SYSTABAUTH system view 1040
SYSTRIGGERS system view 1041
SYSUSERAUTH system view 1042
SYSUSERLIST system view 1043
SYSUSEROPTIONS system view 1044
SYSUSERPERMS system view 1045
SYSVIEWS system view 1046
Views for Transact-SQL Compatibility 1047

1022
Chapter 16 System Views

SYSARTICLECOLS system view


CREATE VIEW SYS.SYSARTICLECOLS
AS SELECT (select publication_name FROM
SYS.SYSPUBLICATION AS p
WHERE p.publication_id=ac.publication_id) AS
publication_name,
(select table_name FROM SYS.SYSTABLE AS t
WHERE t.table_id=ac.table_id) AS table_name,
select column_name FROM SYS.SYSCOLUMN AS c
WHERE c.table_id=ac.table_id
AND c.column_id=ac.column_id) AS column_name
FROM SYS.SYSARTICLECOL AS ac
Presents a readable version of the table SYSARTICLECOL.

1023
SYSARTICLES system view

SYSARTICLES system view


CREATE VIEW SYS.SYSARTICLES
AS SELECT(select publication_name FROM
SYS.SYSPUBLICATION AS p
WHERE p.publication_id=a.publication_id) AS
publication_name,
(select table_name FROM SYS.SYSTABLE AS t
WHERE t.table_id=a.table_id) AS table_name,
where_expr,subscribe_by_expr
FROM SYS.SYSARTICLE AS a
Presents a readable version of the table SYSARTICLE.

1024
Chapter 16 System Views

SYSCAPABILITIES system view


CREATE VIEW SYS.SYSCAPABILITIES
AS
SELECT t1.capid,srvid,capname,capvalue
FROM
SYS.SYSCAPABILITY as t1
JOIN SYS.SYSCAPABILITYNAME as t2
ON t1.capid = t2.capid
Presents a readable version of the table SYSCAPABILITY and
SYSCAPABILITYNAME.

1025
SYSCATALOG system view

SYSCATALOG system view


CREATE VIEW SYS.SYSCATALOG ( creator,
tname, dbspacename, tabletype, ncols,
primary_key, "check", remarks )
AS
SELECT ( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSTABLE.creator ),
table_name,
( SELECT dbspace_name from SYS.SYSFILE
WHERE file_id = SYSTABLE.file_id ),
IF table_type=’BASE’ THEN ’TABLE’
ELSE table_type ENDIF,
( SELECT count(*) FROM SYS.SYSCOLUMN
WHERE table_id = SYSTABLE.table_id ),
IF primary_root = 0 THEN ’N’ ELSE ’Y’ ENDIF,
IF table_type <> VIEW’ THEN view_def ENDIF,
remarks
FROM SYS.SYSTABLE
Lists all the tables and views from SYSTABLE in a readable format.

1026
Chapter 16 System Views

SYSCOLAUTH system view


CREATE VIEW SYS.SYSCOLAUTH ( grantor, grantee,
creator, tname, colname )
AS
SELECT ( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSCOLPERM.grantor ),
( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSCOLPERM.grantee ),
( SELECT user_name
FROM SYS.SYSUSERPERM == SYS.SYSTABLE
WHERE table_id = SYSCOLPERM.table_id ),
( SELECT table_name FROM SYS.SYSTABLE
WHERE table_id = SYSCOLPERM.table_id ),
( SELECT column_name FROM SYS.SYSCOLUMN
WHERE table_id = SYSCOLPERM.table_id
AND column_id = SYSCOLPERM.column_id )
FROM SYS.SYSCOLPERM
Presents column update permission information in SYSCOLPERM in a more
readable format.

1027
SYSCOLUMNS system view

SYSCOLUMNS system view


CREATE VIEW SYS.SYSCOLUMNS ( creator, cname, tname,
coltype, nulls, length, syslength,
in_primary_key, "colno", default_value, column_kind,
remarks )
AS
SELECT ( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSTABLE.creator ),
column_name, table_name,
( SELECT domain_name FROM SYS.SYSDOMAIN
WHERE domain_id = SYSCOLUMN.domain_id ),
nulls, width, scale, pkey, column_id,
"default", column_type, SYSCOLUMN.remarks
FROM SYS.SYSCOLUMN JOIN SYS.SYSTABLE
Presents a readable version of the table SYSCOLUMN. (Note the S at the
end of the view name that distinguishes it from the SYSCOLUMN table.)

1028
Chapter 16 System Views

SYSFOREIGNKEYS system view


CREATE VIEW SYS.SYSFOREIGNKEYS ( foreign_creator,
foreign_tname, primary_creator,
primary_tname, role, columns )
AS
SELECT ( SELECT user_name FROM
SYS.SYSUSERPERM == SYS.SYSTABLE
WHERE table_id = foreign_table_id ),
( SELECT table_name FROM SYS.SYSTABLE
WHERE table_id = foreign_table_id ),
( SELECT user_name
FROM SYS.SYSUSERPERM == SYS.SYSTABLE
WHERE table_id = primary_table_id ),
( SELECT table_name FROM SYS.SYSTABLE
WHERE table_id = primary_table_id ), role,
( SELECT list( string( FK.column_name,
’ IS ’, PK.column_name ) )
FROM SYS.SYSFKCOL KEY JOIN
SYS.SYSCOLUMN FK, SYS.SYSCOLUMN PK
WHERE foreign_table_id =
SYSFOREIGNKEY.foreign_table_id
AND foreign_key_id =
SYSFOREIGNKEY.foreign_key_id
AND PK.table_id =
SYSFOREIGNKEY.primary_table_id
AND PK.column_id =
SYSFKCOL.primary_column_id )
FROM SYS.SYSFOREIGNKEY
Presents foreign key information from SYSFOREIGNKEY and SYSFKCOL
in a more readable format.

1029
SYSGROUPS system view

SYSGROUPS system view


CREATE VIEW SYS.SYSGROUPS ( group_name, member_name )
AS
SELECT g.user_name, u.user_name
FROM SYS.SYSGROUP,
SYS.SYSUSERPERM g,
SYS.SYSUSERPERM u
WHERE group_id = g.user_id
AND group_member = u.user_id
Presents group information from SYSGROUP in a more readable format.

1030
Chapter 16 System Views

SYSINDEXES system view


CREATE VIEW SYS.SYSINDEXES ( icreator, iname, fname,
creator,
tname, indextype, colnames, interval, level )
AS
SELECT ( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSINDEX.creator ),
index_name,
( SELECT file_name FROM SYS.SYSFILE
WHERE file_id = SYSINDEX.file_id ),
( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSINDEX.creator ),
table_name,
IF "unique" = ’Y’ THEN ’Unique’
ELSE ’Non-unique’ ENDIF,
( SELECT list( string( column_name,
IF "order" = ’A’ THEN ’ ASC’ i
ELSE ’ DESC’ ENDIF ) )
FROM SYS.SYSIXCOL == SYS.SYSCOLUMN
WHERE index_id = SYSINDEX.index_id ), 0, 0
FROM SYS.SYSTABLE KEY JOIN SYS.SYSINDEX
Presents index information from SYSINDEX and SYSIXCOL in a more
readable format.

1031
SYSOPTIONS system view

SYSOPTIONS system view


CREATE VIEW SYS.SYSOPTIONS ( user_name, "option",
"setting" )
AS
SELECT ( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSOPTION.user_id ),
"option", "setting"
FROM SYS.SYSOPTION
Presents option settings contained in the table SYSOPTION in a more
readable format.

1032
Chapter 16 System Views

SYSPROCAUTH system view


CREATE VIEW SYS.SYSPROCAUTH(grantee,
creator,procname)
AS
SELECT(select user_name FROM SYS.SYSUSERPERM
WHERE SYSPROCPERM.grantee=SYSUSERPERM.user_id),
(select user_name FROM SYS.SYSUSERPERM
WHERE SYSPROCEDURE.creator=SYSUSERPERM.user_id),
proc_name
FROM
SYS.SYSPROCEDURE JOIN SYS.SYSPROCPERM
Presents the procedure authorities from SYSUSERPERM in a more readable
format.

1033
SYSPROCPARMS system view

SYSPROCPARMS system view


CREATE VIEW SYS.SYSPROCPARMS ( creator, parmname,
procname,
parmtype, parmmode, parmdomain, length, remarks )
AS
SELECT ( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSPROCEDURE.creator ),
parm_name, proc_name, parm_type,
IF parm_mode_in = ’Y’ AND
parm_mode_out = ’N’ THEN ’IN’
ELSE IF parm_mode_in = ’N’
AND parm_mode_out = ’Y’ THEN ’OUT’
ELSE ’INOUT’ ENDIF ENDIF,
( SELECT domain_name FROM SYS.SYSDOMAIN
WHERE domain_id = SYSPROCPARM.domain_id ),
width, SYSPROCPARM.remarks
FROM SYS.SYSPROCPARM == SYS.SYSPROCEDURE
Presents the procedure parameters from SYSPROCPARM in a more
readable format.

1034
Chapter 16 System Views

SYSPUBLICATIONS system view


CREATE VIEW SYS.SYSPUBLICATIONS
AS
SELECT(select user_name FROM SYS.SYSUSERPERM AS u
WHERE u.user_id=p.creator) AS creator,
publication_name,remarks
FROM SYS.SYSPUBLICATION AS p
Presents the user name from the SYSUSERPERM table for all creators and
displays the publication name and remarks from the SYSPUBLICATION
table in a more readable format.

1035
SYSREMOTEOPTIONS system view

SYSREMOTEOPTIONS system view


CREATE VIEW SYS.SYSREMOTEOPTIONS
AS
SELECT type_name,
user_name,
"option",
setting
FROM SYS.SYSREMOTETYPE AS srt,
SYS.SYSREMOTEOPTIONTYPE AS srot,
SYS.SYSREMOTEOPTION AS sro,
SYS.SYSUSERPERM AS sup
WHERE srt.type_id = srot.type_id
AND srot.option_id = sro.option_id
AND sro.user_id = sup.user_id
Presents the data from SYSREMOTEOPTION and
SYSREMOTEOPTIONTYPE in a more readable format.

1036
Chapter 16 System Views

SYSREMOTETYPES system views


CREATE VIEW SYS.SYSREMOTETYPES
AS SELECT type_id,type_name,publisher_address,remarks
FROM SYS.SYSREMOTETYPE
Presents the procedure remote types from the SYSREMOTETYPES in a
more readable format.

1037
SYSREMOTEUSERS system view

SYSREMOTEUSERS system view


CREATE VIEW SYS.SYSREMOTEUSERS
AS SELECT(SELECT user_name FROM SYS.SYSUSERPERM AS u
WHERE u.user_id=r.user_id) AS user_name,
"consolidate",
(SELECT type_name FROM SYS.SYSREMOTETYPE AS t
WHERE t.type_id=r.type_id) AS type_name,
"address",frequency,send_time,
(IF frequency=’A’ THEN
NULL
ELSE
IF frequency=’P’ THEN
IF time_sent IS NULL THEN
current timestamp
ELSE
(SELECT min(minutes(time_sent,
60*hour(a.send_time)
+minute(seconds(a.send_time,59))))
FROM SYS.SYSREMOTEUSER AS a
WHERE a.frequency=’P’
AND a.send_time=r.send_time)
ENDIF
ELSE
IF current date+send_time
>COALESCE(time_sent,current timestamp) THEN
current date+send_time
ELSE
current date+send_time+1
ENDIF
ENDIF
ENDIF) AS next_send,
log_send,time_sent,log_sent,
confirm_sent,send_count,resend_count,
time_received,log_received,confirm_received,
receive_count,rereceive_count
FROM SYS.SYSREMOTEUSER AS r
Presents the information from SYSREMOTEUSER in a more readable
format.

1038
Chapter 16 System Views

SYSSUBSCRIPTIONS system view


CREATE VIEW SYS.SYSSUBSCRIPTIONS
AS
SELECT(select publication_name
FROM SYS.SYSPUBLICATION AS p
WHERE p.publication_id=s.publication_id) AS
publication_name,
(select user_name FROM SYS.SYSUSERPERM AS u
WHERE u.user_id=s.user_id) AS user_name,
subscribe_by,created,started
FROM SYS.SYSSUBSCRIPTION AS s
Presents subscription information, such as the publication name, creation
time, and start time from the SYSPUBLICATION table in a more readable
format.

1039
SYSTABAUTH system view

SYSTABAUTH system view


CREATE VIEW SYS.SYSTABAUTH ( grantor, grantee,
screator, stname, tcreator, ttname,
selectauth, insertauth, deleteauth,
updateauth, updatecols, alterauth, referenceauth )
AS
SELECT ( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSTABLEPERM.grantor ),
( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSTABLEPERM.grantee ),
( SELECT user_name
FROM SYS.SYSUSERPERM == SYS.SYSTABLE
WHERE table_id = SYSTABLEPERM.stable_id ),
( SELECT table_name FROM SYS.SYSTABLE
WHERE table_id = SYSTABLEPERM.stable_id ),
( SELECT user_name FROM
SYS.SYSUSERPERM == SYS.SYSTABLE
WHERE table_id = SYSTABLEPERM.ttable_id ),
( SELECT table_name FROM SYS.SYSTABLE
WHERE table_id = SYSTABLEPERM.ttable_id ),
selectauth, insertauth, deleteauth,
updateauth, updatecols,
alterauth, referenceauthauth
FROM SYS.SYSTABLEPERM
Presents table permission information from SYSTABLEPERM in a more
readable format.

1040
Chapter 16 System Views

SYSTRIGGERS system view


CREATE VIEW SYS.SYSTRIGGERS ( owner, trigname, tname,
event, trigtime, trigdefn )
AS
SELECT ( SELECT user_name FROM SYS.SYSUSERPERM
WHERE user_id = SYSTABLE.creator ),
trigger_name, table_name,
IF event = ’I’ THEN ’INSERT’
ELSE IF event = ’U’ THEN ’UPDATE’
ELSE IF event = ’C’ THEN ’UPDATE’
ELSE ’DELETE’ ENDIF ENDIF ENDIF,
IF trigger_time = ’B’ THEN ’BEFORE’
ELSE ’AFTER’ ENDIF,
trigger_defn
FROM SYS.SYSTRIGGER == SYS.SYSTABLE
WHERE foreign_table_id IS NULL
Lists all the triggers from SYSTRIGGER in a readable format.

1041
SYSUSERAUTH system view

SYSUSERAUTH system view


CREATE VIEW SYS.SYSUSERAUTH ( name, password,
resourceauth, dbaauth, scheduleauth, user_group )
AS
SELECT user_name, password, resourceauth,
dbaauth, scheduleauth, user_group
FROM SYS.SYSUSERPERM
Presents all the information in the table SYSUSERPERM except for user
numbers. Because this view shows passwords, this system view does not
have PUBLIC select permission. (All other system views have PUBLIC
select permission.)

1042
Chapter 16 System Views

SYSUSERLIST system view


CREATE VIEW SYS.SYSUSERLIST ( name, resourceauth,
dbaauth, scheduleauth, user_group )
AS
SELECT user_name, resourceauth,
dbaauth, scheduleauth, user_group
FROM SYS.SYSUSERPERM
Presents all of the information in SYSUSERAUTH except passwords.

1043
SYSUSEROPTIONS system view

SYSUSEROPTIONS system view


CREATE VIEW SYS.SYSUSEROPTIONS ( "user_name",
"option", "setting" )
AS
SELECT u.name, "option",
isnull( ( SELECT "setting"
FROM sys.sysoptions s
WHERE s.user_name = u.name
AND s."option" = o."option" ),
"setting" )
FROM SYS.SYSOPTIONS o, SYS.SYSUSERAUTH u
WHERE o.user_name = ’PUBLIC’
Presents permanent option settings that are in effect for each user. If a user
has no setting for an option, this view displays the public setting for the
option.

1044
Chapter 16 System Views

SYSUSERPERMS system view


CREATE VIEW SYS.SYSUSERPERMS
AS
SELECT user_id, user_name, resourceauth, dbaauth,
scheduleauth, user_group, remarks
FROM SYS.SYSUSERPERM
Contains exactly the same information as the table SYSUSERPERM, except
the password is omitted. All users have read access to this view, but only the
DBA has access to the underlying table (SYSUSERPERM).

1045
SYSVIEWS system view

SYSVIEWS system view


CREATE VIEW SYS.SYSVIEWS ( vcreator, viewname, viewtext
)
AS
SELECT user_name, table_name, view_def
FROM SYS.SYSTABLE KEY JOIN SYS.SYSUSERPERM
WHERE table_type = ’VIEW’
Lists views along with their definitions.

1046
Chapter 16 System Views

Views for Transact-SQL Compatibility


Adaptive Server Enterprise and Adaptive Server Anywhere have different
system catalogs, reflecting the different uses for the two products.
In Adaptive Server Enterprise, a single master database contains a set of
system tables, which information that applies to all databases on the server.
Many databases may exist within the master database, and each has
additional system tables associated with it.
In Adaptive Server Anywhere, each database exists independently, and
contains its own system tables. There is no master database that contains
system information on a collection of databases. Each server may run several
databases at a time, dynamically loading and unloading each database as
needed.
The Adaptive Server Enterprise and Adaptive Server Anywhere system
catalogs are different. The Adaptive Server Enterprise system tables and
views are owned by the special user dbo, and exist partly in the master
database, partly in the sybsecurity database, and partly in each individual
database; the Adaptive Server Anywhere system tables and views are owned
by the special user SYS and exist separately in each database.
To assist in preparing compatible applications, Adaptive Server Anywhere
provides a set of views owned by the special user dbo, which correspond to
the Adaptive Server Enterprise system tables and views. Where architectural
differences make the contents of a particular Adaptive Server Enterprise
table or view meaningless in a Adaptive Server Anywhere context, the view
is empty, containing just the column names and data types.
The following tables list the Adaptive Server Enterprise system tables and
their implementation in the Adaptive Server Anywhere system catalog. The
owner of all tables is dbo in each DBMS.
Tables existing in Table name Description Data?
each Adaptive
Server Enterprise sysalternates One row for each user mapped to a database user No
database syscolumns One row for each column in a table or view, and Yes
for each parameter in a procedure
syscomments One or more rows for each view, rule, default, Yes
trigger, and procedure, giving the SQL definition
statement
sysconstraints One row for each referential or check constraint No
associated with a table or column
sysdepends One row for each procedure, view, or table that No
is referenced by a procedure, view, or trigger

1047
Views for Transact-SQL Compatibility

Table name Description Data?


sysindexes One row for each clustered or nonclustered Yes
index, one row for each table with no indexes,
and an additional row for each table containing
text or image data.
syskeys One row for each primary, foreign, or common No
key; set by the user (not maintained by Adaptive
Server Enterprise)
syslogs Transaction log No
sysobjects One row for each table, view, procedure, rule, Contains
trigger default, log, or (in tempdb only) compatible
temporary object data only
sysprocedures One row for each view, rule, default, trigger, or No
procedure, giving the internal definition
sysprotects User permissions information No
sysreferences One row for each referential integrity constraint No
declared on a table or column
sysroles Maps server-wide roles to local database groups No
syssegments One row for each segment (named collection of No
disk pieces)
systhresholds One row for each threshold defined for the No
database
systypes One row for each system-supplied or user- Yes
defined data type
sysusermessages One row for each user-defined message Yes (this is
an Adaptive
Server
Anywhere
system table)
sysusers One row for each user allowed in the database Yes

Tables existing in Table name Description Data?


the Adaptive
Server Enterprise syscharsets One row for each character set or sort order No
master database sysconfigures One row for each user-settable configuration No
parameter
syscurconfigs Information about configuration parameters No
currently being used by the server
sysdatabases One row for each database on the server No

1048
Chapter 16 System Views

Table name Description Data?


sysdevices One row for each tape dump device, disk No
dump device, disk for databases, or disk
partition for databases
sysengines One row for each server currently online No
syslanguages One row for each language (except U.S. No
English) known to the server
syslocks Information about active locks No
sysloginroles One row for each server login that possesses a No
system-defined role
syslogins One row for each valid user account Yes
sysmessages One row for each system error or warning No
sysprocesses Information about server processes No
sysremotelogins One row for each remote user No
sysservers One row for each remote server No
syssrvroles One row for each server-wide role No
sysusages One row for each disk piece allocated to a No
database

Tables existing in Table name Description Data?


the Adaptive
sysaudits One row for each audit record No
Server Enterprise
sybsecurity sysauditoptions One row for each global audit option No
database

1049
Views for Transact-SQL Compatibility

1050
A P P E N D I X A

Database Performance and Connection


Properties

About this This appendix contains information and tables relating to database
Appendix performance monitoring and database connection parameters.
Contents
Topic Page
Database performance statistics 1052
Database properties 1060

1051
Database performance statistics

Database performance statistics


Adaptive Server Anywhere provides a set of statistics that can be used to
monitor database performance. These are accessible from Sybase Central,
and client applications can access the statistics as functions. In addition,
these statistics are made available by the server to the Windows NT
performance monitor.
This section describes how to access performance and related statistics from
client applications, how to monitor database performance using Sybase
Central, and how to monitor database performance using the Windows NT
performance monitor.

Performance Monitor statistics


The Windows NT performance monitor is an application for viewing the
behavior of objects such as processors, memory, and applications. Adaptive
Server Anywhere provides many statistics for the performance monitor to
display.
$ For information on how to use the Performance Monitor, see
"Monitoring database statistics from the Windows NT Performance Monitor"
on page 811 of the book ASA User’s Guide.
Adaptive Server Anywhere makes statistics available for Performance
Monitor. Rates are reported per second. The statistics are grouped into the
following areas:
♦ "Cache statistics" on page 1052
♦ "Checkpoint and recovery statistics" on page 1053
♦ "Communications statistics" on page 1054
♦ "Disk I/O statistics" on page 1055
♦ "Disk read statistics" on page 1055
♦ "Disk write statistics" on page 1056
♦ "Index statistics" on page 1057
♦ "Java VM statistics" on page 1057
♦ "Miscellaneous statistics" on page 1059
♦ "Memory pages statistics" on page 1058
♦ "Request statistics" on page 1058

Cache statistics These statistics describe the use of the cache.

1052
Appendix A Database Performance and Connection Properties

Statistic Scope Description


Cache Hits/sec Connection The rate at which database page lookups
are satisfied by finding the page in the
Database cache.
Cache Reads: Connection The rate at which index internal-node
Index Interior pages are read from the cache.
Database
Cache Reads: Connection The rate at which index leaf pages are
Index Leaf read from the cache.
Database
Cache Reads: Connection The rate at which table pages are read
Table from the cache.
Database
Cache Reads: Connection The rate at which database pages are
Total looked up in the cache.
Database
Cache Size: Engine The current size of the database server
Current cache, in kilobytes.
Cache Size: Engine The maximum allowed size of the
Maximum database server cache, in kilobytes.
Cache Size: Engine The minimum allowed size of the
Minimum database server cache, in kilobytes.
Cache Size: Peak Engine The peak size of the database server
cache, in kilobytes.

Checkpoint and These statistics isolate the checkpoint and recovery actions performed when
recovery statistics the database is in an idle state.

Statistic Scope Description


Checkpoint Database The rate at which ranges of adjacent
Flushes pages are written out during a checkpoint.
Checkpoint Log Database The rate at which the transaction log is
checkpointed.
Checkpoint Database Checkpoint Urgency, expressed as a
Urgency percentage.
Checkpoints Database The rate at which checkpoints are
performed.
Idle Actives Database The rate at which the engine’s idle thread
becomes active to do idle writes, idle
checkpoints, etc.
Idle Checkpoint Database The total time in seconds spent doing idle
Time checkpoints.

1053
Database performance statistics

Statistic Scope Description


Idle Checkpoints Database The rate at which checkpoints are
completed by the engine’s idle thread. An
idle checkpoint occurs whenever the idle
thread writes out the last dirty page in the
cache.
Idle Writes Database The rate at which disk writes are issued
by the engine’s idle thread.
Recovery IO Database The estimated number of IO operations
Estimate required to recover the database.
Recovery Urgency Database Recovery Urgency is expressed as a
percentage.
Server Idle Waits Server The number of times per second the
server goes idle waiting for IO
completion or a new request.

Communications These statistics describe client/server communications activity.


statistics
Statistic Scope Description
Comm: Server The total number of network buffer
Buffer Misses allocations exceeding the connection
buffer pool.
Comm: Server The rate at which network data (in bytes)
Bytes Received are received.
Comm: Server The rate at which bytes are transmitted
Bytes Sent over the network.
Comm: Server Number of free network buffers.
Free Buffers
Comm: Server The rate at which multi-packet deliveries
Multi-packets are received.
Received
Comm: Server The rate at which multi-packet deliveries
Multi-packets Sent are transmitted.
Comm: Server The rate at which corrupt network
Packets Corrupted packets are being received
Comm: Server The rate at which network packets are
Packets Dropped being dropped due to lack of buffer
space.
Comm: Server The rate at which network packets are
Packets Received received.
Comm: Server The rate at which duplicate network

1054
Appendix A Database Performance and Connection Properties

Statistic Scope Description


Packets Rereceived packets are received.
Comm: Server The rate at which network packets are
Packets Resent being retransmitted
Comm: Server The rate at which network packets are
Packets Sent transmitted.
Comm: Server The rate at which the communication link
Remoteput Waits must wait because it does not have
buffers available to send information.
This statistic is collected for NetBIOS
and IPX protocols only.
Comm: Server The rate at which the underlying
Send Fails protocol(s) failed to send a packet.
Comm: Server The total number of network buffers.
TotalBuffers

Disk I/O statistics These statistics combine disk reads and disk writes to give overall
information about the amount of activity devoted to disk I/O.

Statistic Scope Description


Disk: Active I/O Database The current number of file I/Os issued by
the engine which have not yet completed.
Disk: Maximum IO Database The maximum value "Disk Reads: Active
I/O" has reached.

Disk read statistics These statistics describe the amount and type of activity devoted to reading
information from disk.

1055
Database performance statistics

Statistic Scope Description


Disk Reads: Connection The rate at which pages are read from
Total Pages file.
Database
Disk Reads: Database The current number of file reads issued
Active by the engine which have not yet
completed.
Disk Reads: Connection The rate at which index internal-node
Index interior pages are being read from disk.
Database
Disk Reads: Connection The rate at which index leaf pages are
Index leaf being read from disk.
Database
Disk Reads: Connection The rate at which table pages are being
Table read from disk.
Database
Disk Reads: Database The maximum value "Disk Reads:
Maximum Active Active" has reached.

Disk write statistics These statistics describe the amount and type of activity devoted to reading
information from disk.

1056
Appendix A Database Performance and Connection Properties

Statistic Scope Description


Disk Writes: Database The current number of file writes issued
Active by the engine which are not yet
completed.
Disk Writes: Database The maximum value "Disk Writes:
Maximum Active Active" has reached.
Disk Writes: Database The rate at which the engine forces a
Commit Files flush of the disk cache. Windows NT and
NetWare platforms use unbuffered
(direct) I/O, so the disk cache does not
need to be flushed.
Disk Writes: Database The rate (in pages/sec) at which the
Extend Database database file is extended.
Disk Writes: Database The rate (in pages/sec) at which
Extend Temporary temporary files are extended.
File
Disk Writes: Connection The rate at which modified pages are
Pages being written to disk.
Database
Disk Writes: Connection The rate at which pages are written to the
Transaction log transaction log.
Database
Disk Writes: Connection Occurs when a commit of the transaction
Transaction Log log is requested but the log has already
Group Commits Database been written (so the commit was done for
"free").

Index statistics These statistics describe the use of the index.

Statistic Scope Description


Index: Connection The rate at which entries are added to
Adds indexes.
Database
Index: Connection The rate at which entries are looked up in
Lookups indexes.
Database
Index: Connection The rate at which comparisons beyond
Full compares the hash value in an index must be
Database performed.

Java VM statistics These statistics describe the memory used by the Java VM.

1057
Database performance statistics

Statistic Scope Description


JVM: Server The total bytes allocated to the Java VM
Global Fixed Size fixed heap.
JVM: Connection The total bytes allocated to connection
Heap Size Java VMs
Database
JVM: Database The total number of bytes allocated to the
Namespace size Java VM namespace.

Memory pages These statistics describe the amount and purpose of memory used by the
statistics database server.

Statistic Scope Description


Mem Pages: Server The number of heap pages locked in the
Locked Heap cache.
Mem Pages: Database The number of pages used to store lock
Lock Table information.
Mem Pages: Connection The number of pages in the rollback log.
Rollback Log
Database
Mem Pages: Server The number of pages used for global
Main Heap engine data structures.
Mem Pages: Database The number of map pages used for
Map Pages accessing the lock table, frequency table,
and table layout.
Mem Pages: Database The number of relocatable heap pages
Procedure used for procedures.
Definitions
Mem Pages: Database The number of pages used for relocatable
Relocatable heaps (cursors, statements, procedures,
triggers, views, etc.).
Mem Pages: Database The rate at which relocatable heap pages
Relocations are read from the temporary file.
Mem Pages: Database The number of relocatable heap pages
Trigger Definitions used for triggers.
Mem Pages: Database The number of relocatable heap pages
View Definitions used for views.

Request statistics These statistics describe the database server activity devoted to responding to
requests from client applications.

1058
Appendix A Database Performance and Connection Properties

Statistic Scope Description


Requests Server The rate at which the engine is entered to
allow it to handle a new request or
continue processing an existing request.
Requests: Server The number of engine threads currently
Active handling a request.
Requests: Server The number of requests are currently
Unscheduled queued up waiting for an available engine
thread.
Cursors Connection The number of declared cursors currently
maintained by the engine.
Cursors Open Connection The number of open cursors currently
maintained by the engine.
Statements Connection The number of prepared statements the
engine currently maintains.
Statement Prepares Connection The rate at which statement prepares are
being handled by the engine.
Transaction Connection The rate at which Commit requests are
Commits handled.
Transaction Connection The rate at which Rollback requests are
Rollbacks handled.

Miscellaneous Statistic Scope Description


statistics
Avail I/O Server Expressed as a count.
Context Switches Connection The rate at which the current engine
thread changes.
Main Heap Bytes Server The number of bytes used for global
engine data structures.
Request Queue Server The rate at which the engine must wait
Waits for room in the request queue.

1059
Database properties

Database properties
Adaptive Server Anywhere provides a set of properties that are made
available to client applications. These properties describe aspects of
connection, database and database server behavior.
Accessing Each type of property can be accessed by supplying its name as an argument
properties to a system function.

v To access connection properties:


♦ Use the connection_property system function: The following statement
returns the number of pages that have been read from file by the current
connection.
select connection_property ( ’DiskRead’ )

v To access database properties:


♦ Use the db_property system function: For example, the following
statement returns the page size of the current database:
select db_property ( ’PageSize’ )

v To access database server properties:


♦ Use the property system function: The following statement returns the
number of pages that have been read from file by the current connection.
select property ( ’MainHeapPages’ )

Connection-level properties

The following table lists properties available for each connection.


Examples
v To retrieve the value of a connection property:
♦ Use the connection_property system function: The following statement
returns the number of pages that have been read from file by the current
connection.
select connection_property ( ’DiskRead’ )

v To retrieve the values of all connection properties:


♦ Use the sa_conn_properties system procedure:
call sa_conn_properties

1060
Appendix A Database Performance and Connection Properties

A separate row is displayed for each connection.


Descriptions Property Description
Allow_nulls_by_default "ALLOW_NULLS_BY_DEFAULT option" on
page 157
Ansi_blanks "ANSI_BLANKS option" on page 157
Ansi_close_cursors_on_ro "ANSI_CLOSE_CURSORS_ON_ROLLBACK
llback option" on page 158
Ansi_Integer_Overflow "ANSI_INTEGER_OVERFLOW option" on
page 158
Ansi_permissions "ANSI_PERMISSIONS option" on page 158
Ansinull "ANSINULL option" on page 160
AppInfo "AppInfo connection parameter" on page 46
Automatic_timestamp "AUTOMATIC_TIMESTAMP option" on
page 161
Background_priority "BACKGROUND_PRIORITY option" on
page 162
BlockedOn If the current connection is not blocked this is zero.
If it is blocked, the connection number on which
the connection is blocked due to a locking conflict.
Blocking "BLOCKING option" on page 163
CacheHits The number of successful reads of the cache
CacheRead The number of database pages that have been
looked up in the cache.
CacheReadIndInt The number of index internal-node pages that have
been read from the cache.
CacheReadIndLeaf The number of index leaf pages that have been read
from the cache.
CacheReadTable The number of table pages that have been read
from the cache.
Chained "CHAINED option" on page 163
Checkpoint_time "CHECKPOINT_TIME option" on page 165
CIS_option Reserved
Cis_rowset_size Reserved
ClientLibrary Either CmdSeq for ODBC and Embedded SQL
connections, or TDS for JDBC and Open Client
connections.
Close_on_EndTrans "CLOSE_ON_ENDTRANS option" on page 165

1061
Database properties

Property Description
Commit The number of Commit requests that have been
handled.
CommLink The communication link for the connection. This
is one of the network protocols supported by
Adaptive Server Anywhere, or is local for a same-
machine connection.
CommProtocol Returns CmdSeq for Adaptive Server Anywhere
protocol (ODBC and Embedded SQL) or TDS for
Open Client and jConnect connections.
Continue_after_raiserror "CONTINUE_AFTER_RAISERROR option" on
page 167
Conversion_error "CONVERSION_ERROR option" on page 168
Cooperative_commit_time "COOPERATIVE_COMMIT_TIMEOUT option"
out on page 169
Cooperative_commits "COOPERATIVE_COMMITS option" on
page 168
CurrTaskSwitch The number of current request context switches.
Cursor The number of declared cursors that are currently
being maintained by the server.
CursorOpen The number of open cursors that are currently
being maintained by the server.
Date_format "DATE_FORMAT option" on page 169
Date_order "DATE_ORDER option" on page 171
DBNumber The ID number of the database.
Default_timestamp_incre "DEFAULT_TIMESTAMP_INCREMENT
ment option" on page 171
Delayed_commit_timeout "DELAYED_COMMIT_TIMEOUT option" on
page 172
Delayed_commite "DELAYED_COMMITS option" on page 172
DiskRead The number of pages that have been read from
disk.
DiskReadIndInt The number of index internal-node pages that have
been read from disk.
DiskReadIndLeaf The number of index leaf pages that have been read
from disk.
DiskReadTable The number of table pages that have been read
from disk.
DiskWrite The number of modified pages that have been

1062
Appendix A Database Performance and Connection Properties

Property Description
written to disk.
Divide_by_zero_error "DIVIDE_BY_ZERO_ERROR option" on
page 173
Escape_character "ESCAPE_CHARACTER option" on page 174
Extended_join_syntax "EXTENDED_JOIN_SYNTAX option" on
page 174
Fire_triggers "FIRE_TRIGGERS option" on page 175
Float_as_double "FLOAT_AS_DOUBLE option" on page 175
FullCompare The number of comparisons that have been
performed beyond the hash value in an index.
IndAdd The number of entries that have been added to
indexes.
IndLookup The number of entries that have been looked up in
indexes.
Java_heap_size "JAVA_HEAP_SIZE option" on page 182
Java_input_output "JAVA_INPUT_OUTPUT option" on page 182
Java_namespace_size "JAVA_NAMESPACE_SIZE option" on page 183
Java_page_buffer_size The page buffer size used by the Java VM
JavaHeapSize The heap size per Java VM
Language The locale language
LastIdle The number of ticks between requests.
LastReqTime The time at which the last request for the specified
connection started.
Lock_rejected_rows Reserved
LockName A 64-bit unsigned integer value representing the
lock for which a connection is waiting.
LogFreeCommit The number of Redo Free Commits. A "Redo Free
Commit" occurs when a commit of the transaction
log is requested but the log has already been
written (so the commit was done for "free").
Login_mode "LOGIN_MODE option" on page 183
Login_procedure "LOGIN_PROCEDURE option" on page 184
LogWrite The number of pages that have been written to the
transaction log.
Max_cursor_count "MAX_CURSOR_COUNT option" on page 184
Max_statement_count "MAX_STATEMENT_COUNT option" on

1063
Database properties

Property Description
page 186
Min_password_length "MIN_PASSWORD_LENGTH option" on
page 186
Name The name of the current connection.
Nearest_century "NEAREST_CENTURY option" on page 187
NodeAddress The node for the client in a client/server
connection.
Non_keywords "NON_KEYWORDS option" on page 187
Number The ID number of the connection.
On_tsql_error "ON_TSQL_ERROR option" on page 189
Optimization_goal Reserved
Optimization_level Reserved
Percent_as_comment "PERCENT_AS_COMMENT option" on page 192
Port An application-specific number for each client
machine, identifying the connection port.
Precision "PRECISION option" on page 193
Prefetch "PREFETCH option" on page 193
Prepares Number of statement preparations carried out.
PrepStmt The number of prepared statements currently being
maintained by the server.
Query_plan_on_open "QUERY_PLAN_ON_OPEN option" on page 194
Quoted_identifier "QUOTED_IDENTIFIER option" on page 195
Recovery_time "RECOVERY_TIME option" on page 195
Replicate_all "REPLICATE_ALL option" on page 196
ReqType A string for the type of the last request.
RI_Trigger_time "RI_TRIGGER_TIME option" on page 197
Rlbk The number of Rollback requests that have been
handled.
RollbackLogPages The number of pages in the rollback log
Row_counts "ROW_COUNTS option" on page 196
Scale "SCALE option" on page 198
SQL_flagger_error_level "SQL_FLAGGER_ERROR_LEVEL option" on
page 198
SQL_flagger_warning_lev "SQL_FLAGGER_WARNING_LEVEL option"

1064
Appendix A Database Performance and Connection Properties

Property Description
el on page 199
String_rtruncation "STRING_TRUNCATION option" on page 200
TaskSwitch The number of times the current server thread has
been changed.
Thread_count "THREAD_COUNT option" on page 200
Time_format "TIME_FORMAT option" on page 200
Timestamp_format "TIMESTAMP_FORMAT option" on page 201
Truncate_with_autocomm "TRUNCATE_WITH_AUTO_COMMIT option"
it on page 202
Tsql_hex_constant "TSQL_HEX_CONSTANT option" on page 203
Tsql_variables "TSQL_VARIABLES option" on page 204
UncommitOp The number of uncommitted operations
Userid The user ID for the connection.
Wait_for_commit "WAIT_FOR_COMMIT option" on page 205

Server-level properties
The following table lists properties that apply across the server as a whole.
Examples
v To retrieve the value of a server property:
♦ Use the property system function: For example: the following statement
returns the number of cache pages being used to hold the main heap:
select property ( ’MainHeapPages’)

v To retrieve the values of all server properties:


♦ Use the sa_eng_properties system procedure:
call sa_eng_properties

1065
Database properties

Descriptions Property Description


ActiveReq The number of server threads that are currently
handling a request.
AvailIIO Reserved
BufferMisses The total number of network buffer allocations
exceeding the connection buffer pool
BuildChange Reserved
BuildClient Reserved
BuildReproducible Reserved
BytesReceived The number of bytes received during client/server
communications.
BytesSent The number of bytes sent during client/server
communications.
CacheHits The number of database page lookups satisfied by
finding the page in the cache.
CacheHitsEng The number of database page lookups
CacheRead The number of database pages that have been looked
up in the cache.
CacheReadIndInt The number of index internal-node pages that have
been read from the cache.
CacheReadIndLeaf The number of index leaf pages that have been read
from the cache.
CacheReadTable The number of table pages that have been read from
the cache.
CacheReplacements The number of pages in the cache that have been
replaced.
CharSet The character set in use by the database server.
CheckpointUrgency The time that has elapsed since the last checkpoint, as a
percentage of the checkpoint time setting of the
database.
Chkpt The number of checkpoints that have been performed.
ChkptFlush The number of ranges of adjacent pages written out
during a checkpoint.
ChkptPage The number of transaction log checkpoints.
CommitFile The number of times the server has forced a flush of
the disk cache. On Windows NT and NetWare
platforms, the disk cache does not need to be flushed if
unbuffered (direct) IO is used.

1066
Appendix A Database Performance and Connection Properties

Property Description
CompanyName The name of the company owning this software.
ConnsDisabled Returns ON or OFF, to indicate the current setting of
the server option to disable new connections.

$ For information, see "sa_server_option system


procedure" on page 942.
CurrentCacheSize The current cache size, in kilobytes.
CurrIO The current number of file IOs that were issued by the
server but have not yet completed.
CurrRead The current number of file reads that were issued by
the server but have not yet completed.
CurrWrite The current number of file writes that were issued by
the server but have not yet completed.
DefaultCollation The collation that would be used for new databases, if
none is explicitly specified.
DiskRead The number of pages that have been read from disk.
DiskReadIndInt The number of index internal-node pages that have
been read from disk.
DiskReadIndLeaf The number of index leaf pages that have been read
from disk.
DiskReadTable The number of table pages that have been read from
disk.
DiskWrite The number of modified pages that have been written
to disk.
ExtendDB The number of pages by which the database file has
been extended.
ExtendTempWrite The number of pages by which temporary files have
been extended.
FreeBuffers The number of available network buffers.
FullCompare The number of comparisons that have been performed
beyond the hash value in an index.
IdleCheck The number of times that the server’s idle thread has
become active to do idle writes, idle checkpoints, and
so on.
IdleChkpt The number of checkpoints completed by the server’s
idle thread. An idle checkpoint occurs whenever the
idle thread writes out the last dirty page in the cache.
IdleChkTime The number of 100ths of a second spent checkpointing
during idle IO.

1067
Database properties

Property Description
IdleWrite The number of disk writes that have been issued by the
server’s idle thread.
IndAdd The number of entries that have been added to indexes.
IndLookup The number of entries that have been looked up in
indexes.
IOToRecover The estimated number of IO operations required to
recover the database.
IsNetworkServer Returns YES if connected to a network database
server, and NO if connected to a personal database
server.
IsRuntimeServer Returns YES if connected to the limited desktop
runtime database server, and NO otherwise.
JavaGlobFix Java VM global fixed size
JavaHeapSize Heap size per Java VM
JavaNSSize Java VM Namespace size
Language The locale language for the server
LegalCopyright The copyright string for the software.
LegalTrademarks Trademark information for the software.
LivenessTimeout The client liveness timeout default
LockedHeapPages The number of heap pages locked in the cache.
LockTablePages The number of pages used to store lock information
LogFreeCommit The number of Redo Free Commits. A "Redo Free
Commit" occurs when a commit of the transaction log
is requested but the log has already been written (so the
commit was done for "free").
LogWrite The number of pages that have been written to the
transaction log.
MainHeapBytes The number of bytes used for global server data
structures.
MainHeapPages The number of pages used for global server data
structures.
MapPages The number of map pages used for accessing the lock
table, frequency table, and table layout.
MaxCacheSize The maximum allowed cache size, in kilobytes.
MaxIO The maximum value that Curr IO has reached.
MaxRead The maximum value that Curr Read has reached.

1068
Appendix A Database Performance and Connection Properties

Property Description
MaxWrite The maximum value that Curr Write has reached.
Message The initial message displayed in the server window on
startup.
MinCacheSize The minimum allowed cache size, in kilobytes.
MultiPacketsReceived The number of multi-packet deliveries received during
client/server communications.
MultiPacketsSent The number of multi-packet deliveries sent during
client/server communications.
Name The name of the server.
PacketsCorrupted The number of packets corrupted during client/server
communications.
PacketsDropped The number of client/server communication packets
dropped.
PacketsReceived The number of client/server communication packets
received.
PacketsRereceived The number of duplicate client/server communication
packets received.
PacketsResent The number of client/server communication packets
resent.
PacketsSent The number of client/server communication packets
sent.
PageRelocations The number of relocatable heap pages that have been
read from the temporary file.
PeakCacheSize The largest value the cache has reached in the current
session, in kilobytes.
Platform The operating system on which the software is running.
ProcedurePages The number of relocatable heap pages that have been
used for procedures.
ProcessCPU Process CPU usage
ProcessCPUSystem Process CPU system usage
ProcessCPUUser Process CPU user usage
ProductName The name of the software.
ProductVersion The version of the software being run.
QuittingTime Shutdown time for the server. If none is specified, the
value is none.
RecoveryUrgency An estimate of the amount of time required to recover

1069
Database properties

Property Description
the database.
RelocatableHeapPages The number of pages used for relocatable heaps
(cursors, statements, procedures, triggers, views, etc.).
RemoteputWait The number of times the communication link has had
to wait because it does not have buffers available to
send information. This statistic is collected for
NetBIOS and IPX protocols only.
Req The number of times the server has been entered to
allow it to handle a new request or continue processing
an existing request.
RequestLogFile The name of the request-level logging filename. An
empty string is returned if there is no request level
logging.

$ For information, see "sa_server_option system


procedure" on page 942.
RequestLogging ALL, SQL, or NONE.

$ For information, see "sa_server_option system


procedure" on page 942.
RequestQueueWait The number of times the server has had to wait for
room in the request queue.
RollbackLogPages The number of pages in the rollback log.
SendFail The number of times that the underlying
communications protocols have failed to send a packet.
ServerIdleWaits The number of times the server has gone idle waiting
for IO completion or a new request.
TotalBuffers The total number of network buffers.
TriggerPages The number of relocatable heap pages used for
triggers.
UnschReq The number of requests that are currently queued up
waiting for an available server thread.
ViewPages The number of relocatable heap pages used for views.

Database-level properties
The following table lists properties available for each database on the server.

1070
Appendix A Database Performance and Connection Properties

v To retrieve the value of a database property:


Examples
♦ Use the db_property system function: For example, the following
statement returns the page size of the current database:
select db_property ( ’PageSize’)

v To retrieve the values of all database properties:


♦ Use the sa_db_properties system procedure:
call sa_db_properties

Descriptions Property Description


Alias The database name.
CharSet The character set of the database.
CheckpointUrgency The time that has elapsed since the last checkpoint, as
a percentage of the checkpoint time setting of the
database.
CurrentRedoPos The current offset in the transaction log file, where
the next database operation is to be logged.
ConnCount The number of connections to the database.
File The file name of the database root file, including path.
FileVersion The version of the database file. This does not
correspond to a software release version.
GlobalDBId The value of the GLOBAL_DATABASE_ID option
used to generate unique primary key values in a
replication environment.
IQStore Reserved
Language The locale language of the database
LogName The file name of the transaction log, including path.
LTMTrunc The minimal confirmed log offset for the Replication
Agent.
MultiByteCharSet ON if the database uses a multi-byte character set,
and OFF if the character set is single byte.
Name The database name (identical to alias).

1071
Database properties

Property Description
PageSize The page size of the database, in bytes.
ReadOnly ON if the database is being run in read-only mode.
OFF if the database is not being run in read-only
mode.
RecoveryUrgency An estimate of the amount of time required to recover
the database.
RemoteTrunc The minimal confirmed log offset for the
SQL Remote Message Agent.
SyncTrunc The minimal confirmed log offset for the MobiLink
client dbmlsync executable.

1072
Index

@@pack_received global variable, 241


@@pack_sent global variable, 241
@@packet_errors global variable, 241
@@procid global variable, 240, 241
– comment indicator, 246 @@rowcount global variable, 240, 241
@@servername global variable, 240, 241
@@spid global variable, 241
@@sqlstatus global variable, 240, 241
% @@textsize global variable, 241
% @@thresh_hysteresis global variable, 241
comment delimiter, 192 @@timeticks global variable, 241
modulo operator, 192 @@total_errors global variable, 241
% comment indicator, 246 @@total_read global variable, 241
% operator @@total_write global variable, 241
modulo function, 337 @@tranchained global variable, 241
@@trancount global variable, 241
@@transtate global variable, 241
@@version global variable, 240, 241
/
/* comment indicator, 246
// comment indicator, 246
[
[ESQL], 368
[Interactive SQL], 368
@ [SP], 368
@@char_convert global variable, 241 [TSQL], 368
@@client_csid global variable, 241
@@client_csname global variable, 241
@@connections global variable, 241
@@cpu_busy global variable, 241 >
@@error global variable, 240, 241 >> operator
@@identity global variable, 240, 241, 244 Java methods and fields, 223
@@idle global variable, 241
@@io_busy global variable, 241
@@isolation global variable, 240, 241
@@langid global variable, 241 2
@@language global variable, 241 2000
@@max_connections global variable, 241 NEAREST_CENTURY option, 187
@@maxcharlen global variable, 241 2000 compliance, 285
@@ncharsize global variable, 241
@@nestlevel global variable, 241

1073
A–A

ALTER WRITEFILE statement


A SQL syntax, 388
ABS function
altering
SQL syntax, 301
events, 375
Access
granting permissions, 526
TIMESTAMP comparison, 171
procedures, 377
ACOS function
remote server attributes, 378
SQL syntax, 301
tables, 380
actions
triggers, 386
referential integrity, 461
views, 387
ActiveReq property, 1065
write files, 388
adding
AND
indexes, 435
SQL logical operators, 214
Java classes, 542
ANSI
messages, 439
COMMIT behavior, 168, 172
servers, 451
conformance, 198
Agent connection parameter, 45
cursors, 158
aggregate functions
delete permissions, 158
SQL, 292
update permissions, 158
aggregate SQL functions, 292
UPDATE statement, 113
Alias property, 1070
variable behavior, 157
aliases
ANSI_BLANKS option, 152, 157
for columns, 588
Ansi_blanks property, 1061
in the DELETE statement, 482
ANSI_CLOSE_CURSORS_ON_ROLLBACK
ALL
option, 158
keyword in SELECT statement, 587
Ansi_close_cursors_on_roproperty, 1061
ALL conditions
ANSI_INTEGER_OVERFLOW option, 158
SQL syntax, 227
Ansi_Integer_Overflow property, 1061
ALLOCATE DESCRIPTOR statement
ANSI_PERMISSIONS option, 158
SQL syntax, 369
Ansi_permissions property, 1061
allocating
ANSI_PERMISSIONS Transact-SQL option
disk space, 373
setting, 593
memory for descriptor areas, 369
ANSI_UPDATE_CONSTRAINTS option, 159
ALLOW_NULLS_BY_DEFAULT option, 152, 157
ANSINULL option, 160
Allow_nulls_by_default property, 1061
Ansinull property, 1061
ALTER DATABASE statement
ANSINULL Transact-SQL option
SQL syntax, 371
setting, 593
ALTER DBSPACE statement
ANY conditions
SQL syntax, 373
SQL syntax, 227
ALTER EVENT statement
APC_pw parameter, 105
SQL syntax, 375
APC_user parameter, 105
ALTER PROCEDURE statement
apostrophes
SQL syntax, 377
in SQL strings, 212
ALTER SERVER statement
App connection parameter, 46
SQL syntax, 378
AppInfo connection parameter, 46
ALTER TABLE statement
AppInfo property, 1061
SQL syntax, 380
approximate data types
ALTER TRIGGER statement
about, 256
SQL syntax, 386
archives
ALTER VIEW statement
creating database backups, 389
SQL syntax, 387
restoring databases from, 577

1074
B–B

ARGN function automatic joins


SQL syntax, 302 and foreign keys, 929
arithmetic operators SELECT statement, 588
SQL syntax, 214 AUTOMATIC_TIMESTAMP option, 152, 161
articles Automatic_timestamp property, 1061
system table for, 967, 968 AutoStart connection parameter, 47
asademo.db file AutoStop connection parameter, 47
about, xvi AvailIIO property, 1065
asany.ini AVG function
location, 5 SQL syntax, 304
ASCII
collating sequences, 96
ASCII file format, 177, 190
ASCII function B
SQL syntax, 302 background processing
ASIN function interval, 30
SQL syntax, 302 BACKGROUND_PRIORITY option, 149, 162
assertion failed error, 904 Background_priority property, 1061
assigning BACKUP statement
logins for remote servers, 430 SQL syntax, 389
values to SQL variables, 591 backup utilities
AStart connection parameter, 47 options, 75
ASTMP environment variable, 6 backups
AStop connection parameter, 47 connection parameters, 75
asynchronous procedures creating, 389
user ID for, 105 creating events for, 423
AT clause database only, 76
create existing table, 429 live, 76
ATAN function options, 75
SQL syntax, 303 rename and start new transaction log, 76
ATAN2 function restoring databases from, 577
SQL syntax, 303 utility, 74
ATN2 function base tables
SQL syntax, 303 creating, 454
attributes batch files
altering remote server, 378 starting servers, 117
auditing batch_ltl_cmds parameter, 105
adding comments, 935 batch_ltl_mem parameter, 105
controlling, 160 batch_ltl_sz parameter, 105
AUDITING option, 149, 160 beep, 162
auto_commit BEGIN DELCARE statement
setting Interactive SQL options, 599 SQL syntax, 473
AUTO_COMMIT BEGIN keyword, 393
Interactive SQL option, 161 BEGIN statement
AUTO_REFETCH SQL syntax, 392
Interactive SQL option, 161 BEGIN TRANSACTION statement
autoincrement SQL syntax, 395
about, 455 beginning
AUTOINCREMENT user-defined transactions, 395
@@identity, 244 bell
Interactive SQL option, 162

1075
C–C

BETWEEN conditions BYE statement


SQL syntax, 227 SQL syntax, 506
BIGINT data type BYTE_LENGTH function
about, 256 SQL syntax, 304
binary data BYTE_SUBSTR function
getting from columns, 521 SQL syntax, 305
BINARY data type BytesReceived property, 1065
about, 272 BytesSent property, 1065
binary data types, 272
binary large objects
getting from columns, 521
bind variables C
describing cursors, 486 cache
EXECUTE SQL statement, 500 database server options, 17
OPEN statement, 557 flushing, 940
BINSEARCH communication parameter, 66 size, 17
BIT data type, 264 cache buffers
bitwise operators performance, 21, 22, 23
SQL syntax, 215 cache size
blanks limiting, 22, 23
ANSI behavior, 157 setting, 21
BLOB_THRESHOLD static, 22
replication option, 162 CacheHits property, 1061, 1065
blobs CacheHitsEng property, 1065
GET DATA SQL statement, 521 CacheRead property, 1061, 1065
BLOBS CacheReadIndInt property, 1061, 1065
exporting, 956 CacheReadIndLeaf property, 1061, 1065
inserting, 954 CacheReadTable property, 1061, 1065
block fetches CacheReplacements property, 1065
FETCH statement, 511 CALL statement
OPEN statement, 557 in Transact-SQL, 502
BlockedOn property, 1061 SQL syntax, 398
blocking calling
identifying, 936 procedures, 398
BLOCKING option, 149, 163 capabilities
Blocking property, 1061 remote servers, 969, 970
BREAK statement CASCADE, 461
Transact-SQL syntax, 631 CASE expression
B-tree, 981, 1009 NULLIF function, 341
buffer space SQL syntax, 221
connection parameter, 49 case sensitivity, 93
BufferMisses property, 1065 and SQL LIKE conditions, 229
BuildChange property, 1065 connection parameters, 44
BuildClient property, 1065 in the catalog, 986
BuildReproducible property, 1065 of Java data types, 279
bulk loading of tables, 546 SQL comparison operators, 213
bulk operations CASE statement
-b command-line option, 20 SQL syntax, 400
unload, 618 CAST function, 281
unloading tables, 619 SQL syntax, 306

1076
C–C

catalog CHECK CONSTRAINTS option


diagram, 963 LOAD TABLE statement, 548
system tables, 962 CHECK ON COMMIT clause
system tables list, 965 referential integrity, 461
catalog procedures checkpoint logs
sp_column_privileges, 958 CHECKPOINT SQL statement, 402
sp_columns, 958 CHECKPOINT statement
sp_fkeys, 958 SQL syntax, 402
sp_pkeys, 958 CHECKPOINT_TIME option, 149, 165
sp_special_columns, 958 Checkpoint_time property, 1061
sp_sproc_columns, 958 checkpointing
sp_stored_procedures, 958 databases, 402
sp_tables, 958 checkpoints
Transact-SQL list, 957 CHECKPOINT_TIME option, 165
Transact-SQL, list, 958 interval between, 25
Catalog procedures CheckpointUrgency property, 1065, 1070
list, 935 Chkpt property, 1065
CBSize connection parameter, 48 ChkptFlush property, 1065
CBSpace connection parameter, 49 ChkptPage property, 1065
CD-ROM CIS_ ROWSET_SIZE option
deployment, 33 about, 165
CEILING function CIS_option property, 1061
SQL syntax, 306 Cis_rowset_size property, 1061
century issues, 285 classes
CHAINED option, 163 installing Java, 542
Chained property, 1061 Java methods, 294
chained transaction mode, 163, 395 partially supported, 278
changing removing Java, 575
passwords, 526 supported, 276
CHAR data type unsupported, 277
about, 253 CLEAR statement
and host variables, 157 SQL syntax, 403
CHAR function clearing
SQL syntax, 307 the Interactive SQL window, 403
CHAR_LENGTH function CLIB.NLM, 18
SQL syntax, 308 ClientLibrary property, 1061
CHAR_OEM_TRANSLATION option, 164 ClientPort communication parameter, 61
character set translation clients
enabling, 23 identifying, 46
character sets CLOSE ON ENDTRAN Transact-SQL option
connection parameter, 48 setting, 593
storage, 252 CLOSE statement
CHARACTER VARYING data type SQL syntax, 404
about, 253 CLOSE_ON_ENDTRANS option, 165
CHARINDEX function Close_on_EndTrans property, 1061
SQL syntax, 307 closing
CharSet connection parameter, 48 connections, 494
CharSet property, 1065, 1070 cursors, 404
CHECK conditions Interactive SQL, 506
about, 458 COALESCE function
SQL syntax, 308

1077
C–C

code pages command-line utilities


and data storage, 252 dbbackup syntax, 75
CREATE DATABASE statement, 417 dbcollat syntax, 78
list, 96 dbconsol syntax, 83
Code pages dbdsn syntax, 84
SYSCOLLATION system table, 971 dberase syntax, 89
col_length Adaptive Server Enterprise function, 298 dbexpand syntax, 124
col_name Adaptive Server Enterprise function, 298 dbinfo syntax, 90
collation sequences dbinit syntax, 93
and SQL LIKE conditions, 229 dbisql syntax, 99
CREATE DATABASE statement, 417 dblic syntax, 101
dbcollat command-line syntax, 78 dblocate syntax, 116
list, 96 dblog syntax, 120
utility, 78 dbltm syntax, 103
Collation sequences dbping syntax, 114
SYSCOLLATION system table, 971 dbshrink syntax, 81
column long names, 488 dbspawn syntax, 117
column names dbstop syntax, 118
SQL syntax, 219 dbtran syntax, 109
columns dbunload syntax, 127
aliases, 588 dbupgrad syntax, 134
altering, 380 dbvalid syntax, 137
and domains, 275 dbwrite syntax, 140
and user-defined data types, 275 rebuild syntax, 115
changing heading name, 588 commands
constraints, 275, 458 executing operating system, 613
getting binary data from, 521 CommBufferSize connection parameter, 48
in the system tables, 974 CommBufferSpace connection parameter, 49
naming, 366 COMMENT statement
permissions on, 973 SQL syntax, 406
renaming, 384 comments
SYSCOLUMNS system view, 1028 comment delimiters, 192
updating without logging, 632 database objects, 406
combining SQL syntax, 246
the result of multiple select statements, 617 commit
comma delimited files, 177, 190 preparing for two-phase, 566
command delimiter Commit property, 1061
setting, 166 COMMIT statement
command echo, 174 referential integrity, 935
command files SQL syntax, 408
parameters for Interactive SQL, 563 COMMIT_ON_EXIT
reading SQL statements from, 572 Interactive SQL option, 166
command line CommitFile property, 1065
database server, 14 commits
in configuration file, 19 COOPERATIVE_COMMIT_TIMEOUT option,
server, 19 169
switches, 19 COOPERATIVE_COMMITS option, 168
command-line options DELAYED_COMMIT_TIMEOUT option, 172
dblocate, 116 DELAYED_COMMITS option, 172
dbping, 114 committing
overriding, 942 transactions, 408

1078
C–C

CommLink property, 1061 compound statements, 393


CommLinks connection parameter, 50 about, 392
CommProtocol property, 1061 compressed databases, 124
communication parameters compressing with dbshrink, 81
about, 43 creating, 414
ClientPort, 61 uncompressing, 124
DLL, 63 compressing
DOBROADCAST, 62 database files with dbshrink, 81
EXTENDEDNAME, 63 compression utility, 81
HOST, 64 concatenating strings
MAXLANA, 64 SQL string operators, 215
MYIP, 65 concurrency
ReceiveBufferSize, 66 locking tables, 551
REGISTERBINDERY, 66 conditions
SEARCHBINDERY, 66 SQL search conditions, 226
SendBufferSize, 66 configuration file
ServerPort, 66 for the LTM, 105
SESSIONS, 67 LTM command line, 103
TDS, 68 switch, 19
THREADS, 68 CONFIGURE statement
THREADSTATS, 68 SQL syntax, 410
TIMEOUT, 69 ConnCount property, 1070
UseUDP, 69 CONNECT authority
communications granting permissions, 526
database server, 37 CONNECT statement
debugging, 39 SQL syntax, 411
parameters, 61 connecting
communications parameters creating events for, 423
CommLinks, 50 firewalls, 61, 69
CompanyName property, 1065 to databases, 411
comparing connection parameters
TIMESTAMP, 171 about, 43
comparing dates and times, 267 case insensitivity, 44
comparison operators CharSet, 48
SQL syntax, 213 overview, 44
Transact-SQL compatibility, 213 connection properties
comparisons Allow_nulls_by_default, 1061
DATE data type, 202 Ansi_blanks, 1061
SQL search conditions, 226 Ansi_close_cursors_on_r, 1061
compatibility Ansi_Integer_Overflow, 1061
ANSI, 151 Ansi_permissions, 1061
datetime, 265 Ansinull, 1061
QUERY_PLAN_ON_OPEN, 194 AppInfo, 1061
SQL/92, 151 Automatic_timestamp, 1061
Transact-SQL, 151 Background_priority, 1061
Transact-SQL comparison operators, 213 BlockedOn, 1061
Transact-SQL expressions, 223 Blocking, 1061
Transact-SQL expressions and QUOTED CacheHits, 1061
IDENTIFIER option, 224 CacheRead, 1061
Transact-SQL global variables, 239 CacheReadIndInt, 1061
Transact-SQL local variables, 237 CacheReadIndLeaf, 1061

1079
C–C

CacheReadTable, 1061 Login_procedure, 1061


Chained, 1061 LogWrite, 1061
Checkpoint_time, 1061 Max_cursor_count, 1061
CIS_option, 1061 Max_statement_count, 1061
Cis_rowset_size, 1061 Min_password_length, 1061
ClientLibrary, 1061 Name, 1061
Close_on_EndTrans, 1061 Nearest_century, 1061
Commit, 1061 NodeAddress, 1061
CommLink, 1061 Non_keywords, 1061
CommProtocol, 1061 Number, 1061
Continue_after_raiserror, 1061 On_tsql_error, 1061
Conversion_error, 1061 Optimization_goal, 1061
Cooperative_commit_ti, 1061 Optimization_level, 1061
Cooperative_commits, 1061 Percent_as_comment, 1061
CurrTaskSwitch, 1061 Port, 1061
Cursor, 1061 Precision, 1061
CursorOpen, 1061 Prefetch, 1061
Date_format, 1061 Prepares, 1061
Date_order, 1061 PrepStmt, 1061
DBNumber, 1061 Query_plan_on_open, 1061
Default_timestamp_inc, 1061 Quoted_identifier, 1061
Delayed_commit_timeout, 1061 Recovery_time, 1061
Delayed_commite, 1061 Replicate_all, 1061
DiskRead, 1061 ReqType, 1061
DiskReadIndInt, 1061 RI_Trigger_time, 1061
DiskReadIndLeaf, 1061 Rlbk, 1061
DiskReadTable, 1061 RollbackLogPages, 1061
DiskWrite, 1061 Row_counts, 1061
displaying, 935 Scale, 1061
Divide_by_zero_error, 1061 SQL_flagger_error_level, 1061
e, 1061 SQL_flagger_warning_l, 1061
Escape_character, 1061 String_rtruncation, 1061
Extended_join_syntax, 1061 TaskSwitch, 1061
Fire_triggers, 1061 Thread_count, 1061
Float_as_double, 1061 Time_format, 1061
FullCompare, 1061 Timestamp_format, 1061
i, 1061 Truncate_with_autoco, 1061
IndAdd, 1061 Tsql_hex_constant, 1061
IndLookup, 1061 Tsql_variables, 1061
Java_heap_size, 1061 UncommitOp, 1061
Java_input_output, 1061 Userid, 1061
Java_namespace_size, 1061 Wait_for_commit, 1061
Java_page_buffer_size, 1061 connection_property function
JavaHeapSize, 1061 about, 145
Language, 1061 CONNECTION_PROPERTY function
LastIdle, 1061 SQL syntax, 309
LastReqTime, 1061 connection-level variables
Lock_rejected_rows, 1061 SQL syntax, 238
LockName, 1061 ConnectionName connection parameter, 51
LogFreeCommit, 1061
Login_mode, 1061

1080
C–C

connections CONVERT FUNCTION, 281


creating events for failed, 423 converting ambiguous dates, 287
dropping, 34, 35, 494 COOPERATIVE_COMMIT_TIMEOUT option,
dropping in Interactive SQL, 490 149, 169
enabling pooling, 601 Cooperative_commit_timproperty, 1061
limit, 28 COOPERATIVE_COMMITS option, 149, 168
liveness, 35 Cooperative_commits property, 1061
parameters, 43 copyright
properties, 1060 retrieving, 953
setting, 594 correlation names
troubleshooting, 114, 116 in the DELETE statement, 482
ConnsDisabled property, 1065 COS function
console SQL syntax, 311
displaying messages on, 554 COT function
console utility SQL syntax, 312
command-line syntax, 83 COUNT function
constants SQL syntax, 312
SQL strings, 212 CPU
SQL syntax, 219 number used, 29
Transact-SQL, 224 CREATE COMPRESSED DATABASE statement
constraints SQL syntax, 414
ALTER TABLE statement, 382 CREATE DATABASE statement
column, 458 SQL syntax, 415
CONTINUE statement CREATE DATATYPE statement
Transact-SQL syntax, 631 SQL syntax, 421
CONTINUE_AFTER_RAISERROR option, 167 CREATE DBSPACE statement
RAISERROR statement, 570 SQL syntax, 419
Continue_after_raiserror property, 1061 CREATE DOMAIN statement
control statements SQL syntax, 421
CALL SQL statement, 398 using, 274
CASE SQL statement, 400 CREATE EVENT statement
GOTO Transact-SQL statement, 525 SQL syntax, 423
IF SQL statement, 531 create existing table statement
LEAVE SQL statement, 544 proxy tables, 946, 947
LOOP SQL statement, 553 CREATE EXISTING TABLE statement
Transact-SQL BREAK statement, 631 proxy tables, 495
Transact-SQL CONTINUE statement, 631 SQL syntax, 428
Transact-SQL IF statement, 533 CREATE EXPANDED DATABASE statement
Transact-SQL WHILE statement, 631 SQL syntax, 414
WHILE SQL statement, 553 CREATE EXTERNLOGIN statement
conventions SQL syntax, 430
documentation, xiii CREATE FUNCTION statement
SQL language syntax, 207 SQL syntax, 432
conversion CREATE INDEX statement
strings to dates, 265 SQL syntax, 435
conversion functions table use, 435
data type SQL, 292 CREATE MESSAGE statement
CONVERSION_ERROR option, 152, 168 Transact-SQL syntax, 439
Conversion_error property, 1061 CREATE PROCEDURE statement
CONVERT function SQL syntax, 440
SQL syntax, 310 Transact-SQL syntax, 447

1081
D–D

CREATE SCHEMA statement creator, 366


SQL syntax, 449 CROSS JOIN
CREATE SERVER statement SQL syntax, 518
SQL syntax, 451 CS connection parameter, 48
CREATE TABLE CURRENT DATE
Java classes, 280 SQL special value, 234
create table statement CURRENT PUBLISHER
remote tables, 454 SQL special value, 235
CREATE TABLE statement CURRENT TIME
examples, 962 SQL special value, 234
SQL syntax, 453 CURRENT TIMESTAMP
Transact-SQL, 461 SQL special value, 234
CREATE TRIGGER statement CURRENT USER
SQL syntax, 464 environment settings, 10
Transact-SQL syntax, 467 SQL special value, 235
CREATE VARIABLE statement CurrentCacheSize property, 1065
SQL syntax, 468 CurrIO property, 1065
CREATE VIEW statement CurrRead property, 1065
examples, 1021 CurrTaskSwitch property, 1061
SQL syntax, 469 CurrWrite property, 1065
CREATE WRITEFILE statement Cursor property, 1061
SQL syntax, 471 CursorOpen property, 1061
creating cursors
backups of databases, 389 and transactions, 165
compressed databases, 414 closing, 165, 404
cursors, 475 connection limits, 184
cursors in Transact-SQL, 480 database options, 145
data types, 274 declaring, 475
database fiels, 419 declaring in Transact-SQL, 480
databases, 92, 415 deleting rows from, 484
databases with dbinit, 93 describing, 486
domains, 274, 421 EXPLAIN statement syntax, 507
functions, 432 fetching rows from, 509
indexes, 435 inserting rows using, 568
local temporary tables, 481 looping over, 514
messages, 439 opening, 194, 556
ODBC data sources with dbdsn, 84 preparing statements, 564
proxy tables, 428, 454 ROLLBACK, 158
savepoints, 586 curunreservedpgs Adaptive Server Enterprise
schemas, 449 function, 298
servers, 451 cxmp directory
SQL variables, 468, 474 about, 3
stored procedures, 440
stored procedures in Transact SQL, 447
tables, 453
triggers, 464 D
triggers in Transact-SQL, 467 daemon
views, 469 LTM, 105
write files, 471 Replication Agent, 105
Creating running the server as, 36
proxy tables, 453, 947

1082
D–D

data database options


exporting from tables into files, 559 alphabetical list, 157
importing into tables from files, 536 cursors, 145
selecting rows, 587 DATE_ORDER, 268
data access plans duration, 145
getting text specification, 507 initial settings, 147, 945, 948
data sources QUOTED_IDENTIFIER and Transact-SQL
creating ODBC with dbdsn, 84 compatibility, 224
data type conversion Transact-SQL compatibility, 948
about, 281 database pages
errors, 168 displaying size of, 90
Java-to-SQL, 282 database properties
SQL-to-Java, 283 about, 1060
data types, 1005 Alias, 1070
about, 251 CharSet, 1070
and roundoff errors, 256 CheckpointUrgency, 1070
binary, 272 ConnCount, 1070
bit, 264 displaying, 935
character, 252 File, 1070
compatibility, 265 FileVersion, 1070
converting Java and SQL, 282 GlobalDBId, 1070
creating, 421 IQStore, 1070
date, 265 Language, 1070
dropping user-defined, 491 LogName, 1070
in the system tables, 976, 1018 MultiByteCharSet, 1070
Java class, 276 Name, 1070
money, 263 PageSize, 1070
numeric, 256 ReadOnly, 1070
SQL conversion functions, 292 RecoveryUrgency, 1070
time, 265 database schema
user-defined, 1018 about, 962
user-defined domains, 274 database server
data types in system tables, 977, 978 command line, 14
data_pgs Adaptive Server Enterprise function, 298 command-line options, 942
database files name, 31
compressing with dbshrink, 81 NetWare, 18
dropping, 493 shutting down, 36
erasing, 88 database servers
maximum size, 932 preventing from starting, 47
NDS, 18 starting, 606
paths, 18 stopping, 59, 610
storing indexes in, 436 database size
UNC filenames, 18 limit, 932
uncompressing, 124 DatabaseFile connection parameter, 52
database information DatabaseName connection parameter, 53
getting with dbinfo, 90 databases
database name automatic stopping, 24
setting, 42 backing up, 389
database objects checkpointing, 402
comments, 406 compressed, 124
connecting to, 411

1083
D–D

creating, 92, 415 date to string conversions, 288


creating compressed, 414 DATE_FORMAT option, 149, 169
creating files, 419 Date_format property, 1061
creating with dbinit, 93 DATE_ORDER option, 149, 171, 268
dropping files, 493 and ODBC, 268
erasing, 88 Date_order property, 1061
files, 979 DATEADD function
information, 90 SQL syntax, 314
initializing, 92 DATEDIFF function
loading bulk data into, 546 SQL syntax, 314
maximum size, 932 DATEFORMAT function
page usage, 90 SQL syntax, 316
permissions to load, 27 DATENAME function
permissions to start, 25 SQL syntax, 316
permissions to stop, 27 DATEPART function
permissions to unload, 27 SQL syntax, 317
properties of, 1070 dates, 265
read-only, 33 ambiguous string conversions, 287, 288
rebuilding, 115 comparing, 267
restoring from archives, 577 conversion problems, 288
schema, 962 converting from strings, 265
starting, 604 inserting, 269
stopping, 118, 609 interpretation, 269
structure, 962 interpreting strings as dates, 267
system procedures, 933 queries, 266
system tables, 962 retrieving, 269
unloading, 126 sending to the database, 265
unloading data, 618 SQL conversion functions, 292
unloading tables, 619 time values in, 202
upgrading, 133, 371 unambiguous specification of, 267
validating, 136, 945 year 2000, 285
write files, 139 datetime
databases options definition, 292
setting in Transact-SQL, 593 DATETIME function
DatabaseSwitches connection parameter, 53 SQL syntax, 317
datalength Adaptive Server Enterprise function, 298 DAY function
DATALENGTH function SQL syntax, 318
SQL syntax, 313 DAYNAME function
DataSourceName connection parameter, 53 SQL syntax, 318
DATE data type DAYS function
about, 269 SQL syntax, 318
DATE data types db_id Adaptive Server Enterprise function, 298
time values in, 202 DB_ID function
date format SQL syntax, 319
database option, 169 db_name Adaptive Server Enterprise function, 298
DATE function DB_NAME function
SQL syntax, 313 SQL syntax, 320
date functions DB_PROPERTY function
SQL, 292 SQL syntax, 320
date order
database option, 171

1084
D–D

DBA authority dbping command-line utility


granting permissions, 526 syntax, 114
in the system tables, 1016 DBS connection parameter, 53
dBASE file format, 177, 190 dbshrink, 82
dbbackup, 75 dbshrink command-line utility
dbbackup command-line utility syntax, 81
syntax, 75 DBSize event condition
dbcc function, 122 about, 323
dbcollat command-line utility DBSPACE
syntax, 78 SYSFILE system table, 979
dbconsol command-line utility dbspaces
syntax, 83 limit, 932
dbdsn command-line utility DBSPACEs
syntax, 84 altering, 373
dbeng7 creating, 419
command line, 14 dropping, 491
dberase dbspawn command-line utility
about, 88 syntax, 117
dberase command-line utility dbsrv7
syntax, 89 command line, 14
dbexpand command-line utility dbstop command-line utility
syntax, 124 syntax, 118
DBF connection parameter, 52 dbstop utility
DBFreePercent event condition permissions, 27
about, 323 dbtran
DBFreeSpace event condition command line, 110
about, 323 dbtran command-line utility
DBG connection parameter, 54 syntax, 109
dbinfo command-line utility dbunload command-line utility
syntax, 90 syntax, 127
dbinit command-line utility dbupgrad command-line utility
syntax, 93 syntax, 134
dbisql command-line utility dbvalid command-line utility
syntax, 99 syntax, 137
dblgen7.res dbwrite command-line utility
locating, 4 syntax, 140
dblic command-line utility deadlock
syntax, 101 identifying, 936
dblocate command-line utility troubleshooting, 941
syntax, 116 DEALLOCATE DESCRIPTOR statement
dblog SQL syntax, 472
command line, 121 deallocating
dblog command-line utility descriptor areas, 472
syntax, 120 Debug connection parameter, 54
dbltm command-line utility DECIMAL data type
syntax, 103 about, 257
DBN connection parameter, 53 decimal precision
DBNumber property, 1061 database option, 193
dbo user DECLARE CURSOR statement
system objects, 126 SQL syntax, 475
Transact-SQL syntax, 480

1085
D–D

DECLARE LOCAL TEMPORARY TABLE deletes


statement ANSI behavior, 158
SQL syntax, 481 Transact-SQL permissions, 158
DECLARE statement deleting
compound statements, 393 all rows from a table, 615
SQL syntax, 392, 474 database files, 493
Transact-SQL compatibility, 393 DBSPACEs, 491
declaring domains, 491
cursors, 475 events, 491
cursors in Transact-SQL, 480 functions, 491
host variables in embedded SQL, 473 granting permissions, 526, 581
variables SQL, 474 indexes, 491
DEFAULT TIMESTAMP columns, 457 Java classes, 575
default values optimizer statistics, 496
SQL CURRENT DATE, 234 prepared statements, 498
SQL CURRENT PUBLISHER, 235 procedures, 491
SQL CURRENT TIME, 234 rows, 482
SQL CURRENT TIMESTAMP, 234 rows from cursors, 484
SQL CURRENT USER, 235 SQL variables, 499
SQL LAST USER, 236 tables, 491
SQL SQLCODE, 235 triggers, 491
SQL SQLSTATE, 235 views, 491
DEFAULT_TIMESTAMP_INCREMENT option, DELIMITED BY option
149, 171 LOAD TABLE statement, 548
Default_timestamp_incrproperty, 1061 denying
DefaultCollation property, 1065 granting permissions, 526, 581
defaults derived tables
autoincrement, 455 FROM clause, 518
DEFAULTS option DESCRIBE statement
LOAD TABLE statement, 548 long column names, 488
defining SQL syntax, 486
nulls for output, 192 DESCRIBE_JAVA_FORMAT option, 173
definitions describing
altering tables, 380 cursors, 486
DEGREES function descriptor
SQL syntax, 321 DESCRIBE statement, 486
DELAYED_COMMIT_TIMEOUT option, 149, 172 FETCH SQL statement, 509
Delayed_commit_timeout property, 1061 preparing statements, 564
Delayed_commite property, 1061 descriptor areas
DELAYED_COMMITS option, 172 allocating memory for, 369
DELETE (positioned) statement deallocating, 472
SQL syntax, 484 EXECUTE SQL statement, 500
DELETE statement getting information from, 523
SQL syntax, 482 setting, 595
DELETE_OLD_LOGS UPDATE (positioned) statement, 625
replication option, 173 DIF file format, 177, 190
DELETE_OLD_LOGS option DIFFERENCE function
resetting truncation offset, 122 SQL syntax, 321
transaction log options, 122 digits
maximum number, 193
DIRECTFS.NLM, 18

1086
E–E

directories DROP EXTERNLOGIN statement


executable, xv SQL syntax, 495
installation, xv DROP OPTIMIZER STATISTICS statement
directory structure, 2 SQL syntax, 496
DisableMultiRowFetch connection parameter, 54 DROP SERVER statement
DISCONNECT statement SQL syntax, 497
SQL syntax, 490 DROP statement
disconnecting SQL syntax, 491
creating events for, 423 DROP STATEMENT statement
disk access SQL syntax, 498
switches, 24 DROP VARIABLE statement
disk cache SQL syntax, 499
operating system, 36 dropping
disk space connections, 494
creating events for, 423 connections in Interactive SQL, 490
creating events for out of, 423 database files, 493
DiskRead property, 1061, 1065 DBSPACEs, 491
DiskReadIndInt property, 1061, 1065 domains, 491
DiskReadIndLeaf property, 1061, 1065 events, 491
DiskReadTable property, 1061, 1065 functions, 491
DiskWrite property, 1061, 1065 indexes, 491
displaying logins for remote servers, 495
messages, 554 optimizer statistics, 496
messages in the message window, 567 prepared statements, 498
DISTINCT keyword, 587 procedures, 491
distributed transactions remote servers, 497
enlistment, 35 SQL variables, 499
DIVIDE_BY_ZERO_ERROR option, 173 tables, 491
Divide_by_zero_error property, 1061 triggers, 491
DLL users, 581
location, 4 views, 491
DLL communication parameter, 63 DSN connection parameter, 53
DMRF connection parameter, 54 DYNAMIC SCROLL cursors
DOBROADCAST communication parameter, 62 declaring, 475
documentation dynamic SQL
conventions, xiii executing procedures in, 504
domains
about, 274
creating, 421
dropping, 491 E
Transact-SQL, 275 EBCDIC
dot operator collating sequence, 96
and >>, 223 echo
DOUBLE data type Interactive SQL option, 174
about, 258 elements
DOW function SQL language syntax, 207
SQL syntax, 321 elproperty, 1061
DROP CONNECTION statement ELSE
SQL syntax, 494 SQL CASE expression, 221
DROP DATABASE statement SQL IF expressions, 220
SQL syntax, 493

1087
E–E

e-mail ENDIF
extended stored procedures, 950 SQL IF expressions, 220
system procedures, 951 ending
embedded SQL rolling back transactions, 583
ALLOCATE DESCRIPTOR statement syntax, ENG connection parameter, 55
369 engine properties
BEGIN DECLARE statement syntax, 473 displaying, 935
CLOSE statement syntax, 404 EngineName connection parameter, 55
CONNECT statement syntax, 411 engines
DEALLOCATE DESCRIPTOR statement starting database, 606
syntax, 472 stopping database, 610
DECLARE CURSOR statement syntax, 475 enlistment
DELETE (positioned) statement syntax, 484 distributed transactions, 35
DESCRIBE statement syntax, 486 ENP connection parameter, 55
DISCONNECT statement syntax, 490 entity integrity, 928
DROP STATEMENT statement syntax, 498 environment variable
END DECLARE statement syntax, 473 switches, 19
EXECUTE IMMEDIATE statement syntax, 504 environment variables
EXECUTE statement syntax, 500 about, 6
EXPLAIN statement syntax, 507 ASTMP, 6
FETCH statement syntax, 509 LD_LIBRARY_PATH, 7
GET DATA statement syntax, 521 PATH, 7
GET DESCRIPTOR statement syntax, 523 SATMP, 7
GET OPTION statement syntax, 524 setting, 6
INCLUDE statement syntax, 535 SQLCONNECT, 8
OPEN statement syntax, 556 SQLLOCALE, 8
PREPARE statement syntax, 564 SQLPATH, 8
PUT statement syntax, 568 SQLREMOTE, 9
SET CONNECTION statement syntax, 594 SYBASE, 9
SET DESCRIPTOR statement syntax, 595 TMP, TEMP, and TEMPDIR, 9
SET SQLCA statement syntax, 600 erase utility, 88
WHENEVER statement syntax, 630 erasing databases, 88
ENC connection parameter, 56 error handling
EncryptedPassword connection parameter, 55 Transact-SQL procedures, 189
encryption ErrorNumber event condition
cllient/server communications, 24 about, 323
communications, 56, 68 errors
creating databases with dbinit, 93 codes, 633, 652
database files, 417 creating events for, 423
passwords, 55 divide by zero, 173
Encryption connection parameter, 56 error messages, 693
END in Interactive SQL, 188
SQL CASE expression, 221 messages, 633
END DELCARE statement raising in Transact-SQL, 570
SQL syntax, 473 signaling, 603
END keyword, 393 SQLSTATE values, 652
END LOOP statement Transact-SQL procedures, 189
SQL syntax, 553 trapping in embedded SQL, 630
END statement user-defined messages, 1015
SQL syntax, 392

1088
E–E

escape character EXECUTE statement


INPUT SQL statement, 536 SQL syntax, 500
OUTPUT SQL statement, 559 Transact-SQL syntax, 502
ESCAPE CHARACTER option executing
LOAD TABLE statement, 548 operating system commands, 613
ESCAPE_CHARACTER option, 174 prepared statements, 500
Escape_character property, 1061 resuming execution of procedures, 578
ESCAPES option SQL statements from files, 572
LOAD TABLE statement, 548 stored procedures in Transact-SQL, 502
ESQL execution threads
statement indicator, 368 number, 28
establishing EXISTS conditions
savepoints, 586 SQL syntax, 231
ESTIMATE function EXIT statement
SQL syntax, 322 SQL syntax, 506
ESTIMATE_SOURCE function exiting
SQL syntax, 322 Interactive SQL, 506
estimates procedures, 579
explicit selectivity estimates, 232 EXP function
recovery time, 195 SQL syntax, 325
row count, 196 expanding
event conditions database files, 124
list, 323 EXPERIENCE_ESTIMATE function
event log SQL syntax, 326
suppressing messages, 18 EXPLAIN statement
EVENT_CONDITION function SQL syntax, 507
SQL syntax, 323 explicit selectivity estimates
EVENT_CONDITION_NAME function SQL syntax, 232
SQL syntax, 324 exporting
EVENT_PARAMETER function Java data, 559
SQL syntax, 324 selecting data for, 587
events unloading result sets, 618
altering, 375 unloading tables, 619
creating and scheduling, 423 exporting BLOBS, 956
dropping, 491 exporting data
triggering, 614 from tables into files, 559
examples directories output format, 190
about, 3 expressions
EXCEPTION statement SQL CASE expressions, 221
SQL syntax, 392 SQL column names, 219
exceptions SQL constants, 219
resignaling, 576 SQL IF expressions, 220
signaling, 603 SQL Java expressions, 222
executable directory SQL operator precedence, 216
about, xv SQL subqueries, 220
EXECUTE IMMEDIATE statement SQL syntax, 218
SQL syntax, 504 Transact-SQL compatibility, 223
EXECUTE permissions ExtendDB property, 1065
granting, 526 EXTENDED_JOIN_SYNTAX option, 174
Extended_join_syntax property, 1061
EXTENDEDNAME communication parameter, 63

1089
F–F

ExtendTempWrite property, 1065 FOR statement


external functions SQL syntax, 514
stack size, 26 foreign keys
external logins and integrity, 928
assigning for remote servers, 430 in the system tables, 980, 981
dropping for remote servers, 495 integrity constraints, 460
external options role names, 460
create existing table, 495 system views, 1029
unnamed, 460
foreign table
in the system tables, 981
F format
FALSE conditions input file, 177
IS FALSE conditions, 231 FORMAT option
Feb 29, 287 LOAD TABLE statement, 548
FETCH statement FORWARD TO statement
SQL syntax, 509 SQL syntax, 516
fetching FoxPro file format, 177, 190
rows from cursors, 509 FreeBuffers property, 1065
file locations FROM clause
NetWare, 3 SELECT statement, 588
Windows CE, 3 SQL syntax, 518
File property, 1070 FullCompare property, 1061, 1065
file size functions
creating events for, 423 ABS function SQL syntax, 301
FileDataSourceName connection parameter, 56 ACOS function SQL syntax, 301
files aggregate SQL, 292
allocating space for database, 373 ARGN function SQL syntax, 302
creating database, 419 ASCII function SQL syntax, 302
creating write, 471 ASIN function SQL syntax, 302
exporting data from tables into, 559 ATAN function SQL syntax, 303
importing data into tables from, 536 ATAN2 function SQL syntax, 303
location, 4 ATN2 function SQL syntax, 303
reading SQL statements from, 572 AVG function SQL syntax, 304
xp_read_file system procedure, 954 BYTE_LENGTH function SQL syntax, 304
xp_write_file system procedure, 956 BYTE_SUBSTR function SQL syntax, 305
FileVersion property, 1070 CAST function SQL syntax, 306
FIPS CEILING function SQL syntax, 306
conformance, 198 CHAR function SQL syntax, 307
FIRE_TRIGGERS option, 152, 175 CHAR_LENGTH function SQL syntax, 308
Fire_triggers property, 1061 CHARINDEX function SQL syntax, 307
firewalls COALESCE function SQL syntax, 308
connecting across, 61, 69 col_length Adaptive Server Enterprise function,
FIXED file format, 177, 190 298
float as double, 175 col_name Adaptive Server Enterprise function,
FLOAT data type 298
about, 258 CONNECTION_PROPERTY function SQL
FLOAT_AS_DOUBLE option, 175 syntax, 309
Float_as_double property, 1061 CONVERT function SQL syntax, 310
FLOOR function COS function SQL syntax, 311
SQL syntax, 326 COT function SQL syntax, 312

1090
F–F

COUNT function SQL syntax, 312 IFNULL function SQL syntax, 328
creating, 432 image SQL, 300
curunreservedpgs Adaptive Server Enterprise index_col Adaptive Server Enterprise function,
function, 298 298
data type conversion SQL, 292 INDEX_ESTIMATE function SQL syntax, 329
data_pgs Adaptive Server Enterprise function, INSERTSTR function SQL syntax, 329
298 INTTOHEX function SQL syntax, 330
datalength Adaptive Server Enterprise function, ISNULL function SQL syntax, 330
298 LCASE function SQL syntax, 330
DATALENGTH function SQL syntax, 313 lct_admin Adaptive Server Enterprise function,
date and time SQL, 292 298
DATE function SQL syntax, 313 LEFT function SQL syntax, 331
DATEADD function SQL syntax, 314 LENGTH function SQL syntax, 331
DATEDIFF function SQL syntax, 314 LIST function SQL syntax, 332
DATEFORMAT function SQL syntax, 316 LOCATE function SQL syntax, 333
DATENAME function SQL syntax, 316 LOG function SQL syntax, 333
DATEPART function SQL syntax, 317 LOG10 function SQL syntax, 334
DATETIME function SQL syntax, 317 LOWER function SQL syntax, 334
DAY function SQL syntax, 318 LTRIM function SQL syntax, 334
DAYNAME function SQL syntax, 318 MAX function SQL syntax, 335
DAYS function SQL syntax, 318 MIN function SQL syntax, 335
db_id Adaptive Server Enterprise function, 298 MINUTE function SQL syntax, 336
DB_ID function SQL syntax, 319 MINUTES function SQL syntax, 336
db_name Adaptive Server Enterprise function, miscellaneous SQL, 295
298 MOD function SQL syntax, 337
DB_NAME function SQL syntax, 320 MONTH function SQL syntax, 338
DB_PROPERTY function SQL syntax, 320 MONTHNAME function SQL syntax, 338
DEGREES function SQL syntax, 321 MONTHS function SQL syntax, 338
DIFFERENCE function SQL syntax, 321 NEXT_CONNECTION function SQL syntax,
DOW function SQL syntax, 321 339
dropping, 491 NEXT_DATABASE function SQL syntax, 340
ESTIMATE function SQL syntax, 322 NOW function SQL syntax, 341
ESTIMATE_SOURCE function SQL syntax, NULLIF function SQL syntax, 341
322 NUMBER function SQL syntax, 342
EVENT_CONDITION function SQL syntax, 323 numeric SQL, 296
EVENT_CONDITION_NAME function SQL object_id Adaptive Server Enterprise function,
syntax, 324 298
EVENT_PARAMETER function SQL syntax, object_name Adaptive Server Enterprise
324 function, 298
exiting from user-defined, 579 PATINDEX function SQL syntax, 342
EXP function SQL syntax, 325 PI function SQL syntax, 343
EXPERIENCE_ESTIMATE function SQL PLAN function SQL syntax, 344
syntax, 326 POWER function SQL syntax, 344
FLOOR function SQL syntax, 326 proc_role Adaptive Server Enterprise function,
GETDATE function SQL syntax, 326 298
HEXTOINT function SQL syntax, 327 PROPERTY function SQL syntax, 345
host_id Adaptive Server Enterprise function, 298 PROPERTY_DESCRIPTION function SQL
host_name Adaptive Server Enterprise function, syntax, 344
298 PROPERTY_NAME function SQL syntax, 345
HOUR function SQL syntax, 327 PROPERTY_NUMBER function SQL syntax,
HOURS function SQL syntax, 327 346

1091
G–G

QUARTER function SQL syntax, 346 user_id Adaptive Server Enterprise function, 298
RADIANS function SQL syntax, 347 user_name Adaptive Server Enterprise function,
RAND function SQL syntax, 347 298
REMAINDER function SQL syntax, 348 user-defined SQL, 294
REPEAT function SQL syntax, 348 valid_name Adaptive Server Enterprise function,
REPLACE function SQL syntax, 348 298
REPLICATE function SQL syntax, 349 valid_user Adaptive Server Enterprise function,
reserved_pgs Adaptive Server Enterprise 298
function, 298 WEEKS function SQL syntax, 362
returning values from user-defined, 579 YEARS function SQL syntax, 363
RIGHT function SQL syntax, 350 YMD function SQL syntax, 364
ROUND function SQL syntax, 350 functions system SQL, 298
rowcnt Adaptive Server Enterprise function, 298 functions, numeric
RTRIM function SQL syntax, 351 ATAN, 303
SECOND function SQL syntax, 351
SECONDS function SQL syntax, 351
show_role Adaptive Server Enterprise function,
298 G
SIGN function SQL syntax, 352 GET DATA statement
SIMILAR function SQL syntax, 353 SQL syntax, 521
SIN function SQL syntax, 353 GET DESCRIPTOR statement
SOUNDEX function SQL syntax, 354 SQL syntax, 523
SPACE function SQL syntax, 354 GET OPTION statement
SQL syntax, 291 SQL syntax, 524
SQRT function SQL syntax, 355 GETDATE function
STR function SQL syntax, 355 SQL syntax, 326
STRING function SQL syntax, 356 getting
string SQL, 297 binary data from columns, 521
STUFF function SQL syntax, 356 information from descriptor areas, 523
SUBSTR function SQL syntax, 357 option values, 524
SUBSTRING function SQL syntax, 357 global autoincrement
SUM function SQL syntax, 358 creating events for, 423
suser_id Adaptive Server Enterprise function, global temporary tables
298 creating, 453
suser_name Adaptive Server Enterprise function, global variables
298 @@char_convert, 241
system, 298 @@client_csid, 241
TAN function SQL syntax, 358 @@client_csname, 241
text SQL, 300 @@connections, 241
TEXTPTR function SQL syntax, 359 @@cpu_busy, 241
TODAY function SQL syntax, 359 @@error, 240, 241
TRACEBACK function SQL syntax, 359 @@identity, 240, 241, 244
Transact-SQL, 298 @@idle, 241
TRIM function SQL syntax, 360 @@io_busy, 241
TRUNCATE function SQL syntax, 360 @@isolation, 240, 241
TRUNCNUM function SQL syntax, 361 @@langid, 241
tsequal Adaptive Server Enterprise function, 298 @@language, 241
UCASE function SQL syntax, 361 @@max_connections, 241
UPPER function SQL syntax, 362 @@maxcharlen, 241
used_pgs Adaptive Server Enterprise function, @@ncharsize, 241
298 @@nestlevel, 241

1092
H–I

@@pack_received, 241 heading


@@pack_sent, 241 Interactive SQL option, 177
@@packet_errors, 241 heading name, 588
@@procid, 240, 241 HELP statement
@@rowcount, 240, 241 SQL syntax, 530
@@servername, 240, 241 hexadecimal constants
@@spid, 241 about, 256
@@sqlstatus, 240, 241 data type, 203
@@textsize, 241 HEXTOINT function
@@thresh_hysteresis, 241 SQL syntax, 327
@@timeticks, 241 HOST communication parameter, 64
@@total_errors, 241 host variables
@@total_read, 241 declaring in embedded SQL, 473
@@total_write, 241 syntax, 366
@@tranchained, 241 host_id Adaptive Server Enterprise function, 298
@@trancount, 241 host_name Adaptive Server Enterprise function, 298
@@transtate, 241 HOUR function
@@version, 240, 241 SQL syntax, 327
SQL syntax, 239 HOURS function
triggers and @@identity, 245 SQL syntax, 327
GLOBAL_DATABASE_ID option, 176
GlobalDBId property, 1070
GOTO statement
Transact-SQL syntax, 525 I
GRANT CONNECT statement I/O operations
SQL syntax, 526 database server, 24
GRANT DBA statement IANA
SQL syntax, 526 port number, 66
GRANT GROUP statement icons
SQL syntax, 526 used in manuals, xiv
GRANT RESOURCE statement identification
SQL syntax, 526 client appliations, 46
GRANT statement identifiers
SQL syntax, 526 SQL syntax, 211
granting IDENTITY column
permissions, 526 @@identity, 244
GROUP authority idle server
granting permissions, 526 creating events for, 423
GROUP BY clause IdleCheck property, 1065
SELECT statement, 589 IdleChkpt property, 1065
grouping IdleChkTime property, 1065
statements, 392 IdleTime event condition
about, 323
IdleWrite property, 1065
IF expressions
H SQL syntax, 220
handling IF statement
errors in embedded SQL, 630 SQL syntax, 531
errors in Transact-SQL, 570 Transact-SQL syntax, 533
HAVING clause
SELECT statement, 589

1093
I–I

IF UPDATE clause input format


in triggers, 464 Interactive SQL option, 177
in triggers in Transact-SQL, 467 INPUT statement
triggers, 386 SQL syntax, 536
IFNULL function INSERT
SQL syntax, 328 multi-row, 501
IMAGE data type wide, 501
about, 273 INSERT statement
image SQL functions, 300 SQL syntax, 540
images truncation of strings, 200
reading from the database, 573 inserting
importing data rows in bulk, 546
into tables from files, 536 rows into tables, 540
IN conditions rows using cursors, 568
SQL syntax, 230 inserting BLOBS, 954
INCLUDE statement INSERTSTR function
SQL syntax, 535 SQL syntax, 329
incremental backups INSTALL statement
dbbackup command-line utility, 75 SQL syntax, 542
IndAdd property, 1061, 1065 installation
index_col Adaptive Server Enterprise function, 298 directory, 2
INDEX_ESTIMATE function NetWare, 3
SQL syntax, 329 registry entries, 11
indexes Windows CE, 3
automatically created, 436 installation directory
creating, 435 about, xv
dropping, 491 installing
foreign keys, 436 Java classes, 542
hash size, 185 INT data type
in the system tables, 984, 988 about, 259
naming, 435 INTEGER data type
owner, 435 about, 259
primary keys, 436 integer overflow
system views, 1031 ANSI behavior, 158
table use, 435 Integrated connection parameter, 57
unique, 436 INTEGRATED LOGIN permissions
unique names, 435 granting, 526
validating, 627 integrity
views, 435 constraints, 458
indicator variables, 366 Interactive SQL
indicators BYE statement syntax, 506
SQL comments, 246 CLEAR statement syntax, 403
IndLookup property, 1061, 1065 command line, 99
information utility, 90 CONFIGURE statement syntax, 410
INI files CONNECT statement syntax, 411
about, 10 connecting to a database, 412
initializing dbisql command-line syntax, 99
databases, 415 DISCONNECT statement syntax, 490
initializing databases with dbinit, 93 error handling, 188
INNER JOIN EXIT statement syntax, 506
SQL syntax, 518 HELP statement syntax, 530

1094
J–J

INPUT statement syntax, 536 ISQL_ESCAPE_CHARACTER


Java output, 173 ISQL option, 179
options, 156 ISQL_FIELD_SEPARATOR
OUTPUT statement syntax, 559 ISQL option, 179
PARAMETERS statement syntax, 563 ISQL_LOG
QUIT statement syntax, 506 ISQL option, 180
READ statement syntax, 572 ISQL_PLAN
SET CONNECTION statement syntax, 594 ISQL option, 180
SET OPTION statement syntax, 599 ISQL_QUOTE
START ENGINE statement syntax, 606 ISQL option, 181
START LOGGING statement syntax, 608 IsRuntimeServer property, 1065
starting from Sybase Central, 100 iterating
statement syntax, 365 over cursors, 514
STOP LOGGING statement syntax, 612 itproperty, 1061
SYSTEM statement syntax, 613
interfaces file
LTM command line, 104
Interval event condition J
about, 323 jar files
INTO clause installing, 542
SELECT statement, 588 removing, 575
INTTOHEX function Java
SQL syntax, 330 and memory use, 182, 183
invoking and user-defined functions, 294
procedures, 398 exporting, 559
IOToRecover property, 1065 file access, 182
IP communication parameter, 64 installing classes, 542
IPX method signatures, 444
about, 37 OUTPUT statement, 559
HOST communication parameter, 64 removing classes, 575
server configuration, 61 supported classes, 276
IQStore property, 1070 unsupported classes, 277
IS upgrading databases, 371
SQL logical operators, 214 Java classes
IS FALSE conditions and columns, 280
SQL syntax, 231 built-in, 276
IS NULL conditions data types, 276
SQL syntax, 231 installing, 278
IS TRUE conditions user-defined, 276, 278
SQL syntax, 231 Java data types
IS UNKNOWN conditions case sensitivity, 279
SQL syntax, 231 converting from SQL, 283
IsNetworkServer property, 1065 converting to SQL, 282
ISNULL function Java Development Kit
SQL syntax, 330 preparing classes, 278
isolation levels Java expressions
cursors, 557 SQL syntax, 222
ISOLATION_LEVEL option, 149, 181 Java fields
ISQL_COMMAND_TIMING referencing, 223
ISQL option, 178 Java syntax
SQL expressions, 222

1095
J–J

Java VM java.rmi.dgc package


starting, 607 supported classes, 277
stopping, 611 java.rmi.registry package
java.applet package supported classes, 277
unsupported classes, 277 java.rmi.server package
java.awt package supported classes, 277
unsupported classes, 277 java.security package
java.awt.datatransfer package supported classes, 277
unsupported classes, 277 java.security.acl package
java.awt.event package supported classes, 277
unsupported classes, 277 java.security.interfaces package
java.awt.image package supported classes, 277
unsupported classes, 277 java.sql package
java.beans package supported classes, 277
supported classes, 276 java.text package
java.io package supported classes, 277
support, 182 java.util package
supported classes, 277 supported classes, 277
java.io.File java.util.zip package
partially supported classes, 278 supported classes, 277
java.io.FileDescriptor java.util.zip.Deflater
partially supported classes, 278 partially supported classes, 278
java.io.FileInputStream java.util.zip.Inflater
partially supported classes, 278 partially supported classes, 278
java.io.FileOutputStream JAVA_HEAP_SIZE option, 182
partially supported classes, 278 Java_heap_size property, 1061
java.io.RandomAccessFile JAVA_INPUT_OUTPUT option, 182
partially supported classes, 278 Java_input_output property, 1061
java.lang package JAVA_NAMESPACE_SIZE option, 183
supported classes, 277 Java_namespace_size property, 1061
java.lang.ClassLoader Java_page_buffer_size property, 1061
partially supported classes, 278 JavaGlobFix property, 1065
java.lang.Compiler JavaHeapSize property, 1061, 1065
partially supported classes, 278 JavaNSSize property, 1065
java.lang.reflect package JDBC
supported classes, 277 data type conversion, 282
java.lang.Runtime upgrading databases, 371
partially supported classes, 278 JDK
java.lang.SecurityManager preparing classes, 278
partially supported classes, 278 join operators
java.lang.Thread SQL syntax, 216
partially supported classes, 277 joining
java.math package tables, 587
supported classes, 277 joins
java.net package automatic, 929
supported classes, 277 creating views, 469
java.net.PlainDatagramSocketImpl deletes, 482
partially supported classes, 278 FROM clause syntax, 518
java.rmi package key, 929
supported classes, 277 natural, 929
SELECT statement, 588

1096
K–L

selecting rows using, 587 LENGTH function


updates based on, 624 SQL syntax, 331
updating rows, 621 licenses
jxmp directory adding with dblic, 101
about, 3 licensing
database servers, 101
LIKE conditions
and case-sensitivity, 229
K and collations, 229
KEY JOIN maximum pattern length, 229
SQL syntax, 518 SQL syntax, 228
keywords limit
NON_KEYWORDS option, 187 connections, 28
SQL syntax, 208 Links connection parameter, 50
turning off, 187 LIST function
SQL syntax, 332
literal strings
SQL constants, 219
L SQL syntax, 212
labels liveness
for statements, 367, 525 connections, 35
LAN adapter number, 64 liveness timeout
language database server, 942
registry entries, 11 LivenessTimeout connection parameter, 57
language DLL LivenessTimeout property, 1065
locating, 4 LOAD TABLE statement
language elements SQL syntax, 546
SQL syntax, 207 loading
Language property, 1061, 1065, 1070 bulk inserts, 546
large binary objects local machine
getting from columns, 521 environment settings, 10
large databases local temporary tables
index storage, 436 creating, 481
LAST USER local variables
SQL special value, 236 SQL syntax, 237
LastIdle property, 1061 LOCATE function
LastReqTime property, 1061 SQL syntax, 333
LCASE function LOCATION registry entry, 5
SQL syntax, 330 LOCK TABLE statement
lct_admin Adaptive Server Enterprise function, 298 SQL syntax, 551
LD_LIBRARY_PATH environment variable, 7 Lock_rejected_rows property, 1061
leap years, 287 LockedHeapPages property, 1065
LEAVE statement locking
SQL syntax, 544 deadlocks, 936
LEFT function tables, 551
SQL syntax, 331 locking conflicts
LEFT OUTER JOIN BLOCKING option, 163
SQL syntax, 518 LockName property, 1061
LegalCopyright property, 1065 locks
LegalTrademarks property, 1065 displaying, 941
LockTablePages property, 1065

1097
M–M

log files, 121, 122 configuration file, 105


LOG function transaction log options, 121, 122
SQL syntax, 333 LTM_admin_pw parameter, 105
Log Transfer Manager LTM_admin_user parameter, 105
command-line syntax, 103 LTM_charset parameter, 105
LOG10 function LTO connection parameter, 57
SQL syntax, 334 LTRIM function
Logfile connection parameter, 58 SQL syntax, 334
LogFreeCommit property, 1061, 1065
LogFreePercent event condition
about, 323
LogFreeSpace event condition M
about, 323 MainHeapBytes property, 1065
logging MainHeapPages property, 1065
starting in Interactive SQL, 608 MAPI
stopping in Interactive SQL, 612 extended stored procedures, 950
updating columns without, 632 MapPages property, 1065
logging off mathematical expressions
keeping server running, 36 SQL arithmetic operators, 214
logical operators MAX function
SQL syntax, 214 SQL syntax, 335
three-valued logic, 231 MAX_CURSOR_COUNT option
LOGIN_MODE option, 183 about, 184
Login_mode property, 1061 Max_cursor_count property, 1061
LOGIN_PROCEDURE option MAX_HASH_SIZE option, 149
about, 184 about, 185
Login_procedure property, 1061 MAX_STATEMENT_COUNT option
logins about, 186
assigning for remote servers, 430 Max_statement_count property, 1061
dropping for remote servers, 495 MAX_WORK_TABLE_HASH_SIZE option
LogName property, 1070 about, 185
LogSize event condition MaxCacheSize property, 1065
about, 323 maximum size
LogWrite property, 1061, 1065 database files, 932
LONG BINARY data type databases, 932
about, 272 MaxIO property, 1065
long column names MAXLANA communication parameter, 64
retrieving, 488 MaxRead property, 1065
LONG VARCHAR data type MaxWrite property, 1065
about, 254 MEMBERSHIP clause
LOOP statement granting permissions, 526
SQL syntax, 553 memory
looping allocating for descriptor areas, 369
over cursors, 514 cache size, 21, 22, 23
LOTUS file format, 177, 190 memory use
LOWER function and Java, 182, 183
SQL syntax, 334 Message property, 1065
LTM MESSAGE statement
and interfaces file, 104 SQL syntax, 554
command-line syntax, 103

1098
N–N

messages names
creating, 439 SQL column names, 219
displaying, 554 NATURAL JOIN
messages windows SQL syntax, 518
printing messages in, 567 NDS
method signatures filenames, 18
Java, 444 NEAREST_CENTURY, 187
Microsoft Access Nearest_century property, 1061
TIMESTAMP comparison, 171 nesting
millenium issues, 285 user-defined transactions, 395
MIN function NetBIOS
SQL syntax, 335 about, 37
MIN_PASSWORD_LENGTH, 186 server configuration, 61
Min_password_length property, 1061 NetWare
MinCacheSize property, 1065 cache buffers, 21
MINUTE function database server, 18
SQL syntax, 336 file locations, 3
MINUTES function installation, 3
SQL syntax, 336 server performance, 21
MOD function subdirectories, 3
SQL syntax, 337 network communications
modulo operator command line switches, 61
PERCENT_AS_COMMENT option, 192 network number
MONEY data type in IPX address, 62
about, 263 NEXT_CONNECTION function
monitoring performance, 1052 SQL syntax, 339
MONTH function NEXT_DATABASE function
SQL syntax, 338 SQL syntax, 340
MONTHNAME function NO SCROLL cursors
SQL syntax, 338 declaring, 475
MONTHS function NodeAddress property, 1061
SQL syntax, 338 NON_KEYWORDS, 187
multi-byte character sets Non_keywords property, 1061
unloading data, 620 NOT
MultiByteCharSet property, 1070 SQL logical operators, 214
MultiPacketsReceived property, 1065 NOW function
MultiPacketsSent property, 1065 SQL syntax, 341
multi-row fetches NULL value
FETCH statement, 511 ANSI behavior, 160
OPEN statement, 557 ISNULL function, 330
multi-row inserts, 501 NULLS option, 188
MYIP communication parameter, 65 SQL special value, 247
three-valued logic, 247
Transact-SQL behavior, 160
NULLIF function, 222
N about, 341
name nulls
database, 42 defining for output, 192
Name property, 1061, 1065, 1070 NULLS option
NamedPipes Interactive SQL option, 188
about, 37

1099
O–O

NUMBER function SQL join operators, 216


SQL syntax, 342 SQL logical operators, 214
updates, 623 SQL operator precedence, 216
number of rows, 1009 SQL string operators, 215
Number property, 1061 SQL syntax, 213
numbers optimization
SQL constants, 219 defining existing tables and, 428
NUMERIC data type OPTIMIZATION_GOAL
about, 260 database option, 189
numeric precision Optimization_goal property, 1061
database option, 193 Optimization_level property, 1061
numeric SQL functions, 296 optimizer
nusupported classes explicit selectivity estimates, 232
java.awt.datatransfer, 277 optimizer plans
getting text specification, 507
optimizer statistics
dropping, 496
O options
object_id Adaptive Server Enterprise function, 298 about, 143, 596
object_name Adaptive Server Enterprise function, ALLOW_NULLS_BY_DEFAULT, 152, 157
298 alphabetical list, 157
ODBC ANSI_BLANKS, 152, 157
connection parameters, 44 ANSI_CLOSE_CURSORS_ON_ROLLBACK,
declaring static cursors, 475 158
ODBC data sources ANSI_INTEGER_OVERFLOW, 158
creating with dbdsn, 84 ANSI_PERMISSIONS, 158
ON EXCEPTION RESUME clause ANSI_UPDATE_CONSTRAINTS, 159
about, 442 ANSINULL, 160
stored procedures, 189 AUDITING option, 160
ON_ERROR AUTO_REFETCH, 161
Interactive SQL option, 188 AUTOMATIC_TIMESTAMP, 152, 161
ON_TSQL_ERROR BACKGROUND_PRIORITY, 149, 162
database option, 189 BELL, 162
ON_TSQL_ERROR option BLOCKING, 149, 163
ON EXCEPTION RESUME, 442 CHAINED, 163
RAISERROR statement, 570 CHAR_OEM_TRANSLATION, 164
On_tsql_error property, 1061 CHECKPOINT_TIME, 149, 165
OPEN statement CIS_ ROWSET_SIZE, 165
QUERY_PLAN_ON_OPEN option, 194 CLOSE_ON_ENDTRANS, 165
SQL syntax, 556 COMMAND_DELIMITER, 166
opening COMMIT_ON_EXIT, 166
cursors, 556 compatibility, 152
opening cursors, 194 CONTINUE_AFTER_RAISERROR option, 167
operating system CONVERSION_ERROR, 152, 168
executing commands, 613 COOPERATIVE COMMITS, 168
operator precedence COOPERATIVE_COMMIT_TIMEOUT, 149,
SQL syntax, 216 169
operators COOPERATIVE_COMMITS, 149
SQL arithmetic operators, 214 cursors, 145
SQL bitwise operators, 215 DATE_FORMAT, 149, 169
SQL comparison operators, 213 DATE_ORDER, 149, 171

1100
O–O

DEFAULT_TIMESTAMP_INCREMENT, 149, PREFETCH, 193


171 QUERY_PLAN_ON_OPEN, 152, 194
DELAYED_COMMIT_TIMEOUT, 149, 172 QUOTED_IDENTIFIER, 152, 195
DELAYED_COMMITS, 172 QUOTED_IDENTIFIER and Transact-SQL
DELETE_OLD_LOGS, 173 compatibility, 224
DESCRIBE_JAVA_FORMAT, 173 RECOVERY_TIME, 149, 195
DIVIDE_BY_ZERO_ERROR, 173 REPLICATE_ALL, 196
duration, 145 replication, list, 154
ECHO, 174 REPLICATION_ERROR, 196
ESCAPE_CHARACTER, 174 RETURN_JAVA_AS_STRING, 197
EXTENDED_JOIN_SYNTAX, 174 RI_TRIGGER_TIME, 197
finding values, 145 ROW_COUNTS, 149, 196
FIRE_TRIGGERS, 175 SCALE, 149, 198
FLOAT_AS_DOUBLE, 175 scope, 145
general, 149 setting, 144, 155, 596
getting values, 524 setting in Interactive SQL, 410, 599
GLOBAL_DATABASE_ID, 176 setting in Transact-SQL, 593
HEADINGS, 177 setting temporary, 155
in the system tables, 994 SQL_FLAGGER_ERROR_LEVEL, 198
initial settings, 147, 945, 948 SQL_FLAGGER_WARNING_LEVEL, 199
INPUT_FORMAT, 177 STATISTICS, 199
introduction, 144 STRING_TRUNCATION, 200
ISOLATION_LEVEL, 149, 181 SUBSCRIBE_BY_REMOTE, 200
ISQL_COMMAND_TIMING, 178 system views, 1032, 1044
ISQL_ESCAPE_CHARACTER, 179 THREAD_COUNT, 149, 200
ISQL_FIELD_SEPARATOR, 179 TIME_FORMAT, 149, 200
ISQL_LOG, 180 TIMESTAMP_FORMAT, 201
ISQL_PLAN, 180 Transact-SQL compatibility, 948
ISQL_QUOTE, 181 TRUNCATE_DATE_VALUES, 202
JAVA_HEAP_SIZE, 182 TRUNCATE_WITH_AUTO_COMMIT, 202
JAVA_INPUT_OUTPUT, 182 TRUNCATION_LENGTH, 203
JAVA_NAMESPACE_SIZE, 183 TSQL_HEX_CONSTANT, 203
list, 149 TSQL_VARIABLES, 204
LOGIN_MODE, 183 VERIFY_ALL_COLUMNS, 204
LOGIN_PROCEDURE, 184 VERIFY_THRESHOLD, 204
MAX_CURSOR_COUNT, 184 WAIT_FOR_COMMIT, 149, 205
MAX_HASH_SIZE, 149, 185 OPTIONS_NULL option, 192
MAX_STATEMENT_COUNT, 186 OR
MAX_WORK_TABLE_HASH_SIZE, 185 SQL logical operators, 214
MIN_PASSWORD_LENGTH option, 186 ORDER BY clause, 589
NEAREST_CENTURY option, 187 order of operations
NON_KEYWORDS, 187 SQL operator precedence, 216
ON_ERROR, 188 out of disk space
ON_TSQL_ERROR, 189 creating events for, 423
OPTIMIZATION_GOAL, 189 outer joins
OPTIONS_NULL, 192 SQL join operators, 216
OUTPUT_FORMAT, 190 output format
OUTPUT_LENGTH, 191 Interactive SQL option, 190
PERCENT_AS_COMMENT, 192 output length
precedence, 145 Interactive SQL option, 191
PRECISION, 149, 193

1101
P–P

OUTPUT statement java.net.PlainDatagramSocketImpl, 278


Java data, 559 java.util.zip.Deflater, 278
SQL syntax, 559 java.util.zip.Inflater, 278
owner, 366 password
for the LTM, 105
Password connection parameter, 58
passwords
P changing, 526
packages encrypting, 55
installing Java classes, 542 in the system tables, 1016
removing Java classes, 575 minimum length, 186
supported, 276 PATH environment variable, 7
unsupported, 277 PATINDEX function
packet size SQL syntax, 342
limiting, 33 pattern matching
PacketsCorrupted property, 1065 and case-sensitivity, 229
PacketsDropped property, 1065 and collations, 229
PacketsReceived property, 1065 maximum pattern length, 229
PacketsRereceived property, 1065 PATINDEX function, 342
PacketsResent property, 1065 SQL LIKE conditions, 228
PacketsSent property, 1065 wild cards, 342
page size PeakCacheSize property, 1065
choosing, 95 percent sign
databases, 93 modulo or comment, 192
maximum allowed, 28 PERCENT_AS_COMMENT option
page sizes about, 192
creating databases, 416 Percent_as_comment property, 1061
page usage performance
tables, 944 cache size, 21, 22, 23
PageRelocations property, 1065 monitoring, 1052
pages PowerBuilder DataWindow, 189
displaying usage in database files, 90 preallocating space, 373
PageSize property, 1070 prefetch, 193
parallel execution result sets, 189
processors, 29 setting priorities, 162
threads, 30 TRUNCATE TABLE statement, 202
parameters performance monitor
for Interactive SQL command files, 563 Windows NT, 1052
PARAMETERS statement permissions
SQL syntax, 563 granting, 526
partially supported classes in the system tables, 973, 1010
java.io.File, 278 loading data, 27
java.io.FileDescriptor, 278 revoking, 581
java.io.FileInputStream, 278 SYSCOLAUTH system view, 1027
java.io.FileOutputStream, 278 system views, 1040
java.io.RandomAccessFile, 278 unloading data, 27
java.lang.ClassLoader, 278 PI function
java.lang.Compiler, 278 SQL syntax, 343
java.lang.Runtime (exec/load/loadlibrary), 278 ping utility
java.lang.SecurityManager, 278 command-line syntax, 114
java.lang.Thread, 277

1102
P–P

pinging Prepares property, 1061


servers, 114 preparing
PLAN function for two-phase commit, 566
SQL syntax, 344 statements, 564
plans PrepStmt property, 1061
getting text specification, 507 primary keys
Platform property, 1065 and integrity, 928
plug-ins in the system tables, 975, 1009
registry entries, 11 integrity constraints, 459
pooling order of columns, 459
enabling pooling of connections, 601 primary table
PORT communication parameter, 66 in the system tables, 981
port number PRINT statement
database server, 66 Transact-SQL syntax, 567
TCP/IP, 38, 66 printing
Port property, 1061 messages in the message window, 567
positioned DELETE statement priority
SQL syntax, 484 process, 25
POWER function proc_role Adaptive Server Enterprise function, 298
SQL syntax, 344 ProcedurePages property, 1065
PowerBuilder DataWindow procedures, 565
query performance, 189 altering, 377
precedence catalog, list, 935
SQL operator precedence, 216 CREATE PROCEDURE SQL statement, 447
PRECISION option, 149 creating, 440
about, 193 creating in Transact-SQL, 447
Precision property, 1061 dropping, 491
predicates executing in dynamic SQL, 504
SQL ANY or ALL conditions, 227 executing stored in Transact-SQL, 502
SQL BETWEEN conditions, 227 exiting, 579
SQL comparison operators, 213 extended, list, 950
SQL EXISTS conditions, 231 external function calls, 433, 443
SQL explicit selectivity estimates, 232 invoking, 398
SQL IN conditions, 230 raising errors in Transact-SQL, 570
SQL IS NULL conditions, 231 replicating, 377
SQL IS TRUE or FALSE conditions, 231 resuming execution of, 578
SQL IS UNKNOWN conditions, 231 returning values from, 579
SQL LIKE conditions, 228 system, 933
SQL subqueries in, 227 Transact-SQL, list, 957
SQL syntax, 226 variable result sets, 441, 488
three-valued logic, 231 ProcessCPU property, 1065
PREFETCH option, 193 ProcessCPUSystem property, 1065
Prefetch property, 1061 ProcessCPUUser property, 1065
PREPARE statement processors
SQL syntax, 564 multiple, 29
PREPARE TO COMMIT statement number used, 29
SQL syntax, 566 product name
prepared statements retrieving, 953
connection limits, 186 ProductName property, 1065
dropping, 498 ProductVersion property, 1065
executing, 500

1103
Q–R

projections quitting time


SELECT statement, 587 database server, 942
properties QuittingTime property, 1065
about, 1060 quotation marks
connection, 935, 1060 in SQL strings, 212
database, 935, 1070 SQL identifiers, 211
engine, 935 Quote_all_identifiers
server, 345, 1065 replication option, 195
PROPERTY function QUOTED_IDENTIFIER option, 152, 195
SQL syntax, 345 Transact-SQL expression compatibility, 224
property functions Quoted_identifier property, 1061
about, 1060 QUOTED_IDENTIFIER Transact-SQL option
PROPERTY_DESCRIPTION function setting, 593
SQL syntax, 344 QUOTES option
PROPERTY_NAME function LOAD TABLE statement, 549
SQL syntax, 345
PROPERTY_NUMBER function
SQL syntax, 346
protocol stacks R
TCP/IP, 63 RADIANS function
protocols SQL syntax, 347
disabling shared memory, 34 RAISERROR
proxy procedures behavior of, 167
creating, 440 RAISERROR statement
proxy tables CONTINUE_AFTER_RAISERROR option, 167
creating, 428, 454 Transact-SQL syntax, 570
PUBLIC group raising
in the system tables, 1017 errors in Transact-SQL, 570
publications RAND function
updating, 621 SQL syntax, 347
PURGE clause read only
FETCH statement, 512 locking tables, 551
PUT statement READ statement
SQL syntax, 568 SQL syntax, 572
putting reading
rows into cursors, 568 text and image values from the database, 573
PWD connection parameter, 58 reading files
stored procedures, 954, 956
reading SQL statements from files, 572
read-only
Q databases, 33
Qualify_owners ReadOnly property, 1070
replication option, 194 READTEXT statement
QUARTER function Transact-SQL syntax, 573
SQL syntax, 346 REAL data type
QUERY_PLAN_ON_OPEN option, 152, 194 about, 260
Query_plan_on_open property, 1061 REBUILD, 115
QUIT statement rebuild command-line utility
SQL syntax, 506 syntax, 115
quitting rebuilding databases, 115
Interactive SQL, 506 ReceiveBufferSize communication parameter, 66

1104
R–R

recover remoteoption table


command-line switches, 40 about, 1000
recovery remoteoptiontype table
distributed transactions, 35 about, 1001
LOAD TABLE, 550 RemoteputWait property, 1065
maximum time, 29 REMOVE statement
RECOVERY_TIME option, 149, 195 SQL syntax, 575
Recovery_time property, 1061 removing
RecoveryUrgency property, 1065, 1070 granting permissions, 526
REFERENCES permissions Java classes, 575
granting, 526 permissions, 581
referential integrity, 928 renaming
actions, 461 columns, 384
FROM clause, 518 tables, 384
triggers, 197 rep_func parameter, 105
REGISTERBINDERY communication parameter, REPEAT function
66 SQL syntax, 348
registry REPLACE function
language entry, 11 SQL syntax, 348
location entry, 11 REPLICATE function
Sybase Central, 11 SQL syntax, 349
tools location entry, 11 REPLICATE_ALL
registry entries replication option, 196
about, 6, 10 Replicate_all property, 1061
relationships replicating
in the system tables, 981 procedures, 377
RELEASE SAVEPOINT statement replication
SQL syntax, 574 dbcc, 121, 122
releasing Log Transfer Manager, 103
savepoints, 574 of trigger actions, 174, 175
RelocatableHeapPages property, 1065 options, 154
REMAINDER function replication server, 121, 122
SQL syntax, 348 replication agent
remote data access dbltm command-line syntax, 103
CIS_ ROWSET_SIZE, 165 replication options
FORWARD TO statement, 516 Qualify_owners, 194
remote procedures Quote_all_identifiers, 195
creating, 440, 443 Replication Server
creating in Transact SQL, 447 Log Transfer Manager, 103
remote servers REPLICATION_ERROR
altering attributes, 378 replication option, 196
assigning logins for, 430 Req property, 1065
capabilities, 947, 969, 970 ReqType property, 1061
creating tables, 453 request_level_debugging
dropping, 497 about, 942
dropping logins for, 495 request_level_logging
sending SQL statements to, 516 about, 942
remote tables RequestLogFile property, 1065
columns, 946 RequestLogging property, 1065
creating, 454 RequestQueueWait property, 1065
listing, 947

1105
R–R

reserved words ROLLBACK statement


SQL syntax, 208 cursors, 158
reserved_pgs Adaptive Server Enterprise function, SQL syntax, 583
298 ROLLBACK TO SAVEPOINT statement
RESIGNAL statement SQL syntax, 584
SQL syntax, 576 ROLLBACK TRIGGER statement
resignaling SQL syntax, 585
exceptions, 576 RollbackLogPages property, 1061, 1065
resource authority rolling back
in the system tables, 1016 transactions, 583
RESOURCE authority transactions to savepoints, 584
granting permissions, 526 triggers, 585
resource governor ROUND function
cursors, 184 SQL syntax, 350
statements, 186 rounding
RESTORE statement SCALE option, 198
SQL syntax, 577 roundoff errors
restoring about, 256
databases from archives, 577 routers
RESTRICT, 461 broadcasting over, 62
result sets row counts, 196
resuming execution of procedures, 578 ROW_COUNTS option, 149
shape of, 488 ROW_COUNTS options, 196
unloading, 618 Row_counts property, 1061
variable, 441, 488, 565 rowcnt Adaptive Server Enterprise function, 298
RESUME statement ROWCOUNT Transact-SQL option
SQL syntax, 578 setting, 593
resuming row-level triggers, 464
execution of procedures, 578 rows
RETURN statement deleting all from a table, 615
SQL syntax, 579 deleting from cursors, 484
RETURN_JAVA_AS_STRING fetching from cursors, 509
replication option, 197 inserting in bulk, 546
returning inserting into tables, 540
values from procedures, 579 inserting using cursors, 568
REVOKE statement selecting, 587
SQL syntax, 581 unloading, 618
revoking updating, 621
permissions, 581 RS parameter, 105
RI_TRIGGER_TIME option, 197 RS_pw parameter, 105
RI_Trigger_time property, 1061 RS_source_db parameter, 105
RIGHT function RS_source_ds parameter, 105
SQL syntax, 350 RS_user parameter, 105
RIGHT OUTER JOIN RTRIM function
SQL syntax, 518 SQL syntax, 351
Rlbk property, 1061 rules
role names SQL language syntax, 207
about, 460
foreign keys, 460

1106
S–S

SQL explicit selectivity estimates, 232


S SQL IN conditions, 230
sa_audit_string system procedure, 935
SQL IS NULL conditions, 231
sa_check_commit system procedure, 935
SQL IS TRUE or FALSE conditions, 231
sa_conn_info system procedure, 935, 936
SQL IS UNKNOWN conditions, 231
sa_conn_properties
SQL LIKE conditions, 228
using, 145
SQL subqueries in, 227
sa_conn_properties system procedure, 935, 937
SQL syntax, 226
sa_conn_properties_by_name system procedure, 938
subqueries in, 227
sa_db_info system procedure, 935, 938
three-valued logic, 231
sa_db_properties system procedure, 935, 939
SEARCHBINDERY communication parameter, 66
sa_eng_properties system procedure, 935, 939
SECOND function
sa_flush_cache system procedure, 940
SQL syntax, 351
sa_index_levels system procedure, 940
SECONDS function
sa_locks system procedure, 941
SQL syntax, 351
sa_server_option system procedure, 942
security
sa_table_page_usage procedure, 935
auditing, 160
sa_table_page_usage system procedure, 944
C2, 34, 50
sa_validate system procedure, 935, 945
file access, 27
sample database
minimum password length, 186
about, xvi
temporary file, 6
SATMP environment variable, 7
secutiry
SAVEPOINT statement
encrypting communications, 24
SQL syntax, 586
select list
savepoints
SELECT statement, 588
creating, 586
select lists
name, 367
describing cursors, 486
releasing, 574
SELECT permissions
rolling back to savepoints, 584
granting, 526
saving statements, 180
SELECT statement
SCALE option, 149, 198
examples, 1021
Scale property, 1061
SQL syntax, 587
scan_retry parameter, 105
selecting
scheduled events
for unloading, 618
triggering, 614
forming unions, 617
scheduling
rows, 587
creating events, 423
SELF_RECURSION Transact-SQL option
events, 375
setting, 593
server shutdown, 36
SendBufferSize communication parameter, 66
schema
SendFail property, 1065
and system tables, 962
sending
schemas
SQL statements to remote servers, 516
creating, 449
server
scripts directory
creating events for idle, 423
about, 3
server messages
SCROLL cursors
displaying, 33
declaring, 475
output to file, 32
search conditions
server name, 31
SQL ANY or ALL conditions, 227
server properties
SQL BETWEEN conditions, 227
ActiveReq, 1065
SQL EXISTS conditions, 231
AvailIIO, 1065

1107
S–S

BufferMisses, 1065 LockedHeapPages, 1065


BuildChange, 1065 LockTablePages, 1065
BuildClient, 1065 LogFreeCommit, 1065
BuildReproducible, 1065 LogWrite, 1065
BytesReceived, 1065 MainHeapBytes, 1065
BytesSent, 1065 MainHeapPages, 1065
CacheHits, 1065 MapPages, 1065
CacheHitsEng, 1065 MaxCacheSize, 1065
CacheRead, 1065 MaxIO, 1065
CacheReadIndInt, 1065 MaxRead, 1065
CacheReadIndLeaf, 1065 MaxWrite, 1065
CacheReadTable, 1065 Message, 1065
CacheReplacements, 1065 MinCacheSize, 1065
CharSet, 1065 MultiPacketsReceived, 1065
CheckpointUrgency, 1065 MultiPacketsSent, 1065
Chkpt, 1065 Name, 1065
ChkptFlush, 1065 PacketsCorrupted, 1065
ChkptPage, 1065 PacketsDropped, 1065
CommitFile, 1065 PacketsReceived, 1065
CompanyName, 1065 PacketsRereceived, 1065
ConnsDisabled, 1065 PacketsResent, 1065
CurrentCacheSize, 1065 PacketsSent, 1065
CurrIO, 1065 PageRelocations, 1065
CurrRead, 1065 PeakCacheSize, 1065
CurrWrite, 1065 Platform, 1065
DefaultCollation, 1065 ProcedurePages, 1065
DiskRead, 1065 ProcessCPU, 1065
DiskReadIndInt, 1065 ProcessCPUSystem, 1065
DiskReadIndLeaf, 1065 ProcessCPUUser, 1065
DiskReadTable, 1065 ProductName, 1065
DiskWrite, 1065 ProductVersion, 1065
ExtendDB, 1065 QuittingTime, 1065
ExtendTempWrite, 1065 RecoveryUrgency, 1065
FreeBuffers, 1065 RelocatableHeapPages, 1065
FullCompare, 1065 RemoteputWait, 1065
IdleCheck, 1065 Req, 1065
IdleChkpt, 1065 RequestLogFile, 1065
IdleChkTime, 1065 RequestLogging, 1065
IdleWrite, 1065 RequestQueueWait, 1065
IndAdd, 1065 RollbackLogPages, 1065
IndLookup, 1065 SendFail, 1065
IOToRecover, 1065 ServerIdleWaits, 1065
IsNetworkServer, 1065 TotalBuffers, 1065
IsRuntimeServer, 1065 TriggerPages, 1065
JavaGlobFix, 1065 UnschReq, 1065
JavaHeapSize, 1065 ViewPages, 1065
JavaNSSize, 1065 ServerIdleWaits property, 1065
Language, 1065 ServerName connection parameter, 55, 59
LegalCopyright, 1065 ServerPort communication parameter, 66
LegalTrademarks, 1065
LivenessTimeout, 1065

1108
S–S

servers shutdown
altering remote attributes, 378 specifying time, 36
creating, 451 SIGN function
dropping remote, 497 SQL syntax, 352
locating, 114, 116 SIGNAL statement
properties of, 1065 SQL syntax, 603
starting database, 606 signaling
starting from batch files, 117 errors, 570, 603
stopping database, 610 exceptions, 576
services signatures
event log, 18 Java methods, 444
registry entries, 10 SIMILAR function
Windows 95/98, 39 SQL syntax, 353
SESSIONS communication parameter, 67 SIN function
SET CONNECTION statement SQL syntax, 353
SQL syntax, 594 SLQ functions
SET DEFAULT, 461 date and time, 292
SET DESCRIPTOR statement SMALLDATETIME data type
SQL syntax, 595 about, 269, 270
SET NULL action, 461 SMALLINT data type
SET OPTION statement about, 261
Interactive SQL syntax, 155, 599 SMP
SQL syntax, 596 number of processors, 29
syntax, 144 software
Transact-SQL syntax, 593 dberase, 88
using, 144 dblog, 121
SET PERMANENT statement dbshrink, 82
Interactive SQL syntax, 599 dbtran, 110
SET SQLCA statement Interactive SQL, 99
SQL syntax, 600 REBUILD, 115
SET statement software license
SQL syntax, 591 licensing servers, 101
Transact-SQL syntax, 593 software version
SET TEMPORARY OPTION statement database server, 37
Interactive SQL syntax, 155, 599 SOME conditions
SQL syntax, 596 SQL syntax, 227
syntax, 144 sorting
setting in the system tables, 971
connections, 594 SOUNDEX function
descriptor areas, 595 SQL syntax, 354
options, 596 SP
options in Interactive SQL, 410, 599 statement indicator, 368
options in Transact-SQL, 593 sp_addgroup system procedure, 957
SQLCAs, 600 sp_addlogin system procedure, 957
users, 601 sp_addmessage system procedure, 439, 957
values of SQL variables, 591 sp_addtype system procedure, 957
SETUSER statement sp_adduser system procedure, 957
SQL syntax, 601 sp_changegroup system procedure, 957
shared memory sp_column_privileges
about, 37, 50 catalog procedure, 958
show_role Adaptive Server Enterprise function, 298 sp_column_privileges catalog procedure, 958

1109
S–S

sp_columns catalog procedure, 958 SQL functions


sp_dboption system procedure, 957 ABS function syntax, 301
sp_dropgroup system procedure, 957 ACOS function syntax, 301
sp_droplogin system procedure, 957 aggregate, 292
sp_dropmessage system procedure, 957 ARGN function syntax, 302
sp_droptype system procedure, 957 ASCII function syntax, 302
sp_dropuser system procedure, 957 ASIN function syntax, 302
sp_fkeys catalog procedure, 958 ATAN function syntax, 303
sp_getmessage system procedure, 957 ATAN2 function syntax, 303
sp_helptext system procedure, 957 ATN2 function syntax, 303
sp_login_environment procedure, 935 AVG function syntax, 304
sp_login_environment system procedure, 945 BYTE_LENGTH function syntax, 304
sp_password system procedure, 957 BYTE_SUBSTR function syntax, 305
sp_pkeys catalog procedure, 958 CAST function syntax, 306
sp_remote_columns system procedure, 946 CEILING function syntax, 306
sp_remote_tables system procedure, 947 CHAR function syntax, 307
sp_servercaps system procedure, 947 CHAR_LENGTH function syntax, 308
sp_special_columns catalog procedure, 958 CHARINDEX function syntax, 307
sp_sproc_columns catalog procedure, 958 COALESCE function syntax, 308
sp_stored_procedures catalog procedure, 958 CONNECTION_PROPERTY function syntax,
sp_tables catalog procedure, 958 309
sp_tsql_environment, 935 CONVERT function syntax, 310
sp_tsql_environment system procedure, 948 COS function syntax, 311
SPACE function COT function syntax, 312
SQL syntax, 354 COUNT function syntax, 312
special characters data type conversion, 292
in SQL strings, 212 DATALENGTH function syntax, 313
special tables, 962 DATE function syntax, 313
special values DATEADD function syntax, 314
SQL CURRENT DATE, 234 DATEDIFF function syntax, 314
SQL CURRENT PUBLISHER, 235 DATEFORMAT function syntax, 316
SQL CURRENT TIME, 234 DATENAME function syntax, 316
SQL CURRENT TIMESTAMP, 234 DATEPART function syntax, 317
SQL CURRENT USER, 235 DATETIME function syntax, 317
SQL LAST USER, 236 DAY function syntax, 318
SQL NULL, 247 DAYNAME function syntax, 318
SQL SQLCODE, 235 DAYS function syntax, 318
SQL SQLSTATE, 235 DB_ID function syntax, 319
SQL syntax, 234 DB_NAME function syntax, 320
specifying DB_PROPERTY function syntax, 320
nulls for output, 192 DEGREES function syntax, 321
SPX DIFFERENCE function syntax, 321
HOST communication parameter, 64 DOW function syntax, 321
SQL compatibility ESTIMATE function syntax, 322
ANSI_CLOSE_CURSORS_ON_ROLLBACK ESTIMATE_SOURCE function syntax, 322
option, 158 EVENT_CONDITION function syntax, 323
SQL descriptor area EVENT_CONDITION_NAME function syntax,
INCLUDE statement, 535 324
inserting rows using cursors, 568 EVENT_PARAMETER function syntax, 324
SQL descriptor areas EXP function syntax, 325
DESCRIBE statement, 486

1110
S–S

EXPERIENCE_ESTIMATE function syntax, REPLACE function syntax, 348


326 REPLICATE function syntax, 349
FLOOR function syntax, 326 RIGHT function syntax, 350
GETDATE function syntax, 326 ROUND function syntax, 350
HEXTOINT function syntax, 327 RTRIM function syntax, 351
HOUR function syntax, 327 SECOND function syntax, 351
HOURS function syntax, 327 SECONDS function syntax, 351
IFNULL function syntax, 328 SIGN function syntax, 352
image, 300 SIMILAR function syntax, 353
INDEX_ESTIMATE function syntax, 329 SIN function syntax, 353
INSERTSTR function syntax, 329 SOUNDEX function syntax, 354
INTTOHEX function syntax, 330 SPACE function syntax, 354
ISNULL function syntax, 330 SQRT function syntax, 355
LCASE function syntax, 330 STR function syntax, 355
LEFT function syntax, 331 string, 297
LENGTH function syntax, 331 STRING function syntax, 356
LIST function syntax, 332 STUFF function syntax, 356
LOCATE function syntax, 333 SUBSTR function syntax, 357
LOG function syntax, 333 SUBSTRING function syntax, 357
LOG10 function syntax, 334 SUM function syntax, 358
LOWER function syntax, 334 syntax, 291
LTRIM function syntax, 334 system, 298
MAX function syntax, 335 TAN function syntax, 358
MIN function syntax, 335 text, 300
MINUTE function syntax, 336 TEXTPTR function syntax, 359
MINUTES function syntax, 336 TODAY function syntax, 359
miscellaneous, 295 TRACEBACK function syntax, 359
MOD function syntax, 337 TRIM function syntax, 360
MONTH function syntax, 338 TRUNCATE function syntax, 360
MONTHNAME function syntax, 338 TRUNCNUM function syntax, 361
MONTHS function syntax, 338 UCASE function syntax, 361
NEXT_CONNECTION function syntax, 339 UPPER function syntax, 362
NEXT_DATABASE function syntax, 340 user-defined, 294
NOW function syntax, 341 WEEKS function syntax, 362
NULLIF function syntax, 341 YEARS function syntax, 363
NUMBER function syntax, 342 YMD function syntax, 364
numeric, 296 SQL Remote
PATINDEX function syntax, 342 articles, 967, 968
PI function syntax, 343 options, 154
PLAN function syntax, 344 system tables, 967, 968
POWER function syntax, 344 SQL Remote system tables
PROPERTY function syntax, 345 remoteoption, 1000
PROPERTY_DESCRIPTION function syntax, remoteoptiontype, 1001
344 SQL statements
PROPERTY_NAME function syntax, 345 ALLOCATE DESCRIPTOR syntax, 369
PROPERTY_NUMBER function syntax, 346 ALTER DATABASE syntax, 371
QUARTER function syntax, 346 ALTER DBSPACE syntax, 373
RADIANS function syntax, 347 ALTER EVENT syntax, 375
RAND function syntax, 347 ALTER PROCEDURE syntax, 377
REMAINDER function syntax, 348 ALTER SERVER syntax, 378
REPEAT function syntax, 348 ALTER TABLE syntax, 380

1111
S–S

ALTER TRIGGER syntax, 386 DESCRIBE syntax, 486


ALTER VIEW syntax, 387 DISCONNECT syntax, 490
ALTER WRITEFILE syntax, 388 DROP CONNECTION syntax, 494
BACKUP syntax, 389 DROP DATABASE syntax, 493
BEGIN and END syntax, 392 DROP EXTERNLOGIN syntax, 495
BEGIN DECLARE syntax, 473 DROP OPTIMIZER STATISTICS syntax, 496
BEGIN TRANSACTION syntax, 395 DROP SERVER syntax, 497
BREAK Transact-SQL syntax, 631 DROP STATEMENT syntax, 498
BYE syntax, 506 DROP syntax, 491
CALL syntax, 398 DROP VARIABLE syntax, 499
CASE syntax, 400 END DECLARE syntax, 473
CHECKPOINT syntax, 402 EXECUTE IMMEDIATE syntax, 504
CLEAR syntax, 403 EXECUTE syntax, 500
CLOSE syntax, 404 EXECUTE Transact-SQL syntax, 502
COMMENT syntax, 406 EXIT syntax, 506
COMMIT syntax, 408 EXPLAIN syntax, 507
CONFIGURE syntax, 410 FETCH syntax, 509
CONNECT syntax, 411 FOR syntax, 514
CONTINUE Transact-SQL syntax, 631 FORWARD TO syntax, 516
CREATE COMPRESSED DATABASE syntax, FROM clause syntax, 518
414 GET DATA syntax, 521
CREATE DATABASE syntax, 415 GET DESCRIPTOR syntax, 523
CREATE DBSPACE syntax, 419 GET OPTION syntax, 524
CREATE DOMAIN syntax, 421 GOTO Transact-SQL syntax, 525
CREATE EVENT syntax, 423 GRANT syntax, 526
CREATE EXISTING TABLE syntax, 428 HELP syntax, 530
CREATE EXPANDED DATABASE syntax, IF syntax, 531
414 IF Transact-SQL syntax, 533
CREATE EXTERNLOGIN syntax, 430 INCLUDE syntax, 535
CREATE FUNCTION syntax, 432 INPUT syntax, 536
CREATE INDEX syntax, 435 INSERT syntax, 540
CREATE MESSAGE Transact-SQL syntax, 439 INSTALL syntax, 542
CREATE PROCEDURE syntax, 440 LEAVE syntax, 544
CREATE PROCEDURE Transact-SQL syntax, LOAD TABLE syntax, 546
447 LOCK TABLE syntax, 551
CREATE SCHEMA syntax, 449 LOOP syntax, 553
CREATE SERVER syntax, 451 MESSAGE syntax, 554
CREATE TABLE syntax, 453 OPEN syntax, 556
CREATE TRIGGER syntax, 464 OUTPUT syntax, 559
CREATE TRIGGER Transact-SQL syntax, 467 PARAMETERS syntax, 563
CREATE VARIABLE syntax, 468 PREPARE syntax, 564
CREATE VIEW syntax, 469 PREPARE TO COMMIT syntax, 566
CREATE WRITEFILE syntax, 471 PRINT Transact-SQL syntax, 567
DEALLOCATE DESCRIPTOR syntax, 472 PUT syntax, 568
DECLARE CURSOR syntax, 475 QUIT syntax, 506
DECLARE CURSOR Transact-SQL syntax, 480 RAISERROR Transact-SQL syntax, 570
DECLARE LOCAL TEMPORARY TABLE READ syntax, 572
syntax, 481 READTEXT Transact-SQL syntax, 573
DECLARE syntax, 474 RELEASE SAVEPOINT syntax, 574
DELETE (positioned) syntax, 484 REMOVE syntax, 575
DELETE syntax, 482 RESIGNAL syntax, 576

1112
S–S

RESTORE syntax, 577 comparison operators, 213


RESUME syntax, 578 connection-level variables, 238
RETURN syntax, 579 constants, 219
REVOKE syntax, 581 CURRENT DATE special value, 234
ROLLBACK syntax, 583 CURRENT PUBLISHER special value, 235
ROLLBACK TO SAVEPOINT syntax, 584 CURRENT TIME special value, 234
ROLLBACK TRIGGER syntax, 585 CURRENT TIMESTAMP special value, 234
SAVEPOINT syntax, 586 CURRENT USER special value, 235
SELECT syntax, 587 EXISTS conditions, 231
sending to remote servers, 516 explicit selectivity estimates, 232
SET CONNECTION syntax, 594 expressions, 218
SET DESCRIPTOR syntax, 595 functions, 291
SET OPTION syntax, 596, 599 global variables, 239
SET OPTION Transact-SQL syntax, 593 identifiers, 211
SET SQLCA syntax, 600 IF expressions, 220
SET syntax, 591 IN conditions, 230
SET Transact-SQL syntax, 593 IS NULL conditions, 231
SETUSER syntax, 601 IS TRUE or FALSE conditions, 231
SIGNAL syntax, 603 Java expressions, 222
START DATABASE syntax, 604 join operators, 216
START ENGINE syntax, 606 keywords, 208
START JAVA syntax, 607 language elements, 207
START LOGGING syntax, 608 LAST USER special value, 236
STOP DATABASE syntax, 609 LIKE conditions, 228
STOP ENGINE syntax, 610 local variables, 237
STOP JAVA syntax, 611 logical operators, 214
STOP LOGGING syntax, 612 NULL value, 247
syntax, 365 operator precedence, 216
SYSTEM syntax, 613 operators, 213
TRIGGER EVENT syntax, 614 predicates, 226
TRUNCATE TABLE syntax, 615 reserved words, 208
UNION syntax, 617 search conditions, 226
UNLOAD syntax, 618 SOME conditions, 227
UNLOAD TABLE syntax, 619 special values, 234
UPDATE (positioned) syntax, 625 SQLCODE special value, 235
UPDATE syntax, 621 SQLSTATE special value, 235
VALIDATE INDEX syntax, 627 statements, 365
VALIDATE TABLE syntax, 628 string operators, 215
WHENEVER syntax, 630 strings, 212
WHILE syntax, 553 subqueries, 220
WHILE Transact-SQL syntax, 631 subqueries in search conditions, 227
WRITETEXT Transact-SQL syntax, 632 three-valued logic, 231
SQL syntax Transact-SQL expression compatibility, 223
ALL conditions, 227 variables, 237
ANY conditions, 227 SQL variables
arithmetic operators, 214 creating, 468
BETWEEN conditions, 227 declaring, 474
bitwise operators, 215 dropping, 499
CASE expression, 221 setting values, 591
column names, 219
comments, 246

1113
S–S

SQL/92 START LOGGING statement


conformance, 198 Interactive SQL syntax, 608
UPDATE statement, 113 starting
updates, 159 creating events for, 423
SQL_database parameter, 105 database servers, 606
SQL_FLAGGER_ERROR_LEVEL option, 198 databases, 604
SQL_flagger_error_level property, 1061 Java VM, 607
SQL_flagger_warning_leproperty, 1061 logging in Interactive SQL, 608
SQL_FLAGGER_WARNING_LEVEL option, 199 StartLine connection parameter, 59
SQL_pw parameter, 105 statement labels, 367
SQL_server parameter, 105 GOTO Transact-SQL statement, 525
SQL_user parameter, 105 statement syntax
SQLCA BEGIN and END SQL statements, 392
INCLUDE statement, 535 FROM SQL clause, 518
SQLCAs SQL, 365
setting, 600 statement-level triggers, 464
SQLCODE statements
SQL special value, 235 ALLOCATE DESCRIPTOR statement SQL
values, 633 syntax, 369
SQLCONNECT environment variable, 8 ALTER DATABASE statement SQL syntax, 371
SQLDA ALTER DBSPACE statement SQL syntax, 373
and ANSI_BLANKS, 157 ALTER EVENT statement SQL syntax, 375
DESCRIBE SQL statement, 486 ALTER PROCEDURE statement SQL syntax,
EXECUTE SQL statement, 500 377
INCLUDE statement, 535 ALTER SERVER statement SQL syntax, 378
inserting rows using cursors, 568 ALTER TABLE statement SQL syntax, 380
setting, 595 ALTER TRIGGER statement SQL syntax, 386
UPDATE (positioned) statement, 625 ALTER VIEW statement SQL syntax, 387
SQLDAs ALTER WRITEFILE statement SQL syntax, 388
allocating memory for, 369 BACKUP statement SQL syntax, 389
deallocating, 472 BEGIN DECLARE statement SQL syntax, 473
getting information from, 523 BEGIN TRANSACTION statement SQL syntax,
SQLLOCALE environment variable, 8 395
SQLPATH environment variable, 8 BREAK statement Transact-SQL syntax, 631
SQLREMOTE environment variable, 9 BYE statement SQL syntax, 506
SQLSTATE CALL statement SQL syntax, 398
SQL special value, 235 CASE statement SQL syntax, 400
values, 652 CHECKPOINT statement SQL syntax, 402
SQRT function CLEAR statement SQL syntax, 403
SQL syntax, 355 CLOSE statement SQL syntax, 404
stack overflow COMMENT statement SQL syntax, 406
errors, 29 COMMIT statement SQL syntax, 408
stack size CONFIGURE statement SQL syntax, 410
external functions, 26 CONNECT statement SQL syntax, 411
maximum, 29 CONTINUE statement Transact-SQL syntax,
START DATABASE statement 631
SQL syntax, 604 CREATE COMPRESSED DATABASE
START ENGINE statement statement SQL syntax, 414
Interactive SQL syntax, 606 CREATE DATABASE statement SQL syntax,
START JAVA statement 415
SQL syntax, 607 CREATE DBSPACE statement SQL syntax, 419

1114
S–S

CREATE DOMAIN statement SQL syntax, 421 dropping prepared, 498


CREATE EVENT statement SQL syntax, 423 END DECLARE statement SQL syntax, 473
CREATE EXISTING TABLE statement SQL EXECUTE IMMEDIATE statement SQL syntax,
syntax, 428 504
CREATE EXPANDED DATABASE statement EXECUTE statement SQL syntax, 500
SQL syntax, 414 EXECUTE statement Transact-SQL syntax, 502
CREATE EXTERNLOGIN statement SQL executing prepared, 500
syntax, 430 EXIT statement SQL syntax, 506
CREATE FUNCTION statement SQL syntax, EXPLAIN statement SQL syntax, 507
432 FETCH statement SQL syntax, 509
CREATE INDEX statement SQL syntax, 435 FOR statement SQL syntax, 514
CREATE MESSAGE statement Transact-SQL FORWARD TO statement SQL syntax, 516
syntax, 439 GET DATA statement SQL syntax, 521
CREATE PROCEDURE statement SQL syntax, GET DESCRIPTOR statement SQL syntax, 523
440 GET OPTION statement SQL syntax, 524
CREATE PROCEDURE statement Transact- GOTO statement Transact-SQL syntax, 525
SQL syntax, 447 GRANT statement SQL syntax, 526
CREATE SCHEMA statement SQL syntax, 449 grouping, 392
CREATE SERVER statement SQL syntax, 451 HELP statement SQL syntax, 530
CREATE TABLE statement SQL syntax, 453 IF statement SQL syntax, 531
CREATE TRIGGER statement SQL syntax, 464 IF statement Transact-SQL syntax, 533
CREATE TRIGGER statement Transact-SQL INCLUDE statement SQL syntax, 535
syntax, 467 INPUT statement SQL syntax, 536
CREATE VARIABLE statement SQL syntax, INSERT statement SQL syntax, 540
468 INSTALL statement SQL syntax, 542
CREATE VIEW statement SQL syntax, 469 LEAVE statement SQL syntax, 544
CREATE WRITEFILE statement SQL syntax, LOAD TABLE statement SQL syntax, 546
471 LOCK TABLE statement SQL syntax, 551
DEALLOCATE DESCRIPTOR statement SQL LOOP statement SQL syntax, 553
syntax, 472 MESSAGE statement SQL syntax, 554
DECLARE CURSOR statement SQL syntax, 475 OPEN statement SQL syntax, 556
DECLARE CURSOR statement Transact-SQL OUTPUT statement SQL syntax, 559
syntax, 480 PARAMETERS statement SQL syntax, 563
DECLARE LOCAL TEMPORARY TABLE PREPARE statement SQL syntax, 564
statement SQL syntax, 481 PREPARE TO COMMIT statement SQL syntax,
DECLARE statement SQL syntax, 474 566
DELETE (positioned) statement SQL syntax, 484 preparing, 564
DELETE statement SQL syntax, 482 PRINT statement Transact-SQL syntax, 567
DESCRIBE statement SQL syntax, 486 PUT statement SQL syntax, 568
DISCONNECT statement SQL syntax, 490 QUIT statement SQL syntax, 506
DROP CONNECTION statement SQL syntax, RAISERROR statement Transact-SQL syntax,
494 570
DROP DATABASE statement SQL syntax, 493 READ statement SQL syntax, 572
DROP EXTERNLOGIN statement SQL syntax, READTEXT statement Transact-SQL syntax,
495 573
DROP OPTIMIZER STATISTICS statement RELEASE SAVEPOINT statement SQL syntax,
SQL syntax, 496 574
DROP SERVER statement SQL syntax, 497 REMOVE statement SQL syntax, 575
DROP statement SQL syntax, 491 RESIGNAL statement SQL syntax, 576
DROP STATEMENT statement SQL syntax, 498 RESTORE statement SQL syntax, 577
DROP VARIABLE statement SQL syntax, 499 RESUME statement SQL syntax, 578

1115
S–S

RETURN statement SQL syntax, 579 statistics


REVOKE statement SQL syntax, 581 dropping optimizer, 496
ROLLBACK statement SQL syntax, 583 Interactive SQL option, 199
ROLLBACK TO SAVEPOINT statement SQL monitoring, 1052
syntax, 584 STATS communication parameter, 68
ROLLBACK TRIGGER statement SQL syntax, STOP DATABASE statement
585 SQL syntax, 609
SAVEPOINT statement SQL syntax, 586 STOP ENGINE statement
SELECT statement SQL syntax, 587 SQL syntax, 610
SET CONNECTION statement SQL syntax, 594 STOP JAVA statement
SET DESCRIPTOR statement SQL syntax, 595 SQL syntax, 611
SET OPTION statement SQL syntax, 596, 599 STOP LOGGING statement
SET OPTION statement Transact-SQL syntax, Interactive SQL syntax, 612
593 stopping
SET SQLCA statement SQL syntax, 600 database servers, 610
SET statement SQL syntax, 591 databases, 118
SET statement Transact-SQL syntax, 593 Java VM, 611
SETUSER statement SQL syntax, 601 logging in Interactive SQL, 612
SIGNAL statement SQL syntax, 603 stopping databases, 609
START DATABASE statement SQL syntax, 604 stored procedures
START ENGINE Interactive statement SQL creating, 440
syntax, 606 creating in Transact SQL, 447
START JAVA statement SQL syntax, 607 executing in dynamic SQL, 504
START LOGGING Interactive statement SQL executing in Transact-SQL, 502
syntax, 608 external function calls, 433, 443
STOP DATABASE statement SQL syntax, 609 STR function
STOP ENGINE statement SQL syntax, 610 SQL syntax, 355
STOP JAVA statement SQL syntax, 611 STRING function
STOP LOGGING Interactive statement SQL SQL syntax, 356
syntax, 612 string operators
SYSTEM Interactive statement SQL syntax, 613 SQL syntax, 215
TRIGGER EVENT statement SQL syntax, 614 string SQL functions, 297
TRUNCATE TABLE statement SQL syntax, 615 string truncation
UNION statement SQL syntax, 617 database option, 200
UNLOAD statement SQL syntax, 618 String_rtruncation property, 1061
UNLOAD TABLE statement SQL syntax, 619 STRING_RTRUNCATION Transact-SQL option
UPDATE (positioned) statement SQL syntax, setting, 593
625 strings
UPDATE statement SQL syntax, 621 and host variables, 157
VALIDATE INDEX statement SQL syntax, 627 converting to dates, 265
VALIDATE TABLE statement SQL syntax, 628 delimiter, 224
WHENEVER embedded statement SQL syntax, replacing, 348
630 SQL constants, 219
WHILE statement Transact-SQL syntax, 631 SQL syntax, 212
WRITETEXT statement Transact-SQL syntax, Transact-SQL, 224
632 STRIP option
static cursors LOAD TABLE statement, 549
declaring, 475 STUFF function
SQL syntax, 356
su
setting users, 601

1116
S–S

subdirectories syntax
NetWare, 3 SQL ALL conditions, 227
Windows CE, 3 SQL ANY conditions, 227
subqueries SQL arithmetic operators, 214
in SQL search conditions, 227 SQL BETWEEN conditions, 227
SQL syntax, 220 SQL bitwise operators, 215
SUBSCRIBE_BY_REMOTE SQL CASE expression, 221
replication option, 200 SQL column names, 219
subscriptions SQL comments, 246
updating, 621 SQL comparison operators, 213
SUBSTR function SQL connection-level variables, 238
SQL syntax, 357 SQL constants, 219
SUBSTRING function SQL CURRENT DATE special value, 234
SQL syntax, 357 SQL CURRENT PUBLISHER special value, 235
substrings SQL CURRENT TIME special value, 234
about, 357 SQL CURRENT TIMESTAMP special value,
replacing, 348 234
SUM function SQL CURRENT USER special value, 235
SQL syntax, 358 SQL EXISTS conditions, 231
sun.* packages SQL explicit selectivity estimates, 232
unsupported classes, 277 SQL expressions, 218
supported classes SQL functions, 291
Java, 276 SQL global variables, 239
java.beans, 276 SQL identifiers, 211
java.io, 277 SQL IF expressions, 220
java.lang, 277 SQL IN conditions, 230
java.lang.reflect, 277 SQL IS NULL conditions, 231
java.math, 277 SQL IS TRUE or FALSE conditions, 231
java.net, 277 SQL Java expressions, 222
java.rmi, 277 SQL join operators, 216
java.rmi.dgc, 277 SQL keywords, 208
java.rmi.registry, 277 SQL language elements, 207
java.rmi.server, 277 SQL LAST USER special value, 236
java.security, 277 SQL LIKE conditions, 228
java.security.acl, 277 SQL local variables, 237
java.security.interfaces, 277 SQL logical operators, 214
java.sql, 277 SQL NULL value, 247
java.text, 277 SQL operator precedence, 216
java.util, 277 SQL operators, 213
java.util.zip, 277 SQL predicates, 226
suser_id Adaptive Server Enterprise function, 298 SQL reserved words, 208
suser_name Adaptive Server Enterprise function, SQL search conditions, 226
298 SQL SOME conditions, 227
Sybase Central SQL special values, 234
quoted identifiers, 195 SQL SQLCODE special value, 235
registry entries, 11 SQL SQLSTATE special value, 235
starting Interactive SQL from, 100 SQL statements, 365
syntax highlighting, 192 SQL string operators, 215
SYBASE environment variable, 9 SQL strings, 212
SQL subqueries, 220
SQL subqueries in search conditions, 227

1117
S–S

SQL three-valued logic, 231 sp_changegroup, 957


SQL variables, 237 sp_dboption, 957
Transact-SQL expression compatibility, 223 sp_dropgroup, 957
syntax errors sp_droplogin, 957
joins, 174 sp_dropmessage, 957
syntax highlighiting sp_droptype, 957
comments, 192 sp_dropuser, 957
SYS group sp_getmessage, 957
in the system tables, 1017 sp_helptext, 957
system tables, 972 sp_login_environment, 945
syslog sp_password, 957
user ID for, 34 sp_remote_columns, 946
sysservers system table sp_remote_tables, 947
remote servers for Component Integration sp_servercaps, 947
Services, 452 sp_tsql_environment, 948
SYSSERVERS system table Transact-SQL, 957
adding servers, 451 Transact-SQL list, 957
system calls xp_scanf, 955
from stored procedures, 953 xp_startmail, 950
xp_cmdshell system procedure, 953 System procedures
system catalog, 1026 catalog list, 935
about, 962 overview, 934
diagram, 963 system SQL functions, 298
list, 965 SYSTEM statement
Transact-SQL, 1047 Interactive SQL syntax, 613
system functions, 298 system tables
system objects about, 962
and the dbo user, 126 diagram, 963
system procedures list, 965
about, 933 SYSARTICLE, 967
creating messages, 439 SYSARTICLECOL, 968
extended, list, 950 SYSCAPABILITY, 969
sa_audit_string, 935 SYSCAPABILITYNAME, 970
sa_check_commit, 935 SYSCOLLATE, 971
sa_conn_info, 935, 936 SYSCOLPERM, 973
sa_conn_properties, 937 SYSCOLUMN, 974
sa_conn_properties_by_name, 938 SYSDOMAIN, 976
sa_db_info, 935, 938 SYSEXTENT, 977
sa_db_properties, 939 SYSEXTERNLOGINS, 978
sa_eng_properties, 939 SYSFILE, 979
sa_flush_cache, 940 SYSFKCOL, 980
sa_index_levels, 940 SYSFOREIGNKEY, 981
sa_locks, 941 SYSGROUP, 983
sa_server_option, 942 SYSINDEX, 984
sa_table_page_usage, 944 SYSINFO, 986
sa_validate, 945 SYSIXCOL, 988
sp_addgroup, 957 SYSJAR, 989
sp_addlogin, 957 SYSJARCOMPONENT, 990
sp_addmessage, 957 SYSJAVACLASS, 991
sp_addtype, 957 SYSLOGIN, 993
sp_adduser, 957 SYSOPTION, 994

1118
T–T

SYSPROCEDURE, 995 table list


SYSPROCPARM, 996 FROM clause, 518
SYSPROCPERM, 998 table number, 1008
SYSPUBLICATION, 999 table size
SYSREMOTETYPE, 1002 limit, 932
SYSREMOTEUSER, 1003 number of rows, 932
SYSSERVERS, 1005 tables
SYSSQLSERVERTYPE, 1006 altering, 380
SYSSUBSCRIPTION, 1007 bulk loading, 546
SYSTABLE, 1008 creating, 453
SYSTABLEPERM, 1010 creating local temporary, 481
system views, 1021 creating proxy, 428
SYSTRIGGER, 1012 dropping, 491
SYSTYPEMAP, 1014 exporting data into files from, 559
SYSUSERMESSAGES, 1015 importing data from files into, 536
SYSUSERPERM, 1016 inserting rows into, 540
SYSUSERTYPE, 1018 joinging, 587
Transact-SQL, 1047 locking, 551
System tables renaming, 384
DUMMY, 966 replicating, 380
system views truncating, 615
about, 1021 unloading, 619
SYSARTICLECOLS, 1023 validating, 628
SYSARTICLES, 1024 Tables
SYSCAPABILITIES, 1025 creating proxy, 453
SYSCATALOG, 1026 TAN function
SYSCOLAUTH, 1027 SQL syntax, 358
SYSCOLUMNS, 1028 tapes
SYSFOREIGNKEYS, 1029 creating database backups, 389
SYSGROUPS, 1030 TaskSwitch property, 1061
SYSINDEXES, 1031 TCP/IP
SYSOPTIONS, 1032 connecting across firewalls, 61, 69
SYSPROCAUTH, 1033 HOST communication parameter, 64
SYSPROCPARMS, 1034 port number, 38, 66
SYSPUBLICATIONS, 1035 protocol stacks, 63
SYSREMOTEOPTIONS, 1036 server configuration, 61
SYSREMOTETYPES, 1037 server port number, 66
SYSREMOTEUSERS, 1038 tcpip
SYSSUBSCRIPTIONS, 1039 about, 37
SYSTABAUTH, 1040 TDS communication parameter, 68
SYSTRIGGERS, 1041 TempFreePercent event condition
SYSUSERAUTH, 1042 about, 323
SYSUSERLIST, 1043 TempFreeSpace event condition
SYSUSEROPTIONS, 1044 about, 323
SYSUSERPERMS, 1045 temporary file
SYSVIEWS, 1046 location, 6, 9
security, 6
temporary options
setting, 596
T setting in Interactive SQL, 599
table constraints, 458

1119
T–T

temporary tables timestamp column, 457


creating, 453, 454 timestamp data type, 265
declaring local, 481 TIMESTAMP data type
Transact-SQL, 461 about, 271
views disallowed on local, 469 comparing, 171
TempSize event condition timestamp format
about, 323 database option, 201
text TIMESTAMP_FORMAT option, 201
reading from the database, 573 Timestamp_format property, 1061
TEXT data type TINYINT data type
about, 254 about, 261
TEXT file format, 190 TMP, TEMP, and TMPDIR environment variable, 9
text SQL functions, 300 TO communication parameter, 69
TEXTPTR function TODAY function, 966
SQL syntax, 359 SQL syntax, 359
TEXTSIZE Transact-SQL option TotalBuffers property, 1065
setting, 593 TRACEBACK function
THEN SQL syntax, 359
SQL IF expressions, 220 trademark information
thread count retrieving, 953
database option, 200 TRANSACTION ISOLATION LEVEL Transact-
THREAD_COUNT option, 149, 200 SQL option
Thread_count property, 1061 setting, 593
threads transaction log
execution, 28 dblog, 121, 122
multiple processors, 29 delete after checkpoint, 31
number of, 30 erasing, 88
THREADS communication parameter, 68 translation utilities, 110
THREADSTATS communication parameter, 68 translation utility, 109
three-valued logic TRUNCATE TABLE statement, 615
NULL value, 247 utilities, 121
SQL syntax, 231 transaction logs
time data type, 265 allocating space for, 373
TIME data type backing up, 389
about, 270 transaction management
time format BEGIN TRANSACTION SQL statement, 395
database option, 200 in Transact-SQL, 395
time functions Transact-SQL, 408
SQL, 292 transaction modes
TIME_FORMAT option, 149, 200 chained, 163, 395
Time_format property, 1061 unchained, 163, 395
TIMEOUT communication parameter, 69 transactions
times beginning user-defined, 395
comparing, 267 closing cursors, 165
queries, 266 committing, 408
sending to the database, 265 creating savepoints, 586
SQL conversion functions, 292 distributed, 35
timestamp nesting user-defined, 395
DEFAULT_TIMESTAMP_INCREMENT rolling back, 583
option, 171 rolling back to savepoints, 584
timestamp columns, 161

1120
T–T

Transact-SQL triggering
ALLOW_NULLS_BY_DEFAULT option, 157 events, 614
AUTOMATIC_TIMESTAMP option, 161 TriggerPages property, 1065
bit data type compatibility, 264 triggers
bitwise operators, 215 @@identity global variable, 245
BREAK statement syntax, 631 altering, 386
catalog procedures, 958 and referential integrity actions, 197
column NULLs compatibility, 157, 195 and replication, 174, 175
compatibility options, 152 creating, 464
constants, 224 creating in Transact-SQL, 467
CONTINUE statement syntax, 631 disabling, 27
CREATE MESSAGE SQL statement syntax, 439 dropping, 491
CREATE PROCEDURE statement syntax, 447 rolling back, 585
CREATE SCHEMA statement syntax, 449 row-level, 464
CREATE TABLE statement syntax, 461 statement-level, 464
CREATE TRIGGER statement syntax, 467 TRUNCATE TABLE statement, 615
datetime compatibility, 265 TRIM function
DECLARE CURSOR statement syntax, 480 SQL syntax, 360
DECLARE section, 393 troubleshooting
delete permissions, 158 connections, 114, 116
domains, 275 debugging, 39, 40
EXECUTE statement syntax, 502 identifying client applications, 46
global variables, 239 locks, 941
GOTO statement syntax, 525 logging operations, 943
IF statement syntax, 533 logging server operations, 40
join operators, 216 request_level_logging, 942
local variables, 237, 238 TRUE conditions
money data types, 263 IS TRUE conditions, 231
NULL behavior, 160 TRUNCATE function
PRINT statement syntax, 567 SQL syntax, 360
QUOTED_IDENTIFIER option, 195, 224 TRUNCATE TABLE statement
RAISERROR statement syntax, 570 autocommit behavior, 202
READTEXT statement syntax, 573 SQL syntax, 615
SET OPTION statement syntax, 593 TRUNCATE_DATE_VALUES option
SET statement syntax, 593 about, 202
SQL comparison operators, 213 TRUNCATE_WITH_AUTO_COMMIT option
SQL expression compatibility, 223 about, 202
statement syntax, 365 Truncate_with_autocomproperty, 1061
strings, 224 truncating
system catalog, 1047 tables, 615
system functions, 298 Truncation
system procedures, 957 of character strings, 200
time compatibility, 265 truncation length
update permissions, 158 Interactive SQL option, 203
user-defined data types, 275 TRUNCNUM function
WHILE statement syntax, 631 SQL syntax, 361
WRITETEXT statement syntax, 632 tsequal Adaptive Server Enterprise function, 298
trapping TSQL
errors in embedded SQL, 630 statement indicator, 368
TRIGGER EVENT statement TSQL_HEX_CONSTANT option, 203
SQL syntax, 614 Tsql_hex_constant property, 1061

1121
U–U

TSQL_VARIABLES option, 204 java.awt.image, 277


Tsql_variables property, 1061 sun.*, 277
two-phase commit updatable viewa, 540
preparing for, 566 UPDATE
type conversions, 281 IF UPDATE clause, 464
types IF UPDATE clause in Transact-SQL, 467
about data types, 251 UPDATE (positioned) statement
SQL syntax, 625
update column permission, 973
UPDATE permissions
U granting, 526
UCASE function UPDATE statement
SQL syntax, 361 SQL syntax, 621
UID connection parameter, 60 truncation of strings, 200
UNC connection parameter, 59 updates
unchained transaction mode, 163, 395 ANSI behavior, 158, 159
UncommitOp property, 1061 based on joins, 624
uncompressing SQL/92behavior, 159
database files, 124 Transact-SQL permissions, 158
uncompression utility updating
command-line syntax, 124 columns without logging, 632
Unconditional connection parameter, 59 publications and subscriptions, 621
undoing rows, 621
changes by rolling back transactions, 583 upgrading
UNION statement databases, 133, 371
SQL syntax, 617 UPPER function
unions SQL syntax, 362
of multiple select statements, 617 usage information
unique displaying, 20
constraint, 458 used_pgs Adaptive Server Enterprise function, 298
unique indexes, 436 USER
UNIX special value, 966
environment variables, 6 user Ids
UNKNOWN conditions revoking, 581
IS UNKNOWN conditions, 231 user IDs
UNLOAD statement changing permissions and passwords, 526
SQL syntax, 618 creating, 526
UNLOAD TABLE statement in the system tables, 1009, 1016
SQL syntax, 619 system views, 1042
unloading user number, 1016
databases, 126 user_id Adaptive Server Enterprise function, 298
result sets, 618 user_name Adaptive Server Enterprise function, 298
tables, 619 user-defined data types
unloading data about, 274
multi-byte character sets, 620 creating, 421
UnschReq property, 1065 dropping, 491
unsupported classes Transact-SQL, 275
java.applet, 277 user-defined functions
java.awt, 277 creating, 432
java.awt.event, 277 exiting from, 579
Java, 294

1122
V–V

returning values from, 579 valid_user Adaptive Server Enterprise function, 298
SQL, 294 VALIDATE INDEX statement
Userid connection parameter, 60 SQL syntax, 627
Userid property, 1061 VALIDATE TABLE statement
users SQL syntax, 628
dropping, 581 validating
setting, 601 databases, 136, 945
user-supplied selectivity estimates indexes, 627
SQL syntax, 232 tables, 628
UseUDP communication parameter, 69 validation utility
utilities command-line syntax, 137
backup, 74 values
collation, 78 returning from procedures, 579
compression, 81 VARBINARY data type
dbbackup command-line syntax, 75 about, 273
dbcollat command-line syntax, 78 VARCHAR data type, 253
dbconsol command-line syntax, 83 variable result sets
dbdsn command-line syntax, 84 from procedures, 441, 488, 565
dberase command-line syntax, 89 variables
dbexpand command-line syntax, 124 creating SQL, 468
dbinfo command-line syntax, 90 declaring SQL, 474
dbinit command-line syntax, 93 dropping SQL, 499
dbisql command-line syntax, 99 getting from within a descriptor area, 523
dblic command-line syntax, 101 setting values, 591
dblocate command-line syntax, 116 SQL global variables, 238, 239
dblog command-line syntax, 120 SQL local variables, 237
dbltm command-line syntax, 103 SQL syntax, 237
dbping command-line syntax, 114 VERIFY_ALL_COLUMNS
dbshrink command-line syntax, 81 replication option, 204
dbspawn command-line syntax, 117 VERIFY_THRESHOLD
dbstop command-line syntax, 118 replication option, 204
dbtran command-line syntax, 109 version
dbunload command-line syntax, 127 database server, 37
dbupgrad command-line syntax, 134 version mismatch
dbvalid command-line syntax, 137 file locations, 4
dbwrite command-line syntax, 140 version number
erase, 88 retrieving, 953
information, 90 ViewPages property, 1065
initialization, 92 views
Interactive SQL, 99 altering, 387
log translation, 109 creating, 469
rebuild, 115 dropping, 491
rebuild command-line syntax, 115 examples, 1021
utility commands indexes, 435
permissions, 30 system views, 1046
updatable, 540
VM
starting Java, 607
V stopping Java, 611
valid_name Adaptive Server Enterprise function,
298

1123
W–Y

WITH HOLD clause


W OPEN SQL statement, 556
WAIT_FOR_COMMIT option, 149, 205
write files
Wait_for_commit property, 1061
altering, 388
warnings
creating, 471
error messages, 693
erasing, 88
SQLSTATE values, 652
managing, 139
Watcom-SQL
managing using dbwrite, 140
DECLARE statement, 474
WRITETEXT statement
WATFILE file format, 177, 190
Transact-SQL syntax, 632
WEEKS function
SQL syntax, 362
WHEN
SQL CASE expression, 221 X
WHENEVER statement xp_cmdshell system procedure, 953
embedded SQL syntax, 630 xp_msver system, 953
WHERE clause xp_read_file system procedure, 954
SELECT statement, 589 xp_scanf system procedure, 955
WHILE statement xp_sendmail system procedure, 951
SQL syntax, 553 xp_sprintf system procedure, 955
Transact-SQL syntax, 631 xp_startmail system procedure, 950
wide inserts, 501 xp_stopmail system procedure, 952
wild cards xp_write_file system procedure, 956
pattern matching, 342
Windows CE
file locations, 3
installation, 3 Y
subdirectories, 3 Y2K, 285
Windows NT year 2000
event log, 18 compliance, 285
Windows NT performance monitor, 1052 NEAREST_CENTURY option, 187
Windows NT services YEARS function
registry entries, 10 SQL syntax, 363
WITH CHECKPOINT option YMD function
LOAD TABLE statement, 549 SQL syntax, 364

1124

Você também pode gostar