0% found this document useful (0 votes)
99 views1,394 pages

DB Reference 12

Referencia de sql anywere vers 12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views1,394 pages

DB Reference 12

Referencia de sql anywere vers 12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1394

SQL Anywhere® Server

SQL Reference

Version 12.0.1

January 2012

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Version 12.0.1
January 2012

Copyright © 2012 iAnywhere Solutions, Inc. Portions copyright © 2012 Sybase, Inc. All rights reserved.

This documentation is provided AS IS, without warranty or liability of any kind (unless provided by a separate written agreement between
you and iAnywhere).

You may use, print, reproduce, and distribute this documentation (in whole or in part) subject to the following conditions: 1) you must
retain this and all other proprietary notices, on all copies of the documentation or portions thereof, 2) you may not modify the
documentation, 3) you may not do anything to indicate that you or anyone other than iAnywhere is the author or source of the
documentation.

iAnywhere®, Sybase®, and the marks listed at http://www.sybase.com/detail?id=1011207 are trademarks of Sybase, Inc. or its subsidiaries.
® indicates registration in the United States of America.

All other company and product names mentioned may be trademarks of the respective companies with which they are associated.
Contents

About this book ..................................................................................... v

SQL language elements ........................................................................ 1


Keywords .............................................................................................................. 1
Identifiers .............................................................................................................. 4
Strings .................................................................................................................. 5
Constants ............................................................................................................. 6
Operators .............................................................................................................. 8
Expressions ....................................................................................................... 12
Search conditions .............................................................................................. 32
Special values .................................................................................................... 58
Variables ............................................................................................................. 72
Comments .......................................................................................................... 79

SQL data types ..................................................................................... 81


Character data types ......................................................................................... 81
Numeric data types ............................................................................................ 89
Money data types ............................................................................................... 98
Bit array data types ........................................................................................... 99
Date and time data types ................................................................................ 101
Binary data types ............................................................................................. 117
Domains ............................................................................................................ 120
Data type conversions .................................................................................... 122
Spatial data types ............................................................................................ 132

SQL functions .................................................................................... 133


Function types ................................................................................................. 133
Functions .......................................................................................................... 145

SQL statements ................................................................................. 395

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 iii


SQL Anywhere® Server - SQL Reference

Common elements in SQL syntax .................................................................. 395


Syntax conventions ......................................................................................... 396
Statement applicability indicators ................................................................. 398
SQL statements ............................................................................................... 398

Tables ................................................................................................. 965


System tables ................................................................................................... 965
Diagnostic tracing tables ................................................................................ 980
Other tables ...................................................................................................... 993

System procedures ........................................................................... 995


Viewing details about system procedures and functions ........................... 995
Web services system procedures .................................................................. 996
MAPI and SMTP procedures ........................................................................... 996
Adaptive Server Enterprise system and catalog procedures ...................... 999
Alphabetical list of system procedures ....................................................... 1001

Views ................................................................................................. 1195


System views ................................................................................................. 1195
Consolidated views ....................................................................................... 1260
Compatibility views ....................................................................................... 1280
Views for Transact-SQL compatibility ......................................................... 1288

Index ................................................................................................. 1291

iv Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


About this book
This book provides reference information for system procedures, and the catalog (system tables and
views). It also provides an explanation of the SQL Anywhere implementation of the SQL language
(search conditions, syntax, data types, and functions).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 v


vi Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1
SQL language elements

Keywords
Each SQL statement contains one or more keywords. SQL is case insensitive to keywords, but throughout
the documentation, keywords are indicated in uppercase.

For example, in the following statement, SELECT and FROM are keywords:
SELECT *
FROM Employees;

The following statements are equivalent to the one above:


Select *
From Employees;
select * from Employees;
sELECT * FRoM Employees;

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, square brackets or back quotes. Many, but not all, 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"

SQL keywords are not case sensitive and the following words may appear in uppercase, lowercase, or any
combination of the two. All strings that differ only in capitalization from one of the following words are
reserved words.

You can also turn off keywords using the non_keywords option.

The reserved_keywords option turns on individual keywords that are disabled by default.

If you are using embedded SQL, you can use the sql_needs_quotes database library function 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.

You can obtain a list of the reserved words using the sa_reserved_words system procedure.

The reserved SQL keywords in SQL Anywhere are:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1


SQL language elements

add all alter and

any as asc attach

backup begin between bigint

binary bit bottom break

by call capability cascade

case cast char char_convert

character check checkpoint close

comment commit compressed conflict

connect constraint contains continue

convert create cross cube

current current_timestamp current_user cursor

date datetimeoffset dbspace deallocate

dec decimal declare default

delete deleting desc detach

distinct do double drop

dynamic else elseif encrypted

end endif escape except

exception exec execute existing

exists externlogin fetch first

float for force foreign

forward from full goto

grant group having holdlock

identified if in index

inner inout insensitive insert

inserting install instead int

2 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Keywords

integer integrated intersect into

is isolation join kerberos

key lateral left like

limit lock login long

match membership merge message

mode modify natural nchar

new no noholdlock not

notify null numeric nvarchar

of off on open

openstring openxml option options

or order others out

outer over passthrough precision

prepare primary print privileges

proc procedure publication raiserror

readtext real reference references

refresh release remote remove

rename reorganize resource restore

restrict return revoke right

rollback rollup save savepoint

scroll select sensitive session

set setuser share smallint

some spatial sqlcode sqlstate

start stop subtrans subtransaction

synchronize table temporary then

time timestamp tinyint to

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 3


SQL language elements

top tran treat trigger

truncate tsequal unbounded union

unique uniqueidentifier unknown unsigned

update updating user using

validate values varbinary varbit

varchar variable varying view

wait waitfor when where

while window with within

work writetext xml

See also
● “sql_needs_quotes function” [SQL Anywhere Server - Programming]
● “non_keywords option” [SQL Anywhere Server - Database Administration]
● “reserved_keywords option” [SQL Anywhere Server - Database Administration]
● “sa_reserved_words system procedure” on page 1112

Identifiers
Identifiers are the names of objects in the database, such as user IDs, tables, and columns.

Remarks
Identifiers have a maximum length of 128 bytes. An identifier must be enclosed in double quotes, square
brackets, or back quotes (`...`) if any of the following conditions are true:

● The identifier contains spaces.

● The first character of the identifier is not an alphabetic character (as defined below).

● The identifier is a reserved word.

● The identifier contains characters other than alphabetic characters and digits.

Alphabetic characters include the alphabet, the underscore character (_), at sign (@), number sign (#),
and dollar sign ($). The database collation sequence dictates which characters are considered alphabetic or
digit characters.

The following characters are not permitted in identifiers:

● Double quotes

4 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Strings

● Control characters (any character less than 0x20)

● Backslashes

If the quoted_identifier database option is set to Off, double quotes are used to delimit SQL strings and
cannot be used for identifiers. However, you can use square brackets or back quotes to delimit identifiers,
regardless of the setting of quoted_identifier. The default setting for the quoted_identifier option is Off for
Open Client and jConnect connections; otherwise, the default is On.

Standards and compatibility


● SQL/2008 The ability to create identifiers of up to 128 characters is optional SQL language feature
F391 of the SQL/2008 standard.

See also
● “Reserved words” on page 1
● “quoted_identifier option” [SQL Anywhere Server - Database Administration]

Examples
The following are all valid identifiers.

● Surname
● "Client Name"
● `Client Name`
● [Surname]
● SomeBigName

Strings
A string is a sequence of characters up to 2 GB in size. A string can occur in SQL:

● as a string literal. A string literal is a sequence of characters enclosed in single quotes (apostrophes). A
string literal represents a particular, constant value, and it may contain escape sequences for special
characters that cannot be easily typed as characters.

● as the value of a column or variable with a CHAR or NCHAR data type.

● as the result of evaluating an expression.

The length of a string can be measured in two ways:

● Byte length The byte length is the number of bytes in the string.

● Character length The character length is the number of characters in the string, and is based on
the character set being used.

For single-byte character sets, such as cp1252, the byte-length and character-length are the same. For
multibyte character sets, a string's byte-length is greater than or equal to its character-length.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 5


SQL language elements

See also
● “String literals” on page 7

Constants
This section describes binary literals and string literals.

Binary literals
A binary literal is a sequence of hexadecimal characters consisting of digits 0-9 and uppercase and
lowercase letters A-F. When you enter binary data as literals, you must precede the data by 0x (a zero,
followed by an x), and there should be an even number of digits to the right of this prefix. For example,
the hexadecimal equivalent of 39 is 0027, and is expressed as 0x0027.

Hexadecimal constants in the form of 0x12345678 are treated as binary strings. An unlimited number of
digits can be added after the 0x.

A binary literal is sometimes referred to as a binary constant. In SQL Anywhere, the preferred term is
binary literal.

Converting to and from hexadecimal values


You can use the CAST, CONVERT, HEXTOINT, and INTTOHEX functions to convert a binary string to
an integer. The CAST and CONVERT functions convert hexadecimal constants to TINYINT, signed and
unsigned 32-bit integer, signed and unsigned 64-bit integer, NUMERIC, and so on. The HEXTOINT
function only converts a hexadecimal constant to a signed 32-bit-integer.

The value returned by the CAST function cannot exceed 8 digits. Values exceeding 8 digits return an
error. Zeros are added to the left of values less than 8 digits. For example, the following argument returns
the value -2,147,483,647:
SELECT CAST ( 0x0080000001 AS INT );

The following argument returns an error because the 10-digit value cannot be represented as a signed 32-
bit integer:
SELECT CAST ( 0xff80000001 AS INT );

The value returned by the HEXTOINT function can exceed 8 digits if the value can be represented as a
signed 32-bit integer. The HEXTOINT function accepts string literals or variables consisting only of
digits and the uppercase or lowercase letters A-F, with or without a 0x prefix. The hexadecimal value
represents a negative integer when the 8th digit from the right is one of the digits 8-9, the uppercase or
lowercase letters A-F, or the previous leading digits are all uppercase or lowercase letter F.

The following arguments return the value -2,147,483,647:


SELECT HEXTOINT( '0xFF80000001' );
SELECT HEXTOINT( '0x80000001' );

6 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Constants

SELECT HEXTOINT ( '0xFFFFFFFFFFFFFFFF80000001' );

The following argument returns an error because the argument represents a positive integer value that
cannot be represented as a signed 32-bit integer:
SELECT HEXTOINT( '0x0080000001' );

See also
● “CAST function [Data type conversion]” on page 159
● “CONVERT function [Data type conversion]” on page 172
● “HEXTOINT function [Data type conversion]” on page 234
● “INTTOHEX function [Data type conversion]” on page 250

String literals
A string literal is a sequence of characters enclosed in single quotes. For example, 'Hello world' is a
string literal of type CHAR. Its byte length is 11, and its character length is also 11.

A string literal is sometimes referred to as a string constant, literal string, or just as a string. In SQL
Anywhere, the preferred term is string literal.

You can specify an NCHAR string literal by prefixing the quoted value with N. For example, N'Hello
world' is a string literal of type NCHAR. Its byte length is 11, and its character length is 11. The bytes
within an NCHAR string literal are interpreted using the database's CHAR character set, and then
converted to NCHAR. The syntax N'string' is a shortened form for CAST( 'string' AS
NCHAR ).

Escape sequences
Sometimes you need to put characters into string literals that cannot be typed or entered normally.
Examples include control characters (such as a new line character), single quotes (which would otherwise
mark the end of the string literal), and hexadecimal byte values. For this purpose, you use an escape
sequence.

The following examples show how to use escape sequences in string literals.

● A single quote is used to mark the beginning and end of a string literal, so a single quote in a string
must be escaped using an additional single quote, as follows: 'John''s database'

● 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.
Hexadecimal escape sequences can be used for any character or binary value. A hexadecimal escape
sequence is a backslash followed by an x followed by two hexadecimal digits. The hexadecimal value
is interpreted as a character in the CHAR character set for both CHAR and NCHAR string literals. The
value \x09 must be coded as \\x09 if you don't want the value stored as a single tab character, but \xyy
would be stored as \xyy. The following example, in code page 1252, represents the digits 1, 2, and 3,
followed by the euro currency symbol: '123\x80'.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 7


SQL language elements

● A backslash character in a string must be escaped using an additional backslash, as follows: 'c:\
\november'. For paths, you can also use the forward slash (/) instead of a backslash: 'c:/
november'.

● To represent a new line character, use a backslash followed by n (\n), specify: 'First line:
\nSecond line:'

You can use the same characters and escape sequences with NCHAR string literals as with CHAR string
literals.

If you need to use Unicode characters that cannot be typed directly into the string literal, use the UNISTR
function.

See also
● “UNISTR function [String]” on page 371

Operators
This section describes arithmetic, string, and bitwise operators.

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.

See also
● “Operator precedence” on page 12
● “Search conditions” on page 32

Comparison operators
The syntax for comparison is as follows:

expression comparison-operator expression

where comparison-operator is one of the following:

Operator Description

= Equal to

> Greater than

< Less than

8 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Operators

Operator Description

>= Greater than or equal to

<= Less than or equal to

!= Not equal to

<> Not equal to

!> Not greater than

!< Not less than

Case sensitivity
By default, SQL Anywhere databases are created as case insensitive. Comparisons are carried out with the
same attention to case as the database they are operating on. You can control the case sensitivity of SQL
Anywhere databases with the -c option when you create the database.

Case sensitivity is set at database creation.

Note
All string comparisons are case insensitive unless the database was created as case sensitive.

Trailing blanks
The behavior of SQL Anywhere when comparing strings is set at database creation.

See also
● “Case sensitivity” [SQL Anywhere Server - SQL Usage]
● “Ignore trailing blanks in comparisons” [SQL Anywhere Server - SQL Usage]

Logical operators
Search conditions can be combined using the AND or OR operators. You can also negate them using the
NOT operator, or test whether an expression would evaluate to true, false, or unknown, using the IS
operator.

● AND operator The AND operator is placed between search conditions as follows:

.. WHERE condition1 AND condition2


When using AND, the combined condition is TRUE if both conditions are TRUE, FALSE if either
condition is FALSE, and UNKNOWN otherwise.

● OR operator The OR operator is placed between search conditions as follows:

.. WHERE condition1 OR condition2

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 9


SQL language elements

When using OR, the combined condition is TRUE if either condition is TRUE, FALSE if both
conditions are FALSE, and UNKNOWN otherwise.

● NOT operator The NOT operator is placed before a condition to negate the condition, as follows:

.. WHERE NOT condition

The NOT condition is TRUE if condition is FALSE, FALSE if condition is TRUE, and UNKNOWN
if condition is UNKNOWN.

● IS operator The IS operator is placed between an expression and the truth value you are testing
for. The syntax for the IS operator is as follows:

expression IS [ NOT ] truth-value

The IS 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 example, 5*3=15 IS TRUE tests whether the expression 5*3=15 evaluates to TRUE.

See also
● “Three-valued logic” on page 55

Arithmetic operators
expression + expression Addition. If either expression is the NULL value, the result is NULL.

expression - expression Subtraction. If either expression is the NULL value, the result is NULL.

-expression Negation. If the expression is the NULL value, the result is NULL.

expression * expression Multiplication. If either expression is NULL, the result is NULL.

expression / expression Division. If either expression is NULL or if the second expression is 0, the
result is NULL.

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.

Standards and compatibility


● SQL/2008 The use of % as a modulus operator is a vendor extension.

String operators
expression || expression String concatenation (two vertical bars). If either string is NULL, it is
treated as the empty string for concatenation.

10 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Operators

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.

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.

Standards and compatibility


● SQL/2008 The || operator is the SQL/2008 string concatenation operator. However, in the SQL
standard, if either operand of || is the NULL value the result of the concatenation is also NULL. With
SQL Anywhere, the || operator treats NULL as an empty string.

Bitwise operators
The following operators can be used on bit data types, integer data types (including all variants such as
bit, tinyint, smallint and so on), binary values, and bit array data types in SQL Anywhere.

Operator Description

& bitwise AND

| bitwise OR

^ bitwise exclusive OR

~ bitwise NOT

The bitwise operators &, | and ~ are not interchangeable with the logical operators AND, OR, and NOT.

Standards and compatibility


● SQL/2008 Vendor extension. Bitwise operators, along with the BIT VARYING and BIT datatypes,
were supported in the SQL/1999 standard as SQL language feature F511. This feature was eliminated
outright from the SQL/2003 standard.

Example
For example, the following statement selects rows in which the correct bits are set.

SELECT *
FROM tableA
WHERE ( options & 0x0101 ) <> 0;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 11


SQL language elements

Join operators
Note
Support for Transact-SQL outer join operators *= and =* is deprecated. To use Transact SQL outer joins,
the tsql_outer_joins database option must be set to On.

SQL Anywhere supports two additional comparison operators, *= and =*, which are the Transact-SQL
outer join operators. When one of these operators is used in a comparison predicate, an implicit LEFT or
RIGHT OUTER JOIN is specified.

See also
● “tsql_outer_joins option” [SQL Anywhere Server - Database Administration]
● “Transact-SQL outer joins (*= or =*)” [SQL Anywhere Server - SQL Usage]

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 (operators that require a single operand)

2. &, |, ^, ~

3. *, /, %

4. +, -

5. ||

6. not

7. and

8. or

When you use more than one operator in an expression, it is recommended that you make the order of
operation explicit using parentheses.

Expressions
An expression is a statement that can be evaluated to return values.

Syntax
expression:
case-expression

12 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

| constant
| [correlation-name.]column-name
| - expression
| expression operator expression
| ( expression )
| function-name ( expression, ... )
| if-expression
| special value
| ( subquery )
| variable-name
| sequence-expression

case-expression :
CASE expression
WHEN expression
THEN expression,...
[ ELSE expression ]
END

alternative form of case-expression :


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

sequence-expression :
sequence-name.[ CURRVAL | NEXTVAL ]
FROM table-name

operator:
{ + | - | * | / | || | % }

Remarks
Expressions are used in many different places.

Expressions are formed from several different kinds of elements. These are discussed in the sections on
functions and variables.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 13


SQL language elements

You must be connected to the database in order evaluate expressions.

Side effects
None.

See also
● “Constants in expressions” on page 14
● “Special values” on page 58
● “Column names in expressions” on page 14
● “SQL functions” on page 133
● “Subqueries in expressions” on page 15
● “Search conditions” on page 32
● “SQL data types” on page 81
● “Variables” on page 72
● “CASE expressions” on page 16

Standards and compatibility


● See the separate descriptions of each class of expression, in the following sections.

Constants in expressions
Constants are numbers or string literals. String constants are enclosed in apostrophes ('single quotes'). An
apostrophe is represented inside a 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.

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:

● Employees.Name
● address
● "date hired"
● "salary"."date paid"

See also
● “Identifiers” on page 4
● “FROM clause” on page 738

14 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

Subqueries in expressions
A subquery is a SELECT statement that is nested inside another SELECT, INSERT, UPDATE, or
DELETE statement, or another subquery.

If a subquery matches no rows, it evaluates to NULL.

The SELECT statement must be enclosed in parentheses, and 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.

See also
● “Subqueries in search conditions” on page 34

IF expressions
The syntax of the IF expression is as follows:

IF condition
THEN expression1
[ ELSE expression2 ]
{ ENDIF | END IF }

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 UNKNOWN, the IF expression returns NULL.

expression1 is evaluated only if condition is TRUE. Similarly, expression2 is evaluated only if condition
is FALSE. Both expression1 and expression2 are arbitrary expressions; condition is any valid search
condition.

Note
The IF expression is not the same as the IF statement.

Standards and compatibility


● SQL/2008 Vendor extension. The SQL/2008 standard defines the NULLIF, COALESCE, and
CASE expressions which can substitute for an IF expression.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 15


SQL language elements

See also
● “IF statement” on page 769
● “Search conditions” on page 32
● “NULL special value” on page 64

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-1
WHEN expression-2
THEN expression-3, ...
[ ELSE expression-4 ]
{ END | END CASE }

If the expression following the CASE clause is equal to the expression following the WHEN clause, then
the expression following the THEN statement is returned. Otherwise the expression following the ELSE
statement is returned, if it exists.

the CASE expression returns NULL if the ELSE clause doesn't exist and expression-1' doesn't match any
of the expression-2...expression-n values.

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 Products;

An alternative syntax is as follows:

CASE
WHEN search-condition
THEN expression-1, ...
[ ELSE expression-2 ]
END [ CASE ]

If the search-condition following the WHEN clause is satisfied, the expression following the THEN
statement is returned. Otherwise the expression following the ELSE statement is returned, if it exists.

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

16 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

WHEN Name='Tee Shirt' then 'Sale'


WHEN Quantity >= 50 then 'Big Sale'
ELSE 'Regular price'
END ) as Type
FROM Products;

NULLIF function for abbreviated CASE expressions


The NULLIF function provides a way to write some CASE clauses in short form. The syntax for NULLIF
is as follows:

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.

Note
Do not confuse the syntax of the CASE expression with that of the CASE clause.

Standards and compatibility


● SQL/2008 The CASE expression is a core feature of the SQL/2008 standard. The standard permits
any expression referenced by the statement to be evaluated at any point during execution. With SQL
Anywhere, expression evaluation occurs when each WHEN clause is evaluated, in their syntactic
order, with the exception of constant values that can be determined at compile time.

Support for END CASE with CASE expressions, in addition to END, is a vendor extension. The SQL/
2008 standard defines END for use with CASE expressions and END CASE for use with CASE
clauses.

See also
● “CASE statement” on page 493

Regular expressions overview


A regular expression is a sequence of characters, wildcards, or operators that defines a pattern to search
for within a string. SQL Anywhere supports regular expressions as part of a REGEXP or SIMILAR TO
search conditions in the WHERE clause of a SELECT statement, or as an argument to the
REGEXP_SUBSTR function. The LIKE search condition does not support regular expressions, although
some of the wildcards and operators you can specify with LIKE resemble the regular expression
wildcards and operators.

The following SELECT statement uses a regular expression ((K|C[^h])%) to search the Contacts table
and return contacts whose last name begins with K or C, but not Ch:

SELECT Surname, GivenName


FROM Contacts
WHERE Surname SIMILAR TO '(K|C[^h])%';

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 17


SQL language elements

A regular expression can include additional syntax to specify grouping, quantification, assertions, and
alternation, as described below.

● Grouping Grouping allows you to group parts of a regular expression to apply some additional
matching criteria. For example, '(abc){2}' matches abcabc.

You can also use grouping to control the order in which the parts of the expression are evaluated. For
example, 'ab(cdcd)' looks first for an incidence of cdcd, and then evaluates whether the instance
of cdcd is preceded by ab.

● Quantification Quantification allows you to control the number of times the preceding part of the
expression can occur. For example, a question mark (?) is a quantifier that matches zero or one
instance of the previous character. So, 'honou?r' matches both honor and honour.

● Assertions Normally, searching for a pattern returns that pattern. Assertions allow you to test for
the presence of a pattern, without having that pattern become part of what is returned. For example,
'SQL(?= Anywhere)' matches SQL only if it is followed by a space and then Anywhere.

● Alternation Alternation allows you to specify alternative patterns to search for if the preceding
pattern cannot be found. Alternate patterns are evaluated from left to right, and searching stops at the
first match. For example, 'col(o|ou)r' looks for an instance of color. If no instance is found,
colour is searched for instead.

See also
● “Regular expressions syntax” on page 18
● “Search conditions” on page 32
● “LIKE, REGEXP, and SIMILAR TO search conditions” on page 37
● “REGEXP search condition” on page 43
● “SIMILAR TO search condition” on page 45
● “REGEXP_SUBSTR function [String]” on page 305

Regular expressions syntax


Regular expressions are supported with the SIMILAR TO, and REGEXP search conditions, and the
REGEXP_SUBSTR function. For SIMILAR TO, regular expression syntax is consistent with the
ANSI/ISO SQL standard. For REGEXP and REGEXP_SUBSTR, regular expression syntax and support
is consistent with Perl 5.

Regular expressions are used by REGEXP and SIMILAR TO to match a string, whereas regular
expressions are used by REGEXP_SUBSTR to match a substring. To achieve substring matching
behavior for REGEXP and SIMILAR TO, you can specify wildcards on either side of the pattern you are
trying to match. For example, REGEXP '.*car.*' matches car, carwash, and vicar. Or, you can
rewrite your query to make use the REGEXP_SUBSTR function.

Regular expression matching with SIMILAR TO is case- and accent-insensitive. REGEXP and
REGEXP_SUBSTR is not affected by the database accent and case sensitivity.

18 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

Regular expressions: Metacharacters


Metacharacters are symbols or characters that have a special meaning within a regular expression.

The treatment of metacharacters can vary depending on:

● whether the regular expression is being used with the SIMILAR TO or REGEXP search conditions, or
the REGEXP_SUBSTR function

● whether the metacharacter is inside of a character class in the regular expression

Before continuing, you should understand the definition of a character class. A character class is a set of
characters enclosed in square brackets, against which characters in a string are matched. For example, in
the syntax SIMILAR TO 'ab[1-9]', [1-9] is a character class and matches one digit in the range of 1
to 9, inclusive. The treatment of metacharacters in a regular expression can vary depending on whether
the metacharacter is placed inside a character class. Specifically, most metacharacters are handled as
regular characters when positioned inside of a character class.

For SIMILAR TO (only), the metacharacters *, ?, +, _, |, (, ), { must be escaped within a character class.

To include a literal minus sign (-), caret (^), or right-angle bracket (]) character in a character class, it
must be escaped.

The list of supported regular expression metacharacters is provided below. Almost all metacharacters are
treated the same when used by SIMILAR TO, REGEXP, and REGEXP_SUBSTR:

Character Additional information

[ and ] Left and right square brackets are used to specify a character class. A character class is
a set of characters to match against.

With the exception of the hyphen (-) and the caret (^), metacharacters and quantifiers
(such as * and {m}, respectively) specified within a character class have no special
meaning and are evaluated as actual characters.

SQL Anywhere also supports sub-character classes such as POSIX character classes.

* The asterisk can be used to match a character 0 or more times. For example, REGEXP
'.*abc' matches a string that ends with abc, and starts with any prefix. So, aabc, xy-
zabc, and abc match, but bc and abcc do not.

? The question mark can be used to match a character 0 or 1 times. For example, 'co-
lou?r' matches color and colour.

+ The plus sign can be used to match a character 1 or more times. For example, 'bre+'
matches bre and bree, but not br.

- A hyphen can be used within a character class to denote a range. For example, REGEXP
'[a-e]' matches a, b, c, d, and e.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 19


SQL language elements

Character Additional information

% The percent sign can be used with SIMILAR TO to match any number of characters.

The percent sign is not considered a metacharacter for REGEXP and RE-
GEXP_SUBSTR. When specified, it matches a percent sign (%).

_ (under- The underscore can be used with SIMILAR TO to match a single character.
score char-
acter) The underscore is not considered a metacharacter for REGEXP and RE-
GEXP_SUBSTR. When specified, it matches an underscore (_).

| The pipe symbol is used to specify alternative patterns to use for matching the string. In
a string of patterns separated by a vertical bar, the vertical bar is interpreted as an OR
and matching stops at the first match made starting from the leftmost pattern. So, you
should list the patterns in descending order of preference. You can specify an unlimited
number of alternative patterns.

( and ) Left and right parenthesis are metacharacters when used for grouping parts of the regular
expression. For example, (ab)* matches zero or more repetitions of ab. As with math-
ematical expressions, you use grouping to control the order in which the parts of a regu-
lar expression are evaluated.

{ and } Left and right curly braces are metacharacters when used for specifying quantifiers.
Quantifiers specify the number of times a pattern must repeat to constitute a match. For
example:

● {m} Matches a character exactly m times. For example, '519-[0-9]{3}-


[0-9]{4}' matches a phone number in the 519 area code (providing the data is
formatted in the manner defined in the syntax).

● {m,} Matches a character at least m times. For example, '[0-9]{5,}' matches


any string of five or more digits.

● {m,n} Matches a character at least m times, but not more than n times. For exam-
ple, SIMILAR TO '_{5,10}' matches any string with between 5 and 10 (inclu-
sive) characters.

\ The backslash is used as an escape character for metacharacters. It can also be used to
escape non-metacharacters.

20 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

Character Additional information

^ For REGEXP and REGEXP_SUBSTR, when a caret is outside a character class, the
caret matches the start of a string. For example, '^[hc]at' matches hat and cat, but
only at the beginning of the string.

When used inside a character class, the following behavior applies:

● REGEXP and REGEXP_SUBSTR When the caret is the first character in a char-
acter class, it matches anything other than the characters in the character set. For ex-
ample, REGEXP '[^abc]' matches any character other than a, b, or c.

If the caret is not the first character inside the square brackets, it matches a caret. For
example, REGEXP_SUBSTR '[a-e^c]' matches a, b, c, d, e, and ^.

● SIMILAR TO For SIMILAR TO, the caret is treated as a subtraction operator. For
example, SIMILAR TO '[a-e^c]' matches a, b, d, and e.

$ When used with REGEXP and REGEXP_SUBSTR, matches the end of a string. For ex-
ample, REGEXP 'cat$' matches cat, but not catfish.

. When used with REGEXP and REGEXP_SUBSTR, matches any single character. For
example, REGEXP 'a.cd' matches any string of four characters that starts with a and
ends with cd.

When used with SIMILAR TO, matches a period (.).

: The colon is used within a character set to specify a subcharacter class. For example,
'[[:alnum:]]'.

Regular expressions: Special sub-character classes


Sub-character classes are special character classes embedded within a larger character class. In addition
to custom character classes where you define the set of characters to match (for example, [abxq4]
limits the set of matching characters to a, b, x, q, and 4), SQL Anywhere supports sub-character classes
such as most of the POSIX character classes. For example, [[:alpha:]] represents the set of all
upper- and lowercase letters.

The REGEXP search condition and the REGEXP_SUBSTR function support all the syntax conventions
in the table below, but the SIMILAR TO search expression does not. Conventions supported by
SIMILAR TO have a Y in the SIMILAR TO column.

In REGEXP and when using the REGEXP_SUBSTR function, sub-character classes can be negated using
a caret. For example, [[:^alpha:]] matches the set of all characters except alpha characters.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 21


SQL language elements

Sub- Additional information SIMILAR


character TO
class

[:alpha:] Matches upper- and lowercase alphabetic characters in the current colla- Y
tion. For example, '[0-9]{3}[[:alpha:]]{2}' matches three dig-
its, followed by two letters.

[:alnum:] Match digits, and upper- and lowercase alphabetic characters in the current Y
collation. For example, '[[:alnum:]]+' matches a string of one or
more letters and numbers.

[:digit:] Match digits in the current collation. For example, '[[:digit:]-]+' Y


matches a string of one or more digits or dashes. Likewise, '[^[:dig-
it:]-]+' matches a string of one or more characters that are not digits
or dashes.

[:lower:] Match lowercase alphabetic characters in the current collation. For exam- Y
ple, '[[:lower:]]' does not match A because A is uppercase.

[:space:] Match a single blank (' '). For example, the following statement searches Y
Contacts.City for any city with a two word name:
SELECT City
FROM Contacts
WHERE City REGEXP '.*[[:space:]].*';

[:upper:] Match uppercase alphabetic characters in the current collation. For exam- Y
ple, '[[:upper:]ab]' matches one of: any uppercase letter, a, or b.

[:white- Match a whitespace character such as space, tab, formfeed, and carriage Y
space:] return.

[:ascii:] Match any seven-bit ASCII character (ordinal value between 0 and 127).

[:blank:] Match a blank space, or a horizontal tab.

[[:blank:]] is equivalent to [ \t].

[:cntrl:] Match ASCII characters with an ordinal value of less than 32, or character
value 127 (control characters). Control characters include newline, form
feed, backspace, and so on.

[:graph:] Match printed characters.

[[:graph:]] is equivalent to [[:alnum:][:punct:]].

22 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

Sub- Additional information SIMILAR


character TO
class

[:print:] Match printed characters and spaces.

[[:print:]] is equivalent to [[:graph:][:whitespace:]].

[:punct:] Match one of: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~.

The [:punct:] sub-character class may not include non-ASCII punctu-


ation characters available in the current collation.

[:word:] Match alphabetic, digit, or underscore characters in the current collation.

[[:word:]] is equivalent to [[:alnum:]_].

[:xdigit:] Match a character that is in the character class [0-9A-Fa-f].

Regular expressions: Other supported syntax conventions


The following syntax conventions are supported by the REGEXP search condition and the
REGEXP_SUBSTR function, and they assume that the backslash is the escape character. These
conventions are not supported by the SIMILAR TO search expression.

Regular expression syntax Name and meaning

\0 xxx Matches the character whose value is \0xxx,


where xxx is any sequence of octal digits, and 0 is
a zero. For example, \0134 matches a back-
slash.

\a Matches the bell character.

\A Used outside a character set to match the start of


a string.

Equivalent to ^ used outside a character set.

\b Matches a backspace character.

\B Matches the backslash character (\).

\c X Matches a named control character. For example,


\cZ for ctrl-Z.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 23


SQL language elements

Regular expression syntax Name and meaning

\d Matches a digit in the current collation. For ex-


ample, the following statement searches Con-
tacts.Phone for all phone numbers that end with
00:
SELECT Surname, Surname, City, Phone
FROM Contacts
WHERE Phone REGEXP '\\d{8}00';

\d can be used both inside and outside character


classes, and is equivalent to [[:digit:]].

\D Matches anything that is not a digit. This is the


opposite of \d.

\D can be used both inside and outside character


classes, and is equivalent to [^[:digit:]].

Be careful when using the negated shorthands in-


side square brackets. [\D\S] is not the same as
[^\d\s]. The latter matches any character that
is not a digit or whitespace. So it matches x, but
not 8. The former, however, matches any charac-
ter that is either not a digit, or is not whitespace.
Because a digit is not whitespace, and whitespace
is not a digit, [\D\S] matches any character,
digit, whitespace or otherwise.

\e Matches the escape character.

\E Ends the treatment of metacharacters as non-met-


acharacters, initiated by a \Q.

\f Matches a form feed.

\n Matches a new line.

\Q Treat all metacharacters as non-metacharacters,


until \E is encountered. For example, \Q[$\E is
equivalent to \[\$.

\r Matches a carriage return.

24 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

Regular expression syntax Name and meaning

\s Matches a space or a character treated as white-


space. For example, the following statement re-
turns all product names from Products.Product-
Name that have at least one space in the name:
SELECT Name
FROM Products
WHERE Name REGEXP '.*\\s.*'

\s can be used both inside and outside character


classes, and is equivalent to [[:white-
space:]].

\S Matches a non-whitespace character. This is the


opposite of \s, and is equivalent to [^[:white-
space:]].

\S can be used both inside and outside character


classes.

Be careful when using the negated shorthands in-


side square brackets. [\D\S] is not the same as
[^\d\s]. The latter matches any character that
is not a digit or whitespace. So it matches x, but
not 8. The former, however, matches any charac-
ter that is either not a digit, or is not whitespace.
Because a digit is not whitespace, and whitespace
is not a digit, [\D\S] matches any character,
digit, whitespace or otherwise.

\t Matches a horizontal tab.

\v Matches a vertical tab.

\w Matches a alphabetic character, digit, or under-


score in the current collation. For example, the
following statement returns all surnames from
Contacts.Surname that are exactly seven alpha-
numeric characters in length:
SELECT Surname
FROM Contacts
WHERE Surname REGEXP '\\w{7}';

\w can be used both inside and outside character


classes.

Equivalent to [[:alnum:]_]..

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 25


SQL language elements

Regular expression syntax Name and meaning

\W Matches anything that is not an alphabetic char-


acter, digit, or underscore in the current collation.
This is the opposite of \w, and is equivalent to
[^[:alnum:]_].

This regular expression can be used both inside


and outside character classes

\x hh Matches the character whose value is 0xhh,


where hh is, at most, two hex digits. For example,
\x2D is equivalent to a hyphen.

Equivalent to \x{hh}.

\x{ hhh } Matches the character whose value is 0xhhh,


where hhh is, at most, eight hex digits.

\z and \Z Matches the position (not character) at the end of


the string.

Equivalent to $.

Regular expressions: Assertions


Assertions test whether a condition is true, and affect the position in the string where matching begins.
Assertions do not return characters; the assertion pattern is not included in the final match. These
assertions are supported by the REGEXP search condition and the REGEXP_SUBSTR function. These
conventions are not supported by the SIMILAR TO search expression.

Lookahead and lookbehind assertions can be useful with REGEXP_SUBSTR when trying to split a string.
For example, you can return the list of street names (without the street numbers) in the Address column of
the Customers table by executing the following statement:

SELECT REGEXP_SUBSTR( Street, '(?<=^\\S+\\s+).*$' )


FROM Customers;

Another example is if you want to use a regular expression to verify that a password conforms to certain
rules. You could use a zero width assertion similar to the following:

IF password REGEXP '(?=.*[[:digit:]])(?=.*[[:alpha:]].*[[:alpha:]])[[:word:]]


{4,12}' THEN
MESSAGE 'Password conforms' TO CLIENT;
ELSE
MESSAGE 'Password does not conform' TO CLIENT;
END IF

The password is valid when the following are true:

● password has at least one digit (zero width positive assertion with [[:digit:]])

26 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

● password has at least two alphabetic characters (zero width positive assertion with
[[:alpha:]].*[[:alpha:]])

● password contains only alpha-numeric or underscore characters ([[:word:]])

● password is at least 4 characters, and at most 12 characters ({4,12})

The following table contains the assertions supported by SQL Anywhere:

Syntax Meaning

(?= pat- Positive lookahead zero-width assertion Looks to see if the current position in the
tern ) string is immediately followed by an occurrence of pattern, without pattern becoming part
of the match string. 'A(?=B)' matches an A that is followed by a B, without making the
B part of the match.

For example, SELECT REGEXP_SUBSTR( 'in new york city', 'new(?=\


\syork)'); returns the substring new since it is immediately followed by ' york' (note
the space before york).

(?! pat- Negative lookahead zero-width assertions Looks to see if the current position in
tern ) the string is not immediately followed by an occurrence of pattern, without pattern be-
coming part of the match string. So, 'A(?!B)' matches an A that is not followed by a B.

For example,SELECT REGEXP_SUBSTR('new jersey', 'new(?!\


\syork)'); returns the substring new.

(?<= pat- Positive lookbehind zero-width assertions Looks to see if the current position in
tern ) the string is immediately preceded by an occurrence of pattern, without pattern becoming
part of the match string. So, '(?<=A)B' matches a B that is immediately preceded by an
A, without making A part of the match.

For example, SELECT REGEXP_SUBSTR('new york', '(?<=new\


\s)york'); returns the substring york.

(?<! pat- Negative lookbehind zero-width assertions Looks to see if the current position in
tern ) the string is not immediately preceded by an occurrence of pattern, without pattern be-
coming part of the match string.

For example, SELECT REGEXP_SUBSTR('about york', '(?<!new\


\s)york'); returns the substring york.

(?> pat- Possessive local subexpression Matches only the largest prefix of the remaining
tern ) string that matches pattern.

For example, in 'aa' REGEXP '(?>a*)a', (?>a*) matches (and consumes) the aa,
and never just the leading a. As a result, 'aa' REGEXP '(?>a*)a' evaluates to false.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 27


SQL language elements

Syntax Meaning

(?: pat- Non-capturing block This is functionally equivalent to just pattern, and is provided
tern ) for compatibility.

For example, in 'bb' REGEXP '(?:b*)b', (?:b*) matches (and consumes) the bb.
However, unlike possessive local subexpression, the last b in bb is given up to allow the
whole match to succeed (that is, to allow the matching to the b found outside the non-cap-
turing block).

Likewise, 'a(?:bc|b)c' matches abcc, and abc. In matching abc, backtracking on the
final c in bc takes place so that the c outside the group can be used to make the match
successful.

(?# text ) Used for comments. The content of text is ignored.

See also
● “Regular expression examples” on page 28
● “REGEXP_SUBSTR function [String]” on page 305
● “LIKE, REGEXP, and SIMILAR TO: Differences in character comparisons” on page 38
● “Regular expressions: Metacharacters” on page 19
● “Regular expressions: Special sub-character classes” on page 21

Regular expression examples


The following table shows example uses of regular expressions. All examples work for REGEXP and
some also work for SIMILAR TO, as noted in the Example column. Results vary depending on the search
condition you use for searching. For those that work with SIMILAR TO, results can vary further
depending on case and accent sensitivity.

Note that backslashes should be doubled if the examples are used in literal strings (for example, '.+@.+
\\..+')

28 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

Example Sample matches

Credit Card Numbers (REGEXP only): Matches (Visa): 4123 6453 2222 1746

Visa: Non-Matches (Visa):


4[0-9]{3}\s[0-9]{4}\s[0-9]{4}\s[0-9] 3124 5675 4400 4567, 4123-6453-2222-1746
{4}
Similarly, MasterCard matches a set of 16 num-
MasterCard:
bers, starting with 5, with a space between each
5[0-9]{3}\s[0-9]{4}\s[0-9]{4}\s[0-9] subset of four numbers. American Express and
{4} Discover are the same, but must start with 37
and 6011 respectively.
American Express:
37[0-9]{2}\s[0-9]{4}\s[0-9]{4}\s[0-9]
{4}

Discover:
6011\s[0-9]{4}\s[0-9]{4}\s[0-9]{4}

Dates (REGEXP and SIMILAR TO): Matches: 31/04/1999, 15/12/4567


([0-2][0-9]|30|31)/(0[1-9]|1[0-2])/ Non-Matches: 31/4/1999, 31/4/99, 1999/04/19,
[0-9]{4}
42/67/25456

Windows absolute paths (REGEXP only): Matches: \\server\share\file


([A-Za-z]:|\\)\\[[:alnum:] Non-Matches: \directory\directory2, /directory2
[:whitespace:]!"#$%&'()+,-.\\;=@\
[\]^_`{}~.]*

Email Addresses (REGEXP only): Matches: [email protected], [email protected]


[[:word:]\-.]+@[[:word:]\-.]+\. Non-Matches: abc@dummy, ab*[email protected]
[[:alpha:]]{2,3}

Email Addresses (REGEXP only): Matches: *@[email protected],


__1234^%@@abc.def.ghijkl
.+@.+\..+
Non-Matches: abc.123.*&ca, ^%abcdefg123

HTML Hexadecimal Color Codes (REGEXP Matches: AB1234, CCCCCC, 12AF3B


and SIMILAR TO):
Non-Matches: 123G45, 12-44-CC
[A-F0-9]{6}

HTML Hexadecimal Color Codes (REGEXP on- Matches: AB 11 00, CC 12 D3


ly):
Non-Matches: SS AB CD, AA BB CC DD,
[A-F0-9]{2}\s[A-F0-9]{2}\s[A-F0-9]{2} 1223AB

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 29


SQL language elements

Example Sample matches

IP Addresses (REGEXP only): Matches: 10.25.101.216


((2(5[0-5]|[0-4][0-9])|1([0-9][0-9])| Non-Matches: 0.0.0, 256.89.457.02
([1-9][0-9])|[0-9])\.){3}(2(5[0-5]|
[0-4][0-9])|1([0-9][0-9])|([1-9]
[0-9])|[0-9])

Java Comments (REGEXP only): Matches Java comments that are between /* and
*/, or one line comments prefaced by //.
/\*.*\*/|//[^\n]*
Non-Matches: a=1

Money (REGEXP only): Matches: $1.00, -$97.65


(\+|-)?\$[0-9]*\.[0-9]{2} Non-Matches: $1, 1.00$, $-75.17

Positive, negative numbers, and decimal values Matches: +41, -412, 2, 7968412, 41, +41.1,
(REGEXP only): -3.141592653
(\+|-)?[0-9]+(\.[0-9]+)? Non-Matches: ++41, 41.1.19, -+97.14

Passwords (REGEXP and SIMILAR TO): Matches: abcd, 1234, A1b2C3d4, 1a2B3
[[:alnum:]]{4,10} Non-Matches: abc, *ab12, abcdefghijkl

Passwords (REGEXP only): Matches: AB_cd, A1_b2c3, a123_


[a-zA-Z]\w{3,7} Non-Matches: *&^g, abc, 1bcd

Phone Numbers (REGEXP and SIMILAR TO): Matches: 519-883-6898, 519 888 6898
([2-9][0-9]{2}-[2-9][0-9]{2}-[0-9]
{4})|([2-9][0-9]{2}\s[2-9][0-9] Non-Matches: 888 6898, 5198886898, 519
{2}\s[0-9]{4}) 883-6898

Sentences (REGEXP only): Matches: Hello, how are you?


[A-Z0-9].*(\.|\?|!) Non-Matches: i am fine

Sentences (REGEXP only): Matches: Hello, how are you?


[[:upper:]0-9].*[.?!] Non-Matches: i am fine

Social Security Numbers (REGEXP and SIMI- Matches: 123-45-6789


LAR TO):
Non-Matches:123 45 6789, 123456789,
[0-9]{3}-[0-9]{2}-[0-9]{4} 1234-56-7891

30 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Expressions

Example Sample matches

URLs (REGEXP only): Matches: http://www.sample.com, www.sam-


ple.com
(http://)?www\.[a-zA-Z0-9]+\.[a-zA-Z]
{2,3}
Non-Matches: http://sample.com, http://
www.sample.comm

See also
● “Regular expressions syntax” on page 18
● “LIKE, REGEXP, and SIMILAR TO search conditions” on page 37

Compatibility of expressions
SQL Anywhere employs the SQL/2008 convention, that strings enclosed in apostrophes are constant
expressions, and strings enclosed in quotation marks (double quotes) are delimited identifiers (names for
database objects).

The quoted_identifier option


SQL Anywhere provides a quoted_identifier option that allows the interpretation of delimited strings to
be changed. By default, the quoted_identifier option is set to On in SQL Anywhere.

You cannot use SQL reserved words as identifiers if the quoted_identifier option is Off.

Setting the option


The following statement changes the setting of the quoted_identifier option to On:
SET quoted_identifier On;

The following statement changes the setting of the quoted_identifier option to Off:
SET quoted_identifier Off;

Compatible interpretation of delimited strings


You can choose to use either the SQL/2008 or the default Transact-SQL convention in SQL 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 setting), then the following
statements involving the SQL keyword user are valid for both DBMSs.
CREATE TABLE "user" ( col1 char(5) )
go
INSERT "user" ( col1 )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 31


SQL language elements

VALUES ( 'abcde' )
go

If you choose to operate with the quoted_identifier option off then the following statement is valid for
both DBMSs. In the following example, Chin is a string and not an identifier.

SELECT *
FROM Employees
WHERE Surname = "Chin"
go

See also
● “quoted_identifier option” [SQL Anywhere Server - Database Administration]
● “Reserved words” on page 1

Search conditions
A search condition is the criteria specified for a WHERE clause, a HAVING clause, a CHECK clause, an
ON phrase in a join, or an IF expression. A search condition is also called a predicate.

Syntax
search-condition :
expression comparison-operator expression
| expression comparison-operator { [ ANY | SOME ] | ALL } ( subquery )
| expression IS [ NOT ] DISTINCT FROM expression
| expression IS [ NOT ] NULL
| expression [ NOT ] BETWEEN expression AND expression
| expression [ NOT ] LIKE pattern [ ESCAPE expression ]
| expression [ NOT ] SIMILAR TO pattern [ ESCAPE escape-expression ]
| expression [ NOT ] REGEXP pattern [ ESCAPE escape-expression ]
| expression [ NOT ] IN ( { expression , ... )
| ( query-expression )
| NOT search-condition
| CONTAINS (column-name [,... ] , query-string )
| EXISTS ( query-expression )
| search-condition [ { AND | OR } search-condition ] [ ... ]
| ( search-condition )
| ( search-condition , estimate )
| search-condition IS [ NOT ] { TRUE | FALSE | UNKNOWN }
| expression IS [ NOT ] OF ( [ ONLY ] type-name ,... )
| trigger-operation

comparison-operator :
=
|>
|<
| >=
| <=
| <>
| !=
| !<
| !>

32 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

trigger-operation :
INSERTING
| DELETING
| UPDATING [ ( column-name-string ) ]
| UPDATE( column-name )

Parameters
● ALL search condition

● ANY and SOME search conditions

● IS [NOT] DISTINCT FROM search condition

● BETWEEN search condition

● CONTAINS search condition

● EXISTS search condition

● LIKE search condition

● SIMILAR TO search condition

● REGEXP search condition

● IS OF type-expression, and IS NOT OF type-expression


This type predicate was added for support of spatial geometries, but it can be used for any existing data
type as well.

Remarks
Search conditions are used either 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.

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.

Rows satisfy a search condition only if the result of the condition is TRUE. Rows for which the condition
is UNKNOWN or FALSE do not satisfy the search condition.

Subqueries form an important class of expression that is used in many search conditions.

The LIKE, SIMILAR TO, and REGEXP search conditions are very similar.

Permissions
Must be connected to the database.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 33


SQL language elements

See also
● “Expressions” on page 12
● “ALL search condition” on page 34
● “ANY and SOME search conditions” on page 35
● “BETWEEN search condition” on page 37
● “CONTAINS search condition” on page 47
● “EXISTS search condition” on page 53
● “LIKE search condition” on page 39
● “SIMILAR TO search condition” on page 45
● “REGEXP search condition” on page 43
● “Understand spatial data type syntax” [SQL Anywhere Server - Spatial Data Support]
● “Three-valued logic” on page 55
● “NULL special value” on page 64
● “Subqueries in search conditions” on page 34
● “LIKE, REGEXP, and SIMILAR TO search conditions” on page 37

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 as long as the
subquery does not return more than one row. If the subquery (which must have exactly one column)
returns one row, then the value of that row is compared to the expression. If a subquery returns no rows,
the value of the subquery is NULL.

Subqueries that return exactly one column and any number of rows can be used in IN, ANY, ALL, and
SOME search conditions. Subqueries that return any number of columns and rows can be used in EXISTS
search conditions. These search conditions are discussed in the following sections.

Standards and compatibility


● SQL/2008 The use of a scalar subquery as an arbitrary expression is a core feature of the SQL/2008
standard.

See also
● “Comparison operators” on page 8

ALL search condition


Syntax
expression comparison-operator ALL ( subquery )

comparison-operator:
=

34 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

|>
|<
| >=
| <=
| <>
| !=
| !<
| !>

Remarks
With the ALL search condition, if the value of subquery result set is the empty set, the search condition
evaluates to TRUE. Otherwise, the search condition evaluates to TRUE, FALSE, or UNKNOWN,
depending on the value of expression, and the result set returned by the subquery, as follows:

If the and the result set returned by the or the result set returned by the
expression subquery contains at least one NULL, subquery contains no NULLs, then...
value is... then...

NULL UNKNOWN UNKNOWN

not NULL If there exists at least one value in the If there exists at least one value in the
subquery result set for which the compar- subquery result set for which the com-
ison with the expression value is FALSE, parison with the expression value is
then the search condition evaluates to FALSE, then the search condition evalu-
FALSE. Otherwise, the search condition ates to FALSE. Otherwise, the search
evaluates to UNKNOWN. condition evaluates to TRUE.

Standards and compatibility


● SQL/2008 Core feature.

ANY and SOME search conditions


Syntax
expression comparison-operator { ANY | SOME }( subquery )

comparison-operator:
=
|>
|<
| >=
| <=
| <>
| !=
| !<
| !>

Remarks
The keywords ANY and SOME are synonymous.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 35


SQL language elements

With the ANY and SOME search conditions, if the subquery result set is the empty set, the search
condition evaluates to FALSE. Otherwise, the search condition evaluates to TRUE, FALSE, or
UNKNOWN, depending on the value of expression, and the result set returned by the subquery, as
follows:

If the and the result set returned by the or the result set returned by the
expression subquery contains at least one NULL, subquery contains no NULLs, then...
value is... then...

NULL UNKNOWN UNKNOWN

not NULL If there exists at least one value in the If there exists at least one value in the
subquery result set for which the compar- subquery result set for which the com-
ison with the expression value is TRUE, parison with the expression value is
then the search condition evaluates to TRUE, then the search condition evalu-
TRUE. Otherwise, the search condition ates to TRUE. Otherwise, the search
evaluates to UNKNOWN. condition evaluates to FALSE.

An ANY or SOME search condition with an equality operator, evaluates to TRUE if expression is equal
to any of the values in the result of the subquery, and FALSE if the value of the expression is not NULL,
does not equal any of the values in the result of the subquery, and the result set doesn't contain NULLs.

Note
The usage of = ANY or = SOME is equivalent to using the IN keyword.

Standards and compatibility


● SQL/2008 Core feature.

IS DISTINCT FROM and IS NOT DISTINCT FROM search


conditions
Syntax
expression1 IS [ NOT ] DISTINCT FROM expression2

Remarks
The IS DISTINCT FROM and IS NOT DISTINCT FROM search conditions are sargable and evaluate to
TRUE or FALSE.

The IS NOT DISTINCT FROM search condition evaluates to TRUE if expression1 is equal to
expression2, or if both expressions are NULL. This is equivalent to a combination of two search
conditions, as follows:
expression1 = expression2 OR ( expression1 IS NULL AND expression2 IS NULL )

36 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

The IS DISTINCT FROM syntax reverses the meaning. That is, IS DISTINCT FROM evaluates to TRUE
if expression1 is not equal to expression2, and at least one of the expressions is not NULL. This is
equivalent to the following:
NOT( expression1 = expression2 OR ( expression1 IS NULL AND expression2 IS
NULL ))

Standards and compatibility


● SQL/2008 The IS [NOT] DISTINCT FROM predicate is defined in SQL/2008 standard. The IS
DISTINCT FROM predicate is Feature T151, "DISTINCT predicate", of the SQL/2008 standard. The
IS NOT DISTINCT FROM predicate is Feature T152, "DISTINCT predicate with negation", of the
SQL/2008 standard.

See also
● “Query predicates” [SQL Anywhere Server - SQL Usage]

BETWEEN search condition


Syntax
expression [ NOT ] BETWEEN start-expression AND end-expression

Remarks
The BETWEEN search condition can evaluate as TRUE, FALSE, or UNKNOWN. Without the NOT
keyword, the search condition evaluates as TRUE if expression is between start-expression and end-
expression. The NOT keyword reverses the meaning of the search condition but leaves UNKNOWN
unchanged.

The BETWEEN search condition is equivalent to a combination of two inequalities:

[ NOT ] ( expression >= start-expression AND expression <= end-expression )

Standards and compatibility


● SQL/2008 Core feature.

LIKE, REGEXP, and SIMILAR TO search conditions


The REGEXP, LIKE, and SIMILAR TO search conditions are similar in that they all attempt to match a
pattern to a string. Also, all three attempt to match an entire string, not a substring within the string.

The basic syntax for all three search conditions is similar:

expression search-condition pattern

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 37


SQL language elements

LIKE, REGEXP, and SIMILAR TO: Differences in pattern definition


● REGEXP supports a superset of regular expression syntax supported by SIMILAR TO. In addition, for
compatibility with other products, the REGEXP search condition supports several syntax extensions.
Also, REGEXP and SIMILAR TO have a different default escape character and process the characters
underscore ( _ ), percent ( % ), and caret ( ^ ) differently. REGEXP behavior matches closely with Perl
5 (except where Perl syntax and operators are not supported).

● LIKE syntax for pattern is simple and supports a small set of wildcards, but does not support the full
regular expression syntax.

● SIMILAR TO syntax for pattern allows a robust pattern matching using the regular expression syntax
defined in the ANSI/ISO SQL standard.

LIKE, REGEXP, and SIMILAR TO: Differences in character comparisons


When performing comparisons, REGEXP behavior is different from LIKE and SIMILAR TO. For
REGEXP comparisons, the database server uses code point values in the database character set for
comparisons. This is consistent with other regular expression implementations such as Perl.

For LIKE and SIMILAR TO, the database server uses the equivalence and sort order in the database
collation for comparisons. This is consistent with how the database evaluates comparison operators such
as > and =.

The difference in character comparison methods means that results for matching and range evaluation for
REGEXP and LIKE/SIMILAR differ as well.

● Differences in matching Since REGEXP uses code point values, it only matches a literal in a
pattern if it is the exact same character. REGEXP matching is therefore not impacted by such things as
database collation, case-sensitivity, or accent sensitivity. For example, 'A' could never be returned as a
match for 'a'.

Since LIKE and SIMILAR TO use the database collation, results are impacted by case- and accent-
sensitivity when determining character equivalence. For example, if the database collation is case- and
accent-insensitive, matches are case- and accent-insensitive. So, an 'A' could be returned as a match
for 'a'.

● Differences in range evaluation Since REGEXP uses code points for range evaluation, a
character is considered to be in the range if its code point value is equal to, or between, the code point
values for the start and end of the range. For example, the comparison x REGEXP '[A-C]', for the
single character x, is equivalent to CAST(x AS BINARY) >= CAST(A AS BINARY) AND
CAST(x AS BINARY) <= CAST(C AS BINARY) .

Since LIKE and SIMILAR TO use the collation sort order for range evaluation, a character is
considered to be in the range if its position in the collation is the same as, or between, the position of
the start and end characters for the range. For example, the comparison x SIMILAR TO '[A-C]'
(where x is a single character) is equivalent to x >= A AND x <= C, and the comparison operators
are evaluated using the collation sort ordering.

38 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

The following table shows the set of characters included in the range '[A-C]' as evaluated by
LIKE, SIMILAR TO, and REGEXP. Both databases use the 1252LATIN1 collation, but the first
database is case-insensitive, while the second one is case sensitive.

LIKE/SIMILAR TO '[A-C]' REGEXP '[A-C]'

demo.db (case-insensitive) A,B,C,a,b,c,ª,À,Á,Â,Ã,Ä,Å,Æ,Ç,à,á,â,ã,ä,å,æ,ç A, B, C

charsensitive.db (case-sensi- A,B,C,b,c,À,Á,Â,Ã,Ä,Å,Æ,Ç,ç A, B, C


tive)

The following can be observed in the results:

○ LIKE and SIMILAR TO include accented characters in the range.

○ LIKE and SIMILAR TO include different characters depending on database case-sensitivity.


Specifically, they include any lowercase letters found within the range, which you may not have
anticipated when searching on a case-sensitive database.
Similarly, on a case-sensitive database, some characters included in the range might appear to be
inconsistent. For example, SIMILAR TO '[A-C]' on a case-sensitive database includes A, b, B,
c, C but not a because a occurs before the uppercase A in the sort order.

○ REGEXP returns only A, B, C regardless of database case sensitivity. If you want the range to
include lowercase letters, you must add them to the range definition. For example, REGEXP '[a-
cA-C]'.

○ the REGEXP set of characters does not change, regardless of database case-sensitivity.

Even though your database uses a different collation, or has different case- or accent-sensitivity
settings than the examples above, you can perform a similar test to see what is returned by LIKE,
SIMILAR TO, or REGEXP by connecting to the database and executing any of these statements:
SELECT CHAR( row_num ) FROM RowGenerator WHERE CHAR( row_num ) LIKE '[A-
C]';
SELECT CHAR( row_num ) FROM RowGenerator WHERE CHAR( row_num ) REGEXP '[A-
C]';
SELECT CHAR( row_num ) FROM RowGenerator WHERE CHAR( row_num ) SIMILAR TO
'[A-C]';

See also
● “Regular expressions overview” on page 17
● “Regular expressions syntax” on page 18
● “Regular expression examples” on page 28

LIKE search condition

Syntax
The syntax for the LIKE search condition is as follows:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 39


SQL language elements

expression [ NOT ] LIKE pattern [ ESCAPE escape-character ]

Parameters
● expression The string to be searched.

● pattern The pattern to search for within expression.

● escape-character The character to use to escape special characters such as underscores and
percent signs. The default escape character is the null character, which can be specified in a string
literal as '\x00'.

Remarks
The LIKE search condition attempts to match expression with pattern and evaluates to TRUE, FALSE, or
UNKNOWN.

The search condition evaluates to TRUE if expression matches pattern (assuming NOT was not
specified). If either expression or pattern is the NULL value, the search condition evaluates to
UNKNOWN. The NOT keyword reverses the meaning of the search condition, but leaves UNKNOWN
unchanged.

expression is interpreted as a CHAR or NCHAR string. The entire contents of expression is used for
matching. Similarly, pattern is interpreted as a CHAR or NCHAR string and can contain any number of
the supported wildcards from the following table:

Wildcard Matches

_ (underscore) Any one character. For example, a_ matches ab and ac, but not a.

% (percent) Any string of zero or more characters. For example, bl% matches bl and bla.

[] Any single character in the specified range or set. For example, T[oi]m matches
Tom or Tim.

[^] Any single character not in the specified range or set. For example, M[^c] matches
Mb and Md, but not Mc.

All other characters must match exactly.

For example, the following search condition returns TRUE for any row where name starts with the letter a
and has the letter b as its second last character.
... name LIKE 'a%b_'

If escape-character is specified, it must evaluate to a single-byte CHAR or NCHAR character. The


escape 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 matches a percent, and an underscore matches an underscore.

All patterns of 126 bytes or less are supported. Patterns of greater than 126 bytes that do not contains
wildcards are not supported. Patterns containing wildcard characters that are longer than 126 bytes are

40 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

supported, depending on the contents of the pattern. The number of bytes used to represent the pattern
depends on whether the pattern is CHAR or NCHAR.

Different ways to use the LIKE search condition

To search Example Additional information


for

One of a set LIKE A set of characters to look for is specified by listing the characters
of charac- 'sm[iy]th' inside square brackets. In this example, the search condition match-
ters es smith and smyth.

One of a LIKE '[a- A range of characters to look for is specified by giving the ends of
range of r]ough' the range inside square brackets, separated by a hyphen. In this ex-
characters ample, the search condition matches bough and rough, but not
tough.

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.

The lower end of the range must precede the higher end of the
range. For example, [z-a] does not match anything because no
character matches the [z-a] range.

Ranges and ... LIKE You can combine ranges and sets within square brackets. In this ex-
sets com- '[a- ample, ... LIKE '[a-rt]ough' matches bough, rough, and
bined rt]ough' tough.

The pattern [a-rt] is interpreted as exactly one character that is ei-


ther in the range a to r inclusive, or is t.

One charac- ... LIKE The caret character (^) is used to specify a range of characters that
ter not in a '[^a- is excluded from a search. In this example, LIKE '[^a-
range r]ough' r]ough' matches the string tough, but not the strings rough or
bough.

The caret negates the rest of the contents of the brackets. For exam-
ple, the bracket [^a-rt] is interpreted as exactly one character that is
not in the range a to r inclusive, and is not t.

Search pat- '90 ', When your search pattern includes trailing blanks, the database
terns with '90[ ]' and server matches the pattern only to values that contain blanks—it
trailing '90_' does not blank pad strings. For example, the patterns '90 ', '90[ ]',
blanks and '90_' match the expression '90 ', but do not match the expres-
sion '90', even if the value being tested is in a CHAR or VAR-
CHAR column that is three or more characters in width.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 41


SQL language elements

Special cases of ranges and sets


Any single character in square brackets means that character. For example, [a] matches just the
character a. [^] matches just the caret character, [%] matches just the percent character (the percent
character does not act as a wildcard in this context), and [_] matches just the underscore character. Also,
[[] matches just the character [.

Other special cases are as follows:

● The pattern [a-] matches either of the characters a or -.

● The pattern [] is never matched and always returns no rows.

● The patterns [ or [abp-q return syntax errors because they are missing the closing bracket.

● You cannot use wildcards inside square brackets. The pattern [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
pattern [a^b] finds one of a, ^, or b.

Case sensitivity and how comparisons are performed


If the database collation is case sensitive, the search condition is also case sensitive. To perform a case
insensitive search with a case sensitive collation, you must include upper and lower characters. For
example, the following search condition evaluates to true for the strings Bough, rough, and TOUGH:

LIKE '[a-zA-Z][oO][uU][gG][hH]'

Comparisons are performed character-by-character, unlike the equivalence (=) operator and other
operators where the comparison is done string-by-string. For example, when a comparison is done in a
UCA collation (CHAR or NCHAR with the collation set to UCA), 'Æ'='AE' is true, but 'Æ' LIKE
'AE' is false.

For a character-by-character comparison to match, each single character in the expression being searched
must match a single character (using the collation's character equivalence), or a wildcard in the LIKE
expression.

National character (NCHAR) support


LIKE search conditions can be used to compare CHAR and NCHAR strings. In this case, character set
conversion is performed so that the comparison is done using a common data type. Then, a character-by-
character comparison is performed.

You can specify expression or pattern as an NCHAR string literal by prefixing the quoted value with N
(for example, expression LIKE N'pattern'). You can also use the CAST function to cast the
pattern to CHAR or NCHAR (for example, expression LIKE CAST(pattern AS datatype).

Blank padded databases


The semantics of a LIKE pattern does not change if the database is blank-padded since matching
expression to pattern involves a character-by-character comparison in a left-to-right fashion. No
additional blank padding is performed on the value of either expression or pattern during the evaluation.

42 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

Therefore, the expression a1 matches the pattern a1, but not the patterns 'a1 ' (a1, with a space after it) or
a1_.

Standards and compatibility


● SQL/2008 The LIKE search condition is a core feature of the SQL/2008 standard. However, there
are subtle differences in behavior from that of the standard because SQL Anywhere supports case-
insensitive collations and blank-padding.

SQL Anywhere supports optional SQL language feature F281, which permits the pattern and escape-
expressions to be arbitrary expressions evaluated at execution time. Feature F281 also permits
expression to be an expression more complex than a simple column reference.

The use of character ranges and sets contained in square brackets [] is a vendor extension.

SQL Anywhere supports SQL/2008 feature T042, which permits LIKE search conditions to reference
string-expressions that are LONG VARCHAR values.

LIKE search conditions that specify NCHAR string expressions or patterns is optional SQL language
feature F421 of the ANSI SQL/2008 standard.

See also
● “Comparisons between CHAR and NCHAR” on page 123
● “String literals” on page 7
● “CAST function [Data type conversion]” on page 159
● “LIKE, REGEXP, and SIMILAR TO: Differences in character comparisons” on page 38
● “LIKE, REGEXP, and SIMILAR TO search conditions” on page 37
● “The WHERE clause: Specifying rows” [SQL Anywhere Server - SQL Usage]
● “REGEXP search condition” on page 43
● “SIMILAR TO search condition” on page 45

REGEXP search condition


Match a pattern against a string.

Syntax
expression [ NOT ] REGEXP pattern [ ESCAPE escape-expression ]

Parameters
● expression The string to be searched.

● pattern The regular expression to search for within expression.

● escape-expression The escape character to be used in the match. The default is the backslash
character (\).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 43


SQL language elements

Remarks
The REGEXP search condition matches a whole string, not a substring. To match on a substring with the
string, enclose the string in wildcards that match the rest of the string (.*pattern.*). For example,
SELECT ... WHERE Description REGEXP 'car' matches only car, not sportscar. However,
SELECT ... WHERE Description REGEXP '.*car' matches car, sportscar, and any string
that ends with car. Alternatively, you can rewrite your query to make use the REGEXP_SUBSTR
function, which is designed to search for substrings within a string.

When matching against only a sub-character class, you must include the outer square brackets and the
square brackets for the sub-character class. For example, expression REGEXP '[[:digit:]]'.

Database collation and matching


REGEXP only matches a literal in a pattern if it is the exact same character (that is, they have the same
code point value). Ranges in character classes (for example, '[A-F]') only match characters that code
point values greater than or equal to the code point value of the first character in the range (A) and less
than or equal to the code point value of the second character in the range (F).

Comparisons are performed character-by-character, unlike the equivalence (=) operator and other
operators where the comparison is done string-by-string. For example, when a comparison is done in a
UCA collation (CHAR or NCHAR with the collation set to UCA), 'Æ'='AE' is true, but 'Æ' REGEXP
'AE' is false.

National character (NCHAR) support


REGEXP search conditions can be used to compare CHAR and NCHAR strings. In this case, character
set conversion is performed so that the comparison is done using a common data type. Then, a code point
by code point comparison is performed.

You can specify expression or pattern as an NCHAR string literal by prefixing the quoted value with N
(for example, expression REGEXP N'pattern'). You can also use the CAST function to cast the
pattern to CHAR or NCHAR (for example, expression REGEXP CAST(pattern AS
datatype).

See also
● “Comparisons between CHAR and NCHAR” on page 123
● “String literals” on page 7
● “CAST function [Data type conversion]” on page 159
● “Regular expressions overview” on page 17
● “SIMILAR TO search condition” on page 45
● “LIKE search condition” on page 39
● “REGEXP_SUBSTR function [String]” on page 305
● “LIKE, REGEXP, and SIMILAR TO search conditions” on page 37
● “Regular expressions: Special sub-character classes” on page 21

Standards and compatibility


● SQL/2008 The REGEXP search condition is a vendor extension, but is roughly compatible with the
LIKE_REGEX search condition of the SQL/2008 standard, which is SQL language feature F841.

44 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

SQL Anywhere supports ANSI SQL/2008 feature F281, which permits the pattern and escape-
expressions to be arbitrary expressions evaluated at execution time. Feature F281 also permits
expression to be an expression more complex than a simple column reference.

SQL Anywhere supports ANSI SQL/2008 feature T042, which permits REGEXP search conditions to
reference string-expressions that are LONG VARCHAR values.

REGEXP search conditions that specify NCHAR string expressions or patterns is feature F421 of the
ANSI SQL/2008 standard.

SIMILAR TO search condition


Match a pattern against a string.

Syntax
expression [ NOT ] SIMILAR TO pattern [ ESCAPE escape-expression ]

Parameters
● expression The expression to be searched.

● pattern The regular expression to search for within expression.

● escape-expression The escape character to use in the match. The default escape character is the
null character, which can be specified in a string literal as '\x00'.

Regular Meaning
expression
syntax

\x Match anything that compares equal to x, where the escape character is as-
sumed to be the backslash character (\). For example, \[ matches '['.

x Any character (other than a meta-character) matches itself. For example, A


matches 'A'.

Remarks
To match a substring with the string, use the percentage sign wildcard (%expression). For example,
SELECT ... WHERE Description SIMILAR TO 'car' matches only car, not sportscar.
However, SELECT ... WHERE Description SIMILAR TO '%car' matches car, sportscar,
and any string that ends with car.

When matching against only a sub-character class, you must include the outer square brackets, and the
square brackets for the sub-character class. For example, expression SIMILAR TO '[[:digit:]]').

Comparisons are performed character-by-character, unlike the equivalence (=) operator and other
operators where the comparison is done string-by-string. For example, when a comparison is done in a

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 45


SQL language elements

UCA collation (CHAR or NCHAR with the collation set to UCA), 'Æ'='AE' is true, but 'Æ'
SIMILAR TO 'AE' is false.

For a character-by-character comparison to match, each single character in the expression being searched
must match a single character or a wildcard in the SIMILAR TO pattern.

Database collation and matching


SIMILAR TO use the collation to determine character equivalence and evaluate character class ranges.
For example, if the database is case- and accent-insensitive, matches are case- and accent-insensitive.
Ranges are also evaluated using the collation sort order.

National character (NCHAR) support


SIMILAR TO search conditions can be used to compare CHAR and NCHAR strings. In this case,
character set conversion is performed so that the comparison is done using a common data type. Then, a
character-by-character comparison is performed.

You can specify expression or pattern as an NCHAR string literal by prefixing the quoted value with N
(for example, expression SIMILAR TO N'pattern'). You can also use the CAST function to
cast the pattern to CHAR or NCHAR (for example, expression SIMILAR TO CAST(pattern
AS datatype).

See also
● “Regular expressions overview” on page 17
● “Comparisons between CHAR and NCHAR” on page 123
● “String literals” on page 7
● “CAST function [Data type conversion]” on page 159
● “REGEXP search condition” on page 43
● “LIKE search condition” on page 39
● “REGEXP_SUBSTR function [String]” on page 305
● “Regular expressions: Special sub-character classes” on page 21
● “LIKE, REGEXP, and SIMILAR TO search conditions” on page 37

Standards and compatibility


● SQL/2008 The SIMILAR TO predicate is optional SQL language feature T141 of the SQL/2008
standard.

IN search condition
Syntax
expression [ NOT ] IN { ( query-expression ) | ( expression-list ) }

Remarks
An IN search condition compares expression with the set of values returned by query-expression or the set
of values specified in expression-list. Without the NOT keyword, the IN search condition evaluates
according to the following rules:

46 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

● TRUE if expression is not NULL and equals at least one of the values.

● UNKNOWN if expression is NULL and the values list is not empty, or if at least one of the values is
NULL and expression does not equal any of the other values.

● FALSE if expression is NULL and query-expression returns no values; or if expression is not NULL,
none of the values are NULL, and expression does not equal any of the values.

The NOT keyword interchanges TRUE and FALSE.

The search condition expression IN ( expression-list ) is equivalent to expression = ANY ( expression-


list ).

The search condition expression NOT IN (expression-list ) is equivalent to expression <> ALL (
expression-list ).

The expressions in an expression-list can be a literal, variable, host variable, or a query expression whose
result is a single row and a single column.

Standards and compatibility


● SQL/2008 Core feature.

CONTAINS search condition


Syntax
CONTAINS ( column-name [,...], contains-query-string )

contains-query-string :
simple-expression
| or-expression

simple-expression :
primary-expression
| and-expression

or-expression :
simple-expression { OR | | } contains-query-string

primary-expression :
basic-expression
| FUZZY " fuzzy-expression "
| and-not-expression

and-expression :
primary-expression [ AND | & ] simple-expression

and-not-expression :
primary-expression [ AND | & ] { NOT | - } basic-expression

basic-expression :
term

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 47


SQL language elements

| phrase
| ( contains-query-string )
| near-expression

fuzzy-expression :
term
| fuzzy-expression term

term :
simple-term
| prefix-term

prefix-term :
simple-term*

phrase :
" phrase-string "

near-expression :
term NEAR[distance] term
| term { NEAR | ~ } term

phrase-string :
term
| phrase-string term

simple-term : a string separated by whitespace and special characters that


represents a single indexed term (word) to search for.

distance : a positive integer

Parameters
● and-expression Use and-expression to specify that both primary-expression and simple-
expression must be found in the text index.

By default, if no operator is specified between terms or expressions, an and-expression is assumed.


For example, 'a b' is interpreted as 'a AND b'.

An ampersand (&) can be used instead of AND, and can abut the expressions or terms on either side
(for example, 'a &b').

● and-not-expression Use and-not-expression to specify that primary-expression must be present


in the text index, but that basic-expression must not be found in the text index. This is also known as a
negation.

If you use a hyphen for negation, the hyphen must have a space to the left of it, and must adjoin the
term to the right; otherwise, the hyphen is not interpreted as a negation. For example, 'a -b' is
equivalent to 'a AND NOT b'; whereas for 'a - b', the hyphen is ignored and the string is
equivalent to 'a AND b'. 'a-b' is equivalent to the phrase '"a b"'.

● or-expression Use or-expression to specify that at least one of simple-expression or contains-


query-string must be present in the text index. For example, 'a|b' is interpreted as 'a OR b'.

48 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

● fuzzy-expression Use fuzzy-expression to find terms that are similar to what you specify. Fuzzy
matching is only supported on NGRAM text indexes.

● near-expression Use near-expression to search for terms that are near each other. This is also
known as a proximity search. For example, 'b NEAR[5] c' searches for instances of b and c that
are five or less terms away from each other. The order of terms is not significant; 'b NEAR c' is
equivalent to 'c NEAR b'.

If NEAR is specified without distance, a default of 10 terms is applied.

You can specify a tilde (~) instead of NEAR. This is equivalent to specifying NEAR without a
distance so a default of 10 terms is applied. You cannot specify a distance if you specify a tilde; it is
always 10 terms.

NEAR expressions cannot be chained together (for example, 'a NEAR[1] b NEAR[1] c').

● prefix-term Use prefix-term to search for terms that start with the specified prefix. For example,
'datab*' searches for any term beginning with datab. This is also known as a prefix search. In a
prefix search, matching is performed for the portion of the term to the left of the asterisk.

Remarks
The CONTAINS search condition takes a column list and contains-query-string as arguments. It can be
used anywhere a search condition (also referred to as predicate) can be specified, and returns TRUE or
FALSE. The contains-query-string must be a constant string, or a variable, with a value that is known at
query time. The contains-query-string cannot be NULL, an empty string, or exceed 300 valid terms. A
valid term is a term that is within the permitted term length and is not included in the STOPLIST. An
error is returned when the contains-query-string exceeds 300 valid terms.

If the text configuration settings cause all of the terms in the contains-query-string to be dropped, the
result of the CONTAINS search condition is FALSE.

For more information about how the contains-query-string is interpreted, see “Example text configuration
objects” [SQL Anywhere Server - SQL Usage].

If multiple columns are specified, then they must all refer to a single base table; a text index cannot span
multiple base tables. The base table can be referenced directly in the FROM clause, or it can be used in a
view or derived table.

The following warnings apply to the use of non-alphanumeric characters in query strings:

● An asterisk in the middle of a term returns an error.

● You should not use non-alphanumerics (including special characters) in fuzzy-expression because they
are treated as whitespace and serve as term breakers.

● If possible, do not include non-alphanumeric characters that are not special characters in your query
string. Any non-alphanumeric character that is not a special character causes the term containing it to
be treated as a phrase, breaking the term at the location of the character. For example, 'things
we've done' is interpreted as 'things "we ve" done'.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 49


SQL language elements

Within phrases, the asterisk is the only special character that continues to be interpreted as a special
character. All other special characters within phrases are treated as whitespace and serve as term breakers.

Interpretation of contains-query-string takes place in two main steps:

● Step 1: Interpreting operators and precedence During this step, keywords are interpreted as
operators, and rules of precedence are applied.

● Step 2: Applying text configuration object settings During this step, the text configuration
object settings are applied to terms. For example, on an NGRAM text index, terms are broken down
into their n-gram representation. During this step, the query terms that exceed the term length settings,
or that are in the stoplist, are dropped.

Operator precedence in a CONTAINS search condition


During query evaluation, expressions are evaluated using the following order of precedence:

1. FUZZY, NEAR

2. AND NOT

3. AND

4. OR

Treatment of BEFORE as a keyword


SQL Anywhere does not currently support the BEFORE keyword as an operator. For example, if you
specify CONTAINS(column-name, 'a before b'), an error is returned. Construct your query
using the NEAR keyword instead.

You can search for the word "before", providing it is part of a phrase query. For example,
CONTAINS(column-name, '"a before b"'). This searches for the phrase "a before b".

Allowed syntax for asterisk (*)


The asterisk is used for prefix searching. An asterisk can occur at the end of the query string, or be
followed by a space, ampersand, vertical bar, closing bracket, or closing quotation mark. Any other usage
of asterisk returns an error.

The following table shows allowable asterisk usage:

Query string Equivalent to Interpreted as

'th*' Find any term beginning with th.

'th*&best' 'th* AND Find any term beginning with th, and the term best.
best' and 'th*
best'

50 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

Query string Equivalent to Interpreted as

'th*|best' 'th* OR Find either any term beginning with th, or the term
best' best.

'very&(best| 'very AND Find the term very, and the term best or any term be-
th*)' (best OR ginning with th.
th*)'

'"fast auto*"' Find the term fast, immediately followed by a term be-
ginning with auto.

'"auto* price"' Find a term beginning with auto, immediately fol-


lowed by the term price.

Note
Interpretation of query strings containing asterisks can vary depending on the text configuration object
settings.

Allowed syntax for hyphen (-)


The hyphen can be used for term or expression negation, and is equivalent to NOT. Whether a hyphen is
interpreted as a negation depends on its location in the query string. For example, when a hyphen
immediately precedes a term or expression it is interpreted as a negation. If the hyphen is embedded
within a term, it is interpreted as a hyphen.

A hyphen used for negation must be preceded by a whitespace, and followed immediately by an
expression.

When used in a phrase of a fuzzy expression, the hyphen is treated as whitespace and used as a term
breaker.

The following table shows the allowed syntax for hyphen:

Query string Equivalent to: Interpreted as:

'the -best' 'the AND NOT best', Find the term the, and not the term best.
'the AND -best', 'the &
-best', 'the NOT best'

'the -(very 'the AND NOT (very AND Find the term the, and not the terms very
best)' best)' and best.

'the -"very 'the AND NOT "very Find the term the, and not the phrase very
best"' best"' best.

'alpha-numer- '"alpha numerics"' Find the term alpha, immediately followed


ics' by the term numerics.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 51


SQL language elements

Query string Equivalent to: Interpreted as:

'wild - west' 'wild west', and 'wild Find the term wild, and the term west.
AND west'

Allowed syntax for special characters


The following table shows the allowed syntax for all special characters except asterisk and hyphen.

These characters are not considered special characters if they are found in a phrase, and are dropped.

Note
The same restrictions with regards to specifying string literals also apply to the query string. For example,
apostrophes must be escaped, and so on.

Character or syntax Usage examples and remarks

ampersand (&) The ampersand is equivalent to AND, and can


be specified as follows:

● 'a & b'


● 'a &b'
● 'a&b'
● 'a& b'

vertical bar (|) The vertical bar is equivalent to OR, and can be
specified as follows:

● 'a|b'
● 'a |b'
● 'a | b'
● 'a| b'

double quotes (") Double quotes are used to contain a sequence


of terms where order and relative distance are
important. For example, in the query string
'learn "full text search"', "full
text search" is a phrase. In this example, learn
can come before or after the phrase, or exist in
another column (if the text index is built on
more than one column), but the exact phrase
must be found in a single column.

parentheses () Parentheses are used to specify the order of


evaluation of expressions if different from the
default order. For example 'a AND (b|c)'
is interpreted as a, and b or c.

52 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

Character or syntax Usage examples and remarks

tilde (~) The tilde is equivalent to NEAR[10]. The query


string 'full~text' is equivalent to 'full
NEAR text', and is interpreted as: the term
full within ten terms of the term text.

You cannot specify a distance with the tilde.

square brackets [ ] Square brackets are used in conjunction with


the keyword NEAR to contain distance. Other
uses of square brackets returns an error.

Standards and compatibility


● SQL/2008 The CONTAINS predicate is a vendor extension.

See also
● “Allowed syntax for special characters” on page 52
● “Proximity search” [SQL Anywhere Server - SQL Usage]
● “What to specify when creating or altering text configuration objects” [SQL Anywhere Server - SQL
Usage]
● “View search” [SQL Anywhere Server - SQL Usage]
● “Operator precedence in a CONTAINS search condition” on page 50
● “Prefix search” [SQL Anywhere Server - SQL Usage]
● “Allowed syntax for hyphen (-)” on page 51
● “Allowed syntax for asterisk (*)” on page 50
● “String literals” on page 7
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “What to specify when creating or altering text configuration objects” [SQL Anywhere Server - SQL
Usage]
● “FROM clause” on page 738
● “sa_char_terms system procedure” on page 1009
● “sa_nchar_terms system procedure” on page 1094

EXISTS search condition


Syntax
EXISTS ( subquery )

Remarks
The EXISTS search 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 search condition cannot be UNKNOWN.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 53


SQL language elements

Standards and compatibility


● SQL/2008 Core feature.

IS NULL and IS NOT NULL search conditions


Syntax
expression IS [ NOT ] NULL

Remarks
Without the NOT keyword, the IS NULL search condition is TRUE if the expression is the NULL value,
and FALSE otherwise. The NOT keyword reverses the meaning of the search condition.

Standards and compatibility


● SQL/2008 Core feature.

Truth value search conditions


Syntax
IS [ NOT ] truth-value

Remarks
Without the NOT keyword, the search 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 search condition, but leaves UNKNOWN unchanged.

Standards and compatibility


● SQL/2008 Truth value search conditions comprise optional SQL language feature F571 of the
SQL/2008 standard.

Trigger operation conditions


Syntax
trigger-operation:
INSERTING
| DELETING
| UPDATING [ ( column-name-string ) ]
| UPDATE ( column-name )

Remarks
Trigger-operation conditions can be used only in triggers, to carry out actions depending on the kind of
action that caused the trigger to fire.

54 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

The argument for UPDATING is a quoted string (for example, UPDATING( 'mycolumn' )). The
argument for UPDATE is an identifier (for example, UPDATE( mycolumn )). The two versions are
interoperable, and are included for compatibility with SQL dialects of other vendors' DBMS.

If you supply an UPDATING or UPDATE function, you must also supply a REFERENCING clause in
the CREATE TRIGGER statement to avoid syntax errors.

Example
The following trigger displays a message on the Messages tab of the Interactive SQL Results pane
showing which action caused the trigger to fire.
CREATE TRIGGER tr BEFORE INSERT, UPDATE, DELETE
ON sample_table
REFERENCING OLD AS t1old
FOR EACH ROW
BEGIN
DECLARE msg varchar(255);
SET msg = 'This trigger was fired by an ';
IF INSERTING THEN
SET msg = msg || 'insert'
ELSEIF DELETING THEN
set msg = msg || 'delete'
ELSEIF UPDATING THEN
set msg = msg || 'update'
END IF;
MESSAGE msg TO CLIENT
END;

See also
● “BEGIN statement” on page 484
● “CREATE TRIGGER statement” on page 651
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Three-valued logic
The following tables display how the AND, OR, NOT, and IS logical operators of SQL work in three-
valued logic.

AND operator
AND TRUE FALSE UNKNOWN

TRUE TRUE FALSE UNKNOWN

FALSE FALSE FALSE FALSE

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 55


SQL language elements

AND TRUE FALSE UNKNOWN

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

Standards and compatibility


● SQL/2008 Core feature. Truth value tests, such as IS UNKNOWN, comprise SQL language feature
F571.

See also
● “NULL special value” on page 64

Explicit selectivity estimates


SQL Anywhere uses statistical information to determine the most efficient strategy for executing each
statement. SQL Anywhere automatically gathers and updates these statistics. These statistics are stored
permanently in the database in the system table ISYSCOLSTAT. 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

56 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Search conditions

added, updated, or deleted. In this situation, you may want to execute a CREATE STATISTICS
statement.

If there are problems with a particular execution plan, you can use optimizer hints to require that a
particular index be used.

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's
estimate, you can explicitly supply a user estimate in the search condition.

The estimate is a percentage. It can be a positive integer or can contain fractional values.

Caution
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. If you do use explicit selectivity estimates, ensure that the number is accurate. Do not,
for example, supply values of 0% or 100% to force the use of an index.

You can disable user estimates by setting the database option user_estimates to Off. The default value for
user_estimates is Override-Magic, which means that user-supplied selectivity estimates are used only
when the optimizer would use a MAGIC (default) selectivity value for the condition. The optimizer uses
MAGIC values as a last resort when it is unable to accurately predict the selectivity of a predicate.

Examples
The following query provides an estimate that one percent of the ShipDate values are later than
2001/06/30:
SELECT ShipDate
FROM SalesOrderItems
WHERE ( ShipDate > '2001/06/30', 1 )
ORDER BY ShipDate DESC;

The following query estimates that half a percent of the rows satisfy the condition:
SELECT *
FROM Customers c, SalesOrders o
WHERE (c.ID = o.CustomerID, 0.5);

Fractional values enable more accurate user estimates for joins and large tables.

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 57


SQL language elements

See also
● “CREATE STATISTICS statement” on page 625
● “FROM clause” on page 738
● “user_estimates option” [SQL Anywhere Server - Database Administration]
● “Optimizer estimates and statistics” [SQL Anywhere Server - SQL Usage]

Special values
Special values can be used in expressions, and as column defaults when creating tables.

While some special values can be queried, some can only be used as default values for columns. For
example, LAST USER, TIMESTAMP and UTC TIMESTAMP can only be used as default values.

CURRENT DATABASE special value


CURRENT DATABASE returns the name of the current database.

Data type
string

See also
● “Expressions” on page 12

Standards and compatibility


● SQL/2008 Vendor extension.

CURRENT DATE special value


CURRENT DATE returns the present year, month, and day.

Data type
DATE

58 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Special values

See also
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “Expressions” on page 12
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112

Standards and compatibility


● SQL/2008 Vendor extension. In the ANSI SQL/2008 standard, the special register that defines the
present date is called CURRENT_DATE. SQL Anywhere does not support CURRENT_DATE.

CURRENT PUBLISHER special value


CURRENT PUBLISHER returns a string that contains the publisher user ID of the database for SQL
Remote replications.

Data type
string

Remarks
CURRENT PUBLISHER can be used as a default value in columns with character data types.

See also
● “GRANT PUBLISH statement [SQL Remote]” on page 756
● “REVOKE PUBLISH statement [SQL Remote]” on page 860
● “Viewing the publisher” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

CURRENT REMOTE USER special value


If the current connection belongs to the receive phase of SQL Remote, then CURRENT REMOTE USER
returns the user ID of the remote user that created the messages that are currently being applied on this
connection. In all other circumstances, CURRENT REMOTE USER is a NULL value.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 59


SQL language elements

Data type
string

Remarks
The CURRENT REMOTE USER special value is set by the receive phase of SQL Remote when it is
applying messages to the database. The CURRENT REMOTE USER special value is most useful in
triggers to determine whether the operations being applied are being applied by the receive phase of SQL
Remote, and if they are, which remote user generated the operations being applied.

See also
● “Using the CURRENT REMOTE USER special value” [SQL Remote]
● “-t option, SQL Remote Message Agent utility (dbremote)” [SQL Remote]

Standards and compatibility


Vendor extension.

CURRENT TIME special value


CURRENT TIME returns the present hour, minute, second, and fraction of a second.

Data type
TIME

Remarks
The fraction of a second is stored to 6 decimal places. The accuracy of the present time is limited by the
accuracy of the system clock.

See also
● “Expressions” on page 12
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP data type” on page 113
● “TIMESTAMP special value” on page 69
● “UTC TIMESTAMP special value” on page 71

60 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Special values

Standards and compatibility


● SQL/2008 Vendor extension. In the ANSI SQL/2008 standard, the special register that defines the
present time is called CURRENT_TIME. SQL Anywhere does not support CURRENT_TIME.

CURRENT TIMESTAMP special value


CURRENT TIMESTAMP combines CURRENT DATE and CURRENT TIME to form a TIMESTAMP
value containing the year, month, day, hour, minute, second and fraction of a second.

Data type
TIMESTAMP

Remarks
The fraction of a second is stored to 6 decimal places. The accuracy of the present time is limited by the
accuracy of the system clock.

Unlike DEFAULT TIMESTAMP, columns declared with DEFAULT CURRENT TIMESTAMP do not
necessarily contain unique values. If uniqueness is required, consider using DEFAULT TIMESTAMP
instead.

The information CURRENT TIMESTAMP returns is equivalent to the information returned by the
GETDATE and NOW functions.

CURRENT_TIMESTAMP is equivalent to CURRENT TIMESTAMP.

Note
The main difference between DEFAULT CURRENT TIMESTAMP and DEFAULT TIMESTAMP is
that DEFAULT CURRENT TIMESTAMP is set only at INSERT, while DEFAULT TIMESTAMP is set
at both INSERT and UPDATE.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 61


SQL language elements

See also
● “Expressions” on page 12
● “CURRENT TIME special value” on page 60
● “CURRENT UTC TIMESTAMP special value” on page 63
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP data type” on page 113
● “TIMESTAMP special value” on page 69
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension. In the SQL/2008 standard, the special register that defines the present
timestamp is called CURRENT_TIMESTAMP.

CURRENT USER special value


CURRENT USER contains the user ID of the current connection.

Data type
string

Remarks
CURRENT USER can be used as a default value in columns with character data types.

On UPDATE, columns with the CURRENT USER default are not changed unless explicitly updated. The
LAST USER default may be used to track updates by users.

CURRENT_USER is equivalent to CURRENT USER.

See also
● “Expressions” on page 12
● “LAST USER special value” on page 63
● “USER special value” on page 70

Standards and compatibility


● SQL/2008 Vendor extension. In the SQL/2008 standard, the special register that defines the current
user is called CURRENT_USER.

62 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Special values

CURRENT UTC TIMESTAMP special value


CURRENT UTC TIMESTAMP returns the Coordinated Universal Time (UTC) containing the year,
month, day, hour, minute, second, fraction of a second, and time zone.

Data type
TIMESTAMP WITH TIME ZONE

Remarks
This feature allows data to be entered with a consistent time reference, regardless of the time zone in
which the data was entered.

See also
● “Expressions” on page 12
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP data type” on page 113
● “TIMESTAMP special value” on page 69
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension. The TIMESTAMP WITH TIME ZONE data type is optional SQL
language feature F411 in the SQL/2008 standard.

LAST USER special value


LAST USER is the user ID of the user who last modified the row.

Data type
String

Remarks
LAST USER can be used as a default value in columns with character data types.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 63


SQL language elements

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 of day a row was last changed.

See also
● “CREATE TABLE statement” on page 633
● “CURRENT USER special value” on page 62
● “CURRENT TIMESTAMP special value” on page 61
● “USER special value” on page 70

Standards and compatibility


● SQL/2008 Vendor extension.

NULL special value


The NULL value specifies a value that is unknown or not applicable.

Syntax
NULL

Remarks
NULL is a special value that is different from any valid value for any data type. However, the NULL
value is a legal value in any data type. NULL is used to represent missing or inapplicable information.
There 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 NULL.

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.

Column space utilization for NULL values is 1 bit per column and space is allocated in multiples of 8
bits. The NULL bit usage is fixed based on the number of columns in the table that allow NULL values.

64 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Special values

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.

In the following examples, the column Salary contains NULL.

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 does 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.

Many common errors in formulating SQL queries are caused by the behavior of NULL. You have to be
careful to avoid these problem areas.

Set operators and DISTINCT clause


In SQL, comparisons to NULL within search conditions yield UNKNOWN as the result. However, when
determining whether or not two rows are duplicates of each other, SQL treats NULL as equivalent to
NULL. These semantics apply to the set operators (UNION, INTERSECT, EXCEPT), GROUP BY,
PARTITION within a WINDOW clause, and SELECT DISTINCT.

For example, if a column called redundant contained NULL for every row in a table T1, then the
following statement would return a single row:

SELECT DISTINCT redundant FROM T1;

Permissions
Must be connected to the database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 65


SQL language elements

Side effects
None.

Standards and compatibility


● SQL/2008 Core feature.

● Transact-SQL In some contexts, Adaptive Server Enterprise treats comparisons to NULL values
differently. If an expression is compared to a variable or NULL literal using equality or inequality,
and if expression is a simple expression that refers to the column of a base table or view, then the
comparison is performed using two-valued logic, with NULL = NULL yielding TRUE rather than
UNKNOWN. The list of possible comparisons with these semantics, and their SQL/2008 equivalents,
are as follows:

Transact-SQL comparison SQL/2008 equivalent

expression = NULL expression IS NULL

expression != NULL NOT (expression IS NULL)

expression = variable expression = variable IS TRUE OR (expression IS


NULL AND variable IS NULL)

expression != variable expression != variable IS TRUE AND ( NOT ex-


pression IS NULL OR NOT variable IS NULL)

SQL Anywhere will implement these semantics to match Adaptive Server Enterprise behavior if the
ansinull option is set to OFF. The ansinull option is set to OFF by default for Open Client and
jConnect connections. To ensure SQL/2008 semantics, you can either reset the ansinull option to ON,
or use an IS [NOT] NULL predicate instead of an equality comparison.

Unique indexes in SQL Anywhere can hold rows that hold NULL and are otherwise identical.
Adaptive Server Enterprise does not permit such entries in unique indexes.

If you use jConnect, the tds_empty_string_is_null option controls whether empty strings are returned
as NULL strings or as a string containing one blank character.

See also
● “tds_empty_string_is_null option” [SQL Anywhere Server - Database Administration]
● “Expressions” on page 12
● “ansinull option” [SQL Anywhere Server - Database Administration]
● “tds_empty_string_is_null option” [SQL Anywhere Server - Database Administration]
● “Search conditions” on page 32

Example
The following INSERT statement inserts a NULL into the date_returned column of the Borrowed_book
table.
INSERT INTO Borrowed_book ( date_borrowed, date_returned, book )
VALUES ( CURRENT DATE, NULL, '1234' );

66 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Special values

SQLCODE special value


SQLCODE indicates the disposition of the most recently executed SQL statement.

Data type
Signed INTEGER

Remarks
The database server sets a SQLSTATE and SQLCODE for each SQL statement it executes. SQLCODEs
are product-specific (for example, MobiLink has its own SQLCODEs), and can be used to learn
additional information about the SQLSTATE. For example, positive values other than 100 indicate
product-specific warning conditions. Negative values indicate product-specific exception conditions. The
value 100 indicates "no data" (for example, at the end of a result set fetched via a cursor).

SQLSTATE and SQLCODE are related in that each SQLCODE corresponds to a SQLSTATE, and each
SQLSTATE can correspond to one or more SQLCODEs.

To return the error condition associated with a SQLCODE, you can use the ERRORMSG function.

Note
SQLSTATE is the preferred status indicator for the outcome of a SQL statement.

See also
● “SQLSTATE special value” on page 67
● “SQL Anywhere error messages sorted by SQLCODE” [Error Messages]
● “Expressions” on page 12
● “ERRORMSG function [Miscellaneous]” on page 212

Standards and compatibility


● SQL/2008 SQLCODE was deprecated in the ANSI SQL/1992 standard, and was eliminated
entirely from SQL/1999. SQLCODE values continue to be maintained in SQL Anywhere for
backward compatibility for applications. SQLSTATE is the preferred status indicator.

SQLSTATE special value


SQLSTATE indicates whether the most recently executed SQL statement resulted in a success, error, or
warning condition.

Data type
String

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 67


SQL language elements

Remarks
The database server sets a SQLSTATE and SQLCODE for each SQL statement it executes. A
SQLSTATE is a string that indicates the whether the most recently executed SQL statement resulted in a
success, warning, or error condition.

Each SQLSTATE represents errors that are common to all platforms, and usually contain non-product-
specific wording. The format of a SQLSTATE value is a two-character class value, followed by a three-
character subclass value. Guidelines for SQLSTATE conformance with regard to class and subclass
values are outlined in the ISO/ANSI SQL standard.

SQL Anywhere conforms to the ISO/ANSI SQLSTATE conventions with the following additions and
exceptions:

Class and Condition


subclass

01WCx Warnings related to character set conversion

38xxx External function exception

42Xxx Syntax error: expressions

42Rxx Syntax error: referential integrity (for example, attempt to create second primary
key)

42Wxx Syntax error: generic

42Uxx Syntax error: duplicate, undefined, or ambiguous object reference

42Zxx Access violation

54Wxx Product limit exceeded

55Wxx Object not in required state for operation to succeed

57xxx Resource not available or operator intervention

5Rxxx SQL Remote errors

WBxxx Online backup errors

WIxxx Internal database errors

WPxxx Errors in procedures, variables, and so on

WLxxx Errors loading and/or unloading

WWxxx Miscellaneous SQL Anywhere-specific errors/warnings (including system failures)

68 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Special values

Class and Condition


subclass

WOxxx Remote data access feature-related errors

WJxxx JCS and JDBC related errors

WCxxx Character translation errors

WXxxx XML-related errors

WTxxx Text-related errors

The successful completion class is '00xxx' (for example, '00000').

SQLSTATE and SQLCODE are related in that each SQLCODE corresponds to a SQLSTATE, and each
SQLSTATE can correspond to one or more SQLCODEs.

To return the error condition associated with a SQLSTATE, you can use the ERRORMSG function.

See also
● “ERRORMSG function [Miscellaneous]” on page 212
● “SQLCODE special value” on page 67
● “SQL Anywhere error messages sorted by SQLSTATE” [Error Messages]
● “Expressions” on page 12

Standards and compatibility


● SQL/2008 SQLSTATE classes (the first two characters) beginning with the values '0'-'4', and
'A'-'H' are defined by the ANSI standard. Other classes are implementation-defined. Similarly,
subclass values that begin with values '0'-'4', and 'A'-'H' are defined by the ANSI standard. Subclass
values outside these ranges are implementation-defined.

TIMESTAMP special value


The TIMESTAMP default value is used to record the local date and time of day when a row in a table was
last modified.

Data type
TIMESTAMP

Remarks
The fraction of a second is stored to 6 decimal places. The accuracy of the present time is limited by the
accuracy of the system clock.

When a column is declared with DEFAULT TIMESTAMP, a default value is provided for inserts, and the
value is updated with the present date and time of day whenever the row is updated.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 69


SQL language elements

Columns declared with DEFAULT TIMESTAMP contain unique values so that applications can detect
near-simultaneous updates to the same row. If the present timestamp value is the same as the last value, it
is incremented by the value of the default_timestamp_increment option.

You can automatically truncate timestamp values in SQL Anywhere based on the
default_timestamp_increment option. This is useful for maintaining compatibility with other database
software that records less precise timestamp values.

The global variable @@dbts returns a TIMESTAMP value representing the last value generated for a
column using DEFAULT TIMESTAMP.

Note
The main difference between DEFAULT TIMESTAMP and DEFAULT CURRENT TIMESTAMP is
that DEFAULT CURRENT TIMESTAMP is set only at INSERT, while DEFAULT TIMESTAMP is set
at both INSERT and UPDATE.

See also
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “default_timestamp_increment option” [SQL Anywhere Server - Database Administration]
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP data type” on page 113
● “truncate_timestamp_values option” [SQL Anywhere Server - Database Administration]
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension.

USER special value


USER contains the user ID of the current connection.

Data type
string

70 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Special values

Remarks
USER can be used as a default value in columns with character data types. It is equivalent to CURRENT
USER.

On UPDATE, columns with the USER default are not changed unless explicitly updated. Instead, the
LAST USER default may be used to track updates by users.

See also
● “Expressions” on page 12
● “CURRENT USER special value” on page 62
● “LAST USER special value” on page 63

Standards and compatibility


● SQL/2008 Vendor extension.

UTC TIMESTAMP special value


The UTC TIMESTAMP default value is used to record the Coordinated Universal Time (UTC) when a
row in a table was last modified.

Data type
TIMESTAMP WITH TIME ZONE

Remarks
The fraction of a second is stored to 6 decimal places. The accuracy of the present time is limited by the
accuracy of the system clock.

When a column is declared with DEFAULT UTC TIMESTAMP, a default value is provided for inserts,
and the value is updated with the present UTC date and time of day whenever the row is updated.

Columns declared with DEFAULT UTC TIMESTAMP contain unique values so that applications can
detect near-simultaneous updates to the same row. If the present UTC timestamp value is the same as the
last value, it is incremented by the value of the default_timestamp_increment option.

You can automatically truncate UTC TIMESTAMP values in SQL Anywhere with the
default_timestamp_increment option. This is useful for maintaining compatibility with other database
software that records less precise timestamp values.

Note
DEFAULT UTC TIMESTAMP is set at both INSERT and UPDATE and DEFAULT CURRENT UTC
TIMESTAMP is set at INSERT.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 71


SQL language elements

See also
● “Expressions” on page 12
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “default_timestamp_increment option” [SQL Anywhere Server - Database Administration]
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP data type” on page 113
● “TIMESTAMP special value” on page 69
● “TIMESTAMP WITH TIME ZONE data type” on page 115
● “truncate_timestamp_values option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Variables
SQL 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. 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 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.

See also
● “TIMESTAMP data type” on page 113
● “CREATE VARIABLE statement” on page 660

72 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Variables

Standards and compatibility


● SQL/2008 Variables declared within SQL stored procedures or functions using the DECLARE
statement is supported in the ANSI SQL/2008 standard as SQL language feature P002,
"Computational completeness". CREATE VARIABLE, DROP VARIABLE, and global variables are
all vendor extensions.

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). Only one variable can be declared for
each DECLARE statement in SQL Anywhere.

If the DECLARE is executed within a compound statement, the scope is limited to the compound
statement.

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 displays the message local_var = 10 on the Messages tab
of the Interactive SQL Results pane.

The variable local_var does not exist outside the compound statement in which it is declared. The
following batch is invalid, and gives an error.
-- This batch is invalid.
BEGIN
DECLARE local_var INT;
SET local_var = 10;
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;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 73


SQL language elements

SELECT 10 INTO local_var;


MESSAGE 'local_var = ', local_var TO CLIENT;
END

Running this batch from Interactive SQL displays the message local_var = 10 on the Messages tab
of the Interactive SQL Results pane.

Standards and compatibility


● SQL/2008 The DECLARE statement is supported in the ANSI SQL/2008 standard as SQL
language feature P002, "Computational completeness".

See also
● “Column '%1' not found” [Error Messages]
● “Variables in Transact-SQL procedures” [SQL Anywhere Server - SQL Usage]

Connection-level variables
Connection-level variables are declared with the CREATE VARIABLE statement. Connection-level
variables can be passed as parameters to procedures.

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 displays the message con_var = 10 on the Messages tab of
the Interactive SQL Results pane.

Standards and compatibility


● SQL/2008 Vendor extension.

74 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


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 values 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 special values


The special values (for example, CURRENT DATE, CURRENT TIME, 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.

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.

Supported global variables

Variable name Meaning

@@char_convert 0 (Provided for compatibility with Transact-SQL.)

@@client_csid -1 (Provided for compatibility with Transact-SQL.)

@@client_csname NULL (Provided for compatibility with Transact-SQL.)

@@connections The number of logins since the server was last started.

@@cpu_busy 0 (Provided for compatibility with Transact-SQL.)

@@dbts A value of type TIMESTAMP representing the last generated value used for all
columns defined with DEFAULT TIMESTAMP.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 75


SQL language elements

Variable name Meaning

@@error A Transact-SQL error code that checks the success or failure of the most re-
cently executed statement. If the previous transaction succeeded, 0 is returned.
If the previous transaction was unsuccessful, the last error number generated by
the system is returned. For descriptions of the values returned by @@error, see
“Error handling in Transact-SQL procedures” [SQL Anywhere Server - SQL
Usage].

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
you want verified.

@@fetch_status Contains status information resulting from the last fetch statement. This feature
is the same as @@sqlstatus, except that it returns different values. It is for Mi-
crosoft SQL Server compatibility. @@fetch_status 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.

@@identity Last value inserted into any IDENTITY or DEFAULT AUTOINCREMENT


column by an INSERT or SELECT INTO statement.

@@idle 0 (Provided for compatibility with Transact-SQL.)

@@io_busy 0 (Provided for compatibility with Transact-SQL.)

@@isolation Current isolation level of the connection. @@isolation takes the value of the
active level.

@@langid Unique language ID for the language in use by the current connection.

@@language Name of the language in use by the connection.

@@max_connec- For the personal server, the maximum number of simultaneous connections that
tions 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).

@@maxcharlen Maximum length, in bytes, of a character in the CHAR character set.

@@ncharsize Maximum length, in bytes, of a character in the NCHAR character set.

@@nestlevel -1 (Provided for compatibility with Transact-SQL.)

76 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Variables

Variable name Meaning

@@pack_received 0 (Provided for compatibility with Transact-SQL.)

@@pack_sent 0 (Provided for compatibility with Transact-SQL.)

@@packet_errors 0 (Provided for compatibility with Transact-SQL.)

@@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.

The @@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.

@@spid 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. @@sqlsta-
tus 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 state-
ment. The default setting is 32765, which is the largest byte string that can be
returned using READTEXT. The value can be set using the SET statement.

@@thresh_hystere- 0 (Provided for compatibility with Transact-SQL.)


sis

@@timeticks 0 (Provided for compatibility with Transact-SQL.)

@@total_errors 0 (Provided for compatibility with Transact-SQL.)

@@total_read 0 (Provided for compatibility with Transact-SQL.)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 77


SQL language elements

Variable name Meaning

@@total_write 0 (Provided for compatibility with Transact-SQL.)

@@tranchained Current transaction mode; 0 for unchained or 1 for chained.

@@trancount Nesting level of transactions. Each BEGIN TRANSACTION in a batch incre-


ments the transaction count.

@@transtate -1 (Provided for compatibility with Transact-SQL.)

@@version Version number of the current version of SQL Anywhere.

See also
● “@@identity global variable” on page 78

@@identity global variable


The @@identity variable holds the most recent value inserted by the current connection into an
IDENTITY column, a DEFAULT AUTOINCREMENT column, or a DEFAULT GLOBAL
AUTOINCREMENT column, or zero if the most recent insert was into a table that had no such column.

The value of @@identity is connection specific. 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 zero.

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.

@@identity and triggers


When an insert causes referential integrity actions or fires a trigger, @@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.

Standards and compatibility


● SQL/2008 Global variables are a vendor extension.

78 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Comments

Comments
Comments are used to attach explanatory text to SQL statements or statement blocks. The database server
does not execute comments.

The following comment indicators are supported in SQL Anywhere:

● -- (Double hyphen) The database server ignores any remaining characters on the line. This is the
SQL/2008 comment indicator. You can add and remove this comment indicator by pressing Ctrl
+minus sign in Interactive SQL and in the Stored Procedure window of Sybase Central.

● // (Double slash) The double slash has the same meaning as the double hyphen. You can add and
remove this comment indicator by pressing Ctrl+Forward Slash in Interactive SQL and in the Stored
Procedure window of Sybase Central.

● /* ... */ (Slash-asterisk) Any characters between the two comment markers are ignored. The two
comment markers can 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.

Examples
The following example illustrates the use of double-hyphen 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 SalesEmployees AS
SELECT EmployeeID, Surname, GivenName
FROM Employees
WHERE DepartmentID = 200;

Standards and compatibility


● SQL/2008 The use of double-minus signs for a comment is a core feature of the ANSI SQL/2008
standard. The use of C-style, bracketed comments (/* ... */) is SQL language feature T351 of the SQL/
2008 standard. Double-slash comments (//) are supported as a vendor extension.

See also
● “Keyboard shortcuts for Interactive SQL” [SQL Anywhere Server - Database Administration]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 79


80 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1
SQL data types

Character data types


Character data types are used to store strings of letters, numbers, and other symbols.

SQL Anywhere provides two classes of character data types and some domains defined using those types.

● CHAR, VARCHAR, LONG VARCHAR Character data stored in a single- or multibyte character
set, often chosen to correspond most closely to the primary language or languages stored in the
database.

● NCHAR, NVARCHAR, LONG NVARCHAR Character data stored in the UTF-8 Unicode
encoding. All Unicode code points can be stored using these types, regardless of the primary language
or languages stored in the database.

● TEXT, UNIQUEIDENTIFIERSTR, XML Domains based on other character data types.

Storage
All character data values are stored in the same manner. By default, values up to 128 bytes are stored in a
single piece. Values longer than 128 bytes are stored with a 4-byte prefix kept locally on the database
page and the full value stored in one or more other database pages. These default sizes are controlled by
the INLINE and PREFIX clauses of the CREATE TABLE statement.

See also
● “CREATE TABLE statement” on page 633
● “string_rtruncation option” [SQL Anywhere Server - Database Administration]

CHAR data type


The CHAR data type stores character data, up to 32767 bytes.

Syntax
CHAR [ ( max-length [ CHAR | CHARACTER ] ) ]

Parameters
● max-length The maximum length of the string. If byte-length semantics are used (CHAR or
CHARACTER is not specified as part of the length), then the length is in bytes, and the length must
be in the range 1 to 32767. If the length is not specified, then it is 1.

If character-length semantics are used (CHAR or CHARACTER is specified as part of the length),
then the length is in characters, and you must specify max-length. max-length can be a maximum of
32767 characters.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 81


SQL data types

Remarks
Multibyte characters can be stored as CHAR, but the declared length refers to bytes, not characters, unless
character-length semantics are used.

CHAR can also be specified as CHARACTER. Regardless of which syntax is used, the data type is
described as CHAR.

CHAR is semantically equivalent to VARCHAR, although they are different types. In SQL Anywhere,
CHAR is a variable-length type. In other relational database management systems, CHAR is a fixed-
length type, and data is padded with blanks to max-length bytes of storage. SQL Anywhere does not
blank-pad stored character data.

How CHAR columns are described depends on the client interface, the character sets used, and if
character-length semantics are used. For example, in embedded SQL the described length is the maximum
number of bytes in the client character set. If the described length would be more than 32767 bytes, the
column is described as type DT_LONGVARCHAR. The following table shows some embedded SQL
examples and the results returned when a DESCRIBE is performed:

Type being described Database character set Client character set Result of DESCRIBE

CHAR(10) Windows-1252 Windows-1252 DT_FIXCHAR length 10

CHAR(10) UTF-8 UTF-8 DT_FIXCHAR length 10

CHAR(10) Windows-1252 UTF-8 DT_FIXCHAR length 30

CHAR(20000) Windows-31J UTF-8 DT_LONGVARCHAR

CHAR(10 CHAR ) Windows-1252 Windows-1252 DT_FIXCHAR length 10

CHAR(10 CHAR ) UTF-8 UTF-8 DT_FIXCHAR length 40

For ODBC, CHAR is described as either SQL_CHAR or SQL_VARCHAR depending on the


odbc_distinguish_char_and_varchar option.

See also
● “odbc_distinguish_char_and_varchar option” [SQL Anywhere Server - Database Administration]
● “VARCHAR data type” on page 87
● “LONG VARCHAR data type” on page 83
● “NCHAR data type” on page 84

Standards and compatibility


● SQL/2008 Compatible with SQL/2008. In the standard, character-length semantics are the default,
whereas in SQL Anywhere byte-length semantics are the default. There are minor inconsistencies with
the SQL standard due to case-insensitive collation support and SQL Anywhere blank-padding support.

The SQL/2008 standard supports explicit character- or byte-length semantics as SQL language feature
T061.

82 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Character data types

LONG NVARCHAR data type


The LONG NVARCHAR data type stores Unicode character data of arbitrary length.

Syntax
LONG NVARCHAR

Remarks
The maximum size is 2 GB minus 1 byte (231 - 1).

Characters are stored in UTF-8. Each character requires from one to four bytes. The maximum number of
characters that can be stored in a LONG NVARCHAR is over 500 million and possibly over 2 billion,
depending on the lengths of the characters stored.

When an embedded SQL client performs a DESCRIBE on a LONG NVARCHAR column, the data type
returned is either DT_LONGVARCHAR or DT_LONGNVARCHAR, depending on whether the
db_change_nchar_charset function has been called.

For ODBC, a LONG NVARCHAR expression is described as SQL_WLONGVARCHAR.

See also
● “db_change_nchar_charset function” [SQL Anywhere Server - Programming]
● “NCHAR data type” on page 84
● “NVARCHAR data type” on page 85
● “LONG VARCHAR data type” on page 83

Standards and compatibility


● SQL/2008 The use of LONG NVARCHAR to declare a national character string is a vendor
extension.

LONG VARCHAR data type


The LONG VARCHAR data type stores character data of arbitrary length.

Syntax
LONG VARCHAR

Remarks
The maximum size is 2 GB minus 1 byte (231 - 1).

Multibyte characters can be stored as LONG VARCHAR, but the length is in bytes, not characters.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 83


SQL data types

See also
● “CHAR data type” on page 81
● “VARCHAR data type” on page 87
● “LONG NVARCHAR data type” on page 83

Standards and compatibility


● SQL/2008 Large object support is SQL language feature T041 of the SQL/2008 standard.

NCHAR data type


The NCHAR data type stores Unicode character data, up to 32767 characters.

Syntax
NCHAR [ ( max-length ) ]

Parameters
● max-length The maximum length of the string, in characters. The length must be in the range 1 to
32767. If the length is not specified, then it is 1.

Remarks
Characters are stored using UTF-8 encoding. The maximum number of bytes of storage required is four
multiplied by max-length. However, the actual number of bytes of storage required is usually much less.

NCHAR can also be specified as NATIONAL CHAR or NATIONAL CHARACTER. Regardless of


which syntax is used, the data type is described as NCHAR.

When an embedded SQL client performs a DESCRIBE on an NCHAR column, the data type returned is
either DT_FIXCHAR or DT_NFIXCHAR, depending on whether the db_change_nchar_charset function
has been called.

Also, when an embedded SQL client performs a DESCRIBE on an NCHAR column, the length returned
is the maximum byte length in the client NCHAR character set. For example, for an embedded SQL client
using the Western European character set cp1252 as the NCHAR character set, an NCHAR(10) column is
described as type DT_NFIXCHAR of length 10 (10 characters multiplied by a maximum one byte per
character). For an embedded SQL client using the Japanese character set cp932, the same column is
described as type DT_NFIXCHAR of length 20 (10 characters multiplied by a maximum two bytes per
character). If the described length would return more then 32767 bytes, the column is described as type
DT_LONGNVARCHAR.

NCHAR is semantically equivalent to NVARCHAR, although they are different types. In SQL
Anywhere, NCHAR is a variable-length type. In other relational database management systems, NCHAR
is a fixed-length type, and data is padded with blanks to max-length characters of storage. SQL Anywhere
does not blank-pad stored character data.

For ODBC, NCHAR is described as SQL_WCHAR.

84 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Character data types

See also
● “db_change_nchar_charset function” [SQL Anywhere Server - Programming]
● “CHAR data type” on page 81
● “NVARCHAR data type” on page 85
● “LONG NVARCHAR data type” on page 83

Standards and compatibility


● SQL/2008 National character support is feature F421 of the SQL/2008 standard.

NTEXT data type


The NTEXT data type stores Unicode character data of arbitrary length.

Syntax
NTEXT

Remarks
NTEXT is a domain, implemented as a LONG NVARCHAR.

See also
● “LONG NVARCHAR data type” on page 83
● “TEXT data type” on page 86

Standards and compatibility


● SQL/2008 Vendor extension.

NVARCHAR data type


The NVARCHAR data type stores Unicode character data, up to 32767 characters.

Syntax
NVARCHAR [ ( max-length ) ]

Parameters
● max-length The maximum length of the string, in characters. The length must be in the range 1 to
32767. If the length is not specified, then it is 1.

Remarks
Characters are stored in UTF-8 encoding. The maximum storage number of bytes required is four
multiplied by max-length, although the actual storage required is usually much less.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 85


SQL data types

NVARCHAR can also be specified as NCHAR VARYING, NATIONAL CHAR VARYING, or


NATIONAL CHARACTER VARYING. Regardless of which syntax is used, the data type is described as
NVARCHAR.

When an embedded SQL client performs a DESCRIBE on a NVARCHAR column, the data type returned
is either DT_VARCHAR or DT_NVARCHAR, depending on whether the db_change_nchar_charset
function has been called.

Also, when an embedded SQL client performs a DESCRIBE on an NVARCHAR column, the length
returned is the maximum byte length in the client NCHAR character set. For example, for an embedded
SQL client using the Western European character set cp1252 as the NCHAR character set, an
NVARCHAR(10) column is described as type DT_NVARCHAR of length 10 (10 characters multiplied
by a maximum of one byte per character). For an embedded SQL client using the Japanese character set
cp932, the same column is described as type DT_NVARCHAR of length 20 (10 characters multiplied by
a maximum two bytes per character). If the describe length would return more than 32767 bytes, the
column is described as type DT_LONGNVARCHAR.

For ODBC, NVARCHAR is described as SQL_WVARCHAR.

See also
● “db_change_nchar_charset function” [SQL Anywhere Server - Programming]
● “NCHAR data type” on page 84
● “LONG NVARCHAR data type” on page 83
● “VARCHAR data type” on page 87

Standards and compatibility


● SQL/2008 National character support is SQL language feature F421 in the SQL/2008 standard.

TEXT data type


The TEXT data type stores character data of arbitrary length.

Syntax
TEXT

Remarks
TEXT is a domain, implemented as a LONG VARCHAR.

See also
● “LONG VARCHAR data type” on page 83
● “NTEXT data type” on page 85

Standards and compatibility


● SQL/2008 Vendor extension.

86 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Character data types

UNIQUEIDENTIFIERSTR data type


UNIQUEIDENTIFIERSTR is a domain, implemented as CHAR(36).

Syntax
UNIQUEIDENTIFIERSTR

Remarks
Used for remote data access, when mapping Microsoft SQL Server uniqueidentifier columns.

See also
● “Data type conversions: Microsoft SQL Server” [SQL Anywhere Server - SQL Usage]
● “STRTOUUID function [String]” on page 351

Standards and compatibility


● SQL/2008 Vendor extension.

VARCHAR data type


The VARCHAR data type stores character data, up to 32767 bytes.

Syntax
VARCHAR [ ( max-length [ CHAR | CHARACTER ] ) ]

Parameters
● max-length The maximum length of the string. If byte-length semantics are used (CHAR or
CHARACTER is not specified as part of the length), then the length is in bytes, and the length must
be in the range of 1 to 32767. If the length is not specified, then it is 1.

If character-length semantics are used (CHAR or CHARACTER is specified as part of the length),
then the length is in characters, and you must specify max-length. max-length can be a maximum of
32767 characters.

Remarks
Multibyte characters can be stored as VARCHAR, but the declared length refers to bytes, not characters.

VARCHAR can also be specified as CHAR VARYING or CHARACTER VARYING. Regardless of


which syntax is used, the data type is described as VARCHAR.

How VARCHAR columns are described depends on the client interface, the character sets used, and if
character-length semantics are used. For example, in embedded SQL the described length is the maximum
number of bytes in the client character set. If the described length would be more than 32767 bytes, the
column is described as type DT_LONGVARCHAR. The following table shows some embedded SQL
examples and the results returned when a DESCRIBE is performed:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 87


SQL data types

Type being described Database character Client character set Result of DESCRIBE
set

VARCHAR(10) Windows-1252 Windows-1252 DT_VARCHAR length 10

VARCHAR(10) UTF-8 UTF-8 DT_VARCHAR length 10

VARCHAR(10) Windows-1252 UTF-8 DT_VARCHAR length 30

VARCHAR(20000) Windows-31J UTF-8 DT_LONGVARCHAR

VARCHAR(10 CHAR ) Windows-1252 Windows-1252 DT_VARCHAR length 10

VARCHAR(10 CHAR ) UTF-8 UTF-8 DT_VARCHAR length 40

For ODBC, VARCHAR is described as SQL_VARCHAR.

See also
● “CHAR data type” on page 81
● “LONG VARCHAR data type” on page 83
● “NVARCHAR data type” on page 85

Standards and compatibility


● SQL/2008 Compatible with SQL/2008. In the standard, character-length semantics are the default,
whereas in SQL Anywhere byte-length semantics are the default. There are minor inconsistencies with
the SQL standard due to case-insensitive collation support and SQL Anywhere blank-padding support.

The SQL/2008 standard supports explicit character- or byte-length semantics as SQL language feature
T061.

XML data type


The XML data type stores character data of arbitrary length, and is used to store XML documents.

Syntax
XML

Remarks
The maximum size is 2 GB minus 1 byte (231 - 1).

Data of type XML is not quoted when generating element content from relational data.

You can cast between the XML data type and any other data type that can be cast to or from a string. Note
that there is no checking that the string is well-formed when it is cast to XML.

When an embedded SQL client application performs a DESCRIBE on an XML column, it is described as
LONG VARCHAR.

88 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Numeric data types

See also
● “Use of XML in the database” [SQL Anywhere Server - SQL Usage]
● “Storage of XML documents in relational databases” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 The XML data type is SQL language feature X010 in the SQL/2008 standard.

Numeric data types


The numeric data types are used for storing numerical data.

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.

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.

Be careful using default precision and scale settings for NUMERIC and DECIMAL data types, because
these settings could be different in other database solutions. In SQL Anywhere, the default precision is 30
and the default scale is 6.

You should avoid default precision and scale settings for NUMERIC and DECIMAL data types, because
these are different between SQL Anywhere and Adaptive Server Enterprise. In SQL 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 SQL
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” [SQL
Anywhere Server - Database Administration] and “scale option” [SQL Anywhere Server - Database
Administration].

BIGINT data type


The BIGINT data type is used to store BIGINTs, which are integers requiring 8 bytes of storage.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 89


SQL data types

Syntax
[ UNSIGNED ] BIGINT

Remarks
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 -263 to 263 - 1, or -9223372036854775808 to


9223372036854775807.

The range for unsigned BIGINT values is 0 to 264 - 1, or 0 to 18446744073709551615.

By default, the data type is signed.

When converting a string to a BIGINT, leading and trailing spaces are removed. If the leading character is
'+' it is ignored. If the leading character is '-' the remaining digits are interpreted as a negative number.
Leading '0' characters are skipped, and the remaining characters are converted to an integer value. An
error is returned if the value is out of the valid range for the destination data type, if the string contains
illegal characters, or if the string cannot be decoded as an integer value.

See also
● “BIT data type” on page 90
● “INTEGER data type” on page 94
● “SMALLINT data type” on page 97
● “TINYINT data type” on page 97
● “Numeric functions” on page 140
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 The BIGINT data type is SQL language feature T071 of the SQL/2008 standard.

BIT data type


The BIT data type is used to store a bit (0 or 1).

Syntax
BIT

Remarks
BIT is an integer type that can store the values 0 or 1.

By default, the BIT data type does not allow NULL.

A BIT value requires 1 byte of storage.

90 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Numeric data types

When converting a string to a BIT, leading and trailing spaces are removed. If the leading character is '+'
it is ignored. If the leading character is '-' the remaining digits are interpreted as a negative number.
Leading '0' characters are skipped, and the remaining characters are converted to an integer value. An
error is returned if the value is out of the valid range for the destination data type, if the string contains
illegal characters, or if the string cannot be decoded as an integer value.

See also
● “BIGINT data type” on page 89
● “INTEGER data type” on page 94
● “SMALLINT data type” on page 97
● “TINYINT data type” on page 97
● “Numeric functions” on page 140
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/1999 The BIT data type is SQL language feature F511 of the SQL/1999 standard.

● SQL/2008 The BIT and BIT VARYING data types were dropped from the SQL/2003 standard.
Hence with respect to the SQL/2008 standard, the BIT data type is a vendor extension.

DECIMAL data type


The DECIMAL data type is a decimal number with precision total digits and with scale digits after the
decimal point.

Syntax
DECIMAL [ ( precision [ , scale ] ) ]

Parameters
● precision An integer expression between 1 and 127, inclusive, that specifies the number of digits
in the expression. The default setting is 30.

● scale An integer expression between 0 and 127, inclusive, that specifies the number of digits after
the decimal point. The scale value should always be less than, or equal to, the precision value. The
default setting is 6.

The defaults can be changed by setting database options.

Remarks
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 )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 91


SQL data types

The function 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.

DECIMAL can also be specified as DEC. Regardless of which syntax is used, the data type is described
as DECIMAL.

If you are using a precision of 20 or less and a scale of 0, it may be possible to use one of the integer data
types (BIGINT, INTEGER, SMALLINT, or TINYINT) instead. Integer values require less storage space
than NUMERIC and DECIMAL values with a similar number of significant digits. Operations on integer
values, such as fetching or inserting, and arithmetic operators, typically perform better than operations on
NUMERIC and DECIMAL values.

DECIMAL is semantically equivalent to NUMERIC.

Note
If you create a column or variable of a DECIMAL data type with a precision or scale that exceeds the
precision and scale settings for the database, values are truncated to the database settings. So, if you notice
truncated values in a column or variable defined as DECIMAL, check that precision and scale do not
exceed the database option settings.

See also
● “FLOAT data type” on page 93
● “REAL data type” on page 96
● “DOUBLE data type” on page 92
● “NUMERIC data type” on page 95
● “Numeric functions” on page 140
● “Aggregate functions” on page 133
● “precision option” [SQL Anywhere Server - Database Administration]
● “scale option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 DECIMAL and NUMERIC data types are core features of the SQL/2008 standard.

DOUBLE data type


The DOUBLE data type is used to store double-precision floating-point numbers.

Syntax
DOUBLE [ PRECISION ]

Remarks
The DOUBLE data type holds a double-precision floating-point number. An approximate numeric data
type, it is subject to rounding errors after arithmetic operations. The approximate nature of DOUBLE
values means that queries using equalities should generally be avoided when comparing DOUBLE values.

92 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Numeric data types

DOUBLE values require 8 bytes of storage.

The range of values is -1.79769313486231e+308 to 1.79769313486231e+308, with numbers close to zero


as small as 2.22507385850721e-308. Values held as DOUBLE are accurate to 15 significant digits, but
may be subject to rounding error beyond the fifteenth digit.

See also
● “FLOAT data type” on page 93
● “REAL data type” on page 96
● “DECIMAL data type” on page 91
● “NUMERIC data type” on page 95
● “Numeric functions” on page 140
● “Aggregate functions” on page 133
● “Numeric set conversions” on page 130

Standards and compatibility


● SQL/2008 The DOUBLE PRECISION type is a core feature of the SQL/2008 standard.

FLOAT data type


The FLOAT data type is used to store a floating-point number, which can be single or double precision.

Syntax
FLOAT [ ( precision ) ]

Parameters
● precision An integer expression that specifies the number of bits in the mantissa. A mantissa is the
decimal part of a logarithm. For example, in the logarithm 5.63428, the mantissa is 0.63428. The
IEEE standard 754 floating-point precision is as follows:

Supplied precision value Decimal precision Equivalent SQL data type Storage size

1-24 7 decimal digits REAL 4 bytes

25-53 15 decimal digits DOUBLE 8 bytes

Remarks
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.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 93


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
FLOAT values require 4 bytes of storage, and double-precision FLOAT values require 8 bytes.

The FLOAT data type is an approximate numeric data type. It is subject to rounding errors after
arithmetic operations. The approximate nature of FLOAT values means that queries using equalities
should generally be avoided when comparing FLOAT values.

See also
● “DOUBLE data type” on page 92
● “REAL data type” on page 96
● “DECIMAL data type” on page 91
● “NUMERIC data type” on page 95
● “Numeric functions” on page 140
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 The FLOAT type is a core feature of the SQL/2008 standard.

INTEGER data type


The INTEGER data type is used to store integers that require 4 bytes of storage.

Syntax
[ UNSIGNED ] INTEGER

Remarks
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 -231 to 231 - 1, or -2147483648 to 2147483647.

The range for unsigned integers is 0 to 232 - 1, or 0 to 4294967295.

INTEGER can also be specified as INT. Regardless of which syntax is used, the data type is described as
INTEGER.

When converting a string to a INTEGER, leading and trailing spaces are removed. If the leading character
is '+' it is ignored. If the leading character is '-' the remaining digits are interpreted as a negative number.
Leading '0' characters are skipped, and the remaining characters are converted to an integer value. An
error is returned if the value is out of the valid range for the destination data type, if the string contains
illegal characters, or if the string cannot be decoded as an integer value.

94 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Numeric data types

See also
● “BIGINT data type” on page 89
● “BIT data type” on page 90
● “SMALLINT data type” on page 97
● “TINYINT data type” on page 97
● “Numeric functions” on page 140
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 The INTEGER type is a core feature of the SQL/2008 standard. The UNSIGNED
keyword is a vendor extension.

NUMERIC data type


The NUMERIC data type is used to store decimal numbers with precision total digits and with scale
digits after the decimal point.

Syntax
NUMERIC [ ( precision [ , scale ] ) ]

Parameters
● precision An integer expression between 1 and 127, inclusive, that specifies the number of digits
in the expression. The default setting is 30.

● scale An integer expression between 0 and 127, inclusive, that specifies the number of digits after
the decimal point. The scale value should always be less than or equal to the precision value. The
default setting is 6.

Remarks
The NUMERIC data type is an exact numeric data type; its accuracy is preserved to the least significant
digit after arithmetic operations.

The number of bytes required to store a decimal number can be estimated as


2 + INT( (BEFORE+1)/2 ) + INT( (AFTER+1)/2 )

The INT function 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.

If you are using a precision of 20 or less and a scale of 0, it may be possible to use one of the integer data
types (BIGINT, INTEGER, SMALLINT, or TINYINT) instead. Integer values require less storage space
than NUMERIC and DECIMAL values with a similar number of significant digits. Operations on integer
values, such as fetching or inserting, and arithmetic operators, typically perform better than operations on
NUMERIC and DECIMAL values.

NUMERIC is semantically equivalent to DECIMAL.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 95


SQL data types

Note
If you create a column or variable of a NUMERIC data type with a precision or scale that exceeds the
precision and scale settings for the database, values are truncated to the database settings. So, if you notice
truncated values in a column or variable defined as NUMERIC, check that precision and scale do not
exceed the database option settings.

See also
● “FLOAT data type” on page 93
● “REAL data type” on page 96
● “DOUBLE data type” on page 92
● “DECIMAL data type” on page 91
● “Numeric functions” on page 140
● “Aggregate functions” on page 133
● “Numeric set conversions” on page 130
● “precision option” [SQL Anywhere Server - Database Administration]
● “scale option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Compatible with SQL/2008 if the scale option is set to zero.

REAL data type


The REAL data type is used to store single-precision floating-point numbers stored in 4 bytes.

Syntax
REAL

Remarks
The REAL data type holds a single-precision floating-point number. An approximate numeric data type, it
is subject to rounding errors after arithmetic operations. The approximate nature of REAL values means
that queries using equalities should generally be avoided when comparing REAL values.

REAL values require 4 bytes of storage.

The range of values is -3.402823e+38 to 3.402823e+38, with numbers close to zero as small as
1.175494351e-38. Values held as REAL are accurate to 7 significant digits, but may be subject to
rounding error beyond the sixth digit.

See also
● “DOUBLE data type” on page 92
● “FLOAT data type” on page 93
● “DECIMAL data type” on page 91
● “NUMERIC data type” on page 95
● “Numeric functions” on page 140
● “Aggregate functions” on page 133

96 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Numeric data types

Standards and compatibility


● SQL/2008 The REAL data type is a core feature of the SQL/2008 standard.

SMALLINT data type


The SMALLINT data type is used to store integers that require 2 bytes of storage.

Syntax
[ UNSIGNED ] SMALLINT

Remarks
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 -215 to 215 - 1, or -32768 to 32767.

The range for unsigned SMALLINT values is 0 to 216 - 1, or 0 to 65535.

When converting a string to a SMALLINT, leading and trailing spaces are removed. If the leading
character is '+' it is ignored. If the leading character is '-' the remaining digits are interpreted as a negative
number. Leading '0' characters are skipped, and the remaining characters are converted to an integer
value. An error is returned if the value is out of the valid range for the destination data type, if the string
contains illegal characters, or if the string cannot be decoded as an integer value.

See also
● “BIGINT data type” on page 89
● “BIT data type” on page 90
● “INTEGER data type” on page 94
● “TINYINT data type” on page 97
● “Numeric functions” on page 140
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 Compatible with SQL/2008. The UNSIGNED keyword is a vendor extension.

TINYINT data type


The TINYINT data type is used to store unsigned integers requiring 1 byte of storage.

Syntax
[ UNSIGNED ] TINYINT

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 97


SQL data types

Remarks
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 0 to 28 - 1, or 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 from an application written in C, the type
of the C variable should be integer.

When converting a string to a TINYINT, leading and trailing spaces are removed. If the leading character
is '+' it is ignored. If the leading character is '-' the remaining digits are interpreted as a negative number.
Leading '0' characters are skipped, and the remaining characters are converted to an integer value. An
error is returned if the value is out of the valid range for the destination data type, if the string contains
illegal characters, or if the string cannot be decoded as an integer value.

See also
● “BIGINT data type” on page 89
● “BIT data type” on page 90
● “INTEGER data type” on page 94
● “SMALLINT data type” on page 97
● “Numeric functions” on page 140
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 Vendor extension.

Money data types


Money data types are used for storing monetary data.

MONEY data type


The MONEY data type stores monetary data.

Syntax
MONEY

98 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Bit array data types

Remarks
MONEY is a domain, implemented as NUMERIC(19,4).

See also
● “SMALLMONEY data type” on page 99
● “Numeric functions” on page 140
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 Vendor extension.

SMALLMONEY data type


The SMALLMONEY data type is used to store monetary data that is less than one million currency units.

Syntax
SMALLMONEY

Remarks
SMALLMONEY is a domain, implemented as NUMERIC(10,4).

See also
● “MONEY data type” on page 98
● “Numeric functions” on page 140
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 Vendor extension.

Bit array data types


A bit array is similar to a character string, except that the individual pieces are bit data—0s (zeros) and 1s
(ones) instead of characters. Typically, bit arrays are used to hold a string of Boolean values.

The bit array data types supported by SQL Anywhere include VARBIT and LONG VARBIT.

LONG VARBIT data type


The LONG VARBIT data type is used to store arbitrary length bit arrays.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 99


SQL data types

Syntax
LONG VARBIT

Remarks
Used to store arbitrary length array of bits (1s and 0s), or bit arrays longer than 32767 bits.

LONG VARBIT can also be specified as LONG BIT VARYING. Regardless of which syntax is used, the
data type is described as LONG VARBIT.

See also
● “BIT data type” on page 90
● “VARBIT data type” on page 100
● “Bit array conversions” on page 128
● “Bit array functions” on page 135
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 Vendor extension.

VARBIT data type


The VARBIT data type is used for storing bit arrays that are under 32767 bits in length.

Syntax
VARBIT [ (max-length ) ]

Parameters
● max-length The maximum length of the bit array, in bits. The length must be in the range 1 to
32767. If the length is not specified, then it is 1.

Remarks
VARBIT can also be specified as BIT VARYING. Regardless of which syntax is used, the data type is
described as VARBIT.

See also
● “BIT data type” on page 90
● “LONG VARBIT data type” on page 99
● “Bit array conversions” on page 128
● “Bit array functions” on page 135
● “Aggregate functions” on page 133
● “Bitwise operators” on page 11

Standards and compatibility


● SQL/1999 The BIT VARYING data type is SQL language feature F511 of the SQL/1999 standard.

100 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Date and time data types

● SQL/2008 Both the BIT and BIT VARYING data types were dropped from the SQL/2003
standard. Hence with respect to the SQL/2008 standard, the BIT VARYING data type is a vendor
extension.

Date and time data types


The following list provides a quick overview of how dates are handled:

● SQL Anywhere always returns correct values for any legal arithmetic and logical operations on dates,
regardless of whether the calculated values span different centuries.

● The internal storage of dates by SQL Anywhere always explicitly includes the century portion of a year
value.

● The operation of SQL Anywhere is unaffected by any return value, including the current date.

● Date values can always be output in full century format.

How date and time of day are stored


Date and time of day are stored in SQL Anywhere databases using one of the following data types:

Data type Contains Stored Range of possible values


in

DATE Calendar date (year, month, day) 4 bytes Dates from 0001-01-01 to
9999-12-31.

TIME Time of day (hour, minute, second, 8 bytes Times from 00:00:00.000000 to
and fraction of a second accurate to 24:00:00.000000.
6 decimal places)

TIME- Calendar date and time of day (year, 8 bytes Dates from 0001-01-01 to 9999-12-31
STAMP month, day, hour, minute, second, (precision of the hours and minutes
and fraction of a second accurate to portion of a TIMESTAMP is dropped
6 decimal places) before 1600-02-28 23:59:59 and after
7911-01-01 00:00:00).

TIME- Calendar date, time of day, and time 10 bytes Dates from 0001-01-01 to 9999-12-31
STAMP zone offset (year, month, day, hour, (precision of the hours and minutes
WITH minute, second, fraction of a second portion of a TIMESTAMP WITH
TIME accurate to 6 decimal places, and TIME ZONE is dropped before
ZONE time zone offset in hours and mi- 1600-02-28 23:59:59 and after
nutes) 7911-01-01 00:00:00). Zone offset
from -14:59 to +14:59.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 101


SQL data types

Sending dates and times to the database


The date and time of day can be sent to the database in one of the following ways:

● using any interface, as a string

● using ODBC or OLE DB, as a binary value (using an ODBC TIMESTAMP_STRUCT structure for
example)

● using embedded SQL, as a SQLDATETIME structure

The date and time of day with a time zone offset can be sent to the database as a string only.

Date formats
When a date is sent to the database as a string (for the DATE data type) or as part of a string (for the
TIMESTAMP or TIMESTAMP WITH TIME ZONE data types), the string can be specified in a number
of different ways including that described by ISO 8601, an international standard on the representation of
dates and times.

A date can be specified in one of the following ISO 8601 formats.

● Calendar date The calendar date format is YYYY-MM-DD where YYYY is the year in the
Gregorian calendar, MM is the month of the year between 01 (January) and 12 (December), and DD is
the day of the month between 01 and 31. For example, '2010-04-01' represents the first day of April in
2010. ISO 8601 does not require the separator character. Therefore, '20100401' also represents the
first day of April in 2010.

ISO calendar date Format Example

Basic YYYYMMDD 20100401

Extended YYYY-MM-DD 2010-04-01

● Week date Another ISO date format is the week date. The format is YYYY-Www-D where
YYYY is the year in the Gregorian calendar, W is the letter W, ww is the week of the year between
01 (the first week) and 52 or 53 (the last week), and D is the day in the week between 1 (Monday) and
7 (Sunday). For example, '2010-W13-4' represents the fourth day of the thirteenth week of 2010 (April
1 2010). ISO 8601 does not require the separator character. Therefore, '2010W134' also represents the
fourth day of the thirteenth week of 2010. For reduced accuracy, one digit can be omitted from the
representation ('2010W13' represents March 29 2010).

ISO week date Format Example

Basic YYYYWwwD 2010W134

Extended YYYY-Www-D 2010-W13-4

● Ordinal date The last ISO date format is the ordinal date. The format is YYYY-DDD where
YYYY is the year in the Gregorian calendar and DDD is the ordinal number of a calendar day within

102 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Date and time data types

the calendar year. For example, '2010-091' represents the first day of April in 2010. ISO 8601 does not
require the separator character. For example, '2010091' also represents April 1 2010. The maximum
ordinal date is 366 for those years with leap years. For example, '2008366' represents the last day of
the year in 2008 (December 31 2008).

ISO ordinal date Format Example

Basic YYYYDDD 2010091

Extended YYYY-DDD 2010-091

Other date formats are supported. SQL Anywhere is very flexible in its interpretation of strings containing
dates. Whenever there is any ambiguity, the interpretation of the date value is guided by the date_order
and nearest_century database option settings. For example, depending on the date_order setting,
'02/05/2002' can be interpreted by the database server as the 2nd of May (DMY), or the 5th of February
(MDY), or an illegal value (YMD).

The nearest_century setting determines whether a two-digit year value is interpreted as a year in the
twentieth or twenty-first century. For example, in the string '02/05/10', the date_order setting would
determine whether 02 or 10 is interpreted as the year and the nearest_century setting would determine
whether 02 represented 1902 or 2002, or whether 10 represented 1910 or 2010. The value of the
nearest_century option affects the interpretation of 2-digit years: 2000 is added to values less than
nearest_century and 1900 is added to all other values. The default value of this option is 50. So, by
default, the year 50 is interpreted as 1950 and the year 49 is interpreted as 2049.

The following table shows how the first day of April in 2010 could be specified using the indicated
date_order setting and a nearest_century setting of 50.

date_order Format Example

YMD YYYY/MM/DD 2010/04/01

YMD YY/MM/DD 10/04/01

MDY MM/DD/YYYY 04/01/2010

MDY MM/DD/YY 04/01/10

DMY DD/MM/YYYY 01/04/2010

DMY DD/MM/YY 01/04/10

Since ISO 8601 formats are not ambiguous and are not affected by the user's setting of date_order and
nearest_century, their use is recommended.

Dates can also be specified using month names. Examples are '2010 April 01', 'April 1, 2010', and '1 April
2010'. When the year is ambiguously specified, the date_order option is used to factor the year and day of
month parts. Therefore, '01 April 10' is interpreted as April 10 2001 when the date_order is 'YMD' or as
April 1 2010 when the date_order is 'DMY'.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 103


SQL data types

The year in a date can range from 0001 to 9999. The minimum date in SQL Anywhere is 0001-01-01.

If a string contains only a partial date specification, default values are used to fill out the date. The
following defaults are used:

● year The current year is used when no year is specified (for example, 'April 1').

● month The current month is used when no year and month are specified (for example, '23:59:59')
or 01 if a year is specified (for example, '2010').

● day The current day is used when no year and month are specified (for example, '23:59:59') or 01 if
a month is specified (for example, 'April').

In the following example, the date value is constructed from the current date.
SELECT CAST('23:59:59' AS TIMESTAMP)

Time formats
The time of day can be specified in the ISO 8601 format, using the 24-hour timekeeping system. It is
hh:mm:ss, where hh is the number of complete hours that have passed since midnight, mm is the number
of complete minutes since the start of the hour, and ss is the number of complete seconds since the start of
the minute. For example, '23:59:59' represents the time one second before midnight.

The ISO 8601 standard allows for the omission of seconds and minutes. For example, '23:59' represents
the time sixty seconds before midnight.

The ISO 8601 standard also allows you to include a decimal fraction to the seconds unit. Fractional
seconds are specified using a comma (,) or a period (.). The fraction is stored to a maximum of six
decimal places. For example, '23:59:59,500000' and '23:59:59.500000' both represent the time one-half
second before midnight. SQL Anywhere does not support fractional minutes or hours.

ISO 8601 does not require the colon separator character when the time of day is included with a date
specification. For example, '235959' represents the time one second before midnight.

The maximum time of day is '24:00:00'. It represents midnight. When combined with a date, it represents
midnight, or 00:00:00 of the next day. For example, '2010-04-01 24:00:00' is equivalent to '2010-04-02
00:00:00'.

ISO time Format Example

Basic (with date) hhmmss.ssssss 20100401 235959.500000

Basic (with date) hhmmss,ssssss 20100401 235959,500000

Extended hh:mm:ss.ssssss 23:59:59.500000

Extended hh:mm:ss,ssssss 23:59:59,500000

The non-ISO AM and PM designators are also supported. For example, '11:59:59 PM' is equivalent to
'23:59:59'.

104 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Date and time data types

AM/PM Format Example

AM hh:mm:ss.ssssss AM 11:59:59.500000 AM

AM hh:mm:ss,ssssss AM 11:59:59,500000 AM

PM hh:mm:ss.ssssss PM 11:59:59.500000 PM

PM hh:mm:ss,ssssss PM 11:59:59,500000 PM

Date with time formats


ISO 8601 permits the date and time of day to be combined using a space character or the letter T. For
example, '2010-04-01 23:59:59' and '2010-04-01T23:59:59' both represent the time one second before
midnight on the first day of April in 2010. The hyphen and colon separator characters can be omitted. For
example, '20100401T235959' also represents the same date and time.

SQL Anywhere supports the mixing of basic and extended date and time formats. For example,
'20100401T23:59:59' combines both the basic and extended formats.

Time zone formats


ISO 8601 also permits the addition of a time zone offset to a date and time of day string. The format is
one of:

● Z (Zulu) The date and time of day are in Coordinated Universal Time (UTC). For example,
'2010-04-01 23:00:00Z' represents 11:00 PM Coordinated Universal Time on the first day of April in
2010.

● +hh:mm The specified date and time of day are the indicated number of hours and minutes ahead
of UTC. For example, '2010-04-01 23:00:00+04:00' represents 11:00 PM on the first day of April in
2010 in a time zone 4 hours east of UTC.

● -hh:mm The specified date and time of day are the indicated number of hours and minutes behind
UTC. For example, '2010-04-01 23:00:00-05:00' represents 11:00 PM on the first day of April in 2010
in a time zone 5 hours west of UTC.

If the minutes are 0, they do not need to be specified in the time zone offset. Also, a space can precede the
time zone offset. For example, '2010-04-01 23:00:00 -03:30' represents 11:00 PM on the first day of April
in 2010 in a time zone three and a half hours west of UTC.

ISO time zone Format Example

Basic Z 20100401 235959Z

Basic +hhmm 20100401 235959+0400

Basic +hh 20100401 235959+04

Basic -hhmm 20100401 235959-0500

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 105


SQL data types

ISO time zone Format Example

Basic -hh 20100401 235959-05

Basic using T, fraction 20100401T235959.50-0330

Extended Z 2010-04-01 23:59:59Z

Extended +hh:mm 2010-04-01 23:59:59+04:00

Extended -hh:mm 2010-04-01 23:59:59-05:00

Extended using T, fraction 2010-04-01T23:59:59.50-03:30

SQL Anywhere supports the mixing of basic and extended date, time, and time zone formats. For
example, '20100401T23:59:59-05' combines both basic and extended formats.

See also
● “Comparisons of dates and times” on page 125
● “DATE data type” on page 107
● “date_format option” [SQL Anywhere Server - Database Administration]
● “nearest_century option” [SQL Anywhere Server - Database Administration]
● “TIME data type” on page 112
● “TIMESTAMP data type” on page 113
● “TIMESTAMP WITH TIME ZONE data type” on page 115

Retrieval of dates and times from the database


Dates and times can be retrieved from the database in one of the following ways:

● Using any interface, as a string

● Using ODBC or OLE DB, as a binary value (using an ODBC TIMESTAMP_STRUCT structure for
example)

● Using embedded SQL, as a SQLDATETIME structure

Date and time of day with a time zone offset can be retrieved from the database as a string only.

When a date or time, with or without a time zone offset, is retrieved as a string, it is retrieved in the
format specified by the database options date_format, time_format, timestamp_format, and
timestamp_with_time_zone_format.

The following arithmetic operators are allowed on dates:

● 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.

106 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Date and time data types

● date - date Compute the number of days between two dates or timestamps.

● date + time Create a timestamp combining the given date and time.

Leap years
SQL 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.

SQL Anywhere handles all leap years correctly. For example, the following SQL statement results in a
return value of "Tuesday":
SELECT DAYNAME('2000-02-29');

SQL Anywhere accepts February 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 SQL Anywhere:


SELECT DAYNAME('2001-02-29');

This statement results in an error (cannot convert '2001-02-29' to a date) because February 29th does not
exist in the year 2001.

See also
● “SET OPTION statement” on page 886
● “Date and time functions” on page 136

DATE data type


The DATE data type is used to store calendar dates, such as a year, month, and day.

Syntax
DATE

Remarks
The format in which DATE values are retrieved as strings by applications is controlled by the date_format
option setting. For example, a DATE value representing the 19th of July, 2010 can be returned to an
application as 2010/07/19, or as Jul 19, 2010 depending on the date_format option setting.

A DATE value requires 4 bytes of storage.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 107


SQL data types

See also
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “Date and time functions” on page 136
● “Date formats” on page 102
● “DATE function [Date and time]” on page 187
● “date_format option” [SQL Anywhere Server - Database Administration]
● “date_order option” [SQL Anywhere Server - Database Administration]
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “ISDATE function [Data type conversion]” on page 251
● “nearest_century option” [SQL Anywhere Server - Database Administration]
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP data type” on page 113
● “TIMESTAMP special value” on page 69
● “TIMESTAMP WITH TIME ZONE data type” on page 115
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Compatible with SQL/2008.

● Transact-SQL Supported by Adaptive Server Enterprise.

DATETIME data type


DATETIME is a domain, implemented as TIMESTAMP, used to store date and time of day information.
DATETIME is a Transact-SQL type.

Syntax
DATETIME

Remarks
The format in which DATETIME values are retrieved as strings by applications is controlled by the
timestamp_format option setting. For example, the DATETIME value 2010/04/01T23:59:59.999999 can
be returned to an application as 2010/04/01 23:59:59, or as April 1, 2010
23:59:59.999999 depending on the timestamp_format option setting.

A DATETIME value requires 8 bytes of storage.

Although the range of possible dates for the DATETIME data type is the same as the DATE type
(covering years 0001 to 9999), the useful range of the DATETIME date type is from 1600-02-28 23:59:59
to 7911-01-01 00:00:00. Before and after this range, the hours and minutes portion of the DATETIME
value is not retained.

108 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Date and time data types

Note
When the precision of the DATETIME value is reduced, built-in functions that pertain to minutes or
seconds will produce meaningless results.

When a DATETIME value is converted to a DATETIMEOFFSET, the connection's


time_zone_adjustment setting is used for the time zone offset in the result. In other words, the value is
considered to be local to the connection. When a DATETIMEOFFSET value is converted to DATETIME,
the offset is discarded.

See also
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “Date and time functions” on page 136
● “Sending dates and times to the database” on page 102
● “DATE function [Date and time]” on page 187
● “date_format option” [SQL Anywhere Server - Database Administration]
● “date_order option” [SQL Anywhere Server - Database Administration]
● “DATE data type” on page 107
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP data type” on page 113
● “TIMESTAMP WITH TIME ZONE data type” on page 115
● “timestamp_format option” [SQL Anywhere Server - Database Administration]
● “nearest_century option” [SQL Anywhere Server - Database Administration]
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL DATETIME, rather than TIMESTAMP, is used by Adaptive Server Enterprise. The
DATETIME type in Adaptive Server Enterprise supports dates between January 1, 1753 and
December 31, 9999 and supports less precision with the time portion of the value. In SQL Anywhere,
DATETIME is implemented as a TIMESTAMP without these restrictions. You should be aware of
these differences when migrating data between SQL Anywhere and Adaptive Server Enterprise.

DATETIMEOFFSET data type


The DATETIMEOFFSET data type is an alias for TIMESTAMP WITH TIME ZONE, used to store date,
time of day, and time zone information.

Syntax
DATETIMEOFFSET

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 109


SQL data types

Remarks
The DATETIMEOFFSET value contains the year, month, day, hour, minute, second, fraction of a second,
and number of minutes before or after Coordinated Universal Time (UTC). The fraction is stored to 6
decimal places.

The format in which DATETIMEOFFSET values are retrieved as strings by applications is controlled by
the timestamp_with_time_zone_format option setting. For example, the DATETIMEOFFSET value
2010/04/01T23:59:59.999999-6:00 can be returned to an application as 2010/04/01 23:59:59
-06:00, or as April 1, 2010 23:59:59.999999 -06:00 depending on the
timestamp_with_time_zone_format option setting.

A DATETIMEOFFSET value requires 10 bytes of storage.

Although the range of possible dates for the DATETIMEOFFSET data type is the same as the DATE type
(covering years 0001 to 9999), the useful range of DATETIMEOFFSET date types is from 1600-02-28
23:59:59 to 7911-01-01 00:00:00. Before and after this range, the hours and minutes portion of the
DATETIMEOFFSET value is not retained.

Do not use DATETIMEOFFSET for computed columns or in materialized views because the value of the
governing time_zone_adjustment option varies between connections based on their location and the time
of year.

Two DATETIMEOFFSET values are considered identical when they represent the same instant in UTC,
regardless of the TIME ZONE offset applied. For example, the following statement returns Yes because
the results are considered identical:
IF CAST('2009-07-15 08:00:00 -08:00' AS DATETIMEOFFSET) =
CAST('2009-07-15 11:00:00 -05:00' AS DATETIMEOFFSET) THEN
SELECT 'Yes'
ELSE
SELECT 'No'
END IF;

If you omit the time zone offset from a DATETIMEOFFSET value, it defaults to the current UTC offset
of the client regardless of whether the timestamp represents a date and time in standard time or daylight
time. For example, if the client is located in the Eastern Standard time zone and executes the following
statement while daylight time is in effect, then a timestamp with a time zone appropriate for the Atlantic
Standard time zone (-4 hours from UTC) will be returned.
SELECT CAST('2009/01/30 12:34:55' AS DATETIMEOFFSET);

The comparison of DATETIMEOFFSET values with timestamps without time zones is not recommended
because the default time zone offset of the client varies with the geographic location of the client and with
the time of the year.

Execute the following statement to determine the current time zone offset in minutes for a client:
SELECT CONNECTION_PROPERTY( 'TimeZoneAdjustment' );

Note
The TimeZoneAdjustment connection property is not supported in UltraLite databases.

110 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Date and time data types

See also
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “Date and time functions” on page 136
● “Sending dates and times to the database” on page 102
● “DATE data type” on page 107
● “DATETIME data type” on page 108
● “DATE function [Date and time]” on page 187
● “DATETIME function [Date and time]” on page 193
● “Expressions” on page 12
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP special value” on page 69
● “TIMESTAMP data type” on page 113
● “TIMESTAMP WITH TIME ZONE data type” on page 115
● “timestamp_with_time_zone_format option” [SQL Anywhere Server - Database Administration]
● “nearest_century option” [SQL Anywhere Server - Database Administration]
● “date_order option” [SQL Anywhere Server - Database Administration]
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 The specific use of DATETIMEOFFSET is a vendor extension. To be compatible with
SQL/2008, use TIMESTAMP WITH TIME ZONE. The TIMESTAMP WITH TIME ZONE type is
optional SQL language feature F411 of the SQL/2008 standard.

SMALLDATETIME data type


SMALLDATETIME is a domain, implemented as TIMESTAMP, used to store date and time of day
information. SMALLDATETIME is a Transact-SQL type.

Syntax
SMALLDATETIME

Remarks
For information about the specification of dates and time of day, see “Sending dates and times to the
database” on page 102.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 111


SQL data types

See also
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “Date and time functions” on page 136
● “DATE data type” on page 107
● “DATETIME data type” on page 108
● “DATE function [Date and time]” on page 187
● “DATETIME function [Date and time]” on page 193
● “Expressions” on page 12
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “TIME data type” on page 112
● “TIMESTAMP special value” on page 69
● “TIMESTAMP data type” on page 113
● “TIMESTAMP WITH TIME ZONE data type” on page 115
● “timestamp_format option” [SQL Anywhere Server - Database Administration]
● “timestamp_with_time_zone_format option” [SQL Anywhere Server - Database Administration]
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL SMALLDATETIME is supported by Adaptive Server Enterprise. In Adaptive


Server Enterprise, the SMALLDATETIME type supports dates between January 1, 1900 and June 6,
2079 and supports less precision with the time portion of the value. In SQL Anywhere,
SMALLDATETIME is implemented as a TIMESTAMP without these restrictions. You should be
aware of these differences when migrating data between SQL Anywhere and Adaptive Server
Enterprise.

TIME data type


The TIME data type is used to store the time of day, containing the hour, minute, second, and fraction of a
second.

Syntax
TIME

Remarks
The format in which TIME values are retrieved as strings by applications is controlled by the time_format
option setting. For example, the TIME value 23:59:59.999999 can be returned to an application as
23:59:59, 23:59:59.999, or as 23:59:59.999999 depending on the time_format option setting.

A TIME value requires 8 bytes of storage.

112 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Date and time data types

When using ODBC, a TIME value sent or retrieved as a binary value (using an ODBC TIME_STRUCT
structure) is restricted to an accuracy of hours, minutes, and seconds. Fractional seconds are not part of
the structure. For this reason, TIME values should be sent or retrieved as strings if increased accuracy is
desired.

See also
● “Time formats” on page 104
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “Date and time functions” on page 136
● “DATE data type” on page 107
● “DATETIME data type” on page 108
● “DATE function [Date and time]” on page 187
● “DATETIME function [Date and time]” on page 193
● “Expressions” on page 12
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIMESTAMP special value” on page 69
● “TIMESTAMP data type” on page 113
● “TIMESTAMP WITH TIME ZONE data type” on page 115
● “timestamp_format option” [SQL Anywhere Server - Database Administration]
● “timestamp_with_time_zone_format option” [SQL Anywhere Server - Database Administration]
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Compatible with SQL/2008.

● Transact-SQL The TIME data type is supported by Adaptive Server Enterprise. However,
Adaptive Server Enterprise supports millisecond resolution (three digits) rather than microsecond
resolution (six digits). You should be aware of these differences when migrating data between SQL
Anywhere and Adaptive Server Enterprise. To migrate TIME values, use the Adaptive Server
Enterprise BIGTIME data type.

TIMESTAMP data type


The TIMESTAMP data type is used to store a point in time containing the year, month, day, hour, minute,
second, and fraction of a second.

Syntax
TIMESTAMP

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 113


SQL data types

Remarks
The TIMESTAMP value contains the year, month, day, hour, minute, second, and fraction of a second.
The fraction is stored to 6 decimal places.

The format in which TIMESTAMP values are retrieved as strings by applications is controlled by the
timestamp_format option setting. For example, the TIMESTAMP value 2010/04/01T23:59:59.999999
can be returned to an application as 2010/04/01 23:59:59, or as April 1, 2010
23:59:59.999999 depending on the timestamp_format option setting.

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. Before and after this range, the hours and minutes portion of the TIMESTAMP
value is not retained.

Note
When the precision of the TIMESTAMP value is reduced, built-in functions that pertain to minutes or
seconds produce meaningless results.

When a TIMESTAMP value is converted to TIMESTAMP WITH TIME ZONE, the connection's
time_zone_adjustment setting is used for the time zone offset in the result. In other words, the value is
considered to be local to the connection. When a TIMESTAMP WITH TIME ZONE value is converted to
TIMESTAMP, the offset is discarded.

See also
● “Sending dates and times to the database” on page 102
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “Date and time functions” on page 136
● “DATE data type” on page 107
● “DATETIME data type” on page 108
● “DATE function [Date and time]” on page 187
● “DATETIME function [Date and time]” on page 193
● “date_order option” [SQL Anywhere Server - Database Administration]
● “Expressions” on page 12
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “nearest_century option” [SQL Anywhere Server - Database Administration]
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP special value” on page 69
● “TIMESTAMP WITH TIME ZONE data type” on page 115
● “timestamp_format option” [SQL Anywhere Server - Database Administration]
● “timestamp_with_time_zone_format option” [SQL Anywhere Server - Database Administration]
● “UTC TIMESTAMP special value” on page 71

114 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Date and time data types

Standards and compatibility


● SQL/2008 Compatible with SQL/2008.

● Transact-SQL Adaptive Server Enterprise uses the DATETIME type for TIMESTAMP values.

TIMESTAMP WITH TIME ZONE data type


Stores a point in time with a time zone offset.

Syntax
TIMESTAMP WITH TIME ZONE

Remarks
The TIMESTAMP WITH TIME ZONE value contains the year, month, day, hour, minute, second,
fraction of a second, and number of minutes before or after Coordinated Universal Time (UTC). The
fraction is stored to 6 decimal places.

The format in which TIMESTAMP WITH TIME ZONE values are retrieved as strings by applications is
controlled by the timestamp_with_time_zone_format option setting. For example, the TIMESTAMP
WITH TIME ZONE value 2010/04/01T23:59:59.999999-6:00 can be returned to an application as
2010/04/01 23:59:59 -06:00, or as April 1, 2010 23:59:59.999999 -06:00
depending on the timestamp_with_time_zone_format option setting.

A TIMESTAMP WITH TIME ZONE value requires 10 bytes of storage.

Although the range of possible dates for the TIMESTAMP WITH TIME ZONE data type is the same as
the DATE type (covering years 0001 to 9999), the useful range of TIMESTAMP WITH TIME ZONE
date types is from 1600-02-28 23:59:59 to 7911-01-01 00:00:00. Before and after this range, the hours
and minutes portion of the TIMESTAMP WITH TIME ZONE value is not retained.

Do not use TIMESTAMP WITH TIME ZONE for computed columns or in materialized views because
the value of the governing time_zone_adjustment option varies between connections based on their
location and the time of year.

Two TIMESTAMP WITH TIME ZONE values are considered identical when they represent the same
instant in UTC, regardless of the TIME ZONE offset applied. For example, the following statement
returns Yes because the results are considered identical:
IF CAST('2009-07-15 08:00:00 -08:00' AS TIMESTAMP WITH TIME ZONE) =
CAST('2009-07-15 11:00:00 -05:00' AS TIMESTAMP WITH TIME ZONE) THEN
SELECT 'Yes'
ELSE
SELECT 'No'
END IF;

If you omit the time zone offset from a TIMESTAMP WITH TIME ZONE value, it defaults to the current
UTC offset of the client regardless of whether the timestamp represents a date and time in standard time
or daylight time. For example, if the client is located in the Eastern Standard time zone and executes the

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 115


SQL data types

following statement while daylight time is in effect, then a timestamp with a time zone appropriate for the
Atlantic Standard time zone (-4 hours from UTC) is returned.
SELECT CAST('2009/01/30 12:34:55' AS TIMESTAMP WITH TIME ZONE);

● Comparing TIMESTAMP WITH TIME ZONE with other data types The comparison of
TIMESTAMP WITH TIME ZONE values with timestamps without time zones is not recommended
because the default time zone offset of the client varies with the geographic location of the client and
with the time of the year.

Execute the following statement to determine the current time zone offset in minutes for a client:
SELECT CONNECTION_PROPERTY( 'TimeZoneAdjustment' );

Note
The TimeZoneAdjustment connection property is not supported in UltraLite databases.

● Converting to or from TIMESTAMP WITH TIME ZONE When a TIMESTAMP value is


converted to TIMESTAMP WITH TIME ZONE, the connection's time_zone_adjustment setting is
used for the time zone offset in the result. In other words, the value is considered to be local to the
connection. When a TIMESTAMP WITH TIME ZONE value is converted to TIMESTAMP, the
offset is discarded. Conversions to or from types other than strings, date, or date-time types is not
supported.

See also
● “Comparisons of dates and times” on page 125
● “Sending dates and times to the database” on page 102
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “Date and time functions” on page 136
● “DATE data type” on page 107
● “DATETIME data type” on page 108
● “DATE function [Date and time]” on page 187
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “date_order option” [SQL Anywhere Server - Database Administration]
● “Expressions” on page 12
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “nearest_century option” [SQL Anywhere Server - Database Administration]
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP special value” on page 69
● “TIMESTAMP data type” on page 113
● “timestamp_format option” [SQL Anywhere Server - Database Administration]
● “timestamp_with_time_zone_format option” [SQL Anywhere Server - Database Administration]
● “UTC TIMESTAMP special value” on page 71

116 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Binary data types

Standards and compatibility


● SQL/2008 Support for TIMESTAMP WITH TIME ZONE is optional SQL language feature F411
of the SQL/2008 standard.

Binary data types


Binary data types are used for storing binary data, including images and other types of information that
are not interpreted by the database.

BINARY data type


The BINARY data type is used to store binary data of a specified maximum length (in bytes).

Syntax
BINARY [ ( max-length ) ]

Parameters
● max-length The maximum length of the value, in bytes. The length must be in the range 1 to
32767. If the length is not specified, then it is 1.

Remarks
During comparisons, BINARY values are compared exactly byte for byte. This differs from the CHAR
data type, where values are compared using the collation sequence of the database. If one binary string is
a prefix of the other, the shorter string is considered to be less than the longer string.

Unlike CHAR values, BINARY values are not transformed during character set conversion.

BINARY is semantically equivalent to VARBINARY. It is a variable-length type. In other database


management systems, BINARY is a fixed-length type.

See also
● “VARBINARY data type” on page 119
● “LONG BINARY data type” on page 118
● “String functions” on page 142
● “Bitwise operators” on page 11

Standards and compatibility


● SQL/2008 The BINARY data type is SQL language feature T021 of the SQL/2008 standard.

IMAGE data type


The IMAGE data type is used to store binary data of arbitrary length.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 117


SQL data types

Syntax
IMAGE

Remarks
IMAGE is a domain, implemented as LONG BINARY.

See also
● “LONG BINARY data type” on page 118
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

LONG BINARY data type


The LONG BINARY data type is used to store binary data of arbitrary length.

Syntax
LONG BINARY

Remarks
The maximum size is 2 GB minus 1 byte (231 - 1).

See also
● “BINARY data type” on page 117
● “VARBINARY data type” on page 119
● “String functions” on page 142

Standards and compatibility


● SQL/2008 The LONG BINARY data type comprises SQL language features T021, "BINARY and
VARBINARY data types", and T041, "Basic LOB data type support" in the SQL/2008 standard.

UNIQUEIDENTIFIER data type


The UNIQUEIDENTIFIER data type is used to store UUID (also known as GUID) values.

Syntax
UNIQUEIDENTIFIER

Remarks
The UNIQUEIDENTIFIER data type is typically used for a primary key or other unique column to hold
UUID (Universally Unique Identifier) values that uniquely identify rows. The NEWID function generates

118 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Binary data types

UUID values in such a way that a value produced on one computer will not match a UUID produced on
another computer. UNIQUEIDENTIFIER values generated using NEWID can therefore be used as keys
in a synchronization environment.

For example:
CREATE TABLE T1 (
pk UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
c1 INT );

UUID values are also referred to as GUIDs (Globally Unique Identifier). UUID values contain hyphens so
they are compatible with other RDBMSs. You can change this by setting the uuid_has_hyphens option to
Off.

SQL Anywhere automatically converts UNIQUEIDENTIFIER values between string and binary values as
needed.

UNIQUEIDENTIFIER values are stored as BINARY(16), but are described to client applications as
BINARY(36). This description ensures that if the client fetches the value as a string, it has allocated
enough space for the result. For ODBC client applications, uniqueidentifier values appear as a
SQL_GUID type.

See also
● “The NEWID default” [SQL Anywhere Server - SQL Usage]
● “NEWID function [Miscellaneous]” on page 279
● “UUIDTOSTR function [String]” on page 374
● “STRTOUUID function [String]” on page 351
● “uuid_has_hyphens option” [SQL Anywhere Server - Database Administration]
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

VARBINARY data type


The VARBINARY data type is used to store binary data of a specified maximum length (in bytes).

Syntax
VARBINARY [ ( max-length ) ]

Parameters
● max-length The maximum length of the value, in bytes. The length must be in the range 1 to
32767. If the length is not specified, then it is 1.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 119


SQL data types

Remarks
During comparisons, VARBINARY values are compared exactly byte for byte. This differs from the
CHAR data type, where values are compared using the collation sequence of the database. If one binary
string is a prefix of the other, the shorter string is considered to be less than the longer string.

Unlike CHAR values, VARBINARY values are not transformed during character set conversion.

VARBINARY can also be specified as BINARY VARYING. Regardless of which syntax is used, the
data type is described as VARBINARY.

See also
● “BINARY data type” on page 117
● “LONG BINARY data type” on page 118
● “String functions” on page 142

Standards and compatibility


● SQL/2008 The VARBINARY data type comprises SQL language feature T021, "BINARY and
VARBINARY data types" in the SQL/2008 standard.

Domains
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 predefined in SQL Anywhere, but you can add more of your own.

Domains, also 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.

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.

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 can 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:

120 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Domains

CREATE TABLE twocol (


id INT,
street street_address
);

Domains can be dropped by their owner or by a user with DBA authority, using the DROP DOMAIN
statement:
DROP DOMAIN street_address;

This statement can be executed 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, an error message appears.

See also
● “CREATE DOMAIN statement” on page 519

Constraints and defaults with domains


Many of the attributes associated with columns, such as allowing NULL values, having a DEFAULT
value, and so on, can be built into a domain. 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 SQL Anywhere sample database are integer columns
holding ID numbers. The following statement creates a data type that can be useful for such columns:
CREATE DOMAIN id INT
NOT NULL
DEFAULT AUTOINCREMENT
CHECK( @col > 0 );

By default, a column created using the id data type does not allow 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 a data type can be overridden by explicitly providing attributes for the column. A column
created using the id data type with NULL values explicitly allowed does allow NULLs, regardless of the
setting in the id data type.

Compatibility
● Named constraints and defaults In SQL 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 SQL Anywhere, you can use the sp_addtype system procedure to add a
domain, or you can use the CREATE DOMAIN statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 121


SQL data types

Data type conversions


Type conversions can happen automatically, or they can be explicitly requested using the CAST or
CONVERT function. The following functions can also be used to force type conversions :

● DATE function Converts the expression into a DATE, and removes any hours, minutes or seconds.
Conversion errors can be reported.

● DATETIME function Converts the expression into a TIMESTAMP, and removes any time zone.
Conversion errors can be reported.

● STRING function This function is equivalent to CAST(value AS LONG VARCHAR).

● VALUE+0.0 Equivalent to CAST( value AS DECIMAL ).

The following list is a high-level view of automatic data type conversions:

● 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. For example, the
automatic data type conversion fails in the example below.

'12/31/90' + 5
'a' > 0

See also
● “Data type conversion functions” on page 135
● “DATE function [Date and time]” on page 187
● “DATETIME function [Date and time]” on page 193
● “STRING function [String]” on page 350
● “CAST function [Data type conversion]” on page 159

Comparisons between data types


When a comparison (such as =) is performed between arguments with different data types, one or more
arguments must be converted so that the comparison operation is done using one data type.

Some rules may lead to conversions that fail, or lead to unexpected results from the comparison. In these
cases, you should explicitly convert one of the arguments using CAST or CONVERT.

122 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Data type conversions

You can override these conversion rules by explicitly casting arguments to another type. For example, if
you want to compare a DATE and a CHAR as a CHAR, then you need to explicitly cast the DATE to a
CHAR.

See also
● “CAST function [Data type conversion]” on page 159

Lossy conversion and substitution characters


When a character cannot be represented in the character set into which it is being converted, a substitution
character is used instead. Conversions of this type are considered lossy; the original character is lost if it
cannot be represented in the destination character set.

Also, not only may different character sets have a different substitution character, but the substitution
character for one character set can be a non-substitution character in another character set. This is
important to understand when multiple conversions are performed on a character because the final
character may not appear as the expected substitution character of the destination character set.

For example, suppose that the client character set is Windows-1252, and the database character set is
ISO_8859-1:1987, the U.S. default for some versions of Unix. Then, suppose a non-Unicode client
application (for example, embedded SQL) attempts to insert the euro symbol into a CHAR, VARCHAR,
or LONG VARCHAR column. Since the character does not exist in the CHAR character set, the
substitution character for ISO_8859-1:1987, 0x1A, is inserted.

Now, if this same ISO_8859-1:1987 substitution character is then fetched as Unicode (for example, by
doing a SELECT * FROM t into a SQL_C_WCHAR bound column in ODBC), this character becomes
the Unicode code point U+001A. (In Unicode the code point U+001A is the record separator control
character.) However, the substitution character for Unicode is the code point U+FFFD. This example
illustrates that even if your data contains substitution characters, those characters, due to multiple
conversions, may not be converted to the substitution character of the destination character set.

Therefore, it is important to understand and test how substitution characters are used when converting
between multiple character sets.

The on_charset_conversion_failure option can help determine the behavior during conversion when a
character cannot be represented in the destination character set.

See also
● “Data type conversions” on page 122
● “Comparisons between CHAR and NCHAR” on page 123
● “on_charset_conversion_failure option” [SQL Anywhere Server - Database Administration]

Comparisons between CHAR and NCHAR


When a comparison is performed between a value of CHAR type (CHAR, VARCHAR, LONG
VARCHAR) and a value of NCHAR type (NCHAR, NVARCHAR, LONG NVARCHAR), SQL

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 123


SQL data types

Anywhere uses inference rules to determine the type in which the comparison should be performed.
Generally, if one value is based on a column reference and the other is not, the comparison is performed
in the type of the value containing the column reference.

The inference rules revolve around whether a value is based on a column reference. In the case where one
value is a variable, a host variable, a literal constant, or a complex expression not based on a column
reference and the other value is based on a column reference, then the constant-based value is implicitly
cast to the type of the column-based value.

Following are the inference rules, in the order in which they are applied:

● If the NCHAR value is based on a column reference, the CHAR value is implicitly cast to NCHAR,
and the comparison is done as NCHAR. This includes the case where both the NCHAR and CHAR
value are based on column references.

● Else if the NCHAR value is not based on a column reference, and the CHAR value is based on a
column reference, the NCHAR value is implicitly cast to CHAR, and the comparison is done as CHAR.
It is important to consider the setting for the on_charset_conversion_failure option if you anticipate
NCHAR to CHAR conversions since this option controls behavior if an NCHAR character cannot be
represented in the CHAR character set.

● Else if neither value is based on a column reference, then the CHAR value is implicitly cast to NCHAR
and the comparison is done as NCHAR.

Examples
The condition Employees.GivenName = N'Susan' compares a CHAR column
(Employees.GivenName) to the literal N'Susan'. The value N'Susan' is cast to CHAR, and the comparison
is performed as if it had been written as:
Employees.GivenName = CAST( N'Susan' AS CHAR )

Alternatively, the condition Employees.GivenName = T.nchar_column would find that the


value T.nchar_column can not be cast to CHAR. The comparison would be performed as if it were written
as follows, and an index on Employees.GivenName can not be used:
CAST( Employees.GivenName AS NCHAR ) = T.nchar_column;

See also
● “NCHAR to CHAR conversions” on page 128
● “NCHAR to CHAR conversions” on page 128
● “Lossy conversion and substitution characters” on page 123
● “CAST function [Data type conversion]” on page 159
● “CONVERT function [Data type conversion]” on page 172
● “CAST function [Data type conversion]” on page 159
● “on_charset_conversion_failure option” [SQL Anywhere Server - Database Administration]

124 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Data type conversions

Comparisons between numeric data types

SQL Anywhere uses the following rules when comparing numeric data types. The rules are examined in
the order listed, and the first rule that applies is used:

1. If one argument is TINYINT and the other is INTEGER, convert both to INTEGER and compare.

2. If one argument is TINYINT and the other is SMALLINT, convert both to SMALLINT and compare.

3. If one argument is UNSIGNED SMALLINT and the other is INTEGER, convert both to INTEGER
and compare.

4. If the data types of the arguments have a common super type, convert to the common super type and
compare. The super types are the final data type in each of the following lists:

● BIT » TINYINT » UNSIGNED SMALLINT » UNSIGNED INTEGER » UNSIGNED BIGINT »


NUMERIC

● SMALLINT » INTEGER » BIGINT » NUMERIC

● REAL » DOUBLE

● CHAR » LONG VARCHAR

● BINARY » LONG BINARY

For example, if the two arguments are of types BIT and TINYINT, they are converted to NUMERIC.

Comparisons of dates and times

The table below summarizes the conversions that are implicit when comparing certain data types with
date, time, or date-time data types.

Data type Data type Conversion

CHAR DATE CHAR cast to TIMESTAMP; DATE cast to TIME-


STAMP

CHAR TIME CHAR cast to TIME

CHAR TIMESTAMP CHAR cast to TIMESTAMP

CHAR TIMESTAMP WITH CHAR cast to TIMESTAMP WITH TIME ZONE


TIME ZONE

DATE TIME illegal

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 125


SQL data types

Data type Data type Conversion

DATE TIMESTAMP DATE cast to TIMESTAMP

DATE TIMESTAMP WITH DATE cast to TIMESTAMP WITH TIME ZONE


TIME ZONE

DATE SMALLINT, INTEGER, SMALLINT, INTEGER, BIGINT, and NUMERIC value


BIGINT, and NUMERIC treated as a date string and cast to TIMESTAMP; DATE
cast to TIMESTAMP

DATE REAL, FLOAT, and REAL, FLOAT, and DOUBLE treated as a number of
DOUBLE days since 0000-02-29 and cast to TIMESTAMP; DATE
cast to TIMESTAMP

TIME TIMESTAMP TIMESTAMP cast to TIME

TIME TIMESTAMP WITH illegal


TIME ZONE

TIME- TIMESTAMP WITH TIMESTAMP cast to TIMESTAMP WITH TIME


STAMP TIME ZONE ZONE

TIME- SMALLINT, INTEGER, SMALLINT, INTEGER, BIGINT, and NUMERIC value


STAMP BIGINT, and NUMERIC treated as a date string and cast to TIMESTAMP

TIME- REAL, FLOAT, and REAL, FLOAT, and DOUBLE treated as a number of
STAMP DOUBLE days since 0000-02-29 and cast to TIMESTAMP

The following points expand on the information presented in the table above.

1. Only values of type TIME, TIMESTAMP, and CHAR can be compared to a value of type TIME.
Comparison with values of other data types results in a conversion error. When comparing a time
value and a value of another type, the comparison data type is TIME.

2. When comparing a TIMESTAMP, SMALLINT, INTEGER, BIGINT, NUMERIC, REAL, FLOAT,


or DOUBLE value to a DATE value, the comparison data type is always TIMESTAMP.

3. When comparing a TIMESTAMP WITH TIME ZONE value to a DATE value, the comparison data
type is TIMESTAMP WITH TIME ZONE.

4. When a time value is cast to a TIMESTAMP, the result is formed by combining the current date with
the time value.

5. Exact numeric values of type SMALLINT, INTEGER, BIGINT, and NUMERIC can be converted to
date values. The conversion is performed by treating the number as a string. For example, the integer
value 20100401 represents the first day of April in 2010.

6. The unsigned exact numeric types BIT, TINYINT, UNSIGNED SMALLINT, UNSIGNED
INTEGER, and UNSIGNED BIGINT cannot be converted to date values.

126 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Data type conversions

7. Approximate numeric values of type REAL, FLOAT, and DOUBLE can be converted to dates by
treating the number as the number of days since the fictional date 0000-02-29. For example, 307
represents 0001-01-01 and 734169 represents 2010-04-01.

See also
● “Date and time data types” on page 101

Transact-SQL string to date/time conversions


If a string containing only a time value (no date) is converted to a date/time data type, SQL Anywhere
uses the current date.

If the fraction portion of a time is less than 3 digits, SQL Anywhere interprets the value the same way
regardless of the whether it is preceded by a period or a colon: one digit means tenths, two digits mean
hundredths, and three digits mean thousandths.

Examples
SQL Anywhere converts the milliseconds value in the same manner regardless of the separator.

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

Other comparisons
1. If the data types are a mixture of CHAR (such as CHAR, VARCHAR, LONG VARCHAR, and so
on, but not NCHAR types), convert to LONG VARCHAR and compare.

2. If the data type of any argument is UNIQUEIDENTIFIER, convert to UNIQUEIDENTIFIER and


compare.

3. If the data type of any argument is a bit array (VARBIT or LONG VARBIT), convert to LONG
VARBIT and compare.

4. If one argument has CHARACTER data type and the other has BINARY data type, convert to
BINARY and compare.

5. If one argument is a CHAR type, and the other argument is an NCHAR type, use predefined
inference rules.

6. If no rule exists, convert to NUMERIC and compare.

For example, if the two arguments have REAL and CHAR data types, they are both converted to
NUMERIC.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 127


SQL data types

See also
● “Comparisons between CHAR and NCHAR” on page 123

NCHAR to CHAR conversions


NCHAR to CHAR conversions can occur as part of a comparison of CHAR and NCHAR data, or when
specifically requested. This type of conversion is lossy because depending on the CHAR character set,
there can be some NCHAR characters that cannot be represented in the CHAR type. When an NCHAR
character cannot be converted to CHAR, a substitution character from the CHAR character set is used
instead. For single-byte character sets, this is usually hex 1A.

Depending on the setting of the on_charset_conversion_failure option, when a character cannot be


converted, one of the following can happen:

● a substitute character is used, and no warning is issued

● a substitute character is used, and a warning is issued

● an error is returned

Therefore, it is important to consider this option when converting from NCHAR to CHAR.

See also
● “Comparisons between CHAR and NCHAR” on page 123
● “on_charset_conversion_failure option” [SQL Anywhere Server - Database Administration]

NULL constant conversions to NUMERIC and string types


When converting a NULL constant to a NUMERIC, or to a string type such as CHAR, VARCHAR,
LONG VARCHAR, BINARY, VARBINARY, and LONG BINARY the size is set to 0. For example:

SELECT CAST( NULL AS CHAR ) returns CHAR(0)

SELECT CAST( NULL AS NUMERIC ) returns NUMERIC(1,0)

Bit array conversions


Converting integers to bit arrays
When converting an integer to a bit array, the length of the bit array is the number of bits in the integer
type, and the bit array's value is the binary representation. The most significant bit of the integer becomes
the first bit of the array.

128 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Data type conversions

Examples
SELECT CAST( CAST( 1 AS BIT ) AS VARBIT ) returns a VARBIT(1) containing 1.

SELECT CAST( CAST( 8 AS TINYINT ) AS VARBIT ) returns a VARBIT(8) containing


00001000.

SELECT CAST( CAST( 194 AS INTEGER ) AS VARBIT ) returns a VARBIT(32) containing


00000000000000000000000011000010.

Converting binary to bit arrays


When converting a binary type of length n to a bit array, the length of the array is n * 8 bits. The first 8
bits of the bit array become the first byte of the binary value. The most significant bit of the binary value
becomes the first bit in the array. The next 8 bits of the bit array become the second byte of the binary
value, and so on.

Examples
SELECT CAST( 0x8181 AS VARBIT ) returns a VARBIT(16) containing 1000000110000001.

Converting characters to bit arrays


When converting a character data type of length n to a bit array, the length of the array is n bits. Each
character must be either '0' or '1' and the corresponding bit of the array is assigned the value 0 or 1.

Example
SELECT CAST( '001100' AS VARBIT ) returns a VARBIT(6) containing 001100.

Converting bit arrays to integers


When converting a bit array to an integer data type, the bit array's binary value is interpreted according to
the storage format of the integer type, using the most significant bit first.

Example
SELECT CAST( CAST( '11000010' AS VARBIT ) AS INTEGER ) returns 194 (110000102
= 0xC2 = 194).

Converting bit arrays to binary


When converting a bit array to a binary, the first 8 bits of the array become the first byte of the binary
value. The first bit of the array becomes the most significant bit of the binary value. The next 8 bits are
used as the second byte, and so on. If the length of the bit array is not a multiple of 8, then extra zeroes are
used to fill the least significant bits of the last byte of the binary value.

Examples
SELECT CAST( CAST( '1111' AS VARBIT ) AS BINARY ) returns 0xF0 (11112 becomes
111100002 = 0xF0).

SELECT CAST( CAST( '0011000000110001' AS VARBIT ) AS BINARY ) returns


0x3031 (00110000001100012 = 0x3031).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 129


SQL data types

Converting bit arrays to characters


When converting a bit array of length n bits to a character data type, the length of the result is n
characters. Each character in the result is either '0' or '1', corresponding to the bit in the array.

Example
SELECT CAST( CAST( '01110' AS VARBIT ) AS VARCHAR ) returns the character string
'01110'.

Numeric set conversions


When converting a DOUBLE type to a NUMERIC type, precision is maintained for the first 15
significant digits.

See also
● “CAST function [Data type conversion]” on page 159
● “CONVERT function [Data type conversion]” on page 172

Java and SQL data type conversions


Data type conversion between Java types and SQL types is required for both Java stored procedures and
JDBC applications. 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 conversions

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

130 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Data type conversions

Java type SQL type

short SMALLINT

int INTEGER

long BIGINT

float REAL

double DOUBLE

byte[ ] VARBINARY

byte[ ] IMAGE

java.sql.Date DATE

java.sql.Time TIME

java.sql.Timestamp TIMESTAMP

java.lang.Double DOUBLE

java.lang.Float REAL

java.lang.Integer INTEGER

java.lang.Long BIGINT

SQL to Java data type conversions

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

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 131


SQL data types

SQL type Java type

UNSIGNED BIGINT java.math.BigDecimal (precision=20, scale=0)

BIT boolean

TINYINT byte

SMALLINT short

UNSIGNED SMALLINT int

INTEGER int

UNSIGNED INTEGER long

BIGINT long

REAL float

FLOAT double

DOUBLE double

BINARY byte[ ]

VARBINARY byte[ ]

LONG BINARY byte[ ]

IMAGE byte[ ]

DATE java.sql.Date

TIME java.sql.Time

TIMESTAMP java.sql.Timestamp

Spatial data types


SQL Anywhere supports many spatial data types. The documentation for these data types are located with
the spatial SQL API documentation.

See also
● “Supported spatial data types and their hierarchy” [SQL Anywhere Server - Spatial Data Support]

132 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL functions
Functions are used to return information from the database. They can be called anywhere an expression is
allowed.

Unless otherwise specified in the documentation, NULL is returned for a function if any argument is
NULL.

If an argument is optional, DEFAULT can be provided as an argument.

Functions use the same syntax conventions used by SQL statements.

See also
● “Syntax conventions” on page 396

Function types
This section groups the available function by type.

See also
● “Functions for spatial data” [UltraLite - Database Management and Reference]

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.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 133


SQL functions

List of functions
The following aggregate functions are available:

● “AVG function [Aggregate]”


● “BIT_AND function [Aggregate]”
● “BIT_OR function [Aggregate]”
● “BIT_XOR function [Aggregate]”
● “COVAR_POP function [Aggregate]”
● “COVAR_SAMP function [Aggregate]”
● “COUNT function [Aggregate]”
● “COUNT_BIG function [Aggregate]”
● “CORR function [Aggregate]”
● “FIRST_VALUE function [Aggregate]”
● “GROUPING function [Aggregate]”
● “LAST_VALUE function [Aggregate]”
● “LIST function [Aggregate]”
● “MAX function [Aggregate]”
● “MEDIAN function [Aggregate]”
● “MIN function [Aggregate]”
● “REGR_AVGX function [Aggregate]”
● “REGR_AVGY function [Aggregate]”
● “REGR_COUNT function [Aggregate]”
● “REGR_INTERCEPT function [Aggregate]”
● “REGR_R2 function [Aggregate]”
● “REGR_SLOPE function [Aggregate]”
● “REGR_SXX function [Aggregate]”
● “REGR_SXY function [Aggregate]”
● “REGR_SYY function [Aggregate]”
● “SET_BITS function [Aggregate]”
● “STDDEV function [Aggregate]”
● “STDDEV_POP function [Aggregate]”
● “STDDEV_SAMP function [Aggregate]”
● “SUM function [Aggregate]”
● “VAR_POP function [Aggregate]”
● “VAR_SAMP function [Aggregate]”
● “VARIANCE function [Aggregate]”
● “XMLAGG function [Aggregate]”

134 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Function types

Bit array functions


Bit array functions allow you to perform tasks on bit arrays. The following bit array functions are
available:

● “BIT_AND function [Aggregate]”


● “BIT_OR function [Aggregate]”
● “BIT_XOR function [Aggregate]”
● “BIT_LENGTH function [Bit array]”
● “BIT_SUBSTR function [Bit array]”
● “COUNT_SET_BITS function [Bit array]”
● “GET_BIT function [Bit array]”
● “SET_BIT function [Bit array]”
● “SET_BITS function [Aggregate]”

See also
● “Bitwise operators” on page 11
● “sa_get_bits system procedure” on page 1048

Ranking functions
Ranking functions let you compute a rank value for each row in a result set based on an ordering specified
in the query.

● “CUME_DIST function [Ranking]”


● “DENSE_RANK function [Ranking]”
● “PERCENT_RANK function [Ranking]”
● “RANK function [Ranking]”

Data type conversion functions


Data type conversion functions are used to convert arguments from one data type to another, or to test
whether they can be converted.

List of functions
The following data type conversion functions are available:

● “CAST function [Data type conversion]”


● “CONVERT function [Data type conversion]”
● “HEXTOINT function [Data type conversion]”
● “INTTOHEX function [Data type conversion]”
● “ISDATE function [Data type conversion]”
● “ISNUMERIC function [Miscellaneous]”
● “TREAT function [Data type conversion]”

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 135


SQL functions

Date and time functions


Date and time functions perform operations on DATE, TIME, TIMESTAMP, and TIMESTAMP WITH
TIME ZONE data types.

SQL Anywhere includes compatibility support for Transact-SQL date and time types, including
DATETIME and SMALLDATETIME. These Transact-SQL data types are implemented as domains over
the native SQL Anywhere TIMESTAMP data type.

Specifying date parts


Many of the date functions use dates built from date parts. The following table displays allowed values
of date parts.

When using date and time functions, you can specify a minus sign to subtract from a date or time. For
example, to get a timestamp from 31 days ago, you can execute the following:
SELECT DATEADD(day, -31, NOW());

Date part Abbreviation Values

Year yy 1-9999

Quarter qq 1-4

Month mm 1-12

Week wk 1-54. Weeks begin on Sunday. A 54-week year occurs in leap years
that start on a Saturday.

Day dd 1-31

Dayofyear dy 1-366

Weekday dw 1-7 (Sunday = 1, ..., Saturday = 7)

Hour hh 0-23

Minute mi 0-59

Second ss 0-59

Millisecond ms 0-999

Microsecond mcs or us 0-999999

136 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Function types

Date part Abbreviation Values

Calyearofweek cyr 1-9999. The year in which the week begins. The week containing the
first few days of the year may have started in the previous year, de-
pending 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 1-53. The week number within the year that contains the specified
date.

For more information about the ISO week system and the ISO 8601
date and time standard, see http://en.wikipedia.org/wiki/
ISO_week_date.

Caldayofweek cdw 1-7. (Monday = 1, ..., Sunday = 7)

TZOffset tz -840 to 840

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 137


SQL functions

List of date and time functions


The following date and time functions are available:

● “DATE function [Date and time]”


● “DATEADD function [Date and time]”
● “DATEDIFF function [Date and time]”
● “DATEFORMAT function [Date and time]”
● “DATENAME function [Date and time]”
● “DATEPART function [Date and time]”
● “DATETIME function [Date and time]”
● “DAY function [Date and time]”
● “DAYNAME function [Date and time]”
● “DAYS function [Date and time]”
● “DOW function [Date and time]”
● “GETDATE function [Date and time]”
● “HOUR function [Date and time]”
● “HOURS function [Date and time]”
● “MINUTE function [Date and time]”
● “MINUTES function [Date and time]”
● “MONTH function [Date and time]”
● “MONTHNAME function [Date and time]”
● “MONTHS function [Date and time]”
● “NOW function [Date and time]”
● “QUARTER function [Date and time]”
● “SECOND function [Date and time]”
● “SECONDS function [Date and time]”
● “SWITCHOFFSET function [Date and time]”
● “SYSDATETIMEOFFSET function [Date and time]”
● “TODAY function [Date and time]”
● “TODATETIMEOFFSET function [Date and time]”
● “WEEKS function [Date and time]”
● “YEAR function [Date and time]”
● “YEARS function [Date and time]”
● “YMD function [Date and time]”

See also
● “Date and time data types” on page 101
● “Data types in UltraLite” [UltraLite - Database Management and Reference]

User-defined functions
A user-defined function, or UDF, is a function created by the user of a program or environment. User-
defined functions are in contrast to functions that are built in to the program or environment.

There are two mechanisms for creating user-defined functions in SQL Anywhere. You can use the SQL
language to write the function, or you can use Java.

138 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Function types

User-defined functions in SQL


You can implement your own functions in SQL using the CREATE FUNCTION statement.

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.

User-defined functions in Java


Java classes provide a more powerful 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.

Deciding whether to create a user-defined function or procedure


Functions are similar to procedures. Deciding whether to create a function or a procedure depends on
what you want returned, and the object will be called. When deciding whether to create a UDF or a
procedure, consider their unique characteristics listed below.

Functions:

● can return a single value of arbitrary type, and allow you to declare the returned type using the
RETURNS clause

● can be used in most places an expression can be used

● allow you to define only IN parameters

Procedures:

● can return multiple values using INOUT or OUT parameters

● can return result sets

● can be referenced in the FROM clause of a query, or using a CALL statement, or using a Transact-SQL
EXECUTE statement

● can be called using named parameters

See also
● “CREATE FUNCTION statement” on page 548
● “Creating a class” [SQL Anywhere Server - Programming]
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 139


SQL functions

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 [Miscellaneous]”


● “COALESCE function [Miscellaneous]”
● “CONFLICT function [Miscellaneous]”
● “ERRORMSG function [Miscellaneous]”
● “ESTIMATE function [Miscellaneous]”
● “ESTIMATE_SOURCE function [Miscellaneous]”
● “EXPERIENCE_ESTIMATE function [Miscellaneous]”
● “EXPLANATION function [Miscellaneous]”
● “EXPRTYPE function [Miscellaneous]”
● “GET_IDENTITY function [Miscellaneous]”
● “GRAPHICAL_PLAN function [Miscellaneous]”
● “GREATER function [Miscellaneous]”
● “IDENTITY function [Miscellaneous]”
● “IFNULL function [Miscellaneous]”
● “INDEX_ESTIMATE function [Miscellaneous]”
● “ISNULL function [Miscellaneous]”
● “LESSER function [Miscellaneous]”
● “NEWID function [Miscellaneous]”
● “NULLIF function [Miscellaneous]”
● “NUMBER function [Miscellaneous]”
● “PLAN function [Miscellaneous]”
● “REWRITE function [Miscellaneous]”
● “ROW_NUMBER function [Miscellaneous]”
● “SQLDIALECT function [Miscellaneous]”
● “SQLFLAGGER function [Miscellaneous]”
● “TRACEBACK function [Miscellaneous]”
● “TRANSACTSQL function [Miscellaneous]”
● “VAREXISTS function [Miscellaneous]”
● “WATCOMSQL function [Miscellaneous]”

Numeric functions
Numeric functions perform mathematical operations on numerical data types or return numeric
information.

140 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Function types

List of functions
The following numeric functions are available:

● “ABS function [Numeric]”


● “ACOS function [Numeric]”
● “ASIN function [Numeric]”
● “ATAN function [Numeric]”
● “ATAN2 function [Numeric]”
● “CEILING function [Numeric]”
● “COS function [Numeric]”
● “COT function [Numeric]”
● “DEGREES function [Numeric]”
● “EXP function [Numeric]”
● “FLOOR function [Numeric]”
● “LOG function [Numeric]”
● “LOG10 function [Numeric]”
● “MOD function [Numeric]”
● “PI function [Numeric]”
● “POWER function [Numeric]”
● “RADIANS function [Numeric]”
● “RAND function [Numeric]”
● “REMAINDER function [Numeric]”
● “ROUND function [Numeric]”
● “SIGN function [Numeric]”
● “SIN function [Numeric]”
● “SQRT function [Numeric]”
● “TAN function [Numeric]”
● “TRUNCNUM function [Numeric]”

Web services functions


HTTP functions assist the handling of HTTP requests within web services. Likewise, SOAP functions
assist the handling of SOAP requests within web services.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 141


SQL functions

The following functions are available:

● “HTML_DECODE function [Miscellaneous]”


● “HTML_ENCODE function [Miscellaneous]”
● “HTTP_BODY function [Web service]”
● “HTTP_DECODE function [Web service]”
● “HTTP_ENCODE function [Web service]”
● “HTTP_HEADER function [Web service]”
● “HTTP_RESPONSE_HEADER function [Web service]”
● “HTTP_VARIABLE function [Web service]”
● “NEXT_HTTP_HEADER function [Web service]”
● “NEXT_HTTP_RESPONSE_HEADER function [Web service]”
● “NEXT_HTTP_VARIABLE function [Web service]”
● “NEXT_SOAP_HEADER function [SOAP]”
● “SOAP_HEADER function [SOAP]”

There are also system procedures available for web services.

See also
● “SQL Anywhere as an HTTP web server” [SQL Anywhere Server - Programming]
● “-xs dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “Web services system procedures” on page 996

String functions
String functions perform conversion, extraction, or manipulation operations on strings, or return
information about strings.

When working in a multibyte character set, check carefully whether the function being used returns
information concerning characters or bytes.

142 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Function types

List of functions
The following string functions are available:

● “ASCII function [String]”


● “BASE64_DECODE function [String]”
● “BASE64_ENCODE function [String]”
● “BYTE_LENGTH function [String]”
● “BYTE_SUBSTR function [String]”
● “CHAR function [String]”
● “CHARINDEX function [String]”
● “CHAR_LENGTH function [String]”
● “COMPARE function [String]”
● “COMPRESS function [String]”
● “CSCONVERT function [String]”
● “DECOMPRESS function [String]”
● “DECRYPT function [String]”
● “DIFFERENCE function [String]”
● “ENCRYPT function [String]”
● “HASH function [String]”
● “INSERTSTR function [String]”
● “LCASE function [String]”
● “LEFT function [String]”
● “LENGTH function [String]”
● “LOCATE function [String]”
● “LOWER function [String]”
● “LTRIM function [String]”
● “NCHAR function [String]”
● “PATINDEX function [String]”
● “READ_CLIENT_FILE function [String]”
● “REGEXP_SUBSTR function [String]”
● “REPEAT function [String]”
● “REPLACE function [String]”
● “REPLICATE function [String]”
● “REVERSE function [String]”
● “RIGHT function [String]”
● “RTRIM function [String]”
● “SIMILAR function [String]”
● “SORTKEY function [String]”
● “SOUNDEX function [String]”
● “SPACE function [String]”
● “STR function [String]”
● “STRING function [String]”
● “STRTOUUID function [String]”
● “STUFF function [String]”
● “SUBSTRING function [String]”
● “TO_CHAR function [String]”
● “TO_NCHAR function [String]”
● “TRIM function [String]”

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 143


SQL functions

● “UCASE function [String]”


● “UNICODE function [String]”
● “UNISTR function [String]”
● “UPPER function [String]”
● “UUIDTOSTR function [String]”
● “XMLCONCAT function [String]”
● “XMLELEMENT function [String]”
● “XMLFOREST function [String]”
● “XMLGEN function [String]”

System functions
System functions return system information.

List of functions
The following system functions are available:

● “CONNECTION_EXTENDED_PROPERTY function [String]”


● “CONNECTION_PROPERTY function [System]”
● “DATALENGTH function [System]”
● “DB_ID function [System]”
● “DB_NAME function [System]”
● “DB_EXTENDED_PROPERTY function [System]”
● “DB_PROPERTY function [System]”
● “EVENT_CONDITION function [System]”
● “EVENT_CONDITION_NAME function [System]”
● “EVENT_PARAMETER function [System]”
● “NEXT_CONNECTION function [System]”
● “NEXT_DATABASE function [System]”
● “PROPERTY function [System]”
● “PROPERTY_DESCRIPTION function [System]”
● “PROPERTY_NAME function [System]”
● “PROPERTY_NUMBER function [System]”
● “SUSER_ID function [System]”
● “SUSER_NAME function [System]”
● “TSEQUAL function [System] (deprecated)”
● “USER_ID function [System]”
● “USER_NAME function [System]”

Notes

● Some of the system functions are implemented in SQL 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.

144 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

System function Description

COL_LENGTH( table-name, column-name ) Returns the defined length of column

COL_NAME( table-id, column-id [, database-id ] ) Returns the column name

INDEX_COL ( table-name, index-id, key_# [, userid ] ) Returns the name of the indexed column

OBJECT_ID ( object-name ) Returns the object ID

OBJECT_NAME ( object-id [, database-id ] ) Returns the object name

Text and image functions


Text and image functions operate on text and image data types. SQL Anywhere supports only the textptr
text and image function.

List of functions
The following text and image function is available:

● “TEXTPTR function [Text and image]”

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 133.

ABS function [Numeric]


Returns the absolute value of a numeric expression.

Syntax
ABS( numeric-expression )

Parameters
● numeric-expression The number whose absolute value is to be returned.

Returns
An absolute value of the numeric expression.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 145


SQL functions

Numeric-expression data type Returns

INT INT

FLOAT FLOAT

DOUBLE DOUBLE

NUMERIC NUMERIC

Standards and compatibility


● SQL/2008 The ABS function is part of optional SQL/2008 language feature T441.

Example
The following statement returns the value 66.
SELECT ABS( -66 );

ACOS function [Numeric]


Returns the arc-cosine, in radians, of a numeric expression.

Syntax
ACOS( numeric-expression )

Parameters
● numeric-expression The cosine of the angle.

Returns
DOUBLE

Remarks
This function converts its argument to DOUBLE, and performs the computation in double-precision
floating-point arithmetic.

See also
● “ASIN function [Numeric]” on page 148
● “ATAN function [Numeric]” on page 149
● “ATAN2 function [Numeric]” on page 150
● “COS function [Numeric]” on page 176

Standards and compatibility


● SQL/2008 Vendor extension.

146 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example
The following statement returns the arc-cosine value for 0.52.
SELECT ACOS( 0.52 );

ARGN function [Miscellaneous]


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.

Returns
Using the value of the integer-expression as n, returns the nth argument (starting at 1) from the remaining
list of arguments.

Remarks
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 compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 6.
SELECT ARGN( 6, 1,2,3,4,5,6 );

ASCII function [String]


Returns the integer ASCII value of the first byte in a string-expression.

Syntax
ASCII( string-expression )

Parameters
● string-expression The string.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 147


SQL functions

Returns
SMALLINT

Remarks
If the string is empty, then ASCII returns zero. Literal strings must be enclosed in quotes. If the database
character set is multibyte and the first character of the parameter string consists of more than one byte, the
result is NULL.

See also
● “CHAR function [String]” on page 161
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 90.
SELECT ASCII( 'Z' );

ASIN function [Numeric]


Returns the arc-sine, in radians, of a number.

Syntax
ASIN( numeric-expression )

Parameters
● numeric-expression The sine of the angle.

Returns
DOUBLE

Remarks
The SIN and ASIN functions are inverse operations.

This function converts its argument to DOUBLE, and performs the computation in double-precision
floating-point arithmetic.

See also
● “ACOS function [Numeric]” on page 146
● “ATAN function [Numeric]” on page 149
● “ATAN2 function [Numeric]” on page 150
● “SIN function [Numeric]” on page 337

148 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the arc-sine value for 0.52.
SELECT ASIN( 0.52 );

ATAN function [Numeric]


Returns the arc-tangent, in radians, of a number.

Syntax
ATAN( numeric-expression )

Parameters
● numeric-expression The tangent of the angle.

Remarks
The ATAN and TAN functions are inverse operations.

Returns
DOUBLE

Remarks
This function converts its argument to DOUBLE, and performs the computation in double-precision
floating-point arithmetic.

See also
● “ACOS function [Numeric]” on page 146
● “ASIN function [Numeric]” on page 148
● “ATAN2 function [Numeric]” on page 150
● “TAN function [Numeric]” on page 359

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the arc-tangent value for 0.52.
SELECT ATAN( 0.52 );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 149


SQL functions

ATAN2 function [Numeric]


Returns the arc-tangent, in radians, of the ratio of two numbers.

Syntax
{ ATN2 | ATAN2 }( numeric-expression-1, numeric-expression-2 )

Parameters
● numeric-expression-1 The numerator in the ratio whose arc-tangent is calculated.

● numeric-expression-2 The denominator in the ratio whose arc-tangent is calculated.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic.

See also
● “ACOS function [Numeric]” on page 146
● “ASIN function [Numeric]” on page 148
● “ATAN function [Numeric]” on page 149
● “TAN function [Numeric]” on page 359

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the arc-tangent value for the ratio 0.52 to 0.60.

SELECT ATAN2( 0.52, 0.60 );

AVG function [Aggregate]


Computes the average, for a set of rows, of a numeric expression or of a set of unique values.

Syntax 1
AVG( [ ALL | DISTINCT ] numeric-expression )

Syntax 2
AVG( [ ALL ] numeric-expression ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

150 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Parameters
● [ ALL ] numeric-expression The expression whose average is calculated over the rows in each
group.

● DISTINCT clause Computes the average of the unique numeric values in each group.

Returns
Returns the NULL value for a group containing no rows.

Returns DOUBLE if the argument is DOUBLE, otherwise NUMERIC.

Remarks
This average does not include rows where the numeric-expression is the NULL value.

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition provided in “WINDOW clause” on page 961.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

This function can generate an overflow error, resulting in an error being returned. You can use the CAST
function on numeric-expression to avoid the overflow error.

See also
● “CAST function [Data type conversion]” on page 159
● “SUM function [Aggregate]” on page 355
● “COUNT function [Aggregate]” on page 177

Standards and compatibility


● SQL/2008 Syntax 1 is a core feature of the SQL/2008 standard, while Syntax 2 comprises part of
optional SQL/2008 language feature T611, "Basic OLAP operations". The ability to specify
DISTINCT over an expression that is not a column reference comprises part of optional SQL
language feature F561, "Full value expressions". SQL Anywhere also supports SQL/2008 language
feature F441, "Extended set function support", which permits operands of aggregate functions to be
arbitrary expressions possibly including outer references to expressions in other query blocks that are
not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the AVG function, combined with an outer
reference.

See also
● “Aggregate functions and outer references” [SQL Anywhere Server - SQL Usage]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 151


SQL functions

Example
The following statement returns the value 49988.623200.
SELECT AVG( Salary ) FROM Employees;

The following statement returns the average product price from the Products table:
SELECT AVG( DISTINCT UnitPrice ) FROM Products;

The following statement returns an error with SQLSTATE 42W68 because the arguments of AVG
contain both a quantified expression from the subquery, and an outer reference (p.Quantity) from the
outer SELECT block:
select * from Products as p
where p.Quantity > ( select avg( 0.5 * p.Quantity + 0.5 * s.Quantity )
from SalesOrderItems as s
where s.ProductID = p.ProductID )

BASE64_DECODE function [String]


Decodes data using the MIME base64 format and returns the string as a LONG VARCHAR.

Syntax
BASE64_DECODE( string-expression )

Parameters
● string-expression The string that is to be decoded. Note that the string must be base64-encoded.

Returns
LONG VARCHAR

See also
● “BASE64_ENCODE function [String]” on page 152
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following inserts an image into an image table from an embedded SQL program. The input data (host
variable) must be base64 encoded.
EXEC SQL INSERT INTO images ( image_data ) VALUES ( BASE64_DECODE ( :img ) );

BASE64_ENCODE function [String]


Encodes data using the MIME base64 format and returns it as a 7-bit ASCII string.

152 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Syntax
BASE64_ENCODE( string-expression )

Parameters
● string-expression The string that is to be encoded.

Returns
LONG VARCHAR

See also
● “BASE64_DECODE function [String]” on page 152
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following retrieves data from a table containing images and returns it in ASCII format. The resulting
string can be embedded into an email message, and then decoded by the recipient to retrieve the original
image.
SELECT BASE64_ENCODE( image_data ) FROM IMAGES;

BIT_AND function [Aggregate]


Returns the bit-wise AND of the specified expression for each group of rows.

Syntax
BIT_AND( bit-expression )

Parameters
● bit-expression The object to be aggregated. The expression can be a VARBIT array, a BINARY
value, or an INTEGER (including all integer variants such as BIT and TINYINT).

Returns
The same data type as the argument. For each bit position compared, if every row has a 1 in the bit
position, return 1; otherwise, return 0.

See also
● “BIT_OR function [Aggregate]” on page 155
● “BIT_XOR function [Aggregate]” on page 157
● “Bitwise operators” on page 11

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 153


SQL functions

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example generates four rows containing a CHAR column, then converts the values to
VARBIT.
SELECT BIT_AND( CAST(row_value AS VARBIT) )
FROM dbo.sa_split_list('0001,0111,0100,0011')

The result 0000 is determined as follows:

1. A bitwise AND is performed between row 1 (0001) and row 2 (0111), resulting in 0001 (both values
had a 1 in the fourth bit).

2. A bitwise AND is performed between the result from the previous comparison (0001) and row 3
(0100), resulting in 0000 (neither value had a 1 in the same bit).

3. A bitwise AND is performed between the result from the previous comparison (0000) and row 4
(0011), resulting in 0000 (neither value had a 1 in the same bit).

BIT_LENGTH function [Bit array]


Returns the number of bits stored in the array.

Syntax
BIT_LENGTH( bit-expression )

Parameters
● bit-expression The bit expression for which the length is to be determined.

Returns
INT

See also
● “CHAR_LENGTH function [String]” on page 162

Standards and compatibility


● SQL/2008 Vendor extension.

● SQL/1999 The BIT_LENGTH function was a core feature of the SQL/1999 standard. The BIT
VARYING data type was optional language feature F511 of the SQL/1999 standard. Support for
BIT_LENGTH and the BIT VARYING data type were removed in the SQL/2003 standard.

Example
The following statement returns the value 8:

154 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

SELECT BIT_LENGTH( '01101011' );

BIT_OR function [Aggregate]


Returns the bit-wise OR of the specified expression for each group of rows.

Syntax
BIT_OR( bit-expression )

Parameters
● bit-expression The object to be aggregated. The expression can be a VARBIT array, a BINARY
value, or an INTEGER (including all integer variants such as BIT and TINYINT).

Returns
The same data type as the argument. For each bit position compared, if any row has a 1 in the bit position,
this function returns 1; otherwise, it returns 0.

See also
● “BIT_AND function [Aggregate]” on page 153
● “BIT_XOR function [Aggregate]” on page 157
● “Bitwise operators” on page 11

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example generates four rows containing a CHAR column, then converts the values to
VARBIT.
SELECT BIT_OR( CAST(row_value AS VARBIT) )
FROM dbo.sa_split_list('0001,0111,0100,0011')

The result 0111 is determined as follows:

1. A bitwise OR is performed between row 1 (0001) and row 2 (0111), resulting in 0111.

2. A bitwise OR is performed between the result from the previous comparison (0111) and row 3
(0100), resulting in 0111.

3. A bitwise OR is performed between the result from the previous comparison (0111) and row 4
(0011), resulting in 0111.

BIT_SUBSTR function [Bit array]


Returns a sub-array of a bit array.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 155


SQL functions

Syntax
BIT_SUBSTR( bit-expression [, start [, length ] ] )

Parameters
● bit-expression The bit array from which the sub-array is to be extracted.

● start The start position of the sub-array to return. A negative starting position specifies the number
of bits from the end of the array instead of the beginning. The first bit in the array is at position 1.

● length The length of the sub-array to return. A positive length specifies that the sub-array ends
length bits to the right of the starting position, while a negative length returns, at most, length bits up
to, and including, the starting position, from the left of the starting position.

Returns
LONG VARBIT

Remarks
Both start and length can be either positive or negative. Using appropriate combinations of negative and
positive numbers, you can get a sub-array from either the beginning or end of the string. Using a negative
number for length does not impact the order of the bits returned in the sub-array.

If length is specified, the sub-array is restricted to that length. If start is zero and length is non-negative, a
start value of 1 is used. If start is zero and length is negative, a start value of -1 is used.

If length is not specified, selection continues to the end of the array.

The BIT_SUBSTR function is equivalent to, but faster than, the following:
CAST( SUBSTR( CAST( bit-expression AS VARCHAR ),
start [, length ] )
AS VARBIT )

See also
● “SUBSTRING function [String]” on page 353

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns 1101:
SELECT BIT_SUBSTR( '001101', 3 );

The following statement returns 10110:


SELECT BIT_SUBSTR( '01011011101111011111', 2, 5 );

The following statement returns 11111:


SELECT BIT_SUBSTR( '01011011101111011111', -5, 5 );

156 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

BIT_XOR function [Aggregate]


Returns the bit-wise XOR of the specified expression for each group of rows.

Syntax
BIT_XOR( bit-expression )

Parameters
● bit-expression The object to be aggregated. The expression can be a VARBIT array, a BINARY
value, or an INTEGER (including all integer variants such as BIT and TINYINT).

Returns
The same data type as the argument. For each bit position compared, if an odd number of rows have a 1 in
the bit position, return 1; otherwise, return 0.

See also
● “BIT_AND function [Aggregate]” on page 153
● “BIT_OR function [Aggregate]” on page 155
● “Bitwise operators” on page 11

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example generates four rows containing a CHAR column, then converts the values to
VARBIT.

SELECT BIT_XOR( CAST(row_value AS VARBIT) )


FROM dbo.sa_split_list('0001,0111,0100,0011')

The result 0001 is determined as follows:

1. A bitwise exclusive OR (XOR) is performed between row 1 (0001) and row 2 (0111), resulting in
0110.

2. A bitwise XOR is performed between the result from the previous comparison (0110) and row 3
(0100), resulting in 0010.

3. A bitwise XOR is performed between the result from the previous comparison (0010) and row 4
(0011), resulting in 0001.

BYTE_LENGTH function [String]


Returns the number of bytes in a string.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 157


SQL functions

Syntax
BYTE_LENGTH( string-expression )

Parameters
● string-expression The string whose length is to be calculated.

Returns
INT

Remarks
Trailing white space characters in the string-expression are included in the length returned.

The return value of a NULL string is NULL.

If the string is in a multibyte character set, the BYTE_LENGTH value may differ from the number of
characters returned by CHAR_LENGTH.

This function supports NCHAR inputs and/or outputs.

See also
● “CHAR_LENGTH function [String]” on page 162
● “DATALENGTH function [System]” on page 186
● “LENGTH function [String]” on page 259
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension. The equivalent function in the SQL/2008 standard is the
OCTET_LENGTH function.

Example
The following statement returns the value 12.
SELECT BYTE_LENGTH( 'Test Message' );

BYTE_SUBSTR function [String]


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.

158 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

● 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 returns at most length
bytes up to, and including, the starting position, from the left of the starting position.

Returns
BINARY, VARCHAR, or NVARCHAR. The value returned depends on the type of string-expression.
Also, the arguments you specify determine if the returned value is LONG. For example, LONG is not
returned when you specify a constant < 32K for length.

Remarks
If length is specified, the substring is restricted to that number of bytes. Both start and length can be either
positive or negative. Using appropriate combinations of negative and positive numbers, you can get a
substring from either the beginning or end of the string.

If start is zero and length is non-negative, a start value of 1 is used. If start is zero and length is negative,
a start value of -1 is used.

See also
● “SUBSTRING function [String]” on page 353
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value Test.
SELECT BYTE_SUBSTR( 'Test Message', 1, 4 );

CAST function [Data type conversion]


Returns the value of an expression converted to a supplied data type.

The CAST, CONVERT, HEXTOINT, and INTTOHEX functions can be used to convert to and from
hexadecimal values. For more information about using these functions, see “Converting to and from
hexadecimal values” on page 6.

Syntax
CAST( expression AS datatype )

Parameters
● expression The expression to be converted.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 159


SQL functions

● datatype The target data type.

Returns
Depends on the data type requested.

Remarks
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.

If you use the CAST function to truncate strings, the string_rtruncation database option must be set to
OFF; otherwise, there will be an error. It is recommended that you use the LEFT function to truncate
strings.

See also
● “Data type conversions” on page 122
● “CONVERT function [Data type conversion]” on page 172
● “LEFT function [String]” on page 258

Standards and compatibility


● SQL/2008 The CAST function is a core feature of the SQL/2008 standard. However, in SQL
Anywhere CAST supports a number of data type conversions that are not permitted by the SQL
standard. For example, in SQL Anywhere you can CAST an integer value to a DATE type, whereas in
the SQL standard this type conversion is not permitted. For more information, see “Data type
conversions” on page 122.

Example
The following function ensures a string is used as a date:

SELECT CAST( '2000-10-31' AS DATE );

The value of the expression 1 + 2 is calculated, and the result is then cast into a single-character string.

SELECT CAST( 1 + 2 AS CHAR );

CEILING function [Numeric]


Returns the first integer that is greater or equal to a given value. For positive numbers, this is known as
rounding up.

Syntax
{ CEILING | CEIL } ( numeric-expression )

Parameters
● numeric-expression The number whose ceiling is to be calculated.

160 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Returns
DOUBLE

Remarks
This function converts its argument to DOUBLE, and performs the computation in double-precision
floating-point arithmetic.

See also
● “FLOOR function [Numeric]” on page 225

Standards and compatibility


● SQL/2008 The CEILING function comprises part of optional SQL/2008 language feature T621,
"Enhanced numeric functions".

Example
The following statement returns the value 60.

SELECT CEILING( 59.84567 );

CHAR function [String]


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.

Returns
VARCHAR

Remarks
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.

See also
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 161


SQL functions

Example
The following statement returns the value Y.
SELECT CHAR( 89 );

CHAR_LENGTH function [String]


Returns the number of characters in a string.

Syntax
CHAR_LENGTH ( string-expression )

Parameters
● string-expression The string whose length is to be calculated.

Returns
INT

Remarks
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 multibyte character set, the value returned by the CHAR_LENGTH function may
differ from the number of bytes returned by the BYTE_LENGTH function.

Note
You can use the CHAR_LENGTH function and the LENGTH function interchangeably for CHAR,
VARCHAR, LONG VARCHAR, and NCHAR data types. However, you must use the LENGTH function
for BINARY and bit array data types.

This function supports NCHAR inputs and/or outputs.

See also
● “BYTE_LENGTH function [String]” on page 157
● “String functions” on page 142

Standards and compatibility


● SQL/2008 CHAR_LENGTH is a core feature of the SQL/2008 standard. Using CHAR_LENGTH
over an expression of type NCHAR comprises part of optional SQL/2008 language feature F421.

Example
The following statement returns the value 8.
SELECT CHAR_LENGTH( 'Chemical' );

162 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

CHARINDEX function [String]


Returns the position of one string in another.

Syntax
CHARINDEX( string-expression-1, string-expression-2 )

Parameters
● string-expression-1 The string for which you are searching.

● string-expression-2 The string to be searched.

Returns
INT

Remarks
The first character of string-expression-1 is identified as 1. If the string being searched contains more than
one instance of the other string, then the CHARINDEX function returns the position of the first instance.

If the string being searched does not contain the other string, then the CHARINDEX function returns 0.

If any of the arguments are NULL, the result is NULL.

This function supports NCHAR inputs and/or outputs.

See also
● “SUBSTRING function [String]” on page 353
● “REPLACE function [String]” on page 321
● “LOCATE function [String]” on page 264
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns last and first names from the Surname and GivenName columns of the
Employees table, but only when the last name includes the letter K:
SELECT Surname, GivenName
FROM Employees
WHERE CHARINDEX( 'K', Surname ) = 1;

Results returned:

Surname GivenName

Klobucher James

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 163


SQL functions

Surname GivenName

Kuo Felicia

Kelly Moira

COALESCE function [Miscellaneous]


Returns the first non-NULL expression from a list. This function is identical to the ISNULL function.

Syntax
COALESCE( expression, expression [ , ...] )

Parameters
● expression Any expression.

At least two expressions must be passed into the function, and all expressions must be comparable.

Returns
The return type for this function depends on the expressions specified. That is, when the database server
evaluates the function, it first searches for a data type in which all the expressions can be compared. When
found, the database server compares the expressions and then returns the result in the type used for the
comparison. If the database server cannot find a common comparison type, an error is returned.

Remarks
The result is NULL only if all the arguments are NULL.

The parameters can be of any scalar type, but not necessarily same type.

For a more detailed description of how the database server processes this function, see “ISNULL function
[Miscellaneous]” on page 253.

See also
● “ISNULL function [Miscellaneous]” on page 253

Standards and compatibility


● SQL/2008 Core feature.

Example
The following statement returns the value 34.
SELECT COALESCE( NULL, 34, 13, 0 );

164 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

COMPARE function [String]


Allows you to compare two character strings based on alternate collation rules.

Syntax
COMPARE(
string-expression-1,
string-expression-2
[, { collation-id
| collation-name[(collation-tailoring-string) ] } ]
)

Parameters
● string-expression-1 The first string expression.

● string-expression-2 The second string expression.

The string expression can only contain characters that are encoded in the database's character set.

● collation-id A variable or integer constant that specifies the sort order to use. You can only use a
collation-id for built-in collations. See “SORTKEY function [String]” on page 339.

If you do not specify a collation name or ID, the default is Default Unicode multilingual.

● collation-name A string or a character variable that specifies the name of the collation to use. You
can also specify char_collation or db_collation (for example, COMPARE( 'abc', 'ABC',
'char_collation' );) to use the database's CHAR collation. Similarly, you can specify
nchar_collation to use the database's NCHAR collation. For a list of valid collation names, see
“SORTKEY function [String]” on page 339.

● collation-tailoring-string Optionally, you can specify collation tailoring options (collation-


tailoring-string) for additional control over the character comparison. These options take the form of
keyword=value pairs in parentheses, following the collation name. For example,
'UCA(locale=es;case=LowerFirst;accent=respect)'. The syntax for specifying
these options is identical to the syntax defined for the COLLATION clause of the CREATE
DATABASE statement.

Note
All the collation tailoring options are supported when specifying the UCA collation. For all other
collations, only case sensitivity tailoring option is supported.

See also
● “Collation tailoring options” [SQL Anywhere Server - Database Administration]

Returns
An INTEGER, based on the collation rules that you choose:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 165


SQL functions

Value Meaning

1 string-expression-1 is greater than string-expression-2

0 string-expression-1 is equal to string-expression-2

-1 string-expression-1 is less than string-expression-2

Remarks
The COMPARE function does not equate empty strings and strings containing only spaces, even if the
database has blank-padding enabled. The COMPARE function uses the SORTKEY function to generate
collation keys for comparison. Therefore, an empty string, a string with one space, and a string with two
spaces do not compare equally.

If either string-expression-1 or string-expression-2 is NULL, the result is NULL.

See also
● “SORTKEY function [String]” on page 339
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example performs three comparisons using the COMPARE function:

SELECT COMPARE( 'abc','ABC','UCA(case=LowerFirst)' ),


COMPARE( 'abc','ABC','UCA(case=Ignore)' ),
COMPARE( 'abc','ABC','UCA(case=UpperFirst)' );

The values returned are -1, 0, 1, indicating the result of each comparison. The first comparison results in
-1, indicating that string-expression-2 ('ABC') is less than string-expression-1 ('abc'). This is because case
sensitivity is set to LowerFirst in the first COMPARE statement.

COMPRESS function [String]


Compresses the string and returns a value of type LONG BINARY.

Syntax
COMPRESS( string-expression [ , 'compression-algorithm-alias' ])

Parameters

● string-expression The string to be compressed. Binary values can be passed to this function. This
parameter is case sensitive, even in case-insensitive databases.

166 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

● compression-algorithm-alias Alias for the algorithm to use for compression. The supported
values are zip and gzip (both are based on the same algorithm, but use different headers and trailers).

Zip is a widely supported compression algorithm. Gzip is compatible with the gzip utility on Unix,
whereas the zip algorithm is not.

Decompression must be performed with the same algorithm.

Returns
LONG BINARY

Remarks
The value returned by the COMPRESS is not human-readable. If the value returned is longer than the
original string, its maximum size will not be larger than a 0.1% increase over the original string + 12
bytes. You can decompress a compressed string-expression using the DECOMPRESS function.

If you are storing compressed values in a table, the column should be BINARY or LONG BINARY so
that character set conversion is not performed on the data.

See also
● “DECOMPRESS function [String]” on page 203
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example returns the length of the binary string created by compressing the string 'Hello
World' using the gzip algorithm. This example can be useful when you want to determine whether a value
has a shorter length when compressed.
SELECT LENGTH( COMPRESS( 'Hello world', 'gzip' ) );

CONFLICT function [Miscellaneous]


Indicates if a column is a source of conflict for an UPDATE being performed against a consolidated
database in a SQL Remote environment.

Syntax
CONFLICT( column-name )

Parameters
● column-name The name of the column being tested for conflicts.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 167


SQL functions

Returns
Returns TRUE if the column appears in the VERIFY list of an UPDATE statement executed by the SQL
Remote Message Agent and if the value provided in the VALUES list of that statement does not match
the original value of the column in the row being updated. Otherwise, returns FALSE.

See also
● “CREATE TRIGGER statement” on page 651
● “Default resolution for update conflicts” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The CONFLICT function is intended for use in SQL Remote RESOLVE UPDATE triggers to avoid error
messages. To illustrate the use of the CONFLICT function, consider the following table:
CREATE TABLE Admin (
PKey bigint NOT NULL DEFAULT GLOBAL AUTOINCREMENT,
TextCol CHAR(20) NULL, PRIMARY KEY ( PKey ) );

Assume that consolidated and remote databases both have the following row in the Admin table:
1, 'Initial'

Now, at the consolidated database, update the row as follows:


UPDATE Admin SET TextCol = 'Consolidated Update' WHERE PKey = 1;

At the remote database, update the row to a different value as follows:


UPDATE Admin SET TextCol = 'Remote Update' WHERE PKey = 1;

Next, run dbremote on the remote database. It generates a message file with the following statements in it,
to be executed at the consolidated database:
UPDATE Admin SET TextCol='Remote Update'
VERIFY ( TextCol )
VALUES ( 'Initial' )
WHERE PKey=1;

When the SQL Remote Message Agent runs at the consolidated database and applies this UPDATE
statement, SQL Anywhere uses the VERIFY and VALUES clause to determine whether a RESOLVE
UPDATE trigger will fire. A RESOLVE UPDATE trigger fires only when the update is executed from
the SQL Remote Message Agent against a consolidated database. Here is a RESOLVE UPDATE trigger:
CREATE TRIGGER ResolveUpdateAdmin
RESOLVE UPDATE ON Admin
REFERENCING OLD AS OldConsolidated
NEW AS NewRemote
REMOTE as OldRemote
FOR EACH ROW BEGIN
MESSAGE 'OLD';
MESSAGE OldConsolidated.PKey || ',' || OldConsolidated.TextCol;
MESSAGE 'NEW';

168 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

MESSAGE NewRemote.PKey || ',' || NewRemote.TextCol;


MESSAGE 'REMOTE';
MESSAGE OldRemote.PKey || ',' || OldRemote.TextCol;
END;

The RESOLVE UPDATE trigger fires because the current value of the TextCol column at the
consolidated database ('Consolidated Update') does not match the value in the VALUES clause
for the associated column ('Initial').

This trigger results in a failure because the PKey column was not modified in the UPDATE statement
executed on the remote, so there is no OldRemote.PKey value accessible from this trigger.

The CONFLICT function helps to avoid this error by returning the following values:

● If there is no OldRemote.PKey value, return FALSE.

● If there is an OldRemote.PKey value, but it matches OldConsolidated.PKey, return FALSE.

● If there is an OldRemote.PKey value, and it is different than OldConsolidated.PKey, return TRUE.

You can use the CONFLICT function to rewrite the trigger as follows and avoid the error:
CREATE TRIGGER ResolveUpdateAdmin
RESOLVE UPDATE ON Admin
REFERENCING OLD AS OldConsolidated
NEW AS NewRemote
REMOTE as OldRemote
FOR EACH ROW BEGIN
message 'OLD';
message OldConsolidated.PKey || ',' || OldConsolidated.TextCol;
message 'NEW';
message NewRemote.PKey || ',' || NewRemote.TextCol;
message 'REMOTE';
if CONFLICT( PKey ) then
message OldRemote.PKey;
end if;
if CONFLICT( TextCol ) then
message OldRemote.TextCol;
end if;
END;

CONNECTION_EXTENDED_PROPERTY function [String]


Returns the value of the given property. Allows an optional property-specific string parameter to be
specified.

Syntax
CONNECTION_EXTENDED_PROPERTY(
{ property-id | property-name }
[, property-specific-argument [, connection-id ] ]
)

Parameters
● property-id The connection property ID.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 169


SQL functions

● property-name The connection property name. The supported property names are:

○ CharSet Returns the CHAR character set label for the connection as it is known by the
specified standard. The possible values include: ASE, IANA, MIME, JAVA, WINDOWS,
UTR22, IBM, and ICU. The default is IANA unless the database connection was made through
TDS in which case ASE is the default.

○ NcharCharSet Returns the NCHAR character set label for the connection as it is known by the
specified standard. The possible values are the same as listed above for CharSet.

○ Progress Returns information about how long a statement has been executing. Specify a
property-specific-argument, followed by connection-id, to return information specific to the
statement's progress.

The following statements and procedures support the Progress property:

● BACKUP DATABASE (both image and archive)


● LOAD TABLE (USING FILE and USING CLIENT FILE only)
● MESSAGE
● REORGANIZE TABLE
● RESTORE DATABASE
● UNLOAD (all types)
● sa_table_page_usage system procedure

● property-specific-argument An optional property-specific string parameter associated with the


following connection property:

○ Progress

● PercentComplete Specify PercentComplete to obtain the percentage of the statement that


has been processed.

● Completed Specify Completed to obtain the completed number of units.

● Total Specify Total to obtain the total number of units left to be processed.

● Units Specify Units to obtain the type of units left to be processed (pages, rows, or bytes).

● Elapsed Specify Elapsed to obtain the current elapsed time in milliseconds.

● Remaining Specify Remaining to obtain the estimated remaining time in milliseconds.

● Raw Specify Raw to obtain a string combining all of the above values in the order listed,
separated by semicolons. For example, 43;9728;22230;pages;5025;6138.

● Formatted Specify Formatted to obtain the human readable format. For example:
43% ( 9728 of 22230 pages ) complete after 00:00:05; estimated
00:00:06 remaining

The Remaining value may be empty if the remaining time has not yet been estimated, or if the
number of units completed is greater than the original estimate.

170 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

For all property-specific arguments except Formatted, large byte values are never converted to
kilobytes or megabytes.

● connection-id The connection ID number of a database connection. The ID number for the current
connection is used if a value is not specified.

Returns
Returns extended connection properties. The returned value is a VARCHAR.

Remarks
The CONNECTION_EXTENDED_PROPERTY function is similar to the CONNECTION_PROPERTY
function except that it allows an optional property-specific string parameter to be specified. The
interpretation of the property-specific argument depends on the property ID or name specified in the first
argument.

You can use the CONNECTION_EXTENDED_PROPERTY function to return the value for any
connection property. However, extended information is only available for the extended properties.

Cloud note: Because of tenant database isolation rules, when this function is called in the cloud it
returns only information about the current tenant database.

See also
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “progress_messages option” [SQL Anywhere Server - Database Administration]
● “CONNECTION_PROPERTY function [System]” on page 171
● “DB_EXTENDED_PROPERTY function [System]” on page 197
● “DB_PROPERTY function [System]” on page 202

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example returns the CHAR character set of the current connection as it is known by the
Java standard:

SELECT CONNECTION_EXTENDED_PROPERTY( 'charset', 'Java' );

CONNECTION_PROPERTY function [System]


Returns the value of a given connection property as a string.

Syntax
CONNECTION_PROPERTY(
{ integer-expression-1 | string-expression }
[ , integer-expression-2 ] )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 171


SQL functions

Parameters
● integer-expression-1 It is usually 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 “Accessing connection property values” [SQL Anywhere Server
- Database Administration].

● integer-expression-2 The connection ID of the current database connection. The current


connection is used if this argument is omitted.

Returns
VARCHAR, LONG VARCHAR

Remarks
The current connection is used if the second argument is omitted.

Cloud note: Because of tenant database isolation rules, when this function is called in the cloud it
returns only information about the current tenant database.

See also
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “PROPERTY_NUMBER function [System]” on page 299

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the number of prepared statements being maintained.
SELECT CONNECTION_PROPERTY( 'PrepStmt' );

CONVERT function [Data type conversion]


Returns an expression converted to a supplied data type.

The CAST, CONVERT, HEXTOINT, and INTTOHEX functions can be used to convert to and from
hexadecimal values. For more information about using these functions, see “Converting to and from
hexadecimal values” on page 6.

Syntax
CONVERT( datatype, expression [ , format-style ] )

172 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Parameters
● datatype The data type to which the expression is converted.

● expression The expression to be converted.

● format-style The style code to apply to the output value. Use this parameter when converting
strings to date or time data types, and vice versa. The table below shows the supported style codes,
followed by a representation of the output format produced by that style code. The style codes are
separated into two columns, depending on whether the century is included in the output format (for
example, 06 versus 2006).

Without century With century (yyyy) Output format


(yy) style codes style codes

- 0 or 100 Mmm dd yyyy hh:nnAA

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:sssAA

10 110 mm-dd-yy[yy]

11 111 [yy]yy/mm/dd

12 112 [yy]yymmdd

- 13 or 113 dd Mmm yyyy hh:nn:ss:sss (24 hour clock, Europe de-


fault + milliseconds, 4-digit year )

- 14 or 114 hh:nn:ss:sss (24 hour clock)

- 20 or 120 yyyy-mm-dd hh:nn:ss (24-hour clock, ODBC canonical,


4-digit year)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 173


SQL functions

Without century With century (yyyy) Output format


(yy) style codes style codes

- 21 or 121 yyyy-mm-dd hh:nn:ss.sss (24 hour clock, ODBC canoni-


cal with milliseconds, 4-digit year )

Returns
Depends on the data type specified.

Remarks
If no format-style argument is provided, style code 0 is used.

The CONVERT function can be used to convert a string to a DATE, TIME, or TIMESTAMP data type,
provided that there is no ambiguity when parsing the string. If format-style is specified, the database
server may use it as a hint on how to parse the string. An error is returned if the database server cannot
parse the string unambiguously.

For information about the styles produced by each output symbol (such as Mmm), see “date_format
option” [SQL Anywhere Server - Database Administration].

See also
● “CAST function [Data type conversion]” on page 159
● “CSCONVERT function [String]” on page 183

Standards and compatibility


● SQL/2008 Vendor extension. The CONVERT function is defined in the SQL/2008 standard.
However, in the SQL standard the purpose of CONVERT is to perform a transcoding of the input
string expression to a different character set, which is implemented in SQL Anywhere as the
CSCONVERT function.

Example
The following statements illustrate the use of format style.
SELECT CONVERT( CHAR( 20 ), OrderDate, 104 ) FROM SalesOrders;

OrderDate

16.03.2000

20.03.2000

23.03.2000

25.03.2000

...

SELECT CONVERT( CHAR( 20 ), OrderDate, 7 ) FROM SalesOrders;

174 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

OrderDate

Mar 16, 00

Mar 20, 00

Mar 23, 00

Mar 25, 00

...

The following statement illustrates conversion to an integer, and returns the value 5.
SELECT CONVERT( integer, 5.2 );

CORR function [Aggregate]


Returns the correlation coefficient of a set of number pairs.

Syntax
CORR( dependent-expression, independent-expression )

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

Both dependent-expression and independent-expression are numeric. The function is applied to the set of
(dependent-expression, independent-expression) after eliminating the pairs for which either dependent-
expression or independent-expression is NULL. The following computation is made:

COVAR_POP ( y, x ) / STDDEV_POP ( y ) * STDDEV_POP ( x )

where y represents the dependent-expression and x represents the independent-expression.

See also
● “Aggregate functions” on page 133
● “COVAR_POP function [Aggregate]” on page 181
● “STDDEV_POP function [Aggregate]” on page 346

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 175


SQL functions

Standards and compatibility


● SQL/2008 The CORR function comprises part of optional SQL/2008 language feature T621,
"Enhanced numeric functions".

Example
The following example performs a correlation to discover whether age is associated with income level.
This function returns the value 0.44022675645996.
SELECT CORR( Salary, ( YEAR( NOW( ) ) - YEAR( BirthDate ) ) ) FROM Employees;

COS function [Numeric]


Returns the cosine of the angle in radians given by its argument.

Syntax
COS( numeric-expression )

Parameters
● numeric-expression The angle, in radians.

Returns
This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

See also
● “ACOS function [Numeric]” on page 146
● “COT function [Numeric]” on page 176
● “SIN function [Numeric]” on page 337
● “TAN function [Numeric]” on page 359

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value of the cosine of an angle 0.52 radians.
SELECT COS( 0.52 );

COT function [Numeric]


Returns the cotangent of the angle in radians given by its argument.

Syntax
COT( numeric-expression )

176 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Parameters
● numeric-expression The angle, in radians.

Returns
This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

See also
● “COS function [Numeric]” on page 176
● “SIN function [Numeric]” on page 337
● “TAN function [Numeric]” on page 359

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the cotangent value of 0.52.
SELECT COT( 0.52 );

COUNT function [Aggregate]


Counts the number of rows in a group depending on the specified parameters.

Syntax 1
COUNT( [ * | [ ALL | DISTINCT ] expression ] )

Syntax 2
COUNT( [ * | [ ALL ]expression ] ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● * Return the number of rows in each group. COUNT(*) and COUNT() are semantically equivalent.

● [ ALL ] expression Return the number of rows in each group where the value of expression is not
NULL.

● DISTINCT expression Return the number of distinct values of expression for all of the rows in
each group where expression is not NULL.

Returns
The COUNT function returns a value of type INT.

COUNT never returns the value NULL. If a group contains no rows, or if there are no non-NULL values
of expression in a group, then COUNT returns 0.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 177


SQL functions

Remarks
The COUNT function returns a maximum value of 2147483647. Use the COUNT_BIG function when
counting large result sets, the result might have more rows, or there is a possibility of overflow.

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition in “WINDOW clause” on page 961.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “COUNT( * )” [SQL Anywhere Server - SQL Usage]
● “AVG function [Aggregate]” on page 150
● “SUM function [Aggregate]” on page 355
● “COUNT_BIG function [Aggregate]” on page 179

Standards and compatibility


● SQL/2008 Core feature. When used as a window function (Syntax 2), COUNT comprises part of
optional SQL/2008 language feature T611, "Basic OLAP operations".

The ability to specify DISTINCT over an expression that is not a column reference comprises part of
optional SQL language feature F561, "Full value expressions". SQL Anywhere also supports SQL/
2008 language feature F441, "Extended set function support", which permits operands of aggregate
functions to be arbitrary expressions possibly including outer references to expressions in other query
blocks that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the COUNT function, combined with an outer
reference.

For an example, see “AVG function [Aggregate]” on page 150.

See also
● “Aggregate functions and outer references” [SQL Anywhere Server - SQL Usage]

Example
The following statement returns each unique city, and the number of employees working in that city.
SELECT City, COUNT( * ) FROM Employees GROUP BY City;

178 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

COUNT_BIG function [Aggregate]


Counts the number of rows in a group depending on the specified parameters.

Syntax 1
COUNT_BIG( [ * | [ ALL | DISTINCT ] expression ] )

Syntax 2
COUNT_BIG( [ * | [ ALL ] expression ]) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● * Return the number of rows in each group. COUNT_BIG(*) and COUNT_BIG() are semantically
equivalent.

● [ ALL ] expression Return the number of rows in each group where the value of expression is not
NULL.

● DISTINCT expression Return the number of distinct values of expression for all of the rows in
each group where expression is not NULL.

Returns
COUNT_BIG returns a value of type BIGINT.

COUNT_BIG never returns the value NULL. If a group contains no rows, or if there are no non-NULL
values of expression in a group, then COUNT_BIG returns 0.

Remarks
It is recommended that you use the COUNT_BIG function when counting large result sets, the result
might have more rows, or there is a possibility of overflow. Otherwise, use the COUNT function, which
has a maximum value of 2147483647.

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition in “WINDOW clause” on page 961.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “AVG function [Aggregate]” on page 150
● “SUM function [Aggregate]” on page 355
● “COUNT function [Aggregate]” on page 177

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 179


SQL functions

Standards and compatibility


● SQL/2008 Vendor extension.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the COUNT_BIG function, combined with an outer
reference.

For an example, see “AVG function [Aggregate]” [UltraLite - Database Management and Reference].

See also
● “Aggregate functions and outer references” [SQL Anywhere Server - SQL Usage]

Example
The following statement returns each unique city, and the number of employees working in that city.

SELECT City, COUNT_BIG( * ) FROM Employees GROUP BY City;

COUNT_SET_BITS function [Bit array]


Returns a count of the number of bits set to 1 (TRUE) in the array.

Syntax
COUNT_SET_BITS( bit-expression )

Parameters
● bit-expression The bit array for which to determine the set bits.

Returns
UNSIGNED INT

Remarks
Returns NULL if bit-expression is NULL.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 4:

SELECT COUNT_SET_BITS( '00110011' );

The following statement returns the value 12:

SELECT COUNT_SET_BITS( '0011001111111111' );

180 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

COVAR_POP function [Aggregate]


Returns the population covariance of a set of number pairs.

Syntax 1
COVAR_POP( dependent-expression, independent-expression )

Syntax 2
COVAR_POP( dependent-expression, independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

Both dependent-expression and independent-expression are numeric. The function is applied to the set of
(dependent-expression, independent-expression) pairs after eliminating all pairs for which either
dependent-expression or independent-expression is NULL. The following computation is then made:
( SUM( y * x ) - SUM( x ) * SUM( y ) / n ) / n

where y represents the dependent-expression and x represents the independent-expression.

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition provided in “WINDOW clause” on page 961.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “COVAR_SAMP function [Aggregate]” on page 182
● “SUM function [Aggregate]” on page 355

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 181


SQL functions

Standards and compatibility


● SQL/2008 The COVAR_POP function comprises part of optional SQL/2008 language feature
T621, "Enhanced numeric functions".

Example
The following example measures the strength of association between employees' age and salary. This
function returns the value 73785.84005866687.
SELECT COVAR_POP( Salary, ( YEAR( NOW( ) ) - YEAR( BirthDate ) ) )
FROM Employees;

COVAR_SAMP function [Aggregate]


Returns the sample covariance of a set of number pairs.

Syntax 1
COVAR_SAMP( dependent-expression, independent-expression )

Syntax 2
COVAR_SAMP( dependent-expression, independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

Both dependent-expression and independent-expression are numeric. The function is applied to the set of
(dependent-expression, independent-expression) pairs after eliminating all pairs for which either
dependent-expression or independent-expression is NULL.

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition provided in “WINDOW clause” on page 961.

182 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “COVAR_POP function [Aggregate]” on page 181
● “SUM function [Aggregate]” on page 355

Standards and compatibility


● SQL/2008 The COVAR_SAMP function comprises part of optional SQL/2008 language feature
T621, "Enhanced numeric functions".

Example
The following example returns the value 74782.9460054052.
SELECT COVAR_SAMP( Salary, ( 2008 - YEAR( BirthDate ) ) )
FROM Employees;

CSCONVERT function [String]


Converts strings between character sets.

Syntax
CSCONVERT(
string-expression,
target-charset-string [, source-charset-string [, options ] ] )

Parameters
● string-expression The string to be converted.

● target-charset-string The destination character set. target-charset-string can be any of the SQL
Anywhere supported character set labels. It can also be:

○ os_charset Specify this to use the character set used by the operating system that is hosting the
database server.

○ char_charset Specify this to use the CHAR character set used by the database.

○ nchar_charset Specify this to use the NCHAR character set used by the database.

○ options You can specify one of the following options:

● Read or write a byte order mark (BOM) Specify read_bom=on or read_bom=off to


turn on or off reading byte order marks. Specify write_bom=on or write_bom=off to turn on
or off writing byte order marks. By default, the behavior is read_bom=on and
write_bom=off.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 183


SQL functions

● source-charset-string The character set used for string-expression. The default is db_charset (the
database character set). source-charset-string can be any of the SQL Anywhere supported character
set labels. It can also be:

○ os_charset Specify this to use the character set used by the operating system that is hosting the
database server.

○ char_charset Specify this to use the CHAR character set used by the database.

○ nchar_charset Specify this to use the NCHAR character set used by the database.

Returns
LONG BINARY

Remarks
You can view the list of character sets supported by SQL Anywhere by running the following command:

dbinit -le

For more information about the character set labels you can use with this function, see “Supported
character sets” [SQL Anywhere Server - Database Administration].

See also
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension. In the SQL/2008 standard, conversion of string data from one charset
to another is accomplished with the CONVERT function (not to be confused with the SQL Anywhere
CONVERT function) which has different arguments than CSCONVERT.

Examples
This fragment converts the mytext column from the Traditional Chinese character set to the Simplified
Chinese character set:

SELECT CSCONVERT( mytext, 'cp936', 'cp950' )


FROM mytable;

This fragment converts the mytext column from the database character set to the Simplified Chinese
character set:

SELECT CSCONVERT( mytext, 'cp936' )


FROM mytable;

If a file name is stored in the database, it is stored in the database character set. If the server will read from
or write to a file whose name is stored in a database (for example, in an external stored procedure), the file
name must be explicitly converted to the operating system character set before the file can be accessed.
File names stored in the database and retrieved by the client are converted automatically to the client
character set, so explicit conversion is not necessary.

184 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

This fragment converts the value in the filename column from the database character set to the operating
system character set:
SELECT CSCONVERT( filename, 'os_charset' )
FROM mytable;

A table contains a list of file names. An external stored procedure takes a file name from this table as a
parameter and reads information directly out of that file. The following statement works when character
set conversion is not required:
SELECT MYFUNC( filename )
FROM mytable;

The mytable clause indicates a table with a filename column. However, if you need to convert the file
name to the character set of the operating system, you would use the following statement.
SELECT MYFUNC( csconvert( filename, 'os_charset' ) )
FROM mytable;

CUME_DIST function [Ranking]


Computes the relative position of one value among a group of rows.

Syntax
CUME_DIST( ) OVER ( window-spec )

window-spec : see the Remarks section below

Returns
A DOUBLE value between 0 and 1

Remarks
Composite sort keys are not currently allowed in the CUME_DIST function. You can use composite sort
keys with any of the other rank functions.

Elements of window-spec can be specified either in the function syntax (inline), or in conjunction with a
WINDOW clause in the SELECT statement. When used as a window function, you must specify an
ORDER BY clause, you may specify a PARTITION BY clause, however, you can not specify a ROWS
or RANGE clause. See the window-spec definition provided in “WINDOW clause” on page 961.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 185


SQL functions

See also
● “DENSE_RANK function [Ranking]” on page 206
● “PERCENT_RANK function [Ranking]” on page 292
● “RANK function [Ranking]” on page 303

Standards and compatibility


● SQL/2008 The CUME_DIST function comprises part of optional SQL/2008 language feature
T612, "Advanced OLAP operations".

Example
The following example returns a result set that provides a cumulative distribution of the salaries of
employees who live in California.
SELECT DepartmentID, Surname, Salary,
CUME_DIST() OVER (PARTITION BY DepartmentID
ORDER BY Salary DESC) "Rank"
FROM Employees
WHERE State IN ('CA');

Here is the result set:

DepartmentID Surname Salary Rank

200 Savarino 72300.000 0.333333333333333

200 Clark 45000.000 0.666666666666667

200 Overbey 39300.000 1

DATALENGTH function [System]


Returns the length, in bytes, of the underlying storage for the result of an expression.

Syntax
DATALENGTH( expression )

Parameters
● expression Usually a column name. If expression is a string constant, you must enclose it in
quotes.

Returns
UNSIGNED INT

Remarks
The return values of the DATALENGTH function are as follows:

186 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Data type DATALENGTH

SMALLINT 2

INTEGER 4

DOUBLE 8

CHAR Length of the data

BINARY Length of the data

This function supports NCHAR inputs and outputs.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the length of the longest string in the CompanyName column.
SELECT MAX( DATALENGTH( CompanyName ) )
FROM Customers;

The following statement returns the length of the string '8sdofinsv8s7a7s7gehe4h':


SELECT DATALENGTH( '8sdofinsv8s7a7s7gehe4h' );

DATE function [Date and time]


Converts the expression into a date, and removes any hours, minutes, or seconds.

For information about controlling the interpretation of date formats, see “date_order option” [SQL
Anywhere Server - Database Administration] and “nearest_century option” [SQL Anywhere Server -
Database Administration].

Syntax
DATE( expression )

Returns
DATE

Parameters
● expression The value to be converted to date format, typically a string.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 187


SQL functions

See also
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “DATE data type” on page 107
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “Expressions” on page 12
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP special value” on page 69
● “TIMESTAMP data type” on page 113
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 1999-01-02 as a date.
SELECT DATE( '1999-01-02 21:20:53' );

The following statement returns the create dates of all the objects listed in the SYSOBJECT system view:
SELECT DATE( creation_time ) FROM SYSOBJECT;

DATEADD function [Date and time]


Returns a TIMESTAMP or TIMESTAMP WITH TIME ZONE value produced by adding a date part to
its argument.

Syntax
DATEADD( date-part, integer-expression, timestamp-expression )

date-part :
year
| quarter
| month
| week
| day
| dayofyear
| hour
| minute
| second

188 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

| millisecond
| microsecond

Parameters
● date-part The date part that integer-expression represents.

For a complete listing of allowed date parts, see “Specifying date parts” on page 136.

● integer-expression The number of date-part values to be added to timestamp-expression. Note


that integer-expression can be any numeric type, but its value is truncated to an INTEGER.

● timestamp-expression The TIMESTAMP or TIMESTAMP WITH TIME ZONE value to be


modified.

Returns
TIMESTAMP WITH TIME ZONE if timestamp-expression is a TIMESTAMP WITH TIME ZONE;
otherwise TIMESTAMP.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the TIMESTAMP value 1995-11-02 00:00:00.000.
SELECT DATEADD( month, 102, '1987/05/02' );

The following statement returns the TIMESTAMP value 1987-05-02 04:00:00.000.


SELECT DATEADD( hour, 4, '1987/05/02' );

The following statement returns the TIMESTAMP WITH TIME ZONE value 1987-05-06
11:33:00.000+04:00
SELECT DATEADD( day, 4, CAST( '1987/05/02 11:33:00.000000+04:00' as
TIMESTAMP WITH TIME ZONE ));

DATEDIFF function [Date and time]


Returns the interval between two dates.

Syntax
DATEDIFF( date-part, date-expression-1, date-expression-2 )

date-part :
year
| quarter
| month
| week
| day

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 189


SQL functions

| dayofyear
| hour
| minute
| second
| millisecond
| microsecond

Parameters
● date-part Specifies the date part in which the interval is to be measured.

Choose one of the date objects listed above. For a complete list of date parts, see “Specifying date
parts” on page 136.

● date-expression-1 The starting date for the interval. This value is subtracted from date-
expression-2 to return the number of date-parts between the two arguments.

● date-expression-2 The ending date for the interval. Date-expression-1 is subtracted from this
value to return the number of date-parts between the two arguments.

Returns
INT with year, quarter, month, week, day, and dayofyear. BIGINT with hour, minute, second,
millisecond, and microsecond.

Remarks
This function calculates the number of date parts between two specified dates. The result is a signed
integer value equal to (date-expression-2 - date-expression-1), in date parts.

The DATEDIFF function 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, the DATEDIFF function 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, the DATEDIFF function 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, the DATEDIFF function returns the number of Sundays between the
two dates, including the second date but not the first.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
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' );

190 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

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' );

DATEFORMAT function [Date and time]


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 about date format descriptions, see “timestamp_format option” [SQL Anywhere
Server - Database Administration].

This function supports NCHAR inputs and/or outputs.

Returns
VARCHAR

Remarks
Any allowable date format can be used for the string-expression.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value Jan 01, 1989.
SELECT DATEFORMAT( '1989-01-01', 'Mmm dd, yyyy' );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 191


SQL functions

DATENAME function [Date and time]


Returns the name of the specified part (such as the month June) of a TIMESTAMP or TIMESTAMP
WITH TIME ZONE value, as a character string.

Syntax
DATENAME( date-part, timestamp-expression )

Parameters
● date-part The date part to be named.

For a complete listing of allowed date parts, see “Specifying date parts” on page 136.

● timestamp-expression The TIMESTAMP or TIMESTAMP WITH TIME ZONE value for which
the date part name is to be returned. For meaningful results, timestamp-expression should contain the
requested date-part.

Returns
VARCHAR

Remarks
The DATENAME function returns a string, even if the result is numeric, such as 23 for the day. When the
date part TZOffset is specified, DATENAME returns the offset as a string of the form: { + | - }hh:nn.

See also
● “DATEPART function [Date and time]” on page 192

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value May.
SELECT DATENAME( month, '1987/05/02' );

DATEPART function [Date and time]


Returns a portion of a TIMESTAMP or TIMESTAMP WITH TIME ZONE value.

Syntax
DATEPART( date-part, timestamp-expression )

Parameters
● date-part The date part to be returned.

192 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

For a complete listing of allowed date parts, see “Specifying date parts” on page 136.

● timestamp-expression The TIMESTAMP or TIMESTAMP WITH TIME ZONE value for which
the part is to be returned.

Returns
INT

Remarks
For meaningful results timestamp-expression should contain the required date-part portion.

The numbers that correspond to week days depend on the setting of the first_day_of_week option. By
default Sunday=7.

See also
● “first_day_of_week option” [SQL Anywhere Server - Database Administration]
● “SET statement [T-SQL]” on page 901

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 5.

SELECT DATEPART( month , '1987/05/02' );

The following example creates a table, TableStatistics, and inserts into it the total number of sales orders
per year as stored in the SalesOrders table:

CREATE TABLE TableStatistics (


ID INTEGER NOT NULL DEFAULT AUTOINCREMENT,
Year INT,
NumberOrders INT );
INSERT INTO TableStatistics ( Year, NumberOrders )
SELECT DATEPART( Year, OrderDate ), COUNT(*)
FROM SalesOrders
GROUP BY DATEPART( Year, OrderDate );

DATETIME function [Date and time]


Converts an expression into a TIMESTAMP value.

Syntax
DATETIME( expression )

Parameters
● expression The expression to be converted. It is generally a string.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 193


SQL functions

Returns
TIMESTAMP

Remarks
Attempts to convert numerical values return an error.

See also
● “Expressions” on page 12
● “CAST function [Data type conversion]” on page 159
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIMEOFFSET data type” on page 109
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP special value” on page 69
● “TIMESTAMP data type” on page 113
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns a timestamp with value 1998-09-09 12:12:12.000.
SELECT DATETIME( '1998-09-09 12:12:12.000' );

DAY function [Date and time]


Returns the day of the month of its argument as an integer between 1 and 31.

Syntax
DAY( date-expression )

Parameters
● date-expression The date as a DATE data type.

Returns
SMALLINT

194 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Remarks
The DAY function returns an integer between 1 and 31, corresponding to the day of the month in the
argument.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 12.
SELECT DAY( '2001-09-12' );

DAYNAME function [Date and time]


Returns the name of the day of the week from a date.

Syntax
DAYNAME( date-expression )

Parameters
● date-expression The date.

Returns
VARCHAR

Remarks
The English names are returned as: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value Saturday.
SELECT DAYNAME ( '1987/05/02' );

DAYS function [Date and time]


The DAYS function manipulates a TIMESTAMP, or returns the number of days between two
TIMESTAMP values. For specific details, see the Remarks section below.

Syntax 1
DAYS( timestamp-expression )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 195


SQL functions

Syntax 2
DAYS( timestamp-expression, timestamp-expression )

Syntax 3
DAYS( timestamp-expression, integer-expression )

Parameters
● timestamp-expression A TIMESTAMP value.

● integer-expression The number of days to be added to the timestamp-expression. If the integer-


expression is negative, the appropriate number of days is subtracted from timestamp-expression. If
you supply an integer expression, the timestamp-expression must be explicitly cast as a TIME, DATE
or TIMESTAMP. If timestamp-expression is a TIME value, the current date is assumed.

For information about casting data types, see “CAST function [Data type conversion]” on page 159.

Returns
INTEGER with Syntax 1 or Syntax 2.

TIMESTAMP with Syntax 3.

Remarks
The result of the DAYS function depends on its arguments. The DAYS function ignores hours, minutes,
and seconds in its arguments.

● Syntax 1 If you pass a single timestamp-expression to the DAYS function, it will return the
number of days between 0000-02-29 and timestamp-expression as an INTEGER.

Note
0000-02-29 is not meant to imply an actual date; it is the default date used by the DAYS function.

● Syntax 2 If you pass two TIMESTAMP values to the DAYS function, the function returns the
integer number of days between them.

● Syntax 3 If you pass a TIMESTAMP value and an integer to the DAYS function, the function
returns the TIMESTAMP result of adding the integer number of days to the timestamp-expression
argument.

Instead of Syntax 2, use the DATEDIFF function. Instead of Syntax 3, use the DATEADD function.

See also
● “DATEDIFF function [Date and time]” on page 189
● “DATEADD function [Date and time]” on page 188

Standards and compatibility


● SQL/2008 Vendor extension.

196 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example
The following statement returns the integer 729889.

SELECT DAYS( '1998-07-13 06:07:12' );

The following statements return the integer value -366, indicating that the second DATE value is 366
days before the first. It is recommended that you use the second example (DATEDIFF).

SELECT DAYS( '1998-07-13 06:07:12',


'1997-07-12 10:07:12' );

SELECT DATEDIFF( day,


'1998-07-13 06:07:12',
'1997-07-12 10:07:12' );

The following statements return the TIMESTAMP value 1999-07-14 00:00:00.000. It is recommended
that you use the second example (DATEADD).

SELECT DAYS( CAST('1998-07-13' AS DATE ), 366 );

SELECT DATEADD( day, 366, '1998-07-13' );

DB_EXTENDED_PROPERTY function [System]


Returns the value of the given property. Allows an optional property-specific string parameter to be
specified.

Syntax
DB_EXTENDED_PROPERTY(
{ property-id | property-name }
[, property-specific-argument
[, database-id | database-name ] ]
)

Parameters
● property-id The database property ID to query.

● property-name The database property name to query.

For a complete list of database properties, see “Accessing database property values” [SQL Anywhere
Server - Database Administration].

● property-specific-argument The following database properties allow you to specify additional


arguments, as noted below, to return specific information about the property.

○ CharSet property Specify the name of a standard to obtain the default CHAR character set
label for the standard. Possible values you can specify are: ASE, IANA, MIME, JAVA,
WINDOWS, UTR22, IBM, and ICU. If no standard is specified, IANA is used as the default,
unless the database connection was made through TDS, in which case ASE is the default.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 197


SQL functions

○ CatalogCollation, Collation, and NcharCollation properties When querying these


properties, the following values can be specified as a property-specific-argument to return
information specific to the collation:

● AccentSensitive Specify AccentSensitive to obtain the accent sensitivity setting for the
collation. For example, the following statement returns the accent sensitivity setting for the
NCHAR collation:
SELECT DB_EXTENDED_PROPERTY( 'NcharCollation', 'AccentSensitive');

Possible return values are: Ignore, Respect, and French. For more information, see “Collation
tailoring options” [SQL Anywhere Server - Database Administration].

● CaseSensitivity Specify CaseSensitivity to obtain the case sensitivity setting for the
collation. Possible return values are: Ignore, Respect, UpperFirst, and LowerFirst. For more
information, see “Collation tailoring options” [SQL Anywhere Server - Database
Administration].

● PunctuationSensitivity Specify PunctuationSensitivity to obtain the punctuation


sensitivity setting for the collation. Possible return values are: Ignore, Primary, and
Quaternary. For more information, see “Collation tailoring options” [SQL Anywhere Server -
Database Administration].

● Properties Specify Properties to obtain a string containing all the tailoring options
specified for the collation. For information about the keywords and values in the returned
string, see “Collation tailoring options” [SQL Anywhere Server - Database Administration].

● Specification Specify Specification to obtain a string containing the full collation


specification used for the collation. For information about the keywords and values in the
returned string, see “Collation tailoring options” [SQL Anywhere Server - Database
Administration].

○ DriveType property Specify the name of a dbspace, or the file ID for the dbspace, to obtain its
drive type. The value returned is one of the following: CD, FIXED, RAMDISK, REMOTE,
REMOVABLE, or UNKNOWN. If nothing is specified, the drive type of the system dbspace is
returned. If the specified dbspace doesn't exist, the property function returns NULL. If the name of
a dbspace is specified and the ID of a database that isn't the database of the current connection is
also specified, the function also returns NULL.

○ File property Specify a dbspace name to obtain the file name of the database root file,
including the path. If nothing is specified, information for the system dbspace is returned. If the
specified file doesn't exist, the function returns NULL.

○ FileSize property Specify the name of a dbspace, or the file ID for the dbspace, to obtain the
size of the specified file in pages. You can also specify temporary to return the size of the
temporary dbspace, or translog to return the size of the log file. If nothing is specified, the size of
the system dbspace is returned. If the specified file doesn't exist, the function returns NULL.

○ FreePages property Specify the name of a dbspace, or the file ID for the dbspace, to obtain
the number of free pages. You can also specify temporary to return the number of free pages in the

198 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

temporary dbspace, or translog to return the number of free pages in the log file. If nothing is
specified, the number of free pages in the system dbspace is returned. If the specified file doesn't
exist, the function returns NULL.

○ IOParallelism property Specify a dbspace name to obtain the estimated number of


simultaneous I/O operations supported by the dbspace. If a dbspace is not specified, the current
system dbspace is used.

○ MirrorServerState property Specify a server name to determine the connection status of the
mirror server. Returns CONNECTED, DISCONNECTED, INCOMING ONLY, OUTGOING
ONLY, or NULL.

○ MirrorState property Specify a server name to determine the synchronization status of the
mirror server. Returns SYNCHRONIZING, SYNCHRONIZED, or NULL.

○ NextScheduleTime property Specify an event name to obtain its next scheduled execution
time.

● database-id The database ID number, as returned by the DB_ID function. Typically, the database
name is used.

● database-name The name of the database, as returned by the DB_NAME function.

Returns
VARCHAR

Remarks
Cloud note: Because of tenant database isolation rules, when this function is called in the cloud it
returns only information about the current tenant database.

The DB_EXTENDED_PROPERTY function is similar to the DB_PROPERTY function except that it


allows an optional property-specific-argument string parameter to be specified. The interpretation of
property-specific-argument depends on the property ID or name specified in the first argument.

The current database is used if the third argument is omitted.

When comparing catalog strings such as table names and procedure names, the database server uses the
CHAR collation. For the UCA collation, the catalog collation is the same as the CHAR collation but with
the tailoring changed to be case-insensitive, accent-insensitive and with punctuation sorted in the primary
level. For legacy collations, the catalog collation is the same as the CHAR collation but with the tailoring
changed to be case-insensitive. While you cannot explicitly specify the tailoring used for the catalog
collation, you can query the Specification property to obtain the full collation specification used by the
database server for comparing catalog strings. Querying the Specification property can be useful if you
need to exploit the difference between the CHAR and catalog collations. For example, suppose you have a
punctuation-insensitive CHAR collation and you want to execute an upgrade script that defines a
procedure called my_procedure, and that also attempts to delete an old version named myprocedure. The
following statements cannot achieve the desired results because my_procedure is equivalent to
myprocedure, using the CHAR collation:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 199


SQL functions

CREATE PROCEDURE my_procedure( ) ...;


IF EXISTS ( SELECT * FROM SYS.SYSPROCEDURE WHERE proc_name = 'myprocedure' )
THEN DROP PROCEDURE myprocedure
END IF;

Instead, you could execute the following statements to achieve the desired results:
CREATE PROCEDURE my_procedure( ) ...;
IF EXISTS ( SELECT * FROM SYS.SYSPROCEDURE
WHERE COMPARE( proc_name, 'myprocedure',
DB_EXTENDED_PROPERTY( 'CatalogCollation', 'Specification' ) ) = 0 )
THEN DROP PROCEDURE myprocedure
END IF;

See also
● “DB_ID function [System]” on page 201
● “DB_NAME function [System]” on page 201
● “Accessing database property values” [SQL Anywhere Server - Database Administration]
● “CONNECTION_PROPERTY function [System]” on page 171
● “CONNECTION_EXTENDED_PROPERTY function [String]” on page 169

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the location of the current database:

SELECT DB_EXTENDED_PROPERTY( 'File' );

The following statement returns the file size of the system dbspace, in pages.
SELECT DB_EXTENDED_PROPERTY( 'FileSize' );

The following statement returns the file size of the transaction log, in pages.
SELECT DB_EXTENDED_PROPERTY( 'FileSize', 'translog' );

The following statement returns the case sensitivity setting for the NCHAR collation:
SELECT DB_EXTENDED_PROPERTY( 'NcharCollation',' CaseSensitivity' );

The following statement returns the tailoring options specified for the database CHAR collation:
SELECT DB_EXTENDED_PROPERTY ( 'Collation', 'Properties' );

The following statement returns the full collation specification for the database NCHAR collation:
SELECT DB_EXTENDED_PROPERTY( 'NcharCollation', 'Specification' );

The following statement returns the connection status of the mirror server Test:
SELECT DB_EXTENDED_PROPERTY( 'MirrorServerState', 'Test' );

The following statement returns the synchronization status of the mirror server Test:

200 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

SELECT DB_EXTENDED_PROPERTY( 'MirrorState', 'Test' );

DB_ID function [System]


Returns the database ID number.

Cloud note: Because of tenant database isolation rules, when this function is called in the cloud it
returns only information about the current tenant database.

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.

Returns
INT

See also
● “global_database_id option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The statement returns the value 0, when executed against the SQL Anywhere sample database as the sole
database on the server.
SELECT DB_ID( 'demo' );

The following statement returns the value 0 if executed against the only running database.
SELECT DB_ID( );

DB_NAME function [System]


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.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 201


SQL functions

Returns
VARCHAR

Remarks
If no database ID is supplied, the name of the current database is returned.

Cloud note: Because of tenant database isolation rules, when this function is called in the cloud it
returns only information about the current tenant database.

See also
● “sa_db_list system procedure” on page 1031
● “NEXT_DATABASE function [System]” on page 282

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The statement returns the database name demo when executed against the SQL Anywhere sample
database as the sole database on the server.

SELECT DB_NAME( 0 );

DB_PROPERTY function [System]


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 the DB_ID function. Typically, the database
name is used.

● database-name The name of the database, as returned by the DB_NAME function.

Returns
VARCHAR, LONG VARCHAR

202 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Remarks
Returns a string. The current database is used if the second argument is omitted.

Cloud note: Because of tenant database isolation rules, when this function is called in the cloud it
returns only information about the current tenant database.

See also
● “DB_ID function [System]” on page 201
● “DB_NAME function [System]” on page 201
● “Accessing database property values” [SQL Anywhere Server - Database Administration]
● “PROPERTY function [System]” on page 297

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the page size of the current database, in bytes.

SELECT DB_PROPERTY( 'PageSize' );

DECOMPRESS function [String]


Decompresses the string and returns a LONG BINARY value.

Syntax
DECOMPRESS( string-expression [, compression-algorithm-alias] )

Parameters

● string-expression The string to decompress. Binary values can also be passed to this function.
This parameter is case sensitive, even in case-insensitive databases.

● compression-algorithm-alias Alias (string) for the algorithm to use for decompression. The
supported values are zip and gzip (both are based on the same algorithm, but use different headers and
trailers).

Zip is a widely supported compression algorithm. Gzip is compatible with the gzip utility on Unix,
whereas the zip algorithm is not.

If no algorithm is specified, the function attempts to detect which algorithm was used to compress the
string. If the incorrect algorithm is specified, or the correct algorithm cannot be detected, the string is
not decompressed.

For more information about compression, see “COMPRESS function [String]” on page 166.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 203


SQL functions

Returns
LONG BINARY

Remarks
This function can be used to decompress a value that was compressed using the COMPRESS function.

You do not need to use the DECOMPRESS function on values that are stored in a compressed column.
Compression and decompression of values in a compressed column are handled automatically by the
database server.

See also
● “Column compression considerations” [SQL Anywhere Server - Database Administration]
● “COMPRESS function [String]” on page 166
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example uses the DECOMPRESS function to decompress values from the Attachment
column of a fictitious table, TableA:
SELECT DECOMPRESS ( Attachment, 'gzip' )
FROM TableA;

Since DECOMPRESS returns binary values, if the original values were of a character type, such as
LONG VARCHAR, a CAST can be applied to return human-readable values:
SELECT CAST ( DECOMPRESS ( Attachment, 'gzip' )
AS LONG VARCHAR ) FROM TableA;

DECRYPT function [String]


Decrypts the string using the supplied key and returns a LONG BINARY value.

Syntax
DECRYPT( string-expression, key
[, algorithm ]
)

algorithm :
'AES'
| 'AES256'
| 'AES_FIPS'
| 'AES256_FIPS'

204 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Parameters
● string-expression The string to be decrypted. Binary values can also be passed to this function.
This parameter is case sensitive, even in case-insensitive databases.

● key The encryption key (string) required to decrypt the string-expression. This must be the same
encryption key that was used to encrypt the string-expression to obtain the original value that was
encrypted. This parameter is case sensitive, even in case-insensitive databases.

Caution
For strongly encrypted databases, be sure to store a copy of the key in a safe location. If you lose the
encryption key there is no way to access the data, even with the assistance of technical support. The
database must be discarded and you must create a new database.

● algorithm This optional parameter specifies the algorithm originally used to encrypt the string-
expression.

Returns
LONG BINARY

Remarks
For more information about the supported encryption algorithms, see “ENCRYPT function [String]”
on page 210.

You can use the DECRYPT function to decrypt a string-expression that was encrypted with the
ENCRYPT function. This function returns a LONG BINARY value with the same number of bytes as the
input string.

To successfully decrypt a string-expression, you must use the same encryption key that was used to
encrypt the data. If you specify an incorrect encryption key, an error is generated. A lost key will result in
inaccessible data, from which there is no recovery.

Note
Not all platforms support FIPS-certified encryption. For a list of supported platforms, see http://
www.sybase.com/detail?id=1061806.

See also
● “ENCRYPT function [String]” on page 210
● “ISENCRYPTED function [System]” on page 252
● “Database portion encryption” [SQL Anywhere Server - Database Administration]
● “String functions” on page 142
● “-fips dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 205


SQL functions

Example
The following example decrypts a user's password from the user_info table. The CAST function is used to
convert the password back to a CHAR data type because the DECRYPT function converts values to the
LONG BINARY data type, which is unreadable.
SELECT CAST( DECRYPT( user_pwd, '8U3dkA' ) AS CHAR(100) ) FROM user_info;

DEGREES function [Numeric]


Converts a number from radians to degrees.

Syntax
DEGREES( numeric-expression )

Parameters
● numeric-expression An angle in radians.

Returns
DOUBLE

Remarks
This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns the degrees of the angle given by numeric-expression. If the parameter is
NULL, the result is NULL.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 29.79380534680281.
SELECT DEGREES( 0.52 );

DENSE_RANK function [Ranking]


Calculates the rank of a value in a partition. For tied values, the DENSE_RANK function does not leave
gaps in the ranking sequence.

Syntax
DENSE_RANK( ) OVER ( window-spec )

window-spec : see the Remarks section below

206 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Returns
INTEGER

Remarks
Elements of window-spec can be specified either in the function syntax (inline), or in conjunction with a
WINDOW clause in the SELECT statement. When used as a window function, you must specify an
ORDER BY clause, you may specify a PARTITION BY clause, however, you can not specify a ROWS
or RANGE clause. More information is available in the window-spec definition of the WINDOW clause.

See also
● “WINDOW clause” on page 961
● “CUME_DIST function [Ranking]” on page 185
● “PERCENT_RANK function [Ranking]” on page 292
● “RANK function [Ranking]” on page 303
● “Window functions” [SQL Anywhere Server - SQL Usage]
● “Window definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server -
SQL Usage]

Standards and compatibility


● SQL/2008 The DENSE_RANK function comprises part of optional SQL/2008 language feature
T612, "Advanced OLAP operations".

SQL Anywhere supports SQL/2008 language feature F441, "Extended set function support", which
permits operands of window functions to be arbitrary expressions that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the DENSE_RANK function, combined with an
outer reference. For an example, see “AVG function [Aggregate]” [UltraLite - Database Management
and Reference].

Example
The following example returns a result set that provides a ranking of the employees' salaries in Utah and
New York. Although 19 records are returned in the result set, only 18 rankings are listed because of a 7th-
place tie between the 7th and 8th employee in the list, who have identical salaries. Instead of ranking the
9th employee as '9', the employee is listed as '8' because the DENSE_RANK function does not leave gaps
in the ranks.
SELECT DepartmentID, Surname, Salary, State,
DENSE_RANK() OVER (ORDER BY Salary DESC) AS SalaryRank
FROM Employees
WHERE State IN ('NY','UT');

Here is the result set:

DepartmentID Surname Salary State SalaryRank

100 Shishov 72995.000 UT 1

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 207


SQL functions

DepartmentID Surname Salary State SalaryRank

100 Wang 68400.000 UT 2

100 Cobb 62000.000 UT 3

400 Morris 61300.000 UT 4

300 Davidson 57090.000 NY 5

200 Martel 55700.000 NY 6

400 Blaikie 54900.000 NY 7

100 Diaz 54900.000 UT 7

100 Driscoll 48023.000 UT 8

400 Hildebrand 45829.000 UT 9

100 Whitney 45700.000 NY 10

100 Guevara 42998.000 NY 11

100 Soo 39075.000 NY 12

200 Goggin 37900.000 UT 13

400 Wetherby 35745.000 NY 14

400 Ahmed 34992.000 NY 15

500 Rebeiro 34576.000 UT 16

300 Bigelow 31200.000 UT 17

500 Lynch 24903.000 UT 18

DIFFERENCE function [String]


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.

208 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

● string-expression-2 The second SOUNDEX argument.

Returns
SMALLINT

Remarks
The DIFFERENCE function compares the SOUNDEX values of two strings and evaluates the similarity
between them, returning a value from 0 through 4, where 4 is the best match.

This function always returns some value. The result is NULL only if one of the arguments are NULL.

See also
● “SOUNDEX function [String]” on page 342
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns similarity between the words test and chest:
SELECT DIFFERENCE( 'test', 'chest' );

DOW function [Date and time]


Returns a number from 1 to 7 representing the day of the week of a date, where Sunday=1, Monday=2,
and so on.

Syntax
DOW( date-expression )

Parameters
● date-expression The value (of type DATE) to be evaluated.

Returns
SMALLINT

Remarks
The DOW function is not affected by the value specified for the first_day_of_week database option. For
example, even if first_day_of_week is set to Monday, the DOW function returns a 2 for Monday.

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 209


SQL functions

Example
The following statement returns the value 5.
SELECT DOW( '1998-07-09' );

The following statement returns the value 1.


SELECT DOW( CAST( '2010/05/30 11:33:00.000000+04:00' as TIMESTAMP WITH TIME
ZONE ));

The following statement queries the Employees table and returns the employees StartDate, expressed as
the number of the day of the week:
SELECT DOW( StartDate ) FROM Employees;

ENCRYPT function [String]


Encrypts the specified values using the supplied encryption key and returns a LONG BINARY value.

Syntax
ENCRYPT( string-expression, key
[, algorithm ]
)

algorithm :
'AES'
| 'AES256'
| 'AES_FIPS'
| 'AES256_FIPS'

Parameters
● string-expression The data to be encrypted. Binary values can also be passed to this function.
This parameter is case sensitive, even in case-insensitive databases.

● key The encryption key used to encrypt the string-expression. This same key must be used to
decrypt the value to obtain the original value. This parameter is case sensitive, even in case-insensitive
databases.

As with most passwords, it is best to choose a key value that cannot be easily guessed. It is
recommended that you choose a value for your key that is at least 16 characters long, contains a mix
of uppercase and lowercase, and includes numbers, letters and special characters. You will require this
key each time you want to decrypt the data.

Caution
For strongly encrypted databases, be sure to store a copy of the key in a safe location. If you lose the
encryption key there is no way to access the data, even with the assistance of technical support. The
database must be discarded and you must create a new database.

● algorithm This optional parameter specifies the algorithm to use when encrypting string-
expression. The algorithm used for strong encryption is Rijndael: a block encryption algorithm chosen

210 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

as the new Advanced Encryption Standard (AES) for block ciphers by the National Institute of
Standards and Technology (NIST).

You can specify one of the FIPS-certified algorithms for algorithm on any platform that supports
FIPS-certified encryption.

Note
RSA, ECC, and FIPS-certified encryption are not available on all platforms. For information about
which platforms support which encryption method, see http://www.sybase.com/detail?id=1061806.

If algorithm is not specified, AES is used by default. If the database server was started using the -fips
server option, AES_FIPS is used as the default instead.

Returns
LONG BINARY

Remarks
The LONG BINARY value returned by this function is at most 31 bytes longer than the input string-
expression. The value returned by this function is not human-readable. You can use the DECRYPT
function to decrypt a string-expression that was encrypted with the ENCRYPT function. To successfully
decrypt a string-expression, you must use the same encryption key and algorithm that were used to
encrypt the data. If you specify an incorrect encryption key, an error is generated. A lost key will result in
inaccessible data, from which there is no recovery.

If you are storing encrypted values in a table, the column should be BINARY or LONG BINARY so that
character set conversion is not performed on the data.

See also
● “DECRYPT function [String]” on page 204
● “ISENCRYPTED function [System]” on page 252
● “Database portion encryption” [SQL Anywhere Server - Database Administration]
● “-fips dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following trigger encrypts the user_pwd column of the user_info table. This column contains users'
passwords, and the trigger fires whenever the password value is changed.

CREATE TRIGGER encrypt_updated_pwd


BEFORE UPDATE OF user_pwd
ON user_info
REFERENCING NEW AS new_pwd
FOR EACH ROW
BEGIN
SET new_pwd.user_pwd=ENCRYPT( new_pwd.user_pwd, '8U3dkA' );
END;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 211


SQL functions

ERRORMSG function [Miscellaneous]


Provides the error message for the current error, or for a specified SQLSTATE or SQLCODE value.

Syntax
ERRORMSG( [ sqlstate | sqlcode ] )

sqlstate: string

sqlcode: integer

Parameters
● sqlstate The SQLSTATE value for which the error message is to be returned.

● sqlcode The SQLCODE value for which the error message is to be returned.

Returns
VARCHAR containing the error message.

Remarks
If no argument is supplied, the error message for the current state is supplied. Any substitutions (such as
table names and column names) are made.

If an argument is supplied, the error message for the supplied SQLSTATE or SQLCODE is returned, with
no substitutions. Table names and column names are supplied as placeholders (%1).

See also
● “SQL Anywhere error messages sorted by SQLSTATE” [Error Messages]
● “SQL Anywhere error messages sorted by SQLCODE” [Error Messages]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the error message for SQLCODE -813.
SELECT ERRORMSG( -813 );

ESTIMATE function [Miscellaneous]


Returns selectivity estimates as a percentage calculated by the query optimizer, based on specified
parameters.

Syntax
ESTIMATE( column-name [, value [, relation-string ] ] )

212 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Parameters
● column-name The column used in the estimate.

● value The value to which the column is compared. The default is NULL.

● relation-string The comparison operator used for the comparison, enclosed in single quotes.
Possible values for this parameter are: '=' , '>' , '<' , '>=' , '<=' , '<>' , '!=' , '!<' , and '!>'. The default is
'='.

Returns
REAL

Remarks
This function returns selectivity estimates for the predicate column-name relation-string
value. If value is NULL and the relation string is '=', the selectivity is for the predicate column-name
IS NULL. If value is NULL and the relation string is '!=' or '<>', the selectivity is for the predicate
column-name IS NOT NULL.

See also
● “Selectivity estimate sources” [SQL Anywhere Server - SQL Usage]
● “Selectivity information in the graphical plan” [SQL Anywhere Server - SQL Usage]
● “INDEX_ESTIMATE function [Miscellaneous]” on page 249
● “ESTIMATE_SOURCE function [Miscellaneous]” on page 213
● “EXPERIENCE_ESTIMATE function [Miscellaneous]” on page 220

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the percentage of EmployeeID values estimated to be greater than 200.
The precise value depends on the actions you have carried out on the database.
SELECT FIRST ESTIMATE( EmployeeID, 200, '>' )
FROM Employees
ORDER BY 1;

ESTIMATE_SOURCE function [Miscellaneous]


Provides the source for selectivity estimates used by the query optimizer.

Syntax
ESTIMATE_SOURCE(
column-name
[, value
[, relation-string ] ]
)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 213


SQL functions

Parameters
● column-name The name of the column that is being investigated.

● value The value to which the column is compared. The default is NULL.

● relation-string The comparison operator used for the comparison, enclosed in single quotes.
Possible values for this parameter are: '=' , '>' , '<' , '>=' , '<=' , '<>' , '!=' , '!<' , and '!>'. The default is
'='.

Returns
The following list shows the selectivity estimate sources that ESTIMATE_SOURCE returns. For more
information about the sources, see “Selectivity estimate sources” [SQL Anywhere Server - SQL Usage].

Value Selectivity estimate source

Statistics Stored column statistics

Column Average of all values stored in the column statistics

Index Index probes

Guess Built-in guesses that are defined for each type of predicate. This is returned only when
there is no relevant index to use, no statistics have been collected for the referenced col-
umns, or the predicate is a complex predicate.

Computed Other sources than the ones described above

Always Returned when the specified predicate is always true

Combined One or more of the above sources

Bounded Returned when there are upper and/or lower bounds placed on the selectivity estimate

Remarks
This function returns the source of the selectivity estimate for the predicate column-name
relation-string value. If value is NULL and the relation string is '=', the selectivity source is for
the predicate column-name IS NULL. If value is NULL and the relation string is '!=' or '<>', the
selectivity source is for the predicate column-name IS NOT NULL.

See also
● “Selectivity estimate sources” [SQL Anywhere Server - SQL Usage]
● “ESTIMATE function [Miscellaneous]” on page 212
● “INDEX_ESTIMATE function [Miscellaneous]” on page 249

Standards and compatibility


● SQL/2008 Vendor extension.

214 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example
The following statement returns the selectivity source Index for evaluating whether the first value in the
EmployeeID column is greater than 200. Returning Index means that the query optimizer used an index to
estimate the selectivity.
SELECT FIRST ESTIMATE_SOURCE( EmployeeID, 200, '>' )
FROM Employees
ORDER BY 1;

EVENT_CONDITION function [System]


Specifies 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... Comments

DBFreePercent n/a DBDiskSpace

DBFreeSpace MB DBDiskSpace

DBSize MB GrowDB

ErrorNumber n/a RAISERROR

IdleTime seconds ServerIdle

Interval seconds All Time since handler last executed

LogFreePercent n/a LogDiskSpace

LogFreeSpace MB LogDiskSpace

LogSize MB GrowLog

RemainingValues integer GlobalAutoincrement The number of remaining values

TempFreePercent n/a TempDiskSpace

TempFreeSpace MB TempDiskSpace

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 215


SQL functions

Condition name Units Valid for... Comments

TempSize MB GrowTemp

Returns
INT

Remarks
The EVENT_CONDITION function returns NULL when not called from an event.

See also
● “CREATE EVENT statement” on page 526

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following event definition uses the EVENT_CONDITION function:

CREATE EVENT LogNotifier


TYPE LogDiskSpace
WHERE event_condition( 'LogFreePercent' ) < 50
HANDLER
BEGIN
MESSAGE 'LogNotifier message'
END;

EVENT_CONDITION_NAME function [System]


Lists the possible parameters for EVENT_CONDITION.

Syntax
EVENT_CONDITION_NAME( integer )

Parameters
● integer Must be greater than or equal to zero.

Returns
VARCHAR

Remarks
You can use the EVENT_CONDITION_NAME function to obtain a list of all arguments for the
EVENT_CONDITION function by looping over integers until the function returns NULL.

The EVENT_CONDITION_NAME function returns NULL when not called from an event.

216 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “CREATE EVENT statement” on page 526

Standards and compatibility


● SQL/2008 Vendor extension.

EVENT_PARAMETER function [System]


Provides context information for event handlers.

Syntax
EVENT_PARAMETER( context-name )

context-name :
AppInfo
| ConnectionID
| DisconnectReason
| EventName
| Executions
| MirrorServerName
| NumActive
| ScheduleName
| SQLCODE
| TableName
| User
| condition-name

Parameters
● context-name One of the preset strings. The strings must be quoted, are case insensitive, and carry
the following information:

○ AppInfo The value of the AppInfo connection property for the connection that caused the event
to be triggered. Use the following statement to see the value of the property outside the context of
the event:
SELECT CONNECTION_PROPERTY( 'AppInfo' );

The AppInfo string contains the computer name and application name of the client connection for
embedded SQL, ODBC, OLE DB, ADO.NET, and SQL Anywhere JDBC driver connections.

○ ConnectionID The connection ID of the connection that caused the event to be triggered.

○ DisconnectReason A string indicating the reason the connect was terminated. This parameter
is valid only for Disconnect events. Possible results include:

● abnormal A disconnect occurred as a result of the client application terminating


abnormally before disconnecting from the database, or as a result of a communication failure
between the client and server computers.

● connect failed A connection attempt failed.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 217


SQL functions

● drop connection A DROP CONNECTION statement was executed.

● from client The client application disconnected.

● inactive No requests were received for the period specified by the -ti server option.

● liveness No liveness packets were received for the period specified by the -tl server option.

○ EventName The name of the event that has been triggered.

○ Executions The number of times the event handler has been executed.

○ MirrorServerName The name of the mirror or arbiter server that lost its connection to the
primary server in a database mirroring system.

○ NumActive The number of active instances of an event handler. This is useful if you want to
limit an event handler so that only one instance executes at any given time.

○ ScheduleName The name of the schedule which caused an event to be fired. If the event was
fired manually using TRIGGER EVENT or as a system event, the result will be an empty string. If
the schedule was not assigned a name explicitly when it was created, its name is the name of the
event.

○ SQLCODE The SQLCODE of the error that occurred during a failed connection. This
parameter is valid only for ConnectFailed events.

○ TableName The name of the table, for use with RemainingValues.

○ User The user ID for the user that caused the event to be triggered.

In addition, you can access any of the valid condition-name arguments to the EVENT_CONDITION
function from the EVENT_PARAMETER function.

The following table indicates which context-name values are valid for which system event types.

System event types Context-name value

BackupEnd AppInfo, ConnectionID, EventName, Executions, NumActive, User

Connect AppInfo, ConnectionID, EventName, Executions, NumActive, User

ConnectFailed AppInfo, EventName, Executions, NumActive, SQLCODE, User

"Disconnect" AppInfo, ConnectionID, EventName, Executions, NumActive, User

GlobalAutoincrement ConnectionID, EventName, Executions, NumActive, TableName, User

"RAISERROR" AppInfo, ConnectionID, EventName, Executions, NumActive, User

User events AppInfo, ConnectionID, EventName, Executions, NumActive, User

218 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Returns
VARCHAR

Remarks
The maximum size of values passed to an event is limited by the maximum page size for the server (-gp
server option). Values that are longer are truncated to be less than the maximum page size.

See also
● “EVENT_CONDITION function [System]” on page 215
● “CREATE EVENT statement” on page 526
● “TRIGGER EVENT statement” on page 932
● “-gp dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example shows how to pass a string parameter to an event. The event displays the time it
was triggered in the database server messages window.
CREATE EVENT ev_PassedParameter
HANDLER
BEGIN
MESSAGE 'ev_PassedParameter - was triggered at ' ||
event_parameter( 'time' );
END;
TRIGGER EVENT ev_PassedParameter( "Time"=string(current timestamp ) );

EXP function [Numeric]


Returns the result of the base of natural logarithms e raised to the power of the given argument.

Syntax
EXP( numeric-expression )

Parameters
● numeric-expression The exponent.

Returns
DOUBLE

Remarks
The EXP function returns the result of raising the base of natural logarithms e by the value specified by
numeric-expression.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 219


SQL functions

This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

Standards and compatibility


● SQL/2008 The EXP function comprises part of optional SQL/2008 language feature T621,
"Enhanced numeric functions".

Example
The statement returns the value 3269017.3724721107.
SELECT EXP( 15 );

EXPERIENCE_ESTIMATE function [Miscellaneous]


Returns selectivity estimates as a percentage calculated by the query optimizer, based on specified
parameters.

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. Possible values for this
parameter are: '=' , '>' , '<' , '>=' , '<=' , '<>' , '!=' , '!<' , and '!>'. The default is '='.

Returns
REAL

Remarks
If value is NULL then the relation strings = and != are interpreted as the IS NULL and IS NOT NULL
conditions, respectively.

See also
● “ESTIMATE function [Miscellaneous]” on page 212
● “INDEX_ESTIMATE function [Miscellaneous]” on page 249
● “ESTIMATE_SOURCE function [Miscellaneous]” on page 213

Standards and compatibility


● SQL/2008 Vendor extension.

220 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example
The following statement returns NULL.
SELECT DISTINCT EXPERIENCE_ESTIMATE( EmployeeID, 200, '>' )
FROM Employees;

EXPLANATION function [Miscellaneous]


Returns the optimization strategy of a SQL statement as a plain text string.

Syntax
EXPLANATION(
string-expression
[ , cursor-type ]
[, update-status ]
)

Parameters
● string-expression The SQL statement, which is commonly a SELECT statement, but can also be
an UPDATE, MERGE, or DELETE statement.

● cursor-type A cursor type, expressed as a string. Possible values are asensitive, insensitive,
sensitive, or keyset-driven. If cursor-type is not specified, asensitive is used by default.

● update-status A string parameter accepting one of the following values indicating how the
optimizer should treat the given cursor:

Value Description

READ-ONLY The cursor is read-only.

READ-WRITE (default) The cursor can be read or written to.

FOR UPDATE The cursor can be read or written to. This is the same as READ-
WRITE.

Returns
LONG VARCHAR

Remarks
The statement's access plan is returned as a string. For information about interpreting the result, see
“Advanced: Query execution plans” [SQL Anywhere Server - SQL Usage].

The GRAPHICAL_PLAN function offers significantly greater information about access plans, including
system properties that may have affected how the statement was optimized.

This information can help you decide which indexes to add or how to structure your database for better
performance.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 221


SQL functions

See also
● “Execution plans in UltraLite” [UltraLite - Database Management and Reference]
● “Advanced: Query execution plans” [SQL Anywhere Server - SQL Usage]
● “PLAN function [Miscellaneous]” on page 294
● “GRAPHICAL_PLAN function [Miscellaneous]” on page 229

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement passes a SELECT statement as a string parameter and returns the plan for
executing the query.

SELECT EXPLANATION( 'SELECT * FROM Departments WHERE DepartmentID > 100' );

The following statement returns a string containing the short form of the text plan for an INSENSITIVE
cursor over the query 'select * from Departments where ....'.

SELECT EXPLANATION( 'SELECT * FROM Departments WHERE DepartmentID > 100',


'insensitive', 'read-only' );

EXPRTYPE function [Miscellaneous]


Returns a string that identifies the data type of an expression.

Syntax
EXPRTYPE( string-expression, integer-expression )

Parameters
● string-expression A SELECT statement. The expression whose data type is to be queried must
appear in the SELECT list. If the string is not a valid SELECT statement, NULL is returned.

● integer-expression The position in the SELECT list of the desired expression. The first item in
the SELECT list is numbered 1. If the integer-expression value does not correspond to a SELECT list
item, NULL is returned.

Returns
LONG VARCHAR

Remarks
For user-defined domains, EXPRTYPE returns the description of the underlying data type, not the domain
name. For example, suppose you create a domain, mydomain, and define a table column using mydomain,
as follows:

CREATE DOMAIN mydomain CHAR(20);


CREATE TABLE mytable( colA mydomain, colB DATETIME );

222 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

When you execute SELECT EXPRTYPE( 'SELECT * FROM mytable', 1 ), the data type
returned is char(20), not mydomain.

See also
● “SQL data types” on page 81
● “sa_describe_query system procedure” on page 1037

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns smallint when executed against the SQL Anywhere sample database.
SELECT EXPRTYPE( 'SELECT LineID FROM SalesOrderItems', 1 );

FIRST_VALUE function [Aggregate]


Returns values from the first row of a window.

Syntax
FIRST_VALUE( [ ALL ] expression [ { RESPECT | IGNORE } NULLS ] )
OVER ( window-spec )

window-spec : see the Remarks section below

Parameters
● expression The expression to evaluate. For example, a column name.

Returns
Data type of the values from the first row of a window.

Remarks
The FIRST_VALUE function allows you to select the first value (according to some ordering) in a table,
without having to use a self-join. This is valuable when you want to use the first value as the baseline in
calculations.

The FIRST_VALUE function takes the first record from the window. Then, the expression is computed
against the first record and results are returned.

If IGNORE NULLS is specified, the first non-NULL value of expression is returned. If RESPECT
NULLS is specified (the default), the first value is returned whether or not it is NULL.

The FIRST_VALUE function is different from most other aggregate functions in that it can only be used
with a window specification.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 223


SQL functions

Elements of window-spec can be specified either in the function syntax (inline), or in conjunction with a
WINDOW clause in the SELECT statement. More information is provided in the window-spec definition
of the WINDOW clause. See “WINDOW clause” on page 961.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “Window aggregate functions” [SQL Anywhere Server - SQL Usage]
● “LAST_VALUE function [Aggregate]” on page 255

Standards and compatibility


● SQL/2008 Vendor extension.

SQL Anywhere supports SQL/2008 language feature F441, "Extended set function support", which
permits operands of window functions to be arbitrary expressions that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the FIRST_VALUE function, combined with an
outer reference. For an example, see “AVG function [Aggregate]” [UltraLite - Database Management
and Reference].

Example
The following example returns the relationship, as a percentage, between each employee's salary and that
of the most recently hired employee in the same department:
SELECT DepartmentID, EmployeeID,
100 * Salary / ( FIRST_VALUE( Salary ) OVER (
PARTITION BY DepartmentID ORDER BY StartDate
DESC ) )
AS percentage
FROM Employees;

DepartmentID EmployeeID percentage

500 1658 100

500 1615 110.4284624

500 1570 138.8427097

500 1013 109.5851905

500 921 167.4497049

224 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

DepartmentID EmployeeID percentage

500 868 113.2393688

500 750 137.7344095

500 703 222.8679276

500 191 119.6642975

400 1751 100

400 1740 99.705647

400 1684 130.969936

400 1643 83.9734797

400 1607 175.1828989

400 1576 197.0164609

... ... ...

Employee 1658 is the first row for department 500, indicating that they are the most recent hire in that
department and their percentage is 100%. Percentages for the remaining department 500 employees are
calculated relative to that of employee 1658. For example, employee 1570 earns approximately 139% of
what employee 1658 earns.

If another employee in the same department makes the same salary as the most recent hire, they will have
a percentage of 100 as well.

FLOOR function [Numeric]


Returns the largest integer not greater than the given number.

Syntax
FLOOR( numeric-expression )

Parameters
● numeric-expression The value to be truncated, typically a fixed numeric type with non-zero scale
or an approximate numeric type (DOUBLE, REAL, or FLOAT).

Returns
DOUBLE

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 225


SQL functions

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic.

See also
● “CEILING function [Numeric]” on page 160

Standards and compatibility


● SQL/2008 The FLOOR function comprises part of optional SQL/2008 language feature T621,
"Enhanced numeric functions".

Example
The following statement returns a Floor value of 123:
SELECT FLOOR (123);

The following statement returns a value of 123:


SELECT FLOOR (123.45);

The following statement returns a value of -124:


SELECT FLOOR (-123.45);

GET_BIT function [Bit array]


Returns the value (1 or 0) of a specified bit in a bit array.

Syntax
GET_BIT( bit-expression, position )

Parameters
● bit-expression The bit array containing the bit.

● position The position of the bit for which to return the status.

Returns
BIT

Remarks
The positions in the array are counted from the left side, starting at 1.

If position exceeds the length of the array, 0 (false) is returned.

226 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “Bitwise operators” on page 11
● “SET_BIT function [Bit array]” on page 333
● “SET_BITS function [Aggregate]” on page 334
● “sa_get_bits system procedure” on page 1048

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 1:
SELECT GET_BIT( '00110011' , 4 );

The following statement returns the value 0:


SELECT GET_BIT( '00110011' , 5 );

GET_IDENTITY function [Miscellaneous]


Allocates values to an AUTOINCREMENT column. This is an alternative to using AUTOINCREMENT
to generate numbers.

Syntax
GET_IDENTITY( table_name [, number_to_allocate ] )

Parameters
● table_name A string indicating the name of the table, including, optionally, the owner name.

● number_to_allocate The number of values to reserve. The default is 1.

Returns
UNSIGNED BIGINT

Remarks
Using AUTOINCREMENT or GLOBAL AUTOINCREMENT is still the most efficient way to generate
IDs, but this function is provided as an alternative. The function assumes that the table has an
AUTOINCREMENT column defined. It returns the next available value that would be generated for the
table's AUTOINCREMENT column, and reserves that value so that no other connection will use it by
default.

The function returns an error if the table is not found, and returns NULL if the table has no
AUTOINCREMENT column. If there is more than one AUTOINCREMENT column, it uses the first one
it finds.

number_to_allocate is the number of values to reserve. If number_to_allocate is greater than 1, the


function also reserves the remaining values. The next allocation uses the current number plus the value of

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 227


SQL functions

number_to_allocate. This allows the application to execute the GET_IDENTITY function less frequently.
If number_to_allocate is 0, the next available value is returned without reserving any values.

No COMMIT is required after executing the GET_IDENTITY function, and so it can be called using the
same connection that is used to insert rows. If ID values are required for several tables, they can be
obtained using a single SELECT that includes multiple calls to the GET_IDENTITY function, as in the
example.

The GET_IDENTITY function is non-deterministic function; successive calls to it may return different
values. The optimizer does not cache the results of the GET_IDENTITY function.

For more information about non-deterministic functions, see “Function caching” [SQL Anywhere Server -
SQL Usage].

See also
● “CREATE TABLE statement” on page 633
● “ALTER TABLE statement” on page 451
● “NUMBER function [Miscellaneous]” on page 288

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the next available value for the Customers table AUTOINCREMENT
column (ID). The number returned and the following nine values are reserved:
SELECT GET_IDENTITY( 'Customers', 10 );

GETDATE function [Date and time]


Returns the current year, month, day, hour, minute, second and fraction of a second.

Syntax
GETDATE( )

Returns
TIMESTAMP

Remarks
The accuracy is limited by the accuracy of the system clock.

The information the GETDATE function returns is equivalent to the information returned by the NOW
function and the CURRENT TIMESTAMP special value.

228 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “Expressions” on page 12
● “ISDATE function [Data type conversion]” on page 251
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP special value” on page 69
● “TIMESTAMP data type” on page 113
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the system date and time.

SELECT GETDATE( );

GRAPHICAL_PLAN function [Miscellaneous]


Returns the plan optimization strategy of a SQL statement in XML format, as a string.

Syntax
GRAPHICAL_PLAN(
string-expression
[, statistics-level
[, cursor-type
[, update-status ] ] ] )

Parameters
● string-expression The SQL statement, which is commonly a SELECT statement but which may
also be an UPDATE or DELETE statement.

● statistics-level An integer. Statistics-level can be one of the following values:

Value Description

0 Optimizer estimates only (default).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 229


SQL functions

Value Description

2 Detailed statistics including node statistics.

3 Detailed statistics.

● cursor-type A cursor type, expressed as a string. Possible values are: asensitive, insensitive,
sensitive, or keyset-driven. If cursor-type is not specified, asensitive is used by default.

● update-status A string parameter accepting one of the following values indicating how the
optimizer should treat the given cursor:

Value Description

READ-ONLY The cursor is read-only.

READ-WRITE (default) The cursor can be read or written to.

FOR UPDATE The cursor can be read or written to. This is exactly the same as READ-
WRITE.

Returns
LONG VARCHAR

See also
● “Advanced: Query execution plans” [SQL Anywhere Server - SQL Usage]
● “PLAN function [Miscellaneous]” on page 294
● “EXPLANATION function [Miscellaneous]” on page 221

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following Interactive SQL example passes a SELECT statement as a string parameter and returns the
plan for executing the query. It saves the plan in the file plan.saplan which can be opened and read using
Interactive SQL.

SELECT GRAPHICAL_PLAN( 'SELECT * FROM Departments WHERE DepartmentID >


100' );
OUTPUT TO 'plan.saplan' FORMAT TEXT QUOTE '' HEXADECIMAL ASIS;

The following statement returns a string containing the graphical plan for a keyset-driven, updatable
cursor over the query SELECT * FROM Departments WHERE DepartmentID > 100. It also
causes the server to annotate the plan with actual execution statistics, in addition to the estimated statistics
that were used by the optimizer.
SELECT GRAPHICAL_PLAN(
'SELECT * FROM Departments WHERE DepartmentID > 100',

230 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

2,
'keyset-driven', 'for update' );

GREATER function [Miscellaneous]


Returns the greater of two parameter values.

Syntax
GREATER( expression-1, expression-2 )

Parameters
● expression-1 The first parameter value to be compared.

● expression-2 The second parameter value to be compared.

Returns
The return type for this function depends on the expressions specified. That is, when the database server
evaluates the function, it first searches for a data type in which all the expressions can be compared. When
found, the database server compares the expressions and then returns the result in the type used for the
comparison. If the database server cannot find a common comparison type, an error is returned.

Remarks
If the parameters are equal, the first is returned.

See also
● “LESSER function [Miscellaneous]” on page 260

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 10.
SELECT GREATER( 10, 5 ) FROM dummy;

GROUPING function [Aggregate]


Identifies whether a column in a GROUP BY operation result set is NULL because it is part of a subtotal
row, or NULL because of the underlying data.

Syntax
GROUPING( group-by-expression )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 231


SQL functions

Parameters
● group-by-expression An expression appearing as a grouping column in the result set of a query
that uses a GROUP BY clause. This function can be used to identify subtotal rows added to the result
set by a ROLLUP or CUBE operation.

Returns
● 1 Indicates that group-by-expression is NULL because it is part of a subtotal row. The column is
not a prefix column for that row.

● 0 Indicates that group-by-expression is a prefix column of a subtotal row.

See also
● “The ROLLUP clause” [SQL Anywhere Server - SQL Usage]
● “The CUBE clause” [SQL Anywhere Server - SQL Usage]
● “GROUP BY GROUPING SETS” [SQL Anywhere Server - SQL Usage]
● “SELECT statement” on page 871
● “Detection of NULLs using the GROUPING function” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 The GROUPING function is part of optional SQL/2008 language feature T431,
"Extended grouping capabilities".

Example
For examples of this function, see “Detection of NULLs using the GROUPING function” [SQL Anywhere
Server - SQL Usage].

HASH function [String]


Returns the specified value in hashed form.

Syntax
HASH( string-expression[, algorithm ] )

Parameters
● string-expression The value to be hashed. This parameter is case sensitive, even in case-
insensitive databases.

● algorithm The algorithm to use for the hash. Possible values include: CRC32, MD5, SHA1,
SHA1_FIPS, SHA256, SHA256_FIPS. By default, the MD5 algorithm is used. FIPS-certified
algorithms require a separate license.

Returns
Following are the return types, depending on the algorithm used:

232 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

● CRC32 returns a hexadecimal string. Use the HEXTOINT function to convert the hexadecimal string to
a 32-bit integer.

● MD5 returns a VARCHAR(32)

● SHA1 returns a VARCHAR(40)

● SHA1_FIPS returns a VARCHAR(40)

● SHA256 returns a VARCHAR(64)

● SHA256_FIPS returns a VARCHAR(64)

Remarks
Using a hash converts the value to a byte sequence that is unique to each value passed to the function.

If the database server was started with the -fips option, the algorithm used, or the behavior, may be
different, as follows:

● SHA1_FIPS is used if SHA1 is specified

● SHA256_FIPS is used if SHA256 is specified

● an error is returned if MD5 is specified

● the CRC32 algorithm, which is not FIPS-certified, is allowed in FIPS mode because it is not considered
a cryptographic algorithm.

Caution
All the algorithms are one-way hashes. It is not possible to re-create the original string from the hash.

See also
● “String functions” on page 142
● “-fips dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “SQL Anywhere security option” [SQL Anywhere 12 - Introduction]
● “HEXTOINT function [Data type conversion]” on page 234

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example creates a table called user_info to store information about the users of an
application, including their user ID and password. One row is also inserted into the table. The password is
hashed using the HASH function and the SHA256 algorithm. Storing hashed passwords in this way can
be useful if you do not want to store passwords in clear text, yet you have an external application that
needs to compare passwords.
CREATE TABLE user_info (
employee_id INTEGER NOT NULL PRIMARY KEY,

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 233


SQL functions

user_name CHAR(80),
user_pwd CHAR(80) );
INSERT INTO user_info
VALUES ( '1', 's_phillips', HASH( 'mypass', 'SHA256' ) );

HEXTOINT function [Data type conversion]


Returns the decimal integer equivalent of a hexadecimal string.

The CAST, CONVERT, HEXTOINT, and INTTOHEX functions can be used to convert to and from
hexadecimal values. For more information about using these functions, see “Converting to and from
hexadecimal values” on page 6.

Syntax
HEXTOINT( hexadecimal-string )

Parameters
● hexadecimal-string The string to be converted to an integer.

Returns
The HEXTOINT function returns as INT the platform-independent SQL INTEGER equivalent of the
hexadecimal string. The hexadecimal value represents a negative integer if the 8th digit from the right is
one of the digits 8-9 and the uppercase or lowercase letters A-F and the previous leading digits are all
uppercase or lowercase letter F. The following is not a valid use of HEXTOINT since the argument
represents a positive integer value that cannot be represented as a signed 32-bit integer:

SELECT HEXTOINT( '0x0080000001' );

Remarks
The HEXTOINT function accepts string literals or variables consisting only of digits and the uppercase or
lowercase letters A-F, with or without a 0x prefix. The following are all valid uses of HEXTOINT:

SELECT HEXTOINT( '0xFFFFFFFF' );


SELECT HEXTOINT( '0x00000100' );
SELECT HEXTOINT( '100' );
SELECT HEXTOINT( '0xffffffff80000001' );

The HEXTOINT function removes the 0x prefix, if present. If the data exceeds 8 digits, it must represent
a value that can be represented as a signed 32-bit integer value.

This function supports NCHAR inputs and/or outputs.

See also
● “INTTOHEX function [Data type conversion]” on page 250

Standards and compatibility


● SQL/2008 Vendor extension.

234 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example
The following statement returns the value 420.

SELECT HEXTOINT( '1A4' );

HOUR function [Date and time]


Returns the hour component of a TIMESTAMP value.

Syntax
HOUR( timestamp-expression )

Parameters
● timestamp-expression A TIMESTAMP value.

Returns
SMALLINT

Remarks
The value returned is the hour portion of the TIMESTAMP expression, a SMALLINT value between 0
and 23.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 21:

SELECT HOUR( '1998-07-09 21:12:13' );

HOURS function [Date and time]


The HOURS function manipulates a TIMESTAMP, or returns the number of hours between two
TIMESTAMP values. For specific details, see this function's usage.

Syntax 1
HOURS ( timestamp-expression )

Syntax 2
HOURS ( timestamp-expression, timestamp-expression )

Syntax 3
HOURS ( time-or-timestamp-expression, integer-expression )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 235


SQL functions

Parameters
● time-or-timestamp-expression A value of type TIME or TIMESTAMP.

● timestamp-expression A value of type TIMESTAMP.

● integer-expression The number of hours to be added to time-or-timestamp-expression. If integer-


expression is negative, the appropriate number of hours is subtracted from time-or-timestamp-
expression.

For information about casting data types, see “CAST function [Data type conversion]” on page 159.

Returns
INTEGER with Syntax 1 or Syntax 2.

TIME or TIMESTAMP with Syntax 3.

Remarks
The result of the HOURS function depends on its arguments.

● Syntax 1 If you pass a single timestamp-expression to the HOURS function, it will return the
number of hours between midnight 0000-02-29 and timestamp-expression as an INTEGER.

Note
0000-02-29 is not meant to imply an actual date; it is the default TIMESTAMP value used by the
HOURS function.

● Syntax 2 If you pass two TIMESTAMP values to the HOURS function, the function returns the
integer number of hours between them.

● Syntax 3 If you pass a TIMESTAMP value and an INTEGER value to the HOURS function, the
function returns the TIMESTAMP result of adding the integer number of hours to time-or-timestamp-
expression argument. Similarly, if you pass a TIME value as the first argument, a TIME value is
returned as the result. Syntax 3 does not support implicit conversion of the first argument. It may be
necessary to explicitly cast the first argument to a DATE, TIME or TIMESTAMP value. If the first
argument is a DATE, midnight is assumed for the time portion.

Instead of Syntax 2, use the DATEDIFF function. Instead of Syntax 3, use the DATEADD function.

See also
● “DATEDIFF function [Date and time]” on page 189
● “DATEADD function [Date and time]” on page 188

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements return the value 4, signifying that the second TIMESTAMP value is four hours
after the first. It is recommended that you use the second example (DATEDIFF).

236 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

SELECT HOURS( '1999-07-13 06:07:12', '1999-07-13 10:07:12' );

SELECT DATEDIFF( hour, '1999-07-13 06:07:12', '1999-07-13 10:07:12' );

The following statement returns the value 17517342.


SELECT HOURS( '1998-07-13 06:07:12' );

The following statements return the datetime 1999-05-13 02:05:07.000. It is recommended that you use
the second example (DATEADD).
SELECT HOURS( CAST( '1999-05-12 21:05:07' AS DATETIME ), 5 );

SELECT DATEADD( hour, 5, '1999-05-12 21:05:07' );

HTML_DECODE function [Miscellaneous]


Decodes special character entities that appear in HTML literal strings.

Syntax
HTML_DECODE( string )

Parameters
● string Arbitrary literal string used in an HTML document.

Returns
LONG VARCHAR or LONG NVARCHAR

Remarks
This function returns the string argument after making the appropriate substitutions. The following table
contains a sampling of the acceptable character entities.

Characters Substitution

&quot; "

&#39; '

&amp; &

&lt; <

&gt; >

&#xhexadecimal-number; Unicode codepoint, specified as a hexadecimal number. For example,


&#x27; returns a single apostrophe.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 237


SQL functions

Characters Substitution

&#decimal-number; Unicode codepoint, specified as a decimal number. For example, &#8482;


returns the trademark symbol.

When a Unicode codepoint is specified, if the value can be converted to a character in the database
character set, it is converted to a character. Otherwise, it is returned uninterpreted.

SQL Anywhere supports all character entity references specified in the HTML 4.01 Specification. See
http://www.w3.org/TR/html4/ and http://www.w3.org/TR/html4/sgml/entities.html#h-24.2.

See also
● “HTML_ENCODE function [Miscellaneous]” on page 238
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
SELECT HTML_DECODE('&lt;p&gt;The piano was made ' ||
'by &lsquo;Steinway &amp; Sons&rsquo;.&lt;/p&gt;')

SELECT HTML_DECODE('&lt;p&gt;It cost &euro;85.000,00.&lt;/p&gt;')

HTML_ENCODE function [Miscellaneous]


Encodes special characters within strings to be inserted into HTML documents.

Syntax
HTML_ENCODE( string )

Parameters
● string Arbitrary string to be used in an HTML document.

Returns
LONG VARCHAR or LONG NVARCHAR

Remarks
This function returns the string argument after making the following set of substitutions:

Characters Substitution

" &quot;

238 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Characters Substitution

' &#39;

& &amp;

< &lt;

> &gt;

codes nn less than 0x20 &#xnn;

This function supports NCHAR inputs and/or outputs.

See also
● “HTML_DECODE function [Miscellaneous]” on page 237
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example returns the string '&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML
4.01//EN&quot;&gt; '.
SELECT HTML_ENCODE('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">')

HTTP_BODY function [Web service]


Returns the body of the HTTP request in binary form. For example, in a POST request, this is the raw
POST data.

Syntax
HTTP_BODY( )

Parameters
None

Returns
LONG VARCHAR containing the body of the HTTP request in binary form; no character set conversion
is performed on it.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 239


SQL functions

Remarks
If the request body does not exist, or if the function is not called from a web service, a NULL value is
returned.

This function is useful within the PHP external environment.

See also
● “sa_http_php_page system procedure” on page 1060
● “sa_http_php_page_interpreted system procedure” on page 1060
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

HTTP_DECODE function [Web service]


Decodes HTTP encoded strings. This is also known as URL decoding.

Syntax
HTTP_DECODE( string )

Parameters
● string Arbitrary string taken from a URL or URL encoded request body.

Returns
LONG VARCHAR or LONG NVARCHAR

Remarks
This function returns the string argument after replacing all character sequences of the form %nn, where
nn is a hexadecimal value, with the character with code nn. In addition, all plus signs (+) are replaced
with spaces.

See also
● “HTTP_ENCODE function [Web service]” on page 241
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
SELECT HTTP_DECODE('http%3A%2F%2Fdcx.sybase.com')

240 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

HTTP_ENCODE function [Web service]


Encodes strings for use with HTTP. This is also known as URL encoding.

Syntax
HTTP_ENCODE( string )

Parameters
● string Arbitrary string to be encoded for HTTP transport.

Returns
LONG VARCHAR or LONG NVARCHAR

Remarks
This function returns the string argument after making the following set of substitutions. In addition, all
characters with hexadecimal codes less than 20 or greater than 7E are replaced with %nn, where nn is the
character code.

Character Substitution

space %20

" %22

# %23

% %25

& %26

, %2C

; %3B

< %3C

> %3E

[ %5B

\ %5C

] %5D

` %60

{ %7B

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 241


SQL functions

Character Substitution

| %7C

} %7D

character codes nn that are less than 0x20 and greater than 0x7f %nn

This function supports NCHAR inputs and/or outputs.

See also
● “HTTP_DECODE function [Web service]” on page 240
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
SELECT HTTP_ENCODE('/opt&id=123&text=''oid:c\x09d ef''')

HTTP_HEADER function [Web service]


Returns the value of an HTTP request header.

Syntax
HTTP_HEADER( header-field-name )

Parameters
● header-field-name The name of an HTTP request header field.

Returns
LONG VARCHAR

Remarks
This function returns the value of the named HTTP request header field, or NULL if it does not exist or if
it is not called from an HTTP service. It is used when processing an HTTP request via a web service.

Some headers that may be of interest when processing an HTTP web service request include the
following:

● Cookie The cookie value(s), if any, stored by the client, that are associated with the requested URI.

● Referer The URL of the page that contained the link to the requested URI.

● Host The name or IP of the host that submitted the request.

242 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

● User-Agent The name of the client application.

● Accept-Encoding A list of encodings for the response that are acceptable to the client application.

More information about these headers is available at http://www.w3.org/Protocols/rfc2616/rfc2616-


sec14.html.

The following special headers allow access to the elements within the request line of a client request.

● @HttpMethod Returns the type of request being processed. Possible values include DELETE,
HEAD, GET, PUT, or POST.

● @HttpURI The full URI of the request, as it was specified in the HTTP request (for example, /
myservice?&id=-123&version=109&lang=en).

● @HttpVersion The HTTP version of the request (for example, HTTP/1.0, or HTTP/1.1).

● @HttpQueryString Returns the query portion of the requested URI if it exists (for example,
&id=-123&version=109&lang=en).

See also
● “NEXT_HTTP_HEADER function [Web service]” on page 282
● “sa_set_http_header system procedure” on page 1134
● “sa_http_header_info system procedure” on page 1059
● “Accessing client-supplied HTTP variables and headers” [SQL Anywhere Server - Programming]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Example
When used within a stored procedure that is called by an HTTP web service, the following example gets
the Cookie header value:
SET cookie_value = HTTP_HEADER( 'Cookie' );

When used within a stored procedure that is called by an HTTP web service, the following example
displays the name and values of the HTTP request headers in the database server messages window.

BEGIN
declare header_name long varchar;
declare header_value long varchar;
set header_name = NULL;
header_loop:
LOOP
SET header_name = NEXT_HTTP_HEADER( header_name );
IF header_name IS NULL THEN
LEAVE header_loop
END IF;
SET header_value = HTTP_HEADER( header_name );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 243


SQL functions

MESSAGE 'HEADER: ', header_name, '=',


header_value TO CONSOLE;
END LOOP;
END;

HTTP_RESPONSE_HEADER function [Web service]


Returns the value of an HTTP response header.

Syntax
HTTP_RESPONSE_HEADER( header-field-name )

Parameters
● header-field-name The name of an HTTP response header field.

Returns
LONG VARCHAR

Remarks
This function returns the value of the named HTTP response header field, or NULL if a header for the
given header-field-name does not exist or if it is not called from an HTTP service.

Some headers that may be of interest when processing an HTTP web service response include the
following:

● Connection The Connection field allows the sender to specify options that are desired for that
particular connection. In a SQL Anywhere HTTP server response, the option is always "close".

● Content-Length The Content-Length field indicates the size of the response body, in decimal
number of octets.

● Content-Type The Content-Type field indicates the media type of the body sent to the recipient.
Example: text/xml

● Date The Date field represents the date and time at which the response was originated.

● Expires The Expires field gives the date and time after which the response is considered stale.

● Location The Location field is used to redirect the recipient to a location for completion of the
request or identification of a new resource.

● Server The Server field contains information about the software used by the origin server to handle
the request. In a SQL Anywhere HTTP server response, the web server name together with the version
number is returned.

● Transfer-Encoding The Transfer-Encoding field indicates what (if any) type of transformation has
been applied to the message body in order to safely transfer it between the sender and the recipient.

244 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

● User-Agent The User-Agent field contains information about the user agent originating the
request. In a SQL Anywhere HTTP server response, the web server name together with the version
number is returned.

● WWW-Authenticate The WWW-Authenticate field is included in 401 (Unauthorized) response


messages.

More information about these headers is available at http://www.w3.org/Protocols/rfc2616/rfc2616-


sec14.html.

The following special header allows access to the status within the response of a server response.

● @HttpStatus Returns the status code of the processed request.

See also
● “NEXT_HTTP_RESPONSE_HEADER function [Web service]” on page 284
● “sa_set_http_header system procedure” on page 1134
● “Accessing client-supplied HTTP variables and headers” [SQL Anywhere Server - Programming]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Example
When used within a stored procedure that is called by an HTTP web service, the following example
displays the name and values of the HTTP response headers in the database server messages window.

BEGIN
declare header_name long varchar;
declare header_value long varchar;
set header_name = NULL;
header_loop:
LOOP
SET header_name = NEXT_HTTP_RESPONSE_HEADER( header_name );
IF header_name IS NULL THEN
LEAVE header_loop
END IF;
SET header_value = HTTP_RESPONSE_HEADER( header_name );
MESSAGE 'RESPONSE HEADER: ', header_name, '=', header_value TO CONSOLE;
END LOOP;

HTTP_VARIABLE function [Web service]


Returns the value of an HTTP variable.

Syntax
HTTP_VARIABLE( var-name [ , instance [ , attribute ] ] )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 245


SQL functions

Parameters
● var-name The name of an HTTP variable.

● instance If more than one variable has the same name, the instance number of the field instance, or
NULL to get the first one. Useful for SELECT lists that permit multiple selections.

● attribute In a multi-part request, the attribute can specify a header field name which returns the
value of the header for the multi-part name.

When an attribute is not specified, the returned value is %-decoded and character-set translated to the
database character set. UTF %-encoded data is supported in this mode.

The attribute can also be one of the following modes:

○ '@BINARY' Returns a x-www-form-urlencoded binary data value. This mode indicates that the
returned value is %-decoded and not character-set translated. UTF-8 %-encoding is not supported
in this mode since %-encoded data are simply decoded into their equivalent byte representation.

○ '@TRANSPORT' Returns the raw HTTP transport form of the value, where %-encodings are
preserved.

Returns
LONG VARCHAR

Remarks
This function returns the value of the named HTTP variable. It is used when processing an HTTP request
within a web service.

If var-name does not exist, the return value is NULL.

When the web service request is a POST, and the variable data is posted as multipart/form-data, the HTTP
server receives HTTP headers for each individual variable. When the attribute parameter is specified, the
HTTP_VARIABLE function returns the associated multipart/form-data header value from the POST
request for the particular variable. For a variable representing a file, an attribute of Content-Disposition,
Content-Type, and @BINARY would return the filename, media-type, and file contents respectively.

Normally, all input data goes through character set translation between the client (for example, a browser)
character set, and the character set of the database. However, if @BINARY is specified for attribute, the
variable value is returned without going through character set translation or %-decoding. This may be
useful when receiving binary data, such as image data, from a client.

This function returns NULL when the specified instance does not exist or when the function is called
from outside of an execution of a web service.

246 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “NEXT_HTTP_VARIABLE function [Web service]” on page 285
● “sa_http_variable_info system procedure” on page 1062
● “Accessing client-supplied HTTP variables and headers” [SQL Anywhere Server - Programming]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
When used within a stored procedure that is called by an HTTP web service, the following example
retrieves the values of the HTTP variables indicated in the sample URL.
-- http://sample.com/demo/ShowDetail?product_id=300&customer_id=101
BEGIN
DECLARE v_customer_id LONG VARCHAR;
DECLARE v_product_id LONG VARCHAR;
SET v_customer_id = HTTP_VARIABLE( 'customer_id' );
SET v_product_id = HTTP_VARIABLE( 'product_id' );
CALL ShowSalesOrderDetail( v_customer_id, v_product_id );
END;

When used within a stored procedure that is called by an HTTP web service, the following statements
request the Content-Disposition and Content-Type headers of the image variable:
SET v_name = HTTP_VARIABLE( 'image', NULL, 'Content-Disposition' );
SET v_type = HTTP_VARIABLE( 'image', NULL, 'Content-Type' );

When used within a stored procedure that is called by an HTTP web service, the following statement
requests the value of the image variable in its current character set, that is, without going through
character set translation:
SET v_image = HTTP_VARIABLE( 'image', NULL, '@BINARY' );

IDENTITY function [Miscellaneous]


Generates integer values, starting at 1, for each successive row in a query. Its implementation is identical
to that of the NUMBER function.

Syntax
IDENTITY( expression )

Parameters
● expression An expression. The expression is parsed, but is ignored during the execution of the
function.

Returns
INT

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 247


SQL functions

Remarks
The description of the IDENTITY function is the same as the description of the NUMBER function.

See also
● “NUMBER function [Miscellaneous]” on page 288

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns a sequentially-numbered list of employees.
SELECT IDENTITY( 10 ), Surname FROM Employees;

IFNULL function [Miscellaneous]


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.

Returns
The data type returned depends on the data type of expression-2 and expression-3.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value -66.
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 );

248 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

INDEX_ESTIMATE function [Miscellaneous]


Returns selectivity estimates from the index as a percentage calculated by the query optimizer, based on
specified parameters.

Syntax
INDEX_ESTIMATE( column-name [ , value [ , relation-string ] ] )

Parameters
● column-name The column used in the estimate.

● value The value to which the column is compared. The default is NULL.

● relation-string The comparison operator used for the comparison, enclosed in single quotes.
Possible values for this parameter are: '=' , '>' , '<' , '>=' , '<=' , '<>' , '!=' , '!<' , and '!>'. The default is
'='.

Returns
REAL

Remarks
This function returns selectivity estimates from the index for the predicate column-name relation-
string value. If value is NULL and the relation string is '=', the selectivity is for the predicate
column-name IS NULL. If value is NULL and the relation string is '!=' or '<>', the selectivity is for
the predicate column-name IS NOT NULL.

See also
● “ESTIMATE function [Miscellaneous]” on page 212
● “ESTIMATE_SOURCE function [Miscellaneous]” on page 213
● “EXPERIENCE_ESTIMATE function [Miscellaneous]” on page 220

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the percentage of EmployeeID values estimated to be greater than 200.
SELECT INDEX_ESTIMATE( EmployeeID, 200, '>' )
FROM Employees;

INSERTSTR function [String]


Inserts a string into another string at a specified position.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 249


SQL functions

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.

Returns
LONG VARCHAR

Remarks
This function supports NCHAR inputs and/or outputs.

See also
● “STUFF function [String]” on page 352
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value backoffice.
SELECT INSERTSTR( 0, 'office ', 'back' );

INTTOHEX function [Data type conversion]


Returns a string containing the hexadecimal equivalent of an integer.

Syntax
INTTOHEX( integer-expression )

Parameters
● integer-expression The integer to be converted to hexadecimal.

Returns
VARCHAR

Remarks
The CAST, CONVERT, HEXTOINT, and INTTOHEX functions can be used to convert to and from
hexadecimal values. For more information, see “Converting to and from hexadecimal values” on page 6.

250 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “HEXTOINT function [Data type conversion]” on page 234

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 0000009c.
SELECT INTTOHEX( 156 );

ISDATE function [Data type conversion]


Tests if a string argument can be converted to a date.

Syntax
ISDATE( string )

Parameters
● string The string to be analyzed to determine if the string represents a valid date.

Returns
INT

Remarks
If a conversion is possible, the function returns 1; otherwise, 0 is returned. If the argument is NULL, 0 is
returned.

This function supports NCHAR inputs and/or outputs.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 251


SQL functions

See also
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “Expressions” on page 12
● “GETDATE function [Date and time]” on page 228
● “NOW function [Date and time]” on page 287
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP special value” on page 69
● “TIMESTAMP data type” on page 113
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example imports data from an external file, exports rows which contain invalid values, and
copies the remaining rows to a permanent table.
CREATE GLOBAL TEMPORARY TABLE MyData(
person VARCHAR(100),
birth_date VARCHAR(30),
height_in_cms VARCHAR(10)
) ON COMMIT PRESERVE ROWS;
LOAD TABLE MyData FROM 'exported.dat';
UNLOAD
SELECT * FROM MyData
WHERE ISDATE( birth_date ) = 0
OR ISNUMERIC( height_in_cms ) = 0
TO 'badrows.dat';
INSERT INTO PermData
SELECT person, birth_date, height_in_cms
FROM MyData
WHERE ISDATE( birth_date ) = 1
AND ISNUMERIC( height_in_cms ) = 1;
COMMIT;
DROP TABLE MyData;

ISENCRYPTED function [System]


Determines if a string is encrypted using the ENCRYPT function and the specified key.

Syntax
ISENCRYPTED( string, key[, algorithm ] )

252 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Returns
INT

Parameters
● string The string to be analyzed to determine if it is encrypted. This parameter is case sensitive,
even in case-insensitive databases.

● key The encryption key used to encrypt the string. This parameter is case sensitive, even in case-
insensitive databases.

● algorithm This optional parameter specifies the algorithm used when the string was encrypted.
Supported algorithms include: AES, AES256, AES_FIPS, and AES256_FIPS.

You can specify one of the FIPS-certified algorithms for algorithm on any platform that supports
FIPS-certified encryption.

Note
RSA, ECC, and FIPS-certified encryption are not available on all platforms. For information about
which platforms support which encryption method, see http://www.sybase.com/detail?id=1061806.

If algorithm is not specified, AES is used by default. If the database server was started using the -fips
server option, the default is AES_FIPS.

Remarks
ISENCRYPTED returns 1 when the input string is encrypted with the specified key; otherwise it returns
0.

See also
● “ENCRYPT function [String]” on page 210
● “DECRYPT function [String]” on page 204

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following fragment illustrates the use of the ISENCRYPTED function:
SELECT ISENCRYPTED( ENCRYPT ('test_string', 'key' ), 'key');

ISNULL function [Miscellaneous]


Returns the first non-NULL expression from a list. This function is identical to the COALESCE function.

Syntax
ISNULL( expression, expression [, ...] )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 253


SQL functions

Parameters
● expression An expression to be tested against NULL.

At least two expressions must be passed into the function, and all expressions must be comparable.

Returns
The return type for this function depends on the expressions specified. That is, when the database server
evaluates the function, it first searches for a data type in which all the expressions can be compared. When
found, the database server compares the expressions and then returns the result in the type used for the
comparison. If the database server cannot find a common comparison type, an error is returned.

See also
● “COALESCE function [Miscellaneous]” on page 164

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value -66.
SELECT ISNULL( NULL ,-66, 55, 45, NULL, 16 );

ISNUMERIC function [Miscellaneous]


Determines if a string argument is a valid number.

Syntax
ISNUMERIC( string )

Parameters
● string The string to be analyzed to determine if the string represents a valid number.

Returns
INT

Remarks
ISNUMERIC returns 1 when the input string evaluates to a valid integer or floating-point number;
otherwise it returns 0. The function also returns 0 if the string contains only blanks or is NULL.

Following are values that also cause the ISNUMERIC function to return 0:

● Values that use the letter d or D as the exponent separator. For example, 1d2.

● Special values such as NAN, 0x12, INF, and INFINITY.

● NULL (for example, SELECT ISNUMERIC( NULL );)

254 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example imports data from an external file, exports rows that contain invalid values, and
copies the remaining rows to a permanent table. In this example, the ISNUMERIC statement validates
that the values in height_in_cms values are numeric.
CREATE GLOBAL TEMPORARY TABLE MyData(
person VARCHAR(100),
birth_date VARCHAR(30),
height_in_cms VARCHAR(10)
) ON COMMIT PRESERVE ROWS;
LOAD TABLE MyData FROM 'exported.dat';
UNLOAD
SELECT *
FROM MyData
WHERE ISDATE( birth_date ) = 0
OR ISNUMERIC( height_in_cms ) = 0
TO 'badrows.dat';
INSERT INTO PermData
SELECT person, birth_date, height_in_cms
FROM MyData
WHERE ISDATE( birth_date ) = 1
AND ISNUMERIC( height_in_cms ) = 1;
COMMIT;
DROP TABLE MyData;

LAST_VALUE function [Aggregate]


Returns values from the last row of a window.

Syntax
LAST_VALUE( [ ALL ] expression[ { RESPECT | IGNORE } NULLS ] )
OVER ( window-spec )

window-spec : see the Remarks section below

Parameters
● expression The expression to evaluate. For example, a column name.

Returns
Data type of the argument.

Remarks
The LAST_VALUE function allows you to select the last value (according to some ordering) in a table,
without having to use a self-join. This is valuable when you want to use the last value as the baseline in
calculations.

The LAST_VALUE function takes the last record from the partition after doing the ORDER BY. Then,
the expression is computed against the last record and results are returned.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 255


SQL functions

If IGNORE NULLS is specified, the last non-NULL value of expression is returned. If RESPECT
NULLS is specified (the default), the last value is returned whether or not it is NULL.

The LAST_VALUE function is different from most other aggregate functions in that it can only be used
with a window specification.

Elements of window-spec can be specified either in the function syntax (inline), or in conjunction with a
WINDOW clause in the SELECT statement. See the window-spec definition for the WINDOW clause.
See “WINDOW clause” on page 961.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “Window aggregate functions” [SQL Anywhere Server - SQL Usage]
● “FIRST_VALUE function [Aggregate]” on page 223

Standards and compatibility


● SQL/2008 Vendor extension.

SQL Anywhere supports SQL/2008 language feature F441, "Extended set function support", which
permits operands of window functions to be arbitrary expressions that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the LAST_VALUE function, combined with an
outer reference. For an example, see “AVG function [Aggregate]” [UltraLite - Database Management
and Reference].

Example
The following example returns the salary of each employee, plus the name of the employee with the
highest salary in the same department:

SELECT GivenName + ' ' + Surname AS employee_name,


Salary, DepartmentID,
LAST_VALUE( employee_name ) OVER Salary_Window AS highest_paid
FROM Employees
WINDOW Salary_Window AS ( PARTITION BY DepartmentID ORDER BY Salary
RANGE BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING );

employee_name Salary DepartmentID highest_paid

Michael Lynch 24903 500 Jose Martinez

Joseph Barker 27290 500 Jose Martinez

256 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

employee_name Salary DepartmentID highest_paid

Sheila Romero 27500 500 Jose Martinez

Felicia Kuo 28200 500 Jose Martinez

Jeannette Bertrand 29800 500 Jose Martinez

Jane Braun 34300 500 Jose Martinez

Anthony Rebeiro 34576 500 Jose Martinez

Charles Crowley 41700 500 Jose Martinez

Jose Martinez 55500.8 500 Jose Martinez

Doug Charlton 28300 400 Scott Evans

Elizabeth Lambert 29384 400 Scott Evans

Joyce Butterfield 34011 400 Scott Evans

Robert Nielsen 34889 400 Scott Evans

Alex Ahmed 34992 400 Scott Evans

Ruth Wetherby 35745 400 Scott Evans

... ... ... ...

Jose Martinez makes the highest salary in department 500, and Scott Evans makes the highest salary in
department 400.

LCASE function [String]


Converts all characters in a string to lowercase.

Syntax
LCASE( string-expression )

Parameters
● string-expression The string to be converted to lowercase.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 257


SQL functions

Returns
● CHAR
● NCHAR
● LONG VARCHAR
● VARCHAR
● NVARCHAR

Remarks
The LCASE function is identical to the LOWER function.

See also
● “LOWER function [String]” on page 266
● “UCASE function [String]” on page 370
● “UPPER function [String]” on page 372
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension. The equivalent function LOWER is a core feature of the SQL/2008
standard.

Example
The following statement returns the value chocolate.

SELECT LCASE( 'ChoCOlatE' );

LEFT function [String]


Returns multiple characters from the beginning of a string.

Syntax
LEFT( string-expression, integer-expression )

Parameters
● string-expression The string.

● integer-expression The number of characters to return.

Returns
● LONG VARCHAR
● LONG NVARCHAR

Remarks
If the string contains multibyte characters, and the proper collation is being used, the number of bytes
returned may be greater than the specified number of characters.

258 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

You can specify an integer-expression that is larger than the value in the argument string expression. In
this case, the entire value is returned.

This function supports NCHAR inputs and/or outputs. Whenever possible, if the input string uses
character-length semantics, the return value is described in character-length semantics.

See also
● “RIGHT function [String]” on page 326
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the first 5 characters of each Surname value in the Customers table.
SELECT LEFT( Surname, 5) FROM Customers;

LENGTH function [String]


Returns the number of characters in the specified string.

Syntax
{ LENGTH | LEN }( string-expression )

Parameters
● string-expression The string.

Returns
INT

Remarks
Use this function to determine the length of a string. For example, specify a column name for string-
expression to determine the length of values in the column.

If the string contains multibyte characters, and the proper collation is being used, LENGTH returns the
number of characters, not the number of bytes. If the string is of data type BINARY, the LENGTH
function behaves as the BYTE_LENGTH function.

Note
You can use the LENGTH function and the CHAR_LENGTH function interchangeably for CHAR,
VARCHAR, LONG VARCHAR, and NCHAR data types. However, you must use the LENGTH function
for BINARY and bit array data types.

This function supports NCHAR inputs and/or outputs.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 259


SQL functions

See also
● “BYTE_LENGTH function [String]” on page 157
● “International languages and character sets” [SQL Anywhere Server - Database Administration]
● “String functions” on page 142

Standards and compatibility


● SQL/2008 The LENGTH function is a vendor extension; however, its semantics are identical to
those of the CHAR_LENGTH function in the SQL/2008 standard. Using LENGTH over a string
expression of type NCHAR comprises part of optional SQL/2008 language feature F421.

Example
The following statement returns the value 9.

SELECT LENGTH( 'chocolate' );

LESSER function [Miscellaneous]


Returns the lesser of two parameter values.

Syntax
LESSER( expression-1, expression-2 )

Parameters
● expression-1 The first parameter value to be compared.

● expression-2 The second parameter value to be compared.

Returns
The return type for this function depends on the expressions specified. That is, when the database server
evaluates the function, it first searches for a data type in which all the expressions can be compared. When
found, the database server compares the expressions and then returns the result in the type used for the
comparison. If the database server cannot find a common comparison type, an error is returned.

Remarks
If the parameters are equal, the first value is returned.

See also
● “GREATER function [Miscellaneous]” on page 231

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 5.

260 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

SELECT LESSER( 10, 5 ) FROM dummy;

LIST function [Aggregate]


Returns a delimited list of values for every row in a group.

Syntax
LIST(
[ALL | DISTINCT ] string-expression
[, delimiter-string ]
[ ORDER BY order-by-expression [ ASC | DESC ], ... ] )

Parameters
● string-expression A string expression, usually a column name. When ALL is specified (the
default), for each row in the group, the value of string-expression is added to the result string, with
values separated by delimiter-string. When DISTINCT is specified, only unique string-expression
values are added.

● delimiter-string A delimiter string for the list items. The default setting is a comma. There is no
delimiter if a value of NULL or an empty string is supplied. The delimiter-string must be a constant.

● order-by-expression Order the items returned by the function. There is no comma preceding this
argument, which makes it easy to use in the case where no delimiter-string is supplied.

order-by-expression cannot be an integer literal. However, it can be a variable that contains an integer
literal.

When an ORDER BY clause contains constants, they are interpreted by the optimizer and then
replaced by an equivalent ORDER BY clause. For example, the optimizer interprets ORDER BY 'a' as
ORDER BY expression.

A query block containing more than one aggregate function with valid ORDER BY clauses can be
executed if the ORDER BY clauses can be logically combined into a single ORDER BY clause. For
example, the following clauses:

ORDER BY expression1, 'a', expression2

ORDER BY expression1, 'b', expression2, 'c', expression3

are subsumed by the clause:

ORDER BY expression1, expression2, expression3

Returns
● LONG VARCHAR
● LONG NVARCHAR

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 261


SQL functions

Remarks
The LIST function returns the concatenation (with delimiters) of all the non-NULL values of X for each
row in the group. If there does not exist at least one row in the group with a definite X-value, then
LIST( X ) returns the empty string.

NULL values and empty strings are ignored by the LIST function.

A LIST function cannot be used as a window function, but it can be used as input to a window function.

This function supports NCHAR inputs and/or outputs.

Standards and compatibility


● SQL/2008 Vendor extension.

SQL Anywhere supports SQL/2008 language feature F441, "Extended set function support", which
permits operands of aggregate functions to be arbitrary expressions that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the LIST function, combined with an outer
reference. See “Aggregate functions and outer references” [SQL Anywhere Server - SQL Usage].

For an example, see “AVG function [Aggregate]” [UltraLite - Database Management and Reference].

See also
● “sa_split_list system procedure” on page 1142

Examples
The following statement returns the value 487 Kennedy Court, 547 School Street.
SELECT LIST( Street ) FROM Employees
WHERE GivenName = 'Thomas';

The following statement lists employee IDs. Each row in the result set contains a comma-delimited list of
employee IDs for a single department.
SELECT LIST( EmployeeID )
FROM Employees
GROUP BY DepartmentID;

LIST( EmployeeID )

102,105,160,243,247,249,266,278,...

129,195,299,467,641,667,690,856,...

148,390,586,757,879,1293,1336,...

184,207,318,409,591,888,992,1062,...

262 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

LIST( EmployeeID )

191,703,750,868,921,1013,1570,...

The following statement sorts the employee IDs by the last name of the employee:

SELECT LIST( EmployeeID ORDER BY Surname ) AS "Sorted IDs"


FROM Employees
GROUP BY DepartmentID;

Sorted IDs '1751,591,1062,1191,992,888,318,184,1576,207,1684,1643,1607,1740,409,1507'

Sorted IDs

1013,191,750,921,868,1658,...

1751,591,1062,1191,992,888,318,...

1336,879,586,390,757,148,1483,...

1039,129,1142,195,667,1162,902,...

160,105,1250,247,266,249,445,...

The following statement returns semicolon-separated lists. Note the position of the ORDER BY clause
and the list separator:

SELECT LIST( EmployeeID, ';' ORDER BY Surname ) AS "Sorted IDs"


FROM Employees
GROUP BY DepartmentID;

Sorted IDs

1013;191;750;921;868;1658;703;...

1751;591;1062;1191;992;888;318;...

1336;879;586;390;757;148;1483;...

1039;129;1142;195;667;1162;902; ...

160;105;1250;247;266;249;445;...

Be sure to distinguish the previous statement from the following statement, which returns comma-
separated lists of employee IDs sorted by a compound sort-key of ( Surname, ';' ):

SELECT LIST( EmployeeID ORDER BY Surname, ';' ) AS "Sorted IDs"


FROM Employees
GROUP BY DepartmentID;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 263


SQL functions

LOCATE function [String]


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. If the starting offset is negative, the locate function returns the last matching string offset
rather than the first. A negative offset indicates how much of the end of the string is to be excluded
from the search. The number of bytes excluded is calculated as (-1 * offset) -1.

Returns
INT

Remarks
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 multibyte characters are used, with the appropriate collation, then the starting position and the return
value may be different from the byte positions.

This function supports NCHAR inputs and/or outputs.

See also
● “String functions” on page 142
● “CHARINDEX function [String]” on page 163

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 8.
SELECT LOCATE(
'office party this week - rsvp as soon as possible',
'party',
2 );

264 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

The following statement:

BEGIN
DECLARE STR LONG VARCHAR;
DECLARE POS INT;
SET str = 'c:\test\functions\locate.sql';
SET pos = LOCATE( str, '\', -1 );
select str, pos,
SUBSTR( str, 1, pos -1 ) AS path,
SUBSTR( str, pos +1 ) AS filename;
END;

returns the following output:

str pos path filename

c:\test\functions\locate.sql 18 c:\test\functions locate.sql

LOG function [Numeric]


Returns the natural logarithm of a number.

Syntax
LOG( numeric-expression )

Parameters
● numeric-expression The number.

Returns
This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns a DOUBLE as the result. If the parameter is NULL, the result is NULL.

Remarks
The argument is an expression that returns the value of any built-in numeric data type.

See also
● “LOG10 function [Numeric]” on page 266

Standards and compatibility


● SQL/2008 The SQL/2008 standard defines the natural logarithm function using the keyword LN.
The natural logarithm function comprises part of optional SQL/2008 language feature T621,
"Enhanced numeric functions".

Example
The following statement returns the natural logarithm of 50.

SELECT LOG( 50 );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 265


SQL functions

LOG10 function [Numeric]


Returns the base 10 logarithm of a number.

Syntax
LOG10( numeric-expression )

Parameters
● numeric-expression The number.

Returns
This function converts its argument to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the parameter is NULL, the result is NULL.

Remarks
The argument is an expression that returns the value of any built-in numeric data type.

See also
● “LOG function [Numeric]” on page 265

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the base 10 logarithm for 50.
SELECT LOG10( 50 );

LOWER function [String]


Converts all characters in a string to lowercase. This function is identical to the LCASE function.

Syntax
LOWER( string-expression )

Parameters
● string-expression The string to be converted to lowercase.

Returns
CHAR, VARCHAR, LONG VARCHAR, NCHAR, NVARCHAR, or LONG NVARCHAR
corresponding to the data type of the argument.

Remarks
The LCASE function is identical to the LOWER function.

266 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “LCASE function [String]” on page 257
● “UCASE function [String]” on page 370
● “UPPER function [String]” on page 372
● “String functions” on page 142

Standards and compatibility


● SQL/2008 The LOWER function is a core feature of the SQL/2008 standard. Using LOWER over
an expression of type NCHAR comprises part of optional SQL/2008 language feature F421.

Example
The following statement returns the value chocolate.
SELECT LOWER( 'chOCOLate' );

LTRIM function [String]


Removes leading blanks from the string.

Syntax
LTRIM( string-expression )

Parameters
● string-expression The string to be trimmed.

Returns
● VARCHAR
● NVARCHAR
● LONG VARCHAR
● LONG NVARCHAR

Remarks
The actual length of the result is the length of the expression minus the number of characters removed. If
all the characters are removed, the result is an empty string.

If the parameter can be null, the result can be null.

If the parameter is null, the result is the null value.

This function supports NCHAR inputs and/or outputs.

See also
● “RTRIM function [String]” on page 330
● “TRIM function [String]” on page 367
● “String functions” on page 142

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 267


SQL functions

Standards and compatibility


● SQL/2008 Vendor extension.

The TRIM specifications defined by the SQL/2008 standard (LEADING and TRAILING) are
supplied by the SQL Anywhere LTRIM and RTRIM functions respectively.

Example
The following statement returns the value Test Message with all leading blanks removed.
SELECT LTRIM( ' Test Message' );

MAX function [Aggregate]


Returns the maximum expression value found in each group of rows.

Syntax 1
MAX( [ ALL | DISTINCT ] expression )

Syntax 2
MAX( [ ALL ] expression ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● [ ALL ] expression The expression for which the maximum value is to be calculated. This is
commonly a column name.

● DISTINCT expression Returns the same as MAX( expression ), and is included for completeness.

Returns
The same data type as the argument.

Remarks
Rows where expression is NULL are ignored. Returns NULL for a group containing no rows.

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition of the WINDOW clause. See “WINDOW clause”
on page 961.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

This function supports NCHAR inputs and/or outputs.

268 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

For simple comparisons of two expressions, you can also use the GREATER function.

See also
● “GREATER function [Miscellaneous]” on page 231
● “MIN function [Aggregate]” on page 271

Standards and compatibility


● SQL/2008 Core feature. When used as a window function (Syntax 2), MAX comprises part of
optional SQL/2008 language feature T611, "Basic OLAP operations".

The ability to specify DISTINCT over an expression that is not a column reference comprises part of
optional SQL language feature F561, "Full value expressions". SQL Anywhere also supports SQL/
2008 language feature F441, "Extended set function support", which permits operands of aggregate
functions to be arbitrary expressions possibly including outer references to expressions in other query
blocks that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the MAX function, combined with an outer
reference.

For an example, see “AVG function [Aggregate]” [UltraLite - Database Management and Reference].

See also
● “Aggregate functions and outer references” [SQL Anywhere Server - SQL Usage]

Example
The following statement returns the value 138948.000, representing the maximum salary in the
Employees table.
SELECT MAX( Salary )
FROM Employees;

MEDIAN function [Aggregate]


Computes the median of a numeric expression for a set of rows.

Syntax 1
MEDIAN( [ ALL | DISTINCT ] numeric-expression )

Syntax 2
MEDIAN( [ ALL ] numeric-expression ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● numeric-expression The expression whose median is calculated over a set of rows.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 269


SQL functions

● DISTINCT clause Eliminates duplicate values before computing the median of the unique values
in the input.

● ALL clause Computes the median of all values (including duplicates) in the input. This is the
default behavior.

Returns
The data type of the returned value is the same as that of the input value.

NULLs are ignored in the calculation of the median value. However, a NULL value is returned for a
group that contains no rows.

Remarks
numeric-expression values can be of any numeric data type other than BIT. See “Numeric data types”
on page 89.

The median of a finite list of numbers can be found by arranging all the observations from lowest value to
highest value and picking the middle one. If there is an even number of observations, the median is not
unique so MEDIAN returns the mean of the two middle values. At most, half the population have values
less than the median, and half have values greater than the median. If both groups contain less than half
the population, then some of the population is exactly equal to the median. For example, if a < b < c,
then the median of the list {a, b, c} is b. If a < b < c < d, then the median of the list {a, b,
c, d} is the mean of b and c ( (b + c)/2).

If the result of the mean of the two middle elements has digits after the decimal place, they are truncated
if the input data type can not represent them. To avoid this truncation, cast the input to a numeric type that
allows digits after the decimal place.

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition provided in “WINDOW clause” on page 961.

window-spec can only be over a partition (it cannot contain a ROW or RANGE specification). DISTINCT
is not supported if a WINDOW clause is used. CUBE, ROLLUP, and GROUPING SETS are supported
with syntax 1.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “SUM function [Aggregate]” on page 355
● “COUNT function [Aggregate]” on page 177

Standards and compatibility


● SQL/2008 Vendor extension. Window functions comprise optional SQL/2008 language feature
T611, "Basic OLAP operations".

270 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

SQL Anywhere supports SQL/2008 language feature F441, "Extended set function support", which
permits operands of window functions to be arbitrary expressions that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the MEDIAN function, combined with an outer
reference. For an example, see “AVG function [Aggregate]” [UltraLite - Database Management and
Reference].

Example
The following statement returns the median salary from the Employees table.

SELECT MEDIAN( Salary ) FROM Employees;

The following statement returns the median salary by state from the Employees table:

SELECT EmployeeID, Surname, Salary, State,


MEDIAN( Salary ) OVER Salary_Window
FROM Employees
WINDOW Salary_Window AS ( PARTITION BY State )
ORDER BY State, Surname;

MIN function [Aggregate]


Returns the minimum expression value found in each group of rows.

Syntax 1
MIN( [ ALL | DISTINCT ] expression )

Syntax 2
MIN( [ ALL ] expression ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● [ ALL ] expression The expression for which the minimum value is to be calculated. This is
commonly a column name.

● DISTINCT expression Returns the same as MIN( expression ), and is included for completeness.

Returns
The same data type as the argument.

Remarks
Rows where expression is NULL are ignored. Returns NULL for a group containing no rows.

This function supports NCHAR inputs and/or outputs.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 271


SQL functions

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. More information is available in the window-spec definition for the WINDOW
clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

For simple comparisons of two expressions, you can also use the LESSER function. See “LESSER
function [Miscellaneous]” on page 260.

See also
● “MAX function [Aggregate]” on page 268
● “WINDOW clause” on page 961

Standards and compatibility


● SQL/2008 Core feature. When used as a window function (Syntax 2), MIN comprises part of
optional SQL/2008 language feature T611, "Basic OLAP operations".

The ability to specify DISTINCT over an expression that is not a column reference comprises part of
optional SQL language feature F561, "Full value expressions". SQL Anywhere also supports SQL/
2008 language feature F441, "Extended set function support", which permits operands of aggregate
functions to be arbitrary expressions possibly including outer references to expressions in other query
blocks that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the MIN function, combined with an outer
reference. See “Aggregate functions and outer references” [SQL Anywhere Server - SQL Usage].

For an example, see “AVG function [Aggregate]” [UltraLite - Database Management and Reference].

Example
The following statement returns the value 24903.000, representing the minimum salary in the Employees
table.
SELECT MIN( Salary )
FROM Employees;

MINUTE function [Date and time]


Returns the minute component of a TIMESTAMP value.

Syntax
MINUTE( timestamp-expression )

272 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Parameters
● timestamp-expression The TIMESTAMP value.

Returns
SMALLINT

Remarks
The value returned is the minute portion of the TIMESTAMP expression, a SMALLINT value between 0
and 59.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 22.
SELECT MINUTE( '1998-07-13 12:22:34' );

MINUTES function [Date and time]


The MINUTES function manipulates a TIMESTAMP, or returns the number of minutes between two
TIMESTAMP values. See the Remarks section below.

Syntax 1
MINUTES( timestamp-expression )

Syntax 2
MINUTES( timestamp-expression, timestamp-expression )

Syntax 3
MINUTES( timestamp-or-time-expression, integer-expression )

Parameters
● timestamp-expression An expression of type TIMESTAMP.

● timestamp-or-time-expression An expression of type TIME or TIMESTAMP.

● integer-expression The number of minutes to be added to timestamp-or-time-expression. If


integer-expression is negative, the appropriate number of minutes is subtracted from timestamp-or-
time-expression.

Returns
INTEGER with Syntax 1 or Syntax 2.

TIME or TIMESTAMP with Syntax 3.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 273


SQL functions

Remarks
The result of the MINUTES function depends on its arguments.

● Syntax 1 If you pass a single timestamp-expression to the MINUTES function, it will return the
number of minutes between midnight 0000-02-29 and timestamp-expression as an INTEGER.

Note
0000-02-29 is not meant to imply an actual date; it is the default date used by the MINUTES function.

● Syntax 2 If you pass two TIMESTAMP values to the MINUTES function, the function returns the
integer number of minutes between them.

● Syntax 3 If you pass a TIMESTAMP value and an INTEGER value to the MINUTES function, the
function returns the TIMESTAMP result of adding the integer number of minutes to timestamp-
expression argument. Similarly, if the first argument to MINUTES is a TIME value, then the result is
also a TIME value. Syntax 3 does not support implicit conversion of the first argument. It may be
necessary to explicitly cast the first argument to a DATE, TIME or TIMESTAMP value. If the first
argument is of type DATE, midnight is assumed for the time portion.

Since MINUTES returns an integer, overflow can occur when Syntax 1 is used with TIMESTAMP values
greater than or equal to 4083-03-23 02:08:00.

Instead of Syntax 2, use the DATEDIFF function. Instead of Syntax 3, use the DATEADD function.

See also
● “DATEDIFF function [Date and time]” on page 189
● “DATEADD function [Date and time]” on page 188
● “CAST function [Data type conversion]” on page 159

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements return the value 240, signifying that the second TIMESTAMP value is 240
minutes after the first. It is recommended that you use the second example (DATEDIFF).
SELECT MINUTES( '1999-07-13 06:07:12',
'1999-07-13 10:07:12' );

SELECT DATEDIFF( minute,


'1999-07-13 06:07:12',
'1999-07-13 10:07:12' );

The following statement returns the value 1051040527.


SELECT MINUTES( '1998-07-13 06:07:12' );

The following statements return the TIMESTAMP value 1999-05-12 21:10:07.000. Note that the first
statement requires an explicit cast of the literal string parameter. It is recommended that you use the
second example (DATEADD).

274 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

SELECT MINUTES( CAST( '1999-05-12 21:05:07' AS TIMESTAMP ), 5);

SELECT DATEADD( minute, 5, '1999-05-12 21:05:07' );

The following statement returns 'TIME', illustrating that the MINUTES function returns a TIME value
when it is called with a TIME argument.

SELECT EXPRTYPE('SELECT MINUTES( CAST( ''13:45:00.000'' AS TIME ), 16 )', 1);

MOD function [Numeric]


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.

Returns
● SMALLINT
● INT
● NUMERIC

Remarks
Division involving a negative dividend gives a negative or zero result. The sign of the divisor has no
effect.

See also
● “REMAINDER function [Numeric]” on page 320

Standards and compatibility


● SQL/2008 The MOD function is part of optional SQL/2008 language feature T441.

Example
The following statement returns the value 2.

SELECT MOD( 5, 3 );

MONTH function [Date and time]


Returns the month of the given date.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 275


SQL functions

Syntax
MONTH( date-expression )

Parameters
● date-expression A value of type DATE.

Returns
SMALLINT

Remarks
The value returned is a number between 1 and 12, corresponding to the month of the given date.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 7.
SELECT MONTH( '1998-07-13' );

MONTHNAME function [Date and time]


Returns the name of the month from a date.

Syntax
MONTHNAME( date-expression )

Parameters
● timestamp-expression A TIMESTAMP value.

Returns
VARCHAR

Remarks
The MONTHNAME function returns a string, even if the result is numeric, such as 2 for the month of
February.

See also
● “DATEPART function [Date and time]” on page 192

Standards and compatibility


● SQL/2008 Vendor extension.

276 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example
The following statement returns the value September.

SELECT MONTHNAME( '1998-09-05' );

MONTHS function [Date and time]


The MONTHS function manipulates a TIMESTAMP, or returns the number of months between two
TIMESTAMP values. See the Remarks section below.

Syntax 1
MONTHS( timestamp-expression )

Syntax 2
MONTHS( timestamp-expression, timestamp-expression )

Syntax 3
MONTHS( timestamp-expression, integer-expression )

Parameters
● timestamp-expression A date and time of type TIMESTAMP.

● integer-expression The integer number of months (of type SMALLINT) to be added to the
timestamp-expression. If integer-expression is negative, the appropriate number of months is
subtracted from timestamp-expression. If you supply an integer-expression, the timestamp-expression
must be explicitly cast as a TIME, DATE or TIMESTAMP data type. If timestamp-expression is a
TIME value, the current month is assumed.

For information about casting data types, see “CAST function [Data type conversion]” on page 159.

Returns
INTEGER with Syntax 1 or Syntax 2.

TIMESTAMP with Syntax 3.

Remarks
The result of the MONTHS function depends on its arguments. The MONTHS function ignores hours,
minutes, and seconds in its arguments.

● Syntax 1 If you pass a single timestamp-expression to the MONTHS function, it will return the
number of months between 0000-02 and timestamp-expression as an INTEGER.

Note
0000-02 is not meant to imply an actual date; it is the default date used by the MONTHS function.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 277


SQL functions

● Syntax 2 If you pass two TIMESTAMP values to the MONTHS function, the function returns the
integer number of months between them.

● Syntax 3 If you pass a TIMESTAMP value and a SMALLINT value to the MONTHS function, the
function returns the TIMESTAMP result of adding the integer number of months to timestamp-
expression.

Instead of Syntax 2, use the DATEDIFF function. Instead of Syntax 3, use the DATEADD function.

The value of MONTHS is calculated from the number of first days of the month between the two dates.

See also
● “DATEDIFF function [Date and time]” on page 189
● “DATEADD function [Date and time]” on page 188

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements return the value 2, signifying that the second date is two months after the first. It
is recommended that you use the second example (DATEDIFF).
SELECT MONTHS( '1999-07-13 06:07:12', '1999-09-13 10:07:12' );

SELECT DATEDIFF( month,


'1999-07-13 06:07:12',
'1999-09-13 10:07:12' );

The following statement returns the value 23981.


SELECT MONTHS( '1998-07-13 06:07:12' );

The following statements return the TIMESTAMP value 1999-10-12 21:05:07.000. It is recommended
that you use the second example (DATEADD).
SELECT MONTHS( CAST( '1999-05-12 21:05:07' AS DATETIME ), 5);

SELECT DATEADD( month, 5, '1999-05-12 21:05:07' );

NCHAR function [String]


Returns an NCHAR string containing one character whose Unicode code point is given in the parameter,
or NULL if the value is not a valid code point value.

Syntax
NCHAR( integer )

Parameters
● integer The number to be converted to the corresponding Unicode code point.

278 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Returns
NVARCHAR

See also
● “CONNECTION_EXTENDED_PROPERTY function [String]” on page 169
● “TO_NCHAR function [String]” on page 361
● “TO_CHAR function [String]” on page 360
● “UNICODE function [String]” on page 370
● “UNISTR function [String]” on page 371

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example returns the ALEF Arabic letter, which is Unicode code point U+627:
SELECT NCHAR( 1575 );

NEWID function [Miscellaneous]


Generates a UUID (Universally Unique Identifier) value. A UUID is the same as a GUID (Globally
Unique Identifier).

Syntax
NEWID( )

Parameters
There are no parameters associated with the NEWID function.

Returns
UNIQUEIDENTIFIER

Remarks
The NEWID function can be used in a DEFAULT clause for a column.

UUIDs can be used to uniquely identify rows in a table. A value produced on one computer does not
match a value produced on another computer, so they can be used as keys in synchronization and
replication environments.

UUIDs contain hyphens for compatibility with other RDBMSs. You change this by setting the
uuid_has_hyphens option to Off. For more information, see “uuid_has_hyphens option” [SQL Anywhere
Server - Database Administration].

The NEWID function is non-deterministic; successive calls will return different values. The query
optimizer does not cache the results of the NEWID function.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 279


SQL functions

For more information about non-deterministic functions, see “Function caching” [SQL Anywhere Server -
SQL Usage].

See also
● “The NEWID default” [SQL Anywhere Server - SQL Usage]
● “STRTOUUID function [String]” on page 351
● “UUIDTOSTR function [String]” on page 374
● “UNIQUEIDENTIFIER data type” on page 118

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement creates a table named mytab with two columns. Column pk has a unique
identifier data type, and assigns the NEWID function as the default value. Column c1 has an integer data
type.
CREATE TABLE mytab(
pk UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
c1 INT );

The following statement returns a unique identifier as a string:


SELECT UUIDTOSTR( NEWID() );

For example, the value returned might be 96603324-6FF6-49DE-BF7D-F44C1C7E6856.

NEXT_CONNECTION function [System]


Returns an identifying number for the next connection.

Syntax
NEXT_CONNECTION( connection-id [, database-id ] )

Returns
INT

Parameters
● connection-id An integer, usually returned from a previous call to NEXT_CONNECTION. If
connection-id is NULL, NEXT_CONNECTION returns the most recent 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.

280 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Remarks
NEXT_CONNECTION can be used to enumerate the connections to a database. Connection IDs are
generally created in monotonically increasing order. This function returns the next connection ID in
reverse order.

To get the connection ID value for the most recent connection, enter NULL as the connection-id. To get
the subsequent connection, enter the previous return value. The function returns NULL when there are no
more connections in the order.

NEXT_CONNECTION is useful if you want to disconnect all the connections created before a specific
time. However, because NEXT_CONNECTION returns the connection IDS in reverse order, connections
made after the function is started are not returned. If you want to ensure that all connections are
disconnected, prevent new connections from being created before you run NEXT_CONNECTION.

Cloud note: Because of tenant database isolation rules, when this function is called in the cloud it
returns only information about the current tenant database.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns an identifier for the first connection on the current database. The
identifier is an integer value like 10.
SELECT NEXT_CONNECTION( NULL );

The following statement returns a value like 5.


SELECT NEXT_CONNECTION( 10 );

The following call returns the next connection ID in reverse order from the specified connection-id on the
current database.
SELECT NEXT_CONNECTION( connection-id );

The following call returns the next connection ID in reverse order from the specified connection-id
(regardless of database).
SELECT NEXT_CONNECTION( connection-id, NULL );

The following call returns the next connection ID in reverse order from the specified connection-id on the
specified database.
SELECT NEXT_CONNECTION( connection-id, database-id );

The following call returns the first (earliest) connection (regardless of database).
SELECT NEXT_CONNECTION( NULL, NULL );

The following call returns the first (earliest) connection on the specified database.
SELECT NEXT_CONNECTION( NULL, database-id );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 281


SQL functions

NEXT_DATABASE function [System]


Returns an identifying number for a database.

Syntax
NEXT_DATABASE( database-id )

Parameters
● database-id An integer that specifies the ID number of the database.

Returns
INT

Remarks
The NEXT_DATABASE function is 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. The database ID numbers are not returned in a
particular order, but you can tell the order in which databases were started on the server using the
database ID. The first database started on the server is assigned the value 0, and for subsequent databases
started on the server, the database IDs are incremented by 1.

Cloud note: Because of tenant database isolation rules, when this function is called in the cloud it
returns only information about the current tenant database.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 0, the first database value.
SELECT NEXT_DATABASE( NULL );

The following statement returns NULL, only when one database has been started.
SELECT NEXT_DATABASE( 0 );

See also
● “DB_NAME function [System]” on page 201
● “sa_db_list system procedure” on page 1031

NEXT_HTTP_HEADER function [Web service]


Returns the next HTTP header name.

282 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Syntax
NEXT_HTTP_HEADER( header-name )

Parameters
● header-name The name of the previous request header. If header-name is NULL, this function
returns the name of the first HTTP request header.

Returns
LONG VARCHAR

Remarks
This function is used to iterate over the HTTP request headers returning the next HTTP header name.
Calling it with NULL causes it to return the name of the first header. Subsequent headers are retrieved by
passing the name of the previous header to the function. This function returns NULL when called with the
name of the last header, or when not called from a web service.

Calling this function repeatedly returns all the header fields exactly once, but not necessarily in the order
they appear in the HTTP request.

See also
● “HTTP_HEADER function [Web service]” on page 242
● “sa_http_header_info system procedure” on page 1059
● “Accessing client-supplied HTTP variables and headers” [SQL Anywhere Server - Programming]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Example
When used within a stored procedure that is called by an HTTP web service, the following example
displays the name and values of the HTTP request headers in the database server messages window.

BEGIN
declare header_name long varchar;
declare header_value long varchar;
set header_name = NULL;
header_loop:
LOOP
SET header_name = NEXT_HTTP_HEADER( header_name );
IF header_name IS NULL THEN
LEAVE header_loop
END IF;
SET header_value = HTTP_HEADER( header_name );
MESSAGE 'HEADER: ', header_name, '=',
header_value TO CONSOLE;
END LOOP;
END;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 283


SQL functions

NEXT_HTTP_RESPONSE_HEADER function [Web service]


Returns the next HTTP response header name.

Syntax
NEXT_HTTP_RESPONSE_HEADER( header-name )

Parameters
● header-name The name of the previous response header. If header-name is NULL, this function
returns the name of the first HTTP response header.

Returns
LONG VARCHAR

Remarks
This function is used to iterate over the HTTP response headers returning the next HTTP response header
name. Calling it with NULL causes it to return the name of the first response header. Subsequent response
headers are retrieved by passing the name of the previous response header to the function. This function
returns NULL when called with the name of the last response header, or if it is not called from a web
service.

Calling this function repeatedly returns all the response header fields exactly once, but not necessarily in
the order they appear in the HTTP response.

See also
● “HTTP_RESPONSE_HEADER function [Web service]” on page 244
● “HTTP request header management” [SQL Anywhere Server - Programming]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Example
When used within a stored procedure that is called by an HTTP web service, the following example
displays the name and values of the HTTP response headers in the database server messages window.

BEGIN
declare header_name long varchar;
declare header_value long varchar;
set header_name = NULL;
header_loop:
LOOP
SET header_name = NEXT_HTTP_RESPONSE_HEADER( header_name );
IF header_name IS NULL THEN
LEAVE header_loop
END IF;
SET header_value = HTTP_RESPONSE_HEADER( header_name );

284 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

MESSAGE 'RESPONSE HEADER: ', header_name, '=', header_value TO CONSOLE;


END LOOP;

NEXT_HTTP_VARIABLE function [Web service]


Returns the next HTTP variable name.

Syntax
NEXT_HTTP_VARIABLE( var-name )

Parameters
● var-name The name of the previous variable. If var-name is NULL, this function returns the name
of the first HTTP variable.

Returns
LONG VARCHAR

Remarks
This function iterates over the HTTP variables included within a request. Calling it with NULL causes it
to return the name of the first variable. Subsequent variables are retrieved by passing the function the
name of the previous variable. This function returns NULL when called with the name of the final
variable or when not called from a web service.

Calling this function repeatedly returns all the variables exactly once, but not necessarily in the order they
appear in the HTTP request. The variables url or url1, url2, ..., url10 are included if URL PATH is set to
ON or ELEMENTS, respectively.

See also
● “HTTP_VARIABLE function [Web service]” on page 245
● “NEXT_HTTP_HEADER function [Web service]” on page 282
● “sa_http_variable_info system procedure” on page 1062
● “Accessing client-supplied HTTP variables and headers” [SQL Anywhere Server - Programming]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Example
When used within a stored procedure that is called by an HTTP web service, the following example
returns the name of the first HTTP variable.
BEGIN
DECLARE variable_name LONG VARCHAR;
DECLARE variable_value LONG VARCHAR;
SET variable_name = NULL;
SET variable_name = NEXT_HTTP_VARIABLE( variable_name );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 285


SQL functions

SET variable_value = HTTP_VARIABLE( variable_name );


END;

NEXT_SOAP_HEADER function [SOAP]


Returns the next header key in a SOAP request header.

Syntax
NEXT_SOAP_HEADER( header-key )

Parameters
● header-key The XML local name of the top level XML element for the given header entry.

Returns
LONG VARCHAR

Remarks
If you specify NULL for the header-key, the function returns the header key for the first header entry
found in the SOAP header.

This function returns NULL if called with the last header-key.

See also
● “SOAP_HEADER function [SOAP]” on page 338
● “Tutorial: Using SQL Anywhere to access a SOAP/DISH service” [SQL Anywhere Server -
Programming]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Example
When used within a stored procedure that is called by an HTTP web service, the following example
processes all the keys located in the SOAP request header. When it processes the Authentication key, it
also obtains the key's value.
BEGIN
DECLARE hd_key LONG VARCHAR;
DECLARE hd_entry LONG VARCHAR;
header_loop:
LOOP
SET hd_key = NEXT_SOAP_HEADER( hd_key );
IF hd_key IS NULL THEN
-- no more header entries
LEAVE header_loop;
END IF;
IF hd_key = 'Authentication' THEN
SET hd_entry = SOAP_HEADER( hd_key );

286 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

END IF;
END LOOP header_loop;
END;

NOW function [Date and time]


Returns the current date and time as a TIMESTAMP value. The accuracy is limited by the accuracy of the
system clock.

Syntax
NOW( [ * ] )

Returns
TIMESTAMP

Remarks
NOW is equivalent to the GETDATE function and the CURRENT TIMESTAMP special value. NOW(*)
and NOW() are equivalent constructions.

Each instance of the NOW function in a request is evaluated at most once. Multiple instances of NOW in
the same request may or may not share the identical TIMESTAMP value.

See also
● “CURRENT TIME special value” on page 60
● “CURRENT TIMESTAMP special value” on page 61
● “CURRENT UTC TIMESTAMP special value” on page 63
● “DATE data type” on page 107
● “DATE function [Date and time]” on page 187
● “DATETIME data type” on page 108
● “DATETIME function [Date and time]” on page 193
● “DATETIMEOFFSET data type” on page 109
● “Expressions” on page 12
● “GETDATE function [Date and time]” on page 228
● “ISDATE function [Data type conversion]” on page 251
● “SMALLDATETIME data type” on page 111
● “TIME data type” on page 112
● “TIMESTAMP special value” on page 69
● “TIMESTAMP data type” on page 113
● “UTC TIMESTAMP special value” on page 71

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the current date and time.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 287


SQL functions

SELECT NOW( * );

NULLIF function [Miscellaneous]


Provides 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.

Returns
Data type of the first argument.

Remarks
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.

See also
● “CASE expressions” on page 16

Standards and compatibility


● SQL/2008 Core feature.

Example
The following statement returns the value a:
SELECT NULLIF( 'a', 'b' );

The following statement returns NULL.


SELECT NULLIF( 'a', 'a' );

NUMBER function [Miscellaneous]


Generates numbers starting at 1 for each successive row in the results of the query. The NUMBER
function is primarily intended for use in SELECT lists.

288 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Due to limitations imposed by the NUMBER function (described in the Remarks section below), use the
ROW_NUMBER function instead. The ROW_NUMBER function provides the same functionality, but
without the limitations of the NUMBER function. See “ROW_NUMBER function [Miscellaneous]”
on page 327.

Syntax
NUMBER( [ * ] )

Returns
INT

Remarks
You can use NUMBER(*) in a SELECT list to provide a sequential numbering of the rows in the result
set. NUMBER(*) returns the value of the ANSI row number of each result row. This means that the
NUMBER function can return positive or negative values, depending on how the application scrolls
through the result set. For insensitive cursors, the value of NUMBER(*) will always be positive because
the entire result set is materialized at OPEN.

In addition, the row number may be subject to change for some cursor types. The value is fixed for
insensitive cursors and scroll cursors. If there are concurrent updates, it may change for dynamic and
sensitive cursors.

A syntax error is generated if you use the NUMBER function in: a DELETE statement, a WHERE clause,
a HAVING clause, an ORDER BY clause, a subquery, a query involving aggregation, any constraint, a
GROUP BY clause, a DISTINCT clause, a set operator (UNION, EXCEPT, INTERSECT), or a derived
table.

NUMBER(*) can be used in a view (subject to the above restrictions), but the view column corresponding
to the expression involving NUMBER(*) can be referenced at most once in the query or outer view, and
the view cannot participate as a NULL-supplying table in a left outer join or full outer join.

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).

You can use NUMBER in the right side of an assignment in the SET clause of an UPDATE statement.
For example, SET x = NUMBER(*).

The NUMBER function can also be used to generate primary keys when using the INSERT from
SELECT statement, although using an AUTOINCREMENT clause is a preferred mechanism for
generating sequential primary keys.

For information about the AUTOINCREMENT clause, see “CREATE TABLE statement” on page 633.

NUMBER(*) and NUMBER() are semantically equivalent.

See also
● “INSERT statement” on page 780

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 289


SQL functions

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns a sequentially-numbered list of departments.
SELECT NUMBER( * ), DepartmentName
FROM Departments
WHERE DepartmentID > 5
ORDER BY DepartmentName;

PATINDEX function [String]


Returns an integer representing the starting position of the first occurrence of a pattern in a string.

Syntax
PATINDEX( '%pattern%', string-expression )

Parameters
● pattern The pattern to be searched for. If the leading percent wildcard is omitted, the PATINDEX
function returns one (1) if the pattern occurs at the beginning of the string, and zero if it does not.

The pattern uses the same wildcards as the LIKE comparison. These are as follows:

Wildcard 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.

Returns
INT

Remarks
The PATINDEX function returns the starting position of the first occurrence of the pattern. If the pattern
is not found, it returns zero (0).

290 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “LIKE search condition” on page 39
● “LOCATE function [String]” on page 264
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
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' );

The following statement returns 14 which is the first non-alphanumeric character in the string expression.
The pattern '%[^a-z0-9]%' can be used instead of '%[^a-zA-Z0-9]%' if the database is case
insensitive.
SELECT PATINDEX( '%[^a-zA-Z0-9]%', 'SQLAnywhere12 has many new features' );

To get everything up to and including the first non-alphanumeric character in a string, you can use
something like the following:
SELECT LEFT( @string, PATINDEX( '%[^a-zA-Z0-9]%', @string ) );

The following statements create a table, myTable, and populate it with various strings containing
alphanumeric characters, spaces (blanks), and non-alphanumeric characters. Then, the SELECT statement
and subsequent results show how you can use PATINDEX to find the starting position of spaces and non-
alphanumeric characters in the strings:
CREATE TABLE myTable( col1 LONG VARCHAR );

INSERT INTO myTable (col1) VALUES( 'the quick brown fox jumped over the lazy
dog' ),
( 'the quick brown fox $$$$ jumped over the lazy dog' ),
( 'the quick brown fox 0999 jumped over the lazy dog' ),
( 'the quick brown fox ** jumped over the lazy dog' ),
( 'thequickbrownfoxjumpedoverthelazydog' ),
( 'thequickbrownfoxjum999pedoverthelazydog' ),
( 'thequick$$$$brownfox' ),
( 'the quick brown fox$$ jumped over the lazy dog' );

SELECT col1,
//position of first non-alphanumeric character or space:
PATINDEX( '%[^a-z0-9]%', col1) AS blank_posn,
//position of first non-alphanumeric char that isn't a space:
PATINDEX( '%[^ a-z0-9]%', col1) AS non_alpha_char,
//everything up to and including first non-alphanumeric char that isn't a
space:
LEFT ( col1, PATINDEX( '%[^ a-zA-Z0-9]%', col1) ) AS left_str,
//first non-alphanumeric char that isn't a space, and everything to the
right:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 291


SQL functions

SUBSTRING ( col1, PATINDEX( '%[^ a-zA-Z0-9]%', col1) ) AS sub_str


FROM myTable;

col1 blank_posn non_alpha_char left_str sub_str

the quick brown fox jum- 4 0 the quick brown fox


ped over the lazy dog jumped over the lazy
dog

the quick brown fox $$$$ 4 21 the quick $$$$ jumped over the
jumped over the lazy dog brown fox lazy dog
$

the quick brown fox 0999 4 0 the quick brown fox


jumped over the lazy dog 0999 jumped over the
lazy dog

the quick brown fox ** 4 21 the quick ** jumped over the lazy
jumped over the lazy dog brown fox dog
*

thequickbrownfoxjumpe- 0 0 thequickbrownfoxjum-
doverthelazydog pedoverthelazydog

thequickbrownfox- 0 0 thequickbrownfox-
jum999pedoverthelazydog jum999pedoverthelazy-
dog

thequick$$$$brownfox 9 9 thequick$ $$$$brownfox

the quick brown fox$$ 4 20 the quick $$ jumped over the lazy
jumped over the lazy dog brown fox dog
$

PERCENT_RANK function [Ranking]


For any row X, defined by the function's arguments and ORDER BY specification, the
PERCENT_RANK function determines the rank of row X - 1, divided by the number of rows in the
group.

Syntax
PERCENT_RANK( ) OVER ( window-spec )

window-spec : see the Remarks section below

Returns
The PERCENT_RANK function returns a DOUBLE value between 0 and 1.

292 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Remarks
Elements of window-spec can be specified either in the function syntax (inline), or in conjunction with a
WINDOW clause in the SELECT statement. When used as a window function, you must specify an
ORDER BY clause, you may specify a PARTITION BY clause, however, you can not specify a ROWS
or RANGE clause. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “WINDOW clause” on page 961
● “CUME_DIST function [Ranking]” on page 185
● “DENSE_RANK function [Ranking]” on page 206
● “RANK function [Ranking]” on page 303

Standards and compatibility


● SQL/2008 PERCENT_RANK is part of optional SQL/2008 language feature T612, "Advanced
OLAP operations".

Example
The following example returns a result set that shows the ranking of New York employees' salaries by
gender. The results are ranked in descending order and are partitioned by gender.
SELECT DepartmentID, Surname, Salary, Sex,
PERCENT_RANK() OVER (PARTITION BY Sex
ORDER BY Salary DESC) "Rank"
FROM Employees
WHERE State IN ('NY');

DepartmentID Surname Salary Sex Rank

200 Martel 55700.000 M 0

100 Guevara 42998.000 M 0.333333333

100 Soo 39075.000 M 0.666666667

400 Ahmed 34992.000 M 1

300 Davidson 57090.000 F 0

400 Blaikie 54900.000 F 0.333333333

100 Whitney 45700.000 F 0.666666667

400 Wetherby 35745.000 F 1

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 293


SQL functions

PI function [Numeric]
Returns the numeric value PI.

Syntax
PI( [ * ] )

Returns
DOUBLE

Standards and compatibility


● SQL/2008 Vendor extension.

Remarks
This function returns a DOUBLE value.

PI(*) and PI() are semantically equivalent.

Example
The following statement returns the value 3.141592653...
SELECT PI( * );

PLAN function [Miscellaneous]


Returns the long plan optimization strategy of a SQL statement, as a string.

Syntax
PLAN( string-expression, [ cursor-type [ update-status ] ] )

Parameters
● string-expression The SQL statement, which is commonly a SELECT statement but which may
also be an UPDATE, MERGE, or DELETE statement.

● cursor-type A string. cursor-type can be asensitive (default), insensitive, sensitive, or keyset-


driven.

● update-status A string parameter accepting one of the following values indicating how the
optimizer should treat the given cursor:

Value Description

READ-ONLY The cursor is read-only.

READ-WRITE (default) The cursor can be read or written to.

294 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Value Description

FOR UPDATE The cursor can be read or written to. This is exactly the same as READ-
WRITE.

Returns
LONG VARCHAR

See also
● “Advanced: Query execution plans” [SQL Anywhere Server - SQL Usage]
● “EXPLANATION function [Miscellaneous]” on page 221
● “GRAPHICAL_PLAN function [Miscellaneous]” on page 229

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement passes a SELECT statement as a string parameter and returns the plan for
executing the query.

SELECT PLAN(
'SELECT * FROM Departments WHERE DepartmentID > 100' );

This information can help with decisions about indexes to add or how to structure your database for better
performance.

The following statement returns a string containing the text plan for an INSENSITIVE cursor over the
query SELECT * FROM Departments WHERE DepartmentID > 100;.

SELECT PLAN(
'SELECT * FROM Departments WHERE DepartmentID > 100',
'insensitive',
'read-only' );

POWER function [Numeric]


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.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 295


SQL functions

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If any argument is NULL, the result is a NULL value.

Standards and compatibility


● SQL/2008 The POWER function comprises part of optional SQL/2008 language feature T621,
"Enhanced numeric functions".

Example
The following statement returns the value 64.
SELECT POWER( 2, 6 );

PROPERTY_DESCRIPTION function [System]


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.

Returns
VARCHAR

Remarks
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.

See also
● “Connection, database, and database server properties” [SQL Anywhere Server - Database
Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

296 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example
The following statement returns the description Number of index insertions.
SELECT PROPERTY_DESCRIPTION( 'IndAdd' );

PROPERTY function [System]


Returns the value of the specified database server property as a string.

Syntax
PROPERTY( { property-id | property-name } [, second-parameter ] )

Parameters
● property-id An integer that is the property-number of the database server 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.

● second-parameter You can specify a second parameter for some properties, as follows:

Property Second Description


parameter

EventType- positive-integer Specify an event ID to return the event type description. See
Desc “EventTypeDesc server property” [SQL Anywhere Server - Da-
tabase Administration].

EventType- positive-integer Specify an event ID to return the event type name. See “Even-
Name tTypeName server property” [SQL Anywhere Server - Database
Administration].

Function- positive-integer Specify a function number to return the maximum number of pa-
MaxParms rameters that can be specified for the function. See “Function-
MaxParms server property” [SQL Anywhere Server - Database
Administration].

Function- positive-integer Specify a function number to return the minimum number of pa-
MinParms rameters that must be specified for the function. See “Function-
MinParms server property” [SQL Anywhere Server - Database
Administration].

Function- positive-integer Specify a function number to return the function name. See
Name “FunctionName server property” [SQL Anywhere Server - Data-
base Administration].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 297


SQL functions

Property Second Description


parameter

Message positive-integer Specify a line number to return the contents of the corresponding
line in the database server messages window, prefixed by the
date and time the message appeared. See “Message server prop-
erty” [SQL Anywhere Server - Database Administration].

Message- positive-integer Specify a line number to return the text associated with the
Text specified line number in the database server messages window,
without a date and time prefix. See “MessageText server proper-
ty” [SQL Anywhere Server - Database Administration].

Message- positive-integer Specify a line number to return the date and time associated with
Time the specified line number in the database server messages win-
dow. See “MessageTime server property” [SQL Anywhere Serv-
er - Database Administration].

RemoteCap- positive-integer Specify a remote capability ID to return the remote capability


ability name associated with the ID. See “RemoteCapability server
property” [SQL Anywhere Server - Database Administration].

Returns
VARCHAR, LONG VARCHAR

Remarks
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.

See also
● “Accessing database server property values” [SQL Anywhere Server - Database Administration]
● “DB_PROPERTY function [System]” on page 202

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the name of the current database server:
SELECT PROPERTY( 'Name' );

PROPERTY_NAME function [System]


Returns the name of the property with the supplied property ID for the specified connection level.

298 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Syntax
PROPERTY_NAME( property-id [, property-scope ] )

property-scope:
NULL
| 'server'
| 'database'
| 'db'
| 'connection'
| 'conn'

Parameters
● property-id The property ID of the database property.

● property-scope The scope of the property, or NULL.

Returns
VARCHAR

See also
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “Accessing database server property values” [SQL Anywhere Server - Database Administration]
● “Accessing database property values” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the server-level property associated with property ID 102.
SELECT PROPERTY_NAME( 102, 'server' );

PROPERTY_NUMBER function [System]


Returns the property number of the property with the supplied property-name.

Syntax
PROPERTY_NUMBER( property-name )

Parameters
● property-name A property name.

Returns
INT

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 299


SQL functions

Remarks
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. When either property number or property
name can be used, it is preferable to use the property name. Always use the PROPERTY_NUMBER
function to ensure that the property number is current for the server being used.

See also
● “Connection, database, and database server properties” [SQL Anywhere Server - Database
Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns an integer value. The actual value changes from release to release.
SELECT PROPERTY_NUMBER( 'PAGESIZE' );

QUARTER function [Date and time]


Returns a number indicating the quarter of the year from the supplied TIMESTAMP expression.

Syntax
QUARTER( timestamp-expression )

Parameters
● timestamp-expression The date you want the quarter for.

Returns
INTEGER

Remarks
The quarters are as follows:

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

300 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 2.
SELECT QUARTER( '1987/05/02' );

RADIANS function [Numeric]


Converts a number from degrees to radians.

Syntax
RADIANS( numeric-expression )

Parameters
● numeric-expression A number, in degrees. This angle is converted to radians.

Returns
DOUBLE

Remarks
This function converts its argument to DOUBLE, and performs the computation in double-precision
floating-point arithmetic.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns a value of approximately 0.5236.
SELECT RADIANS( 30 );

RAND function [Numeric]


Returns a random number in the interval 0 to 1, with an optional seed.

Syntax
RAND( [integer-expression] )

Parameters
● integer-expression An optional seed used to create a random number. This argument allows you
to create repeatable random number sequences.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 301


SQL functions

Returns
DOUBLE

Remarks
The RAND function is a multiplicative linear congruential random number generator. See Park and Miller
(1988), CACM 31(10), pp. 1192-1201 and Press et al. (1992), Numerical Recipes in C (2nd edition,
Chapter 7, pp. 279). The result of calling the RAND function is a pseudo-random number n where 0 < n <
1 (neither 0.0 nor 1.0 can be the result).

When a connection is made to the server, the random number generator seeds an initial value. Each
connection is uniquely seeded so that it sees a different random sequence from other connections. You
can also specify a seed value (integer-expression) as an argument. Normally, you should only do this once
before requesting a sequence of random numbers through successive calls to the RAND function. If you
initialize the seed value more than once, the sequence is restarted. If you specify the same seed value, the
same sequence is generated. Seed values that are close in value generate similar initial sequences, with
divergence further out in the sequence.

Never combine the sequence generated from one seed value with the sequence generated from a second
seed value, in an attempt to obtain statistically random results. In other words, do not reset the seed value
at any time during the generation of a sequence of random values.

The RAND function is treated as a non-deterministic function. The query optimizer does not cache the
results of the RAND function.

For more information about non-deterministic functions, see “Function caching” [SQL Anywhere Server -
SQL Usage].

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements produce eleven random results. Each subsequent call to the RAND function
where a seed is not specified continues to produce different results:
SELECT RAND( 1 );
SELECT RAND( ), RAND( ), RAND( ), RAND( ), RAND( );
SELECT RAND( ), RAND( ), RAND( ), RAND( ), RAND( );

The following example produces two sets of results with identical sequences, since the seed value is
specified twice:
SELECT RAND( 1 ), RAND( ), RAND( ), RAND( ), RAND( );
SELECT RAND( 1 ), RAND( ), RAND( ), RAND( ), RAND( );

The following example produces five results that are near each other in value, and do not have a random
distribution. For this reason, calling the RAND function more than once with similar seed values is not
recommended:
SELECT RAND( 1 ), RAND( 2 ), RAND( 3 ), RAND( 4 ), RAND( 5 );

The following example produces five identical results, and should be avoided:

302 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

SELECT RAND( 1 ), RAND( 1 ), RAND( 1 ), RAND( 1 ), RAND( 1 );

RANK function [Ranking]


Calculates the value of a rank in a group of values. For ties, the RANK function leaves a gap in the
ranking sequence.

Syntax
RANK( ) OVER ( window-spec )

window-spec : see the Remarks section below

Returns
INTEGER

Remarks
Elements of window-spec can be specified either in the function syntax (inline), or in conjunction with a
WINDOW clause in the SELECT statement. When used as a window function, you must specify an
ORDER BY clause, you may specify a PARTITION BY clause, however, you can not specify a ROWS
or RANGE clause. See the window-spec definition for the WINDOW clause. See “WINDOW clause”
on page 961.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “CUME_DIST function [Ranking]” on page 185
● “DENSE_RANK function [Ranking]” on page 206
● “ROW_NUMBER function [Miscellaneous]” on page 327
● “PERCENT_RANK function [Ranking]” on page 292

Standards and compatibility


● SQL/2008 The RANK function is part of optional SQL/2008 language feature T612, "Advanced
OLAP operations".

Example
The following example provides a rank in descending order of employees' salaries in Utah and New York.
Notice that the 7th and 8th employees have an identical salary and therefore share the 7th place ranking.
The employee that follows receives the 9th place ranking, which leaves a gap in the ranking sequence (no
8th place ranking).
SELECT Surname, Salary, State,
RANK() OVER (ORDER BY Salary DESC) "Rank"
FROM Employees WHERE State IN ('NY','UT');

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 303


SQL functions

Surname Salary State Rank

Shishov 72995.000 UT 1

Wang 68400.000 UT 2

Cobb 62000.000 UT 3

Morris 61300.000 UT 4

Davidson 57090.000 NY 5

Martel 55700.000 NY 6

Blaikie 54900.000 NY 7

Diaz 54900.000 NY 7

Driscoll 48023.690 UT 9

Hildebrand 45829.000 UT 10

Whitney 45700.000 NY 11

... ... ... ...

Lynch 24903.000 UT 19

READ_CLIENT_FILE function [String]


Reads data from the specified file on the client computer.

Syntax
READ_CLIENT_FILE( client-filename-expression )

Parameters
● client-filename-expression CHAR value indicating the name of the file on the client computer.
The path is resolved on the client computer relative to the current working directory of the client
application.

Returns
LONG BINARY

Remarks
The value returned by the READ_CLIENT_FILE function represents the contents of the specified client
file. You can use the function in syntax wherever a BINARY expression is allowed.

304 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Since the data returns as a binary string, if the data is in another character set, or is compressed, or is
encrypted, you may also need to perform character set conversion, decompression, or decryption on it.

During evaluation of READ_CLIENT_FILE, the database server initiates the transfer of the specified file
from the client. The client, upon receiving the transfer request, obtains a shared lock on the client file, and
holds the lock until the database server requests the client to terminate the request.

Reading of the file is performed by the client software library, and the transfer of data is done using the
command sequence communication protocol.

Permissions
When reading from a file on a client computer:

● READCLIENTFILE authority is required.

● Read permissions are required on the directory being read from.

● The allow_read_client_file database option must be enabled.

● The read_client_file secured feature must be enabled.

See also
● “allow_read_client_file option” [SQL Anywhere Server - Database Administration]
● “-sf dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “READCLIENTFILE authority” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

See also
● “Access to data on client computers” [SQL Anywhere Server - SQL Usage]
● “READCLIENTFILE authority” [SQL Anywhere Server - Database Administration]
● “DECOMPRESS function [String]” on page 203
● “DECRYPT function [String]” on page 204
● “CSCONVERT function [String]” on page 183

REGEXP_SUBSTR function [String]


Extracts substrings from strings using regular expressions.

Syntax
REGEXP_SUBSTR( expression,
regular-expression
[, start-offset [ , occurrence-number [, escape-expression ] ] ] )

Parameters
● expression The string to be searched.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 305


SQL functions

● regular-expression The pattern you are trying to match. For more information about regular
expression syntax, see “Regular expressions overview” on page 17.

● start-offset The offset into expression at which to start searching. start-offset is expressed as a
positive integer, and reflects the number of characters to count when starting from the left side of the
string. The default is 1 (the start of the string).

● occurrence-number For multiple matches within expression, specify an integer indicating the
occurrence to locate. For example, 3 finds the third occurrence. The default is 1.

● escape-expression The escape character to use for regular-expression. The default is the
backslash character (\).

Returns
LONG VARCHAR

Remarks
REGEXP_SUBSTR returns NULL if regular-expression is not found.

Similar to the REGEXP search condition, the REGEXP_SUBSTR function uses code points for matching
and range evaluation. This means that database case sensitivity does not impact results. For more
information about how REGEXP_SUBSTR performs matching and set evaluation, see “LIKE, REGEXP,
and SIMILAR TO: Differences in character comparisons” on page 38.

When matching against a character class that contains only a sub-character class, include the outer square
brackets and the square brackets for the sub-character class (for example, REGEXP_SUBSTR
(expression, '[[:digit:]]')). For more information about sub-character class matching, see
“Regular expressions: Special sub-character classes” on page 21.

If start-offset is specified, that offset specifies the start of the expression to be matched. In particular, ^
matches the beginning of the expression starting at start-offset.

See also
● “Regular expressions syntax” on page 18
● “REGEXP search condition” on page 43

Standards and compatibility


● SQL/2008 Vendor extension. The corresponding function in the SQL/2008 standard is the
SUBSTRING_REGEX function, which has similar parameters. SUBSTRING_REGEX is part of
optional SQL/2008 language feature F844.

Example
The following example breaks values in the Employees.Street column into street number and street name:

SELECT REGEXP_SUBSTR( Street, '^\S+' ) as street_num,


REGEXP_SUBSTR( Street, '(?<=^\S+\s+).*$' ) AS street_name
FROM Employees;

306 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

street_num street_name

9 East Washington Street

7 Pleasant Street

539 Pond Street

1244 Great Plain Avenue

... ...

To determine whether the IP address of the current connection is in a range of IP addresses (in this case,
10.25.101.xxx or 10.25.102.xxx), you can execute the following statement:

IF REGEXP_SUBSTR( CONNECTION_PROPERTY( 'NodeAddress' ), '\\d+\\.\\d+\\.\\d


+' )
IN ( '10.25.101' , '10.25.102' ) THEN
MESSAGE 'In range' TO CLIENT;
ELSE
MESSAGE 'Out of range' TO CLIENT;
END IF;

REGR_AVGX function [Aggregate]


Computes the average of the independent variable of the regression line.

Syntax 1
REGR_AVGX( dependent-expression , independent-expression )

Syntax 2
REGR_AVGX( dependent-expression , independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 307


SQL functions

The function is applied to the set of (dependent-expression and independent-expression) pairs after
eliminating all pairs for which either dependent-expression or independent-expression is NULL. The
function is computed simultaneously during a single pass through the data. After eliminating NULL
values, the following computation is then made, where x represents the independent-expression:
AVG( x )

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “AVG function [Aggregate]” on page 150
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_INTERCEPT function [Aggregate]” on page 311
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_SLOPE function [Aggregate]” on page 314
● “REGR_SXX function [Aggregate]” on page 315
● “REGR_SXY function [Aggregate]” on page 317
● “REGR_SYY function [Aggregate]” on page 319
● “REGR_AVGY function [Aggregate]” on page 308
● “WINDOW clause” on page 961

Standards and compatibility


● SQL/2008 REGR_AVGX is part of optional SQL/2008 language feature T621, "Enhanced numeric
functions".

Example
The following example calculates the average of the dependent variable, employee age.
SELECT REGR_AVGX( Salary, ( 2008 - YEAR( BirthDate ) ) )
FROM Employees;

REGR_AVGY function [Aggregate]


Computes the average of the dependent variable of the regression line.

Syntax 1
REGR_AVGY( dependent-expression , independent-expression )

308 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Syntax 2
REGR_AVGY( dependent-expression , independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

The function is applied to the set of (dependent-expression and independent-expression) pairs after
eliminating all pairs for which either dependent-expression or independent-expression is NULL. The
function is computed simultaneously during a single pass through the data. After eliminating NULL
values, the following computation is then made, where y represents the dependent-expression:
AVG( y )

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_INTERCEPT function [Aggregate]” on page 311
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_SLOPE function [Aggregate]” on page 314
● “REGR_SXX function [Aggregate]” on page 315
● “REGR_SXY function [Aggregate]” on page 317
● “REGR_SYY function [Aggregate]” on page 319
● “REGR_AVGX function [Aggregate]” on page 307
● “AVG function [Aggregate]” on page 150
● “WINDOW clause” on page 961

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 309


SQL functions

Standards and compatibility


● SQL/2008 REGR_AVGY is part of optional SQL/2008 language feature T621, "Enhanced numeric
functions".

Example
The following example calculates the average of the independent variable, employee salary.
SELECT REGR_AVGY( Salary, ( YEAR( NOW( )) - YEAR( BirthDate ) ) )
FROM Employees;

REGR_COUNT function [Aggregate]


Returns an integer that represents the number of non-NULL number pairs used to fit the regression line.

Syntax 1
REGR_COUNT( dependent-expression , independent-expression )

Syntax 2
REGR_COUNT( dependent-expression , independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
INTEGER

Remarks
Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

310 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “WINDOW clause” on page 961
● “REGR_INTERCEPT function [Aggregate]” on page 311
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_SLOPE function [Aggregate]” on page 314
● “REGR_SXX function [Aggregate]” on page 315
● “REGR_SXY function [Aggregate]” on page 317
● “REGR_SYY function [Aggregate]” on page 319
● “REGR_AVGY function [Aggregate]” on page 308
● “REGR_AVGX function [Aggregate]” on page 307
● “COUNT function [Aggregate]” on page 177
● “AVG function [Aggregate]” on page 150
● “SUM function [Aggregate]” on page 355

Standards and compatibility


● SQL/2008 REGR_COUNT is part of optional SQL/2008 language feature T621, "Enhanced
numeric functions".

Example
The following example returns the number of non-NULL pairs that were used to fit the regression line.
SELECT REGR_COUNT( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )
FROM Employees;

REGR_INTERCEPT function [Aggregate]


Computes the y-intercept of the linear regression line that best fits the dependent and independent
variables.

Syntax 1
REGR_INTERCEPT( dependent-expression , independent-expression )

Syntax 2
REGR_INTERCEPT( dependent-expression , independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 311


SQL functions

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

The function is applied to the set of (dependent-expression and independent-expression) pairs after
eliminating all pairs for which either dependent-expression or independent-expression is NULL. The
function is computed simultaneously during a single pass through the data. After eliminating NULL
values, the following computation is then made, where y represents the dependent-expression and x
represents the independent-expression:

AVG( y ) - REGR_SLOPE( y, x ) * AVG( x )

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “WINDOW clause” on page 961
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_SLOPE function [Aggregate]” on page 314
● “REGR_SXX function [Aggregate]” on page 315
● “REGR_SXY function [Aggregate]” on page 317
● “REGR_SYY function [Aggregate]” on page 319
● “REGR_AVGY function [Aggregate]” on page 308
● “REGR_AVGX function [Aggregate]” on page 307
● “REGR_SLOPE function [Aggregate]” on page 314
● “AVG function [Aggregate]” on page 150

Standards and compatibility


● SQL/2008 REGR_INTERCEPT is part of optional SQL/2008 language feature T621, "Enhanced
numeric functions".

Example
The following example returns the y-intercept of the linear regression line.

SELECT REGR_INTERCEPT( Salary, ( YEAR( NOW( )) - YEAR( BirthDate ) ) )


FROM Employees;

312 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

REGR_R2 function [Aggregate]


Computes the coefficient of determination (also referred to as R-squared or the goodness of fit statistic)
for the regression line.

Syntax 1
REGR_R2( dependent-expression , independent-expression )

Syntax 2
REGR_R2( dependent-expression , independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

The function is applied to the set of (dependent-expression and independent-expression) pairs after
eliminating all pairs for which either dependent-expression or independent-expression is NULL.

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 313


SQL functions

See also
● “WINDOW clause” on page 961
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_INTERCEPT function [Aggregate]” on page 311
● “REGR_SLOPE function [Aggregate]” on page 314
● “REGR_SXX function [Aggregate]” on page 315
● “REGR_SXY function [Aggregate]” on page 317
● “REGR_SYY function [Aggregate]” on page 319
● “REGR_AVGX function [Aggregate]” on page 307
● “REGR_AVGY function [Aggregate]” on page 308

Standards and compatibility


● SQL/2008 REGR_R2 is part of optional SQL/2008 language feature T621, "Enhanced numeric
functions".

Example
The following example returns the coefficient of determination for the regression line.
SELECT REGR_R2( Salary, ( YEAR( NOW( )) - YEAR( BirthDate ) ) )
FROM Employees;

REGR_SLOPE function [Aggregate]


Computes the slope of the linear regression line fitted to non-NULL pairs.

Syntax 1
REGR_SLOPE( dependent-expression , independent-expression )

Syntax 2
REGR_SLOPE( dependent-expression , independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

314 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

The function is applied to the set of (dependent-expression and independent-expression) pairs after
eliminating all pairs for which either dependent-expression or independent-expression is NULL. The
function is computed simultaneously during a single pass through the data. After eliminating NULL
values, the following computation is then made, where y represents the dependent-expression and x
represents the independent-expression:
COVAR_POP( y, x ) / VAR_POP( x )

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “WINDOW clause” on page 961
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_INTERCEPT function [Aggregate]” on page 311
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_SXX function [Aggregate]” on page 315
● “REGR_SXY function [Aggregate]” on page 317
● “REGR_SYY function [Aggregate]” on page 319
● “REGR_AVGX function [Aggregate]” on page 307
● “REGR_AVGY function [Aggregate]” on page 308
● “COVAR_POP function [Aggregate]” on page 181
● “VAR_POP function [Aggregate]” on page 375

Standards and compatibility


● SQL/2008 REGR_SLOPE is part of optional SQL/2008 language feature T621, "Enhanced
numeric functions".

Example
The following example returns the value 935.3429749445614.
SELECT REGR_SLOPE( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )
FROM Employees;

REGR_SXX function [Aggregate]


Returns the sum of squares of the independent expressions used in a linear regression model. The
REGR_SXX function can be used to evaluate the statistical validity of a regression model.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 315


SQL functions

Syntax 1
REGR_SXX( dependent-expression , independent-expression )

Syntax 2
REGR_SXX( dependent-expression , independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

The function is applied to the set of (dependent-expression and independent-expression) pairs after
eliminating all pairs for which either dependent-expression or independent-expression is NULL. The
function is computed simultaneously during a single pass through the data. After eliminating NULL
values, the following computation is then made, where y represents the dependent-expression and x
represents the independent-expression:
REGR_COUNT( y, x ) * VAR_POP( x )

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

316 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “WINDOW clause” on page 961
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_INTERCEPT function [Aggregate]” on page 311
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_AVGX function [Aggregate]” on page 307
● “REGR_AVGY function [Aggregate]” on page 308
● “REGR_SXY function [Aggregate]” on page 317
● “REGR_SYY function [Aggregate]” on page 319
● “VAR_POP function [Aggregate]” on page 375

Standards and compatibility


● SQL/2008 REGR_SXX is part of optional SQL/2008 language feature T621, "Enhanced numeric
functions".

Example
The following example returns the value 5916.4800000000105.
SELECT REGR_SXX( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )
FROM Employees;

REGR_SXY function [Aggregate]


Returns the sum of products of the dependent and independent variables. The REGR_SXY function can
be used to evaluate the statistical validity of a regression model.

Syntax 1
REGR_SXY( dependent-expression , independent-expression )

Syntax 2
REGR_SXY( dependent-expression , independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 317


SQL functions

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic, and returns a DOUBLE as the result. If the function is applied to an empty set,
then it returns NULL.

The function is applied to the set of (dependent-expression and independent-expression) pairs after
eliminating all pairs for which either dependent-expression or independent-expression is NULL. The
function is computed simultaneously during a single pass through the data. After eliminating NULL
values, the following computation is then made, where y represents the dependent-expression and x
represents the independent-expression:
REGR_COUNT( y, x ) * COVAR_POP( y, x )

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “WINDOW clause” on page 961
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_INTERCEPT function [Aggregate]” on page 311
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_SLOPE function [Aggregate]” on page 314
● “REGR_AVGX function [Aggregate]” on page 307
● “REGR_AVGY function [Aggregate]” on page 308
● “REGR_SXX function [Aggregate]” on page 315
● “REGR_SYY function [Aggregate]” on page 319

Standards and compatibility


● SQL/2008 REGR_SXY is part of optional SQL/2008 language feature T621, "Enhanced numeric
functions".

Example
The following example returns the sum of products of the dependent and independent variables.
SELECT REGR_SXY( Salary, ( YEAR( NOW( )) - YEAR( BirthDate ) ) )
FROM Employees;

318 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

REGR_SYY function [Aggregate]


Returns values that can evaluate the statistical validity of a regression model.

Syntax 1
REGR_SYY( dependent-expression , independent-expression )

Syntax 2
REGR_SYY( dependent-expression , independent-expression )
OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● dependent-expression The variable that is affected by the independent variable.

● independent-expression The variable that influences the outcome.

Returns
DOUBLE

Remarks
This function converts its arguments to DOUBLE, and performs the computation in double-precision
floating-point arithmetic. If the function is applied to an empty set, then it returns NULL.

The function is applied to the set of (dependent-expression and independent-expression) pairs after
eliminating all pairs for which either dependent-expression or independent-expression is NULL. The
function is computed simultaneously during a single pass through the data. After eliminating NULL
values, the following computation is then made, where y represents the dependent-expression and x
represents the independent-expression:
REGR_COUNT( y, x ) * VAR_POP( y )

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 319


SQL functions

See also
● “WINDOW clause” on page 961
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_INTERCEPT function [Aggregate]” on page 311
● “REGR_COUNT function [Aggregate]” on page 310
● “REGR_AVGX function [Aggregate]” on page 307
● “REGR_AVGY function [Aggregate]” on page 308
● “REGR_SLOPE function [Aggregate]” on page 314
● “REGR_SXX function [Aggregate]” on page 315
● “REGR_SXY function [Aggregate]” on page 317

Standards and compatibility


● SQL/2008 REGR_SYY is part of optional SQL/2008 language feature T621, "Enhanced numeric
functions".

Example
The following example returns the value 26, 708, 672,843.3002.
SELECT REGR_SYY( Salary, ( YEAR( NOW( )) - YEAR( BirthDate ) ) )
FROM Employees;

REMAINDER function [Numeric]


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.

Returns
● INTEGER
● NUMERIC

Remarks
You can also use the MOD function to return the remainder.

See also
● “MOD function [Numeric]” on page 275

Standards and compatibility


● SQL/2008 Vendor extension.

320 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example
The following statement returns the value 2.
SELECT REMAINDER( 5, 3 );

REPEAT function [String]


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.

Returns
● LONG VARCHAR
● LONG NVARCHAR

Remarks
If the actual length of the result string exceeds the maximum for the return type, an error occurs. The
result is truncated to the maximum string size allowed.

The behavior of this function is identical to that of the REPLICATE function.

This function supports NCHAR inputs and/or outputs.

See also
● “REPLICATE function [String]” on page 323
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value repeatrepeatrepeat.
SELECT REPEAT( 'repeat', 3 );

REPLACE function [String]


Replaces a string with another string, and returns the new results.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 321


SQL functions

Syntax
REPLACE( original-string, search-string, replace-string )

Parameters
If any argument is NULL, the function returns NULL.

● 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.

Returns
● LONG VARCHAR
● LONG NVARCHAR

Remarks
This function replaces all occurrences.

Comparisons are case-sensitive on case-sensitive databases.

This function supports NCHAR inputs and/or outputs.

See also
● “SUBSTRING function [String]” on page 353
● “CHARINDEX function [String]” on page 163
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
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 must be unique.)

SELECT REPLACE(
REPLACE( proc_defn, 'OldTableName', 'NewTableName' ),
'CREATE PROCEDURE',
'ALTER PROCEDURE')
FROM SYS.SYSPROCEDURE
WHERE proc_defn LIKE '%OldTableName%';

322 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

REPLICATE function [String]


Concatenates a string a specified number of times.

Syntax
REPLICATE( string-expression, integer-expression )

Parameters
● string-expression The string to be repeated.

● integer-expression The number of times the string is to be repeated.

Returns
● LONG VARCHAR
● LONG NVARCHAR

Remarks
If the actual length of the result string exceeds the maximum for the return type, an error occurs. The
result is truncated to the maximum string size allowed.

The behavior of this function is identical to that of the REPEAT function.

This function supports NCHAR inputs and/or outputs.

See also
● “REPEAT function [String]” on page 321
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value repeatrepeatrepeat.
SELECT REPLICATE( 'repeat', 3 );

REVERSE function [String]


Returns the reverse of a character expression.

Syntax
REVERSE( string-expression )

Parameters
● string-expression The string to be reversed.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 323


SQL functions

Returns
● LONG VARCHAR
● LONG NVARCHAR

Remarks
This function supports NCHAR inputs and/or outputs.

See also
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value cba.
SELECT REVERSE( 'abc' );

REWRITE function [Miscellaneous]


Returns a rewritten SELECT, UPDATE, or DELETE statement.

Syntax
REWRITE( select-statement [, 'ANSI' ] )

Parameters
● select-statement The SQL statement to which the rewrite optimizations are applied to generate
the function's results.

Returns
LONG VARCHAR

Remarks
You can use the REWRITE function without the ANSI argument to help understand how the optimizer
generated the access plan for a given query. In particular, you can find how SQL Anywhere has rewritten
the conditions in the statement's WHERE, ON, and HAVING clauses, and then determine if applicable
indexes exist that can be exploited to improve the request's execution time.

The statement that is returned by REWRITE may not match the semantics of the original statement. This
is because several rewrite optimizations introduce internal mechanisms that cannot be translated directly
into SQL. For example, the server's use of row identifiers to perform duplicate elimination cannot be
translated into SQL.

The rewritten query from the REWRITE function is not intended to be executable. It is a tool for
analyzing performance issues by showing what gets passed to the optimizer after the rewrite phase.

324 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

There are some rewrite optimizations that are not reflected in the output of REWRITE. They include
LIKE optimization, optimization for minimum or maximum functions, upper/lower elimination, and
predicate subsumption.

If ANSI is specified, REWRITE returns the ANSI equivalent to the statement. In this case, only the
following rewrite optimizations are applied:

● Transact-SQL outer joins are rewritten as ANSI SQL outer joins.

● Duplicate correlation names are eliminated.

● KEY and NATURAL joins are rewritten as ANSI SQL joins.

See also
● “Optimizations performed during query processing” [SQL Anywhere Server - SQL Usage]
● “extended_join_syntax option” [SQL Anywhere Server - Database Administration]
● “Transact-SQL outer joins (*= or =*)” [SQL Anywhere Server - SQL Usage]
● “Key joins” [SQL Anywhere Server - SQL Usage]
● “Natural joins” [SQL Anywhere Server - SQL Usage]
● “Duplicate correlation names in joins (star joins)” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
In the following example, two rewrite optimizations are performed on a query. The first is the un-nesting
of the subquery into a join between the Employees and SalesOrders tables. The second optimization
simplifies the query by eliminating the primary key - foreign key join between Employees and
SalesOrders. Part of this rewrite optimization is to replace the join predicate
e.EmployeeID=s.SalesRepresentative with the predicate s.SalesRepresentative IS NOT NULL.
SELECT REWRITE( 'SELECT s.ID, s.OrderDate
FROM SalesOrders s
WHERE EXISTS ( SELECT *
FROM Employees e
WHERE e.EmployeeID = s.SalesRepresentative)' ) FROM dummy;

The query returns a single column result set containing the rewritten query:
'SELECT s.ID, s.OrderDate FROM SalesOrders s WHERE s.SalesRepresentative IS
NOT NULL'

The next example of REWRITE uses the ANSI argument.


SELECT REWRITE( 'SELECT DISTINCT s.ID, s.OrderDate, e.GivenName, e.EmployeeID
FROM SalesOrders s, Employees e
WHERE e.EmployeeID *= s.SalesRepresentative', 'ANSI' ) FROM dummy;

The result is the ANSI equivalent of the statement. In this case, the Transact-SQL outer join is converted
to an ANSI outer join. The query returns a single column result set (broken into separate lines for
readability):

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 325


SQL functions

'SELECT DISTINCT s.ID, s.OrderDate, e.GivenName, e.EmployeeID


FROM Employees as e
LEFT OUTER JOIN SalesOrders as s
ON e.EmployeeID = s.SalesRepresentative';

RIGHT function [String]


Returns the rightmost characters of a string.

Syntax
RIGHT( string-expression, integer-expression )

Parameters
● string-expression The string to return the rightmost characters for.

● integer-expression The number of characters at the end of the string to return.

Returns
● LONG VARCHAR
● LONG NVARCHAR

Remarks
If the string contains multibyte characters, and the proper collation is being used, the number of bytes
returned may be greater than the specified number of characters.

You can specify an integer-expression that is larger than the value in the column. In this case, the entire
value is returned.

This function supports NCHAR inputs and/or outputs. Whenever possible, if the input string uses
character-length semantics, the return value is described in character-length semantics.

See also
● “LEFT function [String]” on page 258
● “International languages and character sets” [SQL Anywhere Server - Database Administration]
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the last 5 characters of each Surname value in the Customers table.
SELECT RIGHT( Surname, 5) FROM Customers;

326 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

ROUND function [Numeric]


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.

Returns
NUMERIC

Remarks
The result of this function is either numeric or double. When there is a numeric result and the integer
integer-expression is a negative value, the precision is increased by one.

See also
● “TRUNCNUM function [Numeric]” on page 368

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 123.200.

SELECT ROUND( 123.234, 1 );

ROW_NUMBER function [Miscellaneous]


Assigns a unique number to each row. Use this function instead of the NUMBER function.

Syntax
ROW_NUMBER( ) OVER ( window-spec )

window-spec : see the Remarks section below

Returns
INTEGER

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 327


SQL functions

Remarks
Elements of window-spec can be specified either in the function syntax (inline), or in conjunction with a
WINDOW clause in the SELECT statement. When used as a window function, you must specify an
ORDER BY clause, you may specify a PARTITION BY clause, however, you can not specify a ROWS
or RANGE clause. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “WINDOW clause” on page 961
● “NUMBER function [Miscellaneous]” on page 288
● “RANK function [Ranking]” on page 303
● “ROWID function [Miscellaneous]” on page 329

Standards and compatibility


● SQL/2008 ROW_NUMBER is part of optional SQL/2008 language feature T611, "Elementary
OLAP operations".

Example
The following example returns a result set that provides unique row numbers for each employee in New
York and Utah. Because the query is ordered by Salary in descending order, the first row number is given
to the employee with the highest salary in the data set. Although two employees have identical salaries,
the tie is not resolved because the two employees are assigned unique row numbers.
SELECT Surname, Salary, State,
ROW_NUMBER() OVER (ORDER BY Salary DESC) "Rank"
FROM Employees WHERE State IN ('NY','UT');

Surname Salary State Rank

Shishov 72995.000 UT 1

Wang 68400.000 UT 2

Cobb 62000.000 UT 3

Morris 61300.000 UT 4

Davidson 57090.000 NY 5

Martel 55700.000 NY 6

Blaikie 54900.000 NY 7

328 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Surname Salary State Rank

Diaz 54900.000 NY 8

Driscoll 48023.690 UT 9

Hildebrand 45829.000 UT 10

... ... ... ...

Lynch 24903.000 UT 19

ROWID function [Miscellaneous]


Returns an UNSIGNED BIGINT value that uniquely identifies a row within a table.

Syntax
ROWID( correlation-name )

Parameters
● correlation-name The correlation name of a table used in the query. The correlation name should
refer to a base table, a temporary table, a global temporary table or a proxy table (permitted only when
the underlying proxy server supports a similar function). The argument of the ROWID function
should not refer to a view, derived table, common table expression or a procedure.

Returns
UNSIGNED BIGINT

Remarks
Returns the row identifier of the row in the table corresponding to the given correlation name.

The value returned by the function is not necessarily constant between queries as various operations
performed on the database may result in changes to the row identifiers of a table. In particular, the
REORGANIZE TABLE statement is likely to result in changes to row identifiers. Additionally, row
identifiers may be reused after a row has been deleted. So, users should refrain from using the ROWID
function in ordinary situations; retrieval by primary key value should be used instead. It is recommended
that ROWID be used only in diagnostic situations.

Although the result of this function is an UNSIGNED BIGINT, the results of most arithmetic operations
on this value have no particular meaning. For example, you should not expect that adding one to a row
identifier will give you the row identifier of the next row. Also, only equality and IN predicates are
sargable if they involve the use of ROWID. If necessary, predicates involving ROWID, such as
ROWID( T ) = literal, may be used to cast to a 64-bit UNSIGNED INTEGER value. If the
conversion cannot be performed a data exception will occur. If the value of literal is an invalid row
identifier then the comparison predicate evaluates to FALSE.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 329


SQL functions

The ROWID function cannot be used inside a CHECK constraint on either a table or a column, nor can it
be used in the COMPUTE expression for a computed column.

See also
● “ROW_NUMBER function [Miscellaneous]” on page 327

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the row identifier of the row in Employee where id is equal to 105:
SELECT ROWID( Employees ) FROM Employees WHERE Employees.EmployeeID = 105;

The following statement returns a list of the locks on rows in the Employees table along with the contents
of those rows:
SELECT *
FROM sa_locks() S JOIN Employees WITH( NOLOCK )
ON ROWID( Employees ) = S.row_identifier
WHERE S.table_name = 'Employees';

RTRIM function [String]


Removes trailing blanks from the string.

Syntax
RTRIM( string-expression )

Parameters
● string-expression The string to be trimmed.

Returns
● VARCHAR
● NVARCHAR
● LONG VARCHAR
● LONG NVARCHAR

Remarks
The actual length of the result is the length of the expression minus the number of characters removed. If
all the characters are removed, the result is an empty string.

If the argument is null, the result is the NULL value.

This function supports NCHAR inputs and/or outputs.

330 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “TRIM function [String]” on page 367
● “LTRIM function [String]” on page 267
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

The TRIM specifications defined by the SQL/2008 standard (LEADING and TRAILING) are
supplied by the SQL Anywhere LTRIM and RTRIM functions respectively.

Example
The following statement returns the string Test Message, with all trailing blanks removed.
SELECT RTRIM( 'Test Message ' );

SECOND function [Date and time]


Returns the seconds value of the TIMESTAMP argument.

Syntax
SECOND( timestamp-expression )

Parameters
● timestamp-expression The TIMESTAMP value.

Returns
SMALLINT

Remarks
Returns a number from 0 to 59 corresponding to the seconds component of the given TIMESTAMP
argument value.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 25.
SELECT SECOND( '1998-07-13 21:21:25' );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 331


SQL functions

SECONDS function [Date and time]


The SECONDS function manipulates a TIMESTAMP, or returns the number of seconds between two
TIMESTAMP values. See the Remarks section below.

Syntax 1
SECONDS( timestamp-expression )

Syntax 2
SECONDS( timestamp-expression, timestamp-expression )

Syntax 3
SECONDS( time-or-timestamp-expression, integer-expression )

Parameters
● timestamp-expression A TIMESTAMP value.

● time-or-timestamp-expression A value of type TIME or TIMESTAMP.

● integer-expression The number of seconds to be added to the time-or-timestamp-expression. If


integer-expression is negative, the appropriate number of seconds is subtracted from time-or-
timestamp-expression. If you supply an integer expression, the time-or-timestamp-expression must be
explicitly cast as a TIME, DATE, or TIMESTAMP data type. If time-or-timestamp-expression is a
DATE type, its time portion is assumed to be midnight.

Returns
UNSIGNED BIGINT with Syntax 1.

SIGNED BIGINT with Syntax 2.

TIME or TIMESTAMP with Syntax 3.

Remarks
The result of the SECONDS function depends on its arguments.

● Syntax 1 If you pass a single timestamp-expression to the SECONDS function, it will return the
number of seconds between midnight 0000-02-29 and timestamp-expression as an UNSIGNED
BIGINT.

Note
0000-02 is not meant to imply an actual date; it is the default date used by the SECONDS function.

● Syntax 2 If you pass two TIMESTAMP values to the SECONDS function, the function returns the
integer number of seconds between them as a SIGNED BIGINT value.

● Syntax 3 If you pass a TIMESTAMP value and a INTEGER value to the SECONDS function, the
function returns the TIMESTAMP result of adding the integer number of seconds to time-or-

332 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

timestamp-expression. Similarly, if you pass a TIME value to the SECONDS function, the function
returns a value of type TIME.

Instead of Syntax 2, use the DATEDIFF function. Instead of Syntax 3, use the DATEADD function.

See also
● “CAST function [Data type conversion]” on page 159
● “DATEADD function [Date and time]” on page 188
● “DATEDIFF function [Date and time]” on page 189

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements return the value 14400, signifying that the second TIMESTAMP value is 14400
seconds after the first.
SELECT SECONDS( '1999-07-13 06:07:12',
'1999-07-13 10:07:12' );
SELECT DATEDIFF( second,
'1999-07-13 06:07:12',
'1999-07-13 10:07:12' );

The following statement returns the value 63062431632.


SELECT SECONDS( '1998-07-13 06:07:12' );

The following statements return the TIMESTAMP value 1999-05-12 21:05:12.000.


SELECT SECONDS( CAST( '1999-05-12 21:05:07' AS TIMESTAMP ), 5);
SELECT DATEADD( second, 5, '1999-05-12 21:05:07' );

SET_BIT function [Bit array]


Set the value of a specific bit in a bit array.

Syntax
SET_BIT( [ bit-expression, ]bit-position [, value ] )

Parameters
● bit-expression The bit array in which to change the bit.

● bit-position The position of the bit to be set. This must be an unsigned integer.

● value The value to which the bit is to be set.

Returns
LONG VARBIT

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 333


SQL functions

Remarks
The default value of bit-expression is a bit array of length bit-position, containing all bits set to 0
(FALSE).

The default value of value is 1 (TRUE).

The result is NULL if any parameter is NULL.

The positions in the array are counted from the left side, starting at 1.

See also
● “GET_BIT function [Bit array]” on page 226
● “SET_BITS function [Aggregate]” on page 334
● “INTEGER data type” on page 94
● “Bitwise operators” on page 11
● “sa_get_bits system procedure” on page 1048

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 00100011:
SELECT SET_BIT( '00110011', 4 , 0);

The following statement returns the value 00111011:


SELECT SET_BIT( '00110011', 5 , 1);

The following statement returns the value 00111011:


SELECT SET_BIT( '00110011', 5 );

The following statement returns the value 00001:


SELECT SET_BIT( 5 );

SET_BITS function [Aggregate]


Creates a bit array where specific bits, corresponding to values from a set of rows, are set to 1 (TRUE).

Syntax
SET_BITS( expression )

Parameters
● expression The expression used to determine which bits to set to 1. This is typically a column
name.

334 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Returns
LONG VARBIT

Remarks
Rows where the specified values are NULL are ignored.

If there are no rows, NULL is returned.

The length of the result is the largest position that was set to 1.

The SET_BITS function is equivalent to, but faster than, the following statement:

SELECT BIT_OR( SET_BIT( expression ) )


FROM table;

See also
● “Bitwise operators” on page 11
● “GET_BIT function [Bit array]” on page 226
● “SET_BIT function [Bit array]” on page 333
● “sa_get_bits system procedure” on page 1048

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements return a bit array with the 2nd, 5th, and 10th bits set to 1 (or 0100100001):

CREATE TABLE t( r INTEGER );


INSERT INTO t values( 2 );
INSERT INTO t values( 5 );
INSERT INTO t values(10 );
SELECT SET_BITS( r ) FROM t;

SIGN function [Numeric]


Returns the sign (positive or negative) of the given number.

Syntax
SIGN( numeric-expression )

Parameters
● numeric-expression The number for which the sign is to be returned. numeric-expression may be
of type INTEGER, DOUBLE, or NUMERIC.

Returns
SMALLINT

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 335


SQL functions

Remarks
For negative numbers, the SIGN function returns -1.

For zero, the SIGN function returns 0.

For positive numbers, the SIGN function returns 1.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value -1
SELECT SIGN( -550 );

SIMILAR function [String]


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.

Returns
SMALL INT

Remarks
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. You can use the SIMILAR function to find
similar customer names by joining the customer table to itself, producing a report of all similarities
greater than 90 percent, but less than 100 percent.

The calculation performed for the SIMILAR function is more complex than just the number of characters
that match.

See also
● “String functions” on page 142

336 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 75, indicating that the two values are 75% similar.
SELECT SIMILAR( 'toast', 'coast' );

SIN function [Numeric]


Returns the sine of a number.

Syntax
SIN( numeric-expression )

Parameters
● numeric-expression The angle, in radians.

Returns
DOUBLE

Remarks
The SIN function returns the sine of the argument, where the argument is an angle expressed in radians.
The SIN and ASIN functions are inverse operations.

This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns a DOUBLE as the result.

See also
● “ASIN function [Numeric]” on page 148
● “COS function [Numeric]” on page 176
● “COT function [Numeric]” on page 176
● “TAN function [Numeric]” on page 359

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the SIN value of 0.52.
SELECT SIN( 0.52 );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 337


SQL functions

SOAP_HEADER function [SOAP]


Returns a SOAP header entry, or an attribute value for a header entry of the SOAP request.

Syntax
SOAP_HEADER( header-key [, index, header-attribute ] )

Parameters
● header-key This VARCHAR parameter specifies the XML local name of the top level XML
element for a given SOAP header entry.

● index This optional INTEGER parameter differentiates between SOAP header fields that have
identical names. This can occur when multiple header entries have top level XML elements with the
same localname. Usually, such elements have unique namespaces.

● header-attribute This optional VARCHAR parameter can specify any attribute node within a
header entry element, including:

○ @namespace A special SQL Anywhere attribute used to access the namespace of the given
header entry.

○ mustUnderstand A SOAP 1.1 header entry attribute indicating whether a header entry is
mandatory or optional for the recipient to process.

○ encodingStyle A SOAP 1.1 header entry attribute indicating the encoding style. This attribute
may be accessed, but it is not used internally by SQL Anywhere.

○ actor A SOAP 1.1 header entry attribute indicating the intended recipient of a header entry by
specifying the recipient's URL.

Returns
LONG VARCHAR

Remarks
This function may be used with a single parameter header-key to return a header entry. A header entry is
an XML string representation of an element, and all its sub-elements, contained within a SOAP header.

This function may also be used to extract a header entry attribute by specifying the optional index and
header-attribute parameters.

This function returns the value of the named SOAP header field, or NULL if not called from a SOAP
service. It is used when processing a SOAP request via a web service.

If a header for the given header-key does not exist, the return value is NULL.

338 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “NEXT_SOAP_HEADER function [SOAP]” on page 286
● “sa_set_soap_header system procedure” on page 1139
● “Tutorial: Using SQL Anywhere to access a SOAP/DISH service” [SQL Anywhere Server -
Programming]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Standards and compatibility


● SQL/2008 Vendor extension.

Example
When used within a stored procedure that is called by an HTTP web service, the following example
processes all the keys located in the SOAP request header. When it processes the Authentication key, it
also obtains the key's value.
BEGIN
DECLARE hd_key LONG VARCHAR;
DECLARE hd_entry LONG VARCHAR;
header_loop:
LOOP
SET hd_key = NEXT_SOAP_HEADER( hd_key );
IF hd_key IS NULL THEN
-- no more header entries
LEAVE header_loop;
END IF;
IF hd_key = 'Authentication' THEN
SET hd_entry = SOAP_HEADER( hd_key );
END IF;
END LOOP header_loop;
END;

SORTKEY function [String]


Generates sort key values. That is, values that can be used to sort character strings based on alternate
collation rules.

Syntax
SORTKEY( string-expression
[, { collation-id
| collation-name[ ( collation-tailoring-string) ] } ]
)

Parameters
● string-expression The string expression must contain characters that are encoded in the database's
character set.

If string-expression is an empty string, the SORTKEY function returns a zero-length binary value. If
string-expression is NULL, the SORTKEY function returns a NULL value. An empty string has a
different sort order value than a NULL string from a database column.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 339


SQL functions

The maximum length of the string that the SORTKEY function can handle is 254 bytes. Any longer
part is ignored.

● collation-name A string or a character variable that specifies the name of the sort order to use.
You can also specify the alias char_collation, or, equivalently, db_collation, to generate sortkeys as
used by the CHAR collation in use by the database. Similarly, you can specify the alias
nchar_collation to generate sortkeys as used by the NCHAR collation in use by the database.

● collation-id A variable, integer constant, or string that specifies the ID number of the sort order to
use. If you do not specify collation-id, the default is Default Unicode multilingual.

● collation-tailoring-string Optionally, you can specify collation tailoring options (collation-


tailoring-string) for additional control over the sorting and comparing of characters. These options
take the form of keyword=value pairs assembled in parentheses, following the collation name. For
example, 'UCA(locale=es;case=LowerFirst;accent=respect)'. The syntax for
specifying these options is identical to the syntax defined for the COLLATION clause of the
CREATE DATABASE statement.

Note
All the collation tailoring options are supported when specifying the UCA collation. For all other
collations, only case sensitivity tailoring is supported.

Returns
BINARY

Remarks
The SORTKEY function generates values that can be used to order results based on predefined sort order
behavior. This allows you to work with character sort order behaviors that may not be available from the
database collation. The returned value is a binary value that contains coded sort order information for the
input string that is retained from the SORTKEY function. For example, you can store the values returned
by the SORTKEY function in a column with the source character string. When you want to retrieve the
character data in the desired order, the SELECT statement only needs to include an ORDER BY clause on
the columns that contain the results of running the SORTKEY function.

The SORTKEY function guarantees that the values it returns for a given set of sort order criteria work for
the binary comparisons that are performed on VARBINARY data types.

Generating sortkeys for queries can be expensive. As an alternative for frequently requested sortkeys,
consider creating a computed column to hold the sortkey values, and then referencing that column in the
ORDER BY clause of the query.

The input of the SORTKEY function can generate up to six bytes of sort order information for each input
character. The output of the SORTKEY function is of type VARBINARY and has a maximum length of
1024 bytes.

When specifying UCA for the collation during sort key generation, by default, collation tailorings are
accent and case sensitive. For example, when UCA is specified by itself, the default tailoring applied is
equivalent to 'UCA(case=UpperFirst;accent=Respect;punct=Primary)'.

340 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

If a different tailoring is provided in the second parameter to SORTKEY, those settings override the
default settings. For example, the following two statements are equivalent:
SELECT SORTKEY( 'abc', 'UCA(accent=Ignore)' );
SELECT SORTKEY( 'abc', 'UCA(case=UpperFirst;accent=Ignore;punct=Primary)' );

When specifying a non-UCA collation, by default, collation tailorings are also accent and case sensitive.
However, for non-UCA collations, only the case sensitivity can be overridden using a collation tailoring.
For example:
SELECT SORTKEY( 'abc', '1252LATIN1(case=Respect)' );

If the database was created without specifying tailoring options (for example, dbinit -c -zn uca
mydb.db), the following two clauses may generate different sort orders, even if the database collation
name is specified for the SORTKEY function:
ORDER BY string-expression
ORDER BY SORTKEY( string-expression, database-collation-name )

This is because the default tailoring settings used for database creation and for the SORTKEY function
are different. To get the same behavior from SORTKEY as for the database collation, either provide a
tailoring syntax for collation-tailoring-string that matches the settings for the database collation, or
specify db_collation for collation-name. For example:
SORTKEY( expression, 'db_collation' )

Note
Sort key values are generated differently depending on the version of SQL Anywhere. This can cause
sorting issues if sort key values created by one version of SQL Anywhere are used in a database created
by a different version of SQL Anywhere. You should regenerate sort key values if sorting issues occur.

You should also regenerate sort key values when upgrading your database using unload/reload.

See also
● “sort_collation option” [SQL Anywhere Server - Database Administration]
● “Supported and alternate collations” [SQL Anywhere Server - Database Administration]
● “Collation tailoring options” [SQL Anywhere Server - Database Administration]
● “Recommended character sets and collations” [SQL Anywhere Server - Database Administration]
● “COMPARE function [String]” on page 165
● “CREATE DATABASE statement” on page 508
● “International languages and character sets” [SQL Anywhere Server - Database Administration]
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements queries the Employees table and returns the FirstName and Surname of all
employees, sorted by the sortkey values for the Surname column using the dict collation (Latin-1,
English, French, German dictionary).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 341


SQL functions

SELECT Surname, GivenName FROM Employees ORDER BY SORTKEY( Surname, 'dict' );

The following example returns the sortkey value for abc, using the UCA collation and tailoring options.
SELECT SORTKEY( 'abc', 'UCA(locale=es;case=LowerFirst;accent=respect)' );

SOUNDEX function [String]


Returns a number representing the sound of a string.

Syntax
SOUNDEX( string-expression )

Parameters
● string-expression The string to be evaluated.

Returns
SMALLINT

Remarks
The SOUNDEX function value for a string is based on the first letter and the next three consonants other
than H, Y, and W. Vowels in string-expression are ignored unless they are the first letter of the string.
Doubled letters are counted as one letter. For example, the word "apples" is based on the letters A, P, L,
and S.

Multibyte characters are ignored by the SOUNDEX function.

Although it is not perfect, the SOUNDEX function normally returns the same number for words that
sound similar and that start with the same letter.

The SOUNDEX function works best with English words. It is less useful for other languages.

See also
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns two identical numbers, 3827, representing the sound of each name.
SELECT SOUNDEX( 'Smith' ), SOUNDEX( 'Smythe' );

342 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

SPACE function [String]


Returns a specified number of spaces.

Syntax
SPACE( integer-expression )

Parameters
● integer-expression The number of spaces to return.

Returns
LONG VARCHAR

Remarks
If integer-expression is negative, a null string is returned.

See also
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns a string containing 10 spaces.

SELECT SPACE( 10 );

SQLDIALECT function [Miscellaneous]


Returns either Watcom SQL or Transact-SQL, to indicate the SQL dialect of a statement.

Syntax
SQLDIALECT( sql-statement-string )

Parameters
● sql-statement-string The SQL statement that the function uses to determine its dialect.

Returns
LONG VARCHAR

See also
● “TRANSACTSQL function [Miscellaneous]” on page 365
● “WATCOMSQL function [Miscellaneous]” on page 380

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 343


SQL functions

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the string Transact-SQL.

SELECT
SQLDIALECT( 'SELECT EmployeeName = Surname FROM Employees' )
FROM dummy;

SQLFLAGGER function [Miscellaneous]


Returns the conformity of a given SQL statement to a specified standard.

Syntax
SQLFLAGGER( sql-standard-string, sql-statement-string )

Parameters
● sql-standard-string The standard level against which to test compliance. Possible values are the
same as for the sql_flagger_error_level database option:

○ SQL:2008/Core Test for conformance to core SQL/2008 syntax.

○ SQL:2008/Package Test for conformance to full SQL/2008 syntax.

○ SQL:2003/Core Test for conformance to core SQL/2003 syntax.

○ SQL:2003/Package Test for conformance to full SQL/2003 syntax.

○ SQL:1999/Core Test for conformance to core SQL/1999 syntax.

○ SQL:1999/Package Test for conformance to full SQL/1999 syntax.

○ SQL:1992/Entry Test for conformance to entry-level SQL/1992 syntax.

○ SQL:1992/Intermediate Test for conformance to intermediate-level SQL/1992 syntax.

○ SQL:1992/Full Test for conformance to full-SQL/1992 syntax.

○ UltraLite Test for conformance to UltraLite.

● sql-statement-string The SQL statement to check for conformance.

Returns
LONG VARCHAR

344 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “sql_flagger_error_level option” [SQL Anywhere Server - Database Administration]
● “The SQL preprocessor” [SQL Anywhere Server - Programming]
● “sa_ansi_standard_packages system procedure” on page 1007
● “SQL compliance testing using the SQL Flagger” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement shows an example of the message that is returned when a disallowed extension is
found:
SELECT SQLFLAGGER(
'SQL:2003/Package', 'SELECT top 1 dummy_col FROM sys.dummy ORDER BY
dummy_col' );

This statement returns the message '0AW03 Disallowed language extension detected
in syntax near 'top' on line 1'.

The following statement returns '00000' because it does not contain any disallowed extensions:
SELECT SQLFLAGGER( 'SQL:2003/Package', 'SELECT dummy_col FROM sys.dummy' );

SQRT function [Numeric]


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.

Returns
DOUBLE

Remarks
This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns a DOUBLE as the result.

Standards and compatibility


● SQL/2008 The SQRT function comprises part of optional SQL/2008 language feature T621,
"Enhanced numeric functions".

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 345


SQL functions

Example
The following statement returns the value 3.
SELECT SQRT( 9 );

STDDEV function [Aggregate]


An alias for STDDEV_SAMP.

See also
● “STDDEV_SAMP function [Aggregate]” on page 348

STDDEV_POP function [Aggregate]


Computes the standard deviation of a population consisting of a numeric-expression, as a DOUBLE.

Syntax 1
STDDEV_POP( numeric-expression )

Syntax 2
STDDEV_POP( numeric-expression ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● numeric-expression The expression whose population-based standard deviation is calculated
over a set of rows. The expression is commonly a column name.

Returns
DOUBLE

Remarks
This function converts its argument to DOUBLE, and performs the computation in double-precision
floating-point arithmetic.

The population-based standard deviation (s) is computed according to the following formula:

s = [ (1/N) * SUM( xI - mean( x ) )2 ]½

This standard deviation does not include rows where numeric-expression is NULL. It returns NULL for a
group containing no rows.

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

346 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “WINDOW clause” on page 961
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 The STDDEV_POP function comprises part of optional SQL /2008 language feature
T621, "Enhanced numeric functions". When used as window function, STDDEV_POP comprises part
of optional SQL foundation feature T611, "Elementary OLAP operations".

The ability to specify DISTINCT over an expression that is not a column reference comprises part of
optional SQL language feature F561, "Full value expressions". SQL Anywhere also supports SQL/
2008 language feature F441, "Extended set function support", which permits operands of aggregate
functions to be arbitrary expressions possibly including outer references to expressions in other query
blocks that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the STDDEV_POP function, combined with an
outer reference. For an example, see “AVG function [Aggregate]” [UltraLite - Database Management
and Reference].

Example
The following statement lists the average and variance in the number of items per order in different time
periods:
SELECT YEAR( ShipDate ) AS Year,
QUARTER( ShipDate ) AS Quarter,
AVG( Quantity ) AS Average,
STDDEV_POP( quantity ) AS Variance
FROM SalesOrderItems
GROUP BY Year, Quarter
ORDER BY Year, Quarter;

Year Quarter Average Variance

2000 1 25.775148 14.2794...

2000 2 27.050847 15.0270...

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 347


SQL functions

Year Quarter Average Variance

... ... ... ...

STDDEV_SAMP function [Aggregate]


Computes the standard deviation of a sample consisting of a numeric-expression, as a DOUBLE.

Syntax 1
STDDEV_SAMP( numeric-expression )

Syntax 2
STDDEV_SAMP( numeric-expression ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● numeric-expression The expression whose sample-based standard deviation is calculated over a
set of rows. The expression is commonly a column name.

Returns
DOUBLE

Remarks
This function converts its argument to DOUBLE, and performs the computation in double-precision
floating-point arithmetic.

The standard deviation (s) is computed according to the following formula, which assumes a normal
distribution:

s = [ (1/( N - 1 )) * SUM( xI - mean( x ) )2 ]½

This standard deviation does not include rows where numeric-expression is NULL. It returns NULL for a
group containing either 0 or 1 rows.

For more information about the statistical computation performed, see “Mathematical formulas for the
aggregate functions” [SQL Anywhere Server - SQL Usage].

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

348 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “WINDOW clause” on page 961
● “Aggregate functions” on page 133

Standards and compatibility


● SQL/2008 The STDDEV_SAMP function comprises part of optional SQL /2008 language feature
T621, "Enhanced numeric functions". When used as window function, STDDEV_SAMP comprises
part of optional SQL foundation feature T611, "Elementary OLAP operations".

The ability to specify DISTINCT over an expression that is not a column reference comprises part of
optional SQL language feature F561, "Full value expressions". SQL Anywhere also supports SQL/
2008 language feature F441, "Extended set function support", which permits operands of aggregate
functions to be arbitrary expressions possibly including outer references to expressions in other query
blocks that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the STDDEV_SAMP function, combined with an
outer reference. For an example, see “AVG function [Aggregate]” [UltraLite - Database Management
and Reference].

Example
The following statement lists the average and variance in the number of items per order in different time
periods:

SELECT YEAR( ShipDate ) AS Year,


QUARTER( ShipDate ) AS Quarter,
AVG( Quantity ) AS Average,
STDDEV_SAMP( quantity ) AS Variance
FROM SalesOrderItems
GROUP BY Year, Quarter
ORDER BY Year, Quarter;

Year Quarter Average Variance

2000 1 25.775148 14.3218...

2000 2 27.050847 15.0696...

... ... ... ...

STR function [String]


Returns the string equivalent of a number.

Syntax
STR( numeric-expression [, length [, decimal ] ] )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 349


SQL functions

Parameters
● numeric-expression Any approximate numeric (float, real, or double precision) expression
between -1E126 and 1E127.

● 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.

Returns
VARCHAR

Remarks
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 );

Note
The maximum length that is supported is 128. Any length that is not between 1 and 128 yields a result of
NULL.

See also
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
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 );

STRING function [String]


Concatenates one or more strings into one large string.

Syntax
STRING( string-expression [, ... ] )

Parameters
● string-expression The string to be evaluated.

350 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

If only one argument is supplied, it is converted into a single expression. If multiple arguments are
supplied, they are concatenated into a single string.

Returns
● LONG VARCHAR
● LONG NVARCHAR
● LONG BINARY

Remarks
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. If any parameters are non-NULL, then any NULL
parameters are treated as empty strings.

See also
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value testing123.
SELECT STRING( 'testing', NULL, 123 );

STRTOUUID function [String]


Converts a string value to a unique identifier (UUID or GUID) value.

Note
In databases created before version 9.0.2, the UNIQUEIDENTIFIER data type was defined as a user-
defined data type and the STRTOUUID and UUIDTOSTR functions were needed to convert between
binary and string representations of UUID values.

In databases created using version 9.0.2 or later, the UNIQUEIDENTIFIER data type was changed to a
native data type and SQL Anywhere carries out conversions as needed. You do not need to use
STRTOUUID and UUIDTOSTR functions with these versions.

For more information, see “UNIQUEIDENTIFIER data type” on page 118.

Syntax
STRTOUUID( string-expression )

Parameters
● string-expression A string in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 351


SQL functions

Returns
UNIQUEIDENTIFIER

Remarks
Converts a string in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is a hexadecimal digit, to
a unique identifier value.

If the string is not a valid UUID string, a conversion error is returned unless the conversion_error option
is set to OFF, in which case it returns NULL.

This function is useful for inserting UUID values into a database.

This function supports NCHAR inputs and/or outputs.

Curly braces can be used as the first and last characters in the string-expression.

See also
● “UUIDTOSTR function [String]” on page 374
● “NEWID function [Miscellaneous]” on page 279
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements are equivalent and return the result 0x6c2b64a93c6f47dc901536b9ed49fec2.

SELECT STRTOUUID( '6c2b64a9-3c6f-47dc-9015-36b9ed49fec2' );

SELECT STRTOUUID( '{6c2b64a9-3c6f-47dc-9015-36b9ed49fec2}' );

STUFF function [String]


Deletes multiple characters from one string and replaces them with another string.

Syntax
STUFF( string-expression-1, start, length, string-expression-2 )

Parameters
● string-expression-1 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.

352 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

● string-expression-2 The string to be inserted. To delete a portion of a string using the STUFF
function, use a replacement string of NULL.

Returns
LONG NVARCHAR

Remarks
This function supports NCHAR inputs and/or outputs.

See also
● “INSERTSTR function [String]” on page 249
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value chocolate pie.
SELECT STUFF( 'chocolate cake', 11, 4, 'pie' );

SUBSTRING function [String]


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.

● length The length of the substring to return, in characters. If length is specified, the substring is
restricted to that length.

Returns
● LONG BINARY
● LONG VARCHAR
● LONG NVARCHAR

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 353


SQL functions

Remarks
The behavior of this function depends on the setting of the ansi_substring database option. When the
ansi_substring option is set to On (the default), the behavior of the SUBSTRING function corresponds to
ANSI/ISO SQL/2008 behavior. The behavior is as follows:

ansi_substring start value length value


option setting

On The first character in the string is at posi- A positive length specifies that the
tion 1. A negative or zero start offset is substring ends length characters to
treated as if the string were padded on the the right of the starting position.
left with non-characters.
A negative length returns an error.

Off The first character in the string is at posi- A positive length specifies that the
tion 1. A negative starting position specifies substring ends length characters to
a number of characters from the end of the the right of the starting position.
string instead of the beginning.
A negative length returns at most
If start is zero and length is non-negative, a length characters up to, and includ-
start value of 1 is used. If start is zero and ing, the starting position, from the
length is negative, a start value of -1 is left of the starting position.
used.

If string-expression is of binary data type, the SUBSTRING function behaves as BYTE_SUBSTR.

To obtain characters at the end of a string, use the RIGHT function.

This function supports NCHAR inputs and/or outputs. Whenever possible, if the input string uses
character-length semantics, the return value is described in character-length semantics.

See also
● “BYTE_SUBSTR function [String]” on page 158
● “LEFT function [String]” on page 258
● “RIGHT function [String]” on page 326
● “CHARINDEX function [String]” on page 163
● “String functions” on page 142

Standards and compatibility


● SQL/2008 SUBSTRING is a core feature of the SQL/2008 standard. The standard's
implementation differs slightly from the SQL Anywhere implementation: in the standard,
SUBSTRING is defined with three parameters using the keywords FROM and FOR, neither of which
are required by SQL Anywhere.

Example
The following table shows the values returned by the SUBSTRING function.

354 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example Result

SUBSTRING( 'front yard', 1, 4 ) fron

SUBSTRING( 'back yard', 6, 4 ) yard

SUBSTR( 'abcdefgh', 0, -2 ) Returns an error if ansi_substring is On

SUBSTR( 'abcdefgh', -2, 2 ) Returns an empty string if ansi_substring is On

SUM function [Aggregate]


Returns the total of the specified expression for each group of rows.

Syntax 1
SUM( [ ALL | DISTINCT ] expression )

Syntax 2
SUM( [ ALL ] expression ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● [ ALL ] expression The name of the expression to be summed. This is commonly a column name.

● DISTINCT expression Computes the sum of the unique values of expression within each group.

Returns
● INTEGER
● DOUBLE
● NUMERIC

Remarks
Rows where the specified expression is NULL are not included.

Returns NULL for a group containing no rows.

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 355


SQL functions

This function can generate an overflow error, resulting in an error being returned. You can use the CAST
function on numeric-expression to avoid the overflow error. See “CAST function [Data type conversion]”
[UltraLite - Database Management and Reference].

See also
● “WINDOW clause” on page 961
● “COUNT function [Aggregate]” on page 177
● “AVG function [Aggregate]” on page 150

Standards and compatibility


● SQL/2008 Core feature. When used as a window function (Syntax 2), SUM comprises part of
optional SQL/2008 language feature T611, "Basic OLAP operations".

The ability to specify DISTINCT over an expression that is not a column reference comprises part of
optional SQL language feature F561, "Full value expressions". SQL Anywhere also supports SQL/
2008 language feature F441, "Extended set function support", which permits operands of aggregate
functions to be arbitrary expressions possibly including outer references to expressions in other query
blocks that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the SUM function, combined with an outer
reference. See “Aggregate functions and outer references” [SQL Anywhere Server - SQL Usage].

For an example, see “AVG function [Aggregate]” [UltraLite - Database Management and Reference].

Example
The following statement returns the value 3749146.740.

SELECT SUM( Salary )


FROM Employees;

SUSER_ID function [System]


Returns the numeric user ID for the specified user name.

Syntax
SUSER_ID( [ user-name ] )

Parameters
● user-name The user name for the user ID you are searching for.

Returns
INT

356 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Remarks
If you do not specify user-name, the ID of the current user is returned.

See also
● “SUSER_NAME function [System]” on page 357
● “USER_ID function [System]” on page 373

Standards and compatibility


● SQL/2008 Transact-SQL extension.

Example
The following statement returns the ID for the GROUPO user.
SELECT SUSER_ID( 'GROUPO' );

SUSER_NAME function [System]


Returns the user name for the specified user ID.

Syntax
SUSER_NAME( [ user-id ] )

Parameters
● user-id The user ID of the user you are searching for.

Returns
LONG VARCHAR

Remarks
If you do not specify user-id, the user name of the current user is returned.

See also
● “SUSER_ID function [System]” on page 356
● “USER_NAME function [System]” on page 374

Standards and compatibility


● SQL/2008 Transact-SQL extension.

Example
The following statement returns the user name for a user with ID 101.
SELECT SUSER_NAME( 101 );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 357


SQL functions

SWITCHOFFSET function [Date and time]


Returns a TIMESTAMP WITH TIME ZONE value that is converted from its original time zone offset to
the specified time zone offset.

Syntax
SWITCHOFFSET( tmz-expression, time-zone-offset )

Parameters
● tmz-expression The TIMESTAMP WITH TIME ZONE value to be converted.

● time-zone-offset The time zone offset of the result. The value can be an integer representing the
minutes before or after Coordinated Universal Time (UTC), a string in the form { + | - } hh:nn, or Z
for the Zulu Time Zone. The Zulu Time Zone is the same time zone as UTC.

Returns
TIMESTAMP WITH TIME ZONE

See also
● “TIMESTAMP WITH TIME ZONE data type” on page 115
● “SYSDATETIMEOFFSET function [Date and time]” on page 358

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example changes a time zone offset value from -04:00 hours to -07:00 hours. The value
returned is 2009-04-03 11:45:12.123-07:00.
SELECT CAST ( '2009-04-03 14:45:12.123-04:00' AS datetimeoffset ) AS EDT,
SWITCHOFFSET( EDT,'-07:00' ) AS PDT;

SYSDATETIMEOFFSET function [Date and time]


Returns the current date, time, and time zone offset of the database server using the system clock.

Syntax
SYSDATETIMEOFFSET ( )

Returns
TIMESTAMP WITH TIME ZONE

See also
● “TIMESTAMP WITH TIME ZONE data type” on page 115
● “SWITCHOFFSET function [Date and time]” on page 358

358 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example returns the current date and time and the time zone offset of the database server.
SELECT SYSDATETIMEOFFSET ( );

The following example converts the SYSDATETIMEOFFSET value to the time zone of the client
computer.
SELECT SWITCHOFFSET ( SYSDATETIMEOFFSET ( ),
CAST( connection_property ('TimeZoneAdjustment') AS INT ));

TAN function [Numeric]


Returns the tangent of a number.

Syntax
TAN( numeric-expression )

Parameters
● numeric-expression An angle, in radians.

Returns
DOUBLE

Remarks
The ATAN and TAN functions are inverse operations.

This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns a DOUBLE as the result.

See also
● “COS function [Numeric]” on page 176
● “SIN function [Numeric]” on page 337

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value of the tan of 0.52.
SELECT TAN( 0.52 );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 359


SQL functions

TEXTPTR function [Text and image]


Returns a 16-byte binary pointer to the specified column. This feature is provided solely for compatibility
with Transact-SQL and its use is not recommended.

Syntax
TEXTPTR( column-name )

Parameters
● column-name The name of a column containing CHAR, NCHAR, or BINARY data.

Returns
BINARY

Remarks
This function is included for Transact-SQL compatibility.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following embedded SQL example uses TEXTPTR to locate the Description column associated with
ProductID 500 in the MarketingInformation table.

The text pointer is stored in the variable txtptr and supplied as a parameter to the READTEXT statement
which returns 55 bytes, starting at column offset 181.
EXEC SQL BEGIN DECLARE SECTION;
char hostvar[100];
EXEC SQL END DECLARE SECTION;

EXEC SQL create variable txtptr binary(16);


EXEC SQL set txtptr =
( SELECT textptr(Description)
FROM GROUPO.MarketingInformation
WHERE ProductID = '500' );
EXEC SQL PREPARE S1 FROM
'READTEXT GROUPO.MarketingInformation.Description txtptr 181 55';
EXEC SQL EXECUTE S1 INTO :hostvar;
printf( "hostvar: %s\n", hostvar );

READTEXT returns the following string.


Lightweight 100% organically grown cotton construction.

TO_CHAR function [String]


Converts character data from any supported character set into the CHAR character set for the database.

360 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Syntax
TO_CHAR( string-expression [, source-charset-name ] )

Parameters
● string-expression The string to be converted.

● source-charset-name The character set of the string.

Returns
LONG VARCHAR

Remarks
If source-charset-name is specified, then this function is equivalent to:

CAST( CSCONVERT( CAST( string-expression AS BINARY ),


'db_charset', source-charset-name )
AS CHAR );

For more information about db_charset, see “CSCONVERT function [String]” on page 183.

If source-charset-name is not specified, then this function is equivalent to:

CAST( string-expression AS CHAR );

See also
● “Recommended character sets and collations” [SQL Anywhere Server - Database Administration]
● “CONNECTION_EXTENDED_PROPERTY function [String]” on page 169
● “CSCONVERT function [String]” on page 183
● “NCHAR function [String]” on page 278
● “TO_NCHAR function [String]” on page 361
● “UNICODE function [String]” on page 370
● “UNISTR function [String]” on page 371

Standards and compatibility


● SQL/2008 Vendor extension.

Example
If you have a BINARY value containing data in the cp850 character set, the following statement converts
the data to the CHAR character set and data type:

SELECT TO_CHAR( 'cp850_data', 'cp850' );

TO_NCHAR function [String]


Converts character data from any supported character set into the NCHAR character set.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 361


SQL functions

Syntax
TO_NCHAR( string-expression [, source-charset-name ] )

Parameters
● string-expression The string to be converted

● source-charset-name The character set of the string.

Returns
LONG NVARCHAR

Remarks
If source-charset-name is specified then this function is equivalent to:

CAST( CSCONVERT( CAST( string-expression AS BINARY ),


'nchar_charset', source-charset-name )
AS NCHAR );

For more information about nchar_charset, see “CSCONVERT function [String]” on page 183.

If source-charset-name is not provided then this function is equivalent to:

CAST( string-expression AS NCHAR );

See also
● “Recommended character sets and collations” [SQL Anywhere Server - Database Administration]
● “CONNECTION_EXTENDED_PROPERTY function [String]” on page 169
● “CSCONVERT function [String]” on page 183
● “NCHAR function [String]” on page 278
● “TO_CHAR function [String]” on page 360
● “UNICODE function [String]” on page 370
● “UNISTR function [String]” on page 371

Standards and compatibility


● SQL/2008 Vendor extension.

Example
If you have a BINARY value containing data in the cp850 character set, the following example to
converts the data to the NCHAR character set and data type:

SELECT TO_NCHAR( 'cp850_data', 'cp850' );

TODATETIMEOFFSET function [Date and time]


Converts a TIMESTAMP value to a TIME STAMP WITH TIME ZONE value using the specified time
zone offset.

362 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Syntax
TODATETIMEOFFSET( timestamp-expression, time-zone-offset )

Parameters
● timestamp-expression The TIMESTAMP expression to be converted.

● time-zone-offset The time zone offset. The value can be an INTEGER representing minutes
before or after UTC, a VARCHAR string in the form of { + | - }hh:nn, or the string "Z" for the Zulu
Time Zone. The Zulu Time Zone is the same time zone as UTC.

Returns
TIMESTAMP WITH TIME ZONE

See also
● “TIMESTAMP WITH TIME ZONE data type” on page 115

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example converts a TIMESTAMP value to a TIMESTAMP WITH TIME ZONE value.

SELECT CAST('2009-04-03 14:45:12.123' AS TIMESTAMP) AS orig,


TODATETIMEOFFSET (orig,'+11:00');

TODAY function [Date and time]


Returns the current date as a DATE value.

Syntax
TODAY( [ * ] )

Returns
DATE

Remarks
TODAY(*) and TODAY() are semantically equivalent. TODAY is equivalent to the CURRENT DATE
special value.

Each instance of the TODAY function in a request is evaluated at most once. Multiple instances of
TODAY in the same request may or may not share the identical DATE value.

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 363


SQL functions

Example
The following statements return the current day according to the system clock.
SELECT TODAY( * );
SELECT CURRENT DATE;

TRACEBACK function [Miscellaneous]


Returns a string containing a traceback of the procedures and triggers that were executing when the most
recent exception (error) occurred.

Syntax
TRACEBACK( [ * ] )

Returns
LONG VARCHAR

Remarks
TRACEBACK(*) and TRACEBACK() are semantically equivalent.

This function is useful for debugging procedures and triggers, particularly those that are written in the
Transact-SQL dialect.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
To use the traceback function, enter the following after an error occurs while executing a procedure:
SELECT TRACEBACK( * );

TRACED_PLAN function [Miscellaneous]


This function is used by Sybase Central to generate a graphical plan for a query using tracing data.

Syntax
TRACED_PLAN( logging_session_id, query_id )

Parameters
● logging_session_id Combined with query_id, this INTEGER parameter identifies a row from the
sa_diagnostic_query table for which to generate the plan.

● query_id Combined with logging_session_id, this INTEGER parameter identifies a row from the
sa_diagnostic_query table for which to generate the plan.

364 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Returns
LONG VARCHAR

Remarks
This function is for use by Sybase Central.

See also
● “sa_diagnostic_query table” on page 987

Standards and compatibility


● SQL/2008 Vendor extension.

TRANSACTSQL function [Miscellaneous]


Takes a Watcom SQL statement and rewrites it in the Transact-SQL dialect.

Syntax
TRANSACTSQL( sql-statement-string )

Parameters
● sql-statement-string The SQL statement that is to be rewritten in Transact-SQL.

Returns
LONG VARCHAR

See also
● “SQLDIALECT function [Miscellaneous]” on page 343
● “WATCOMSQL function [Miscellaneous]” on page 380

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the string 'SELECT EmployeeName=empl_name FROM
Employees'.
SELECT TRANSACTSQL( 'SELECT empl_name as EmployeeName FROM Employees' ) FROM
dummy;

TREAT function [Data type conversion]


The TREAT function allows you to change the declared type of a geometry expression to a subtype. This
function is for use with spatial data.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 365


SQL functions

Syntax
TREAT ( geometry-expression AS subtype )

Parameters
● geometry-expression The expression to be converted.

● subtype The target subtype to convert geometry-expression into.

Returns
Depends on the data type requested.

Remarks
The TREAT function can only be used on geometries.

If the dynamic type of the expression is not a subtype of the target data type, an error is returned. The
CAST function can also be used to change the declared type of a geometry expression. However, the
CAST function allows changes outside of the subtype hierarchy. For example, CAST can be used to
convert a point to a multipoint. These types of conversions may change the dynamic type of an expression
in unexpected ways, so TREAT is preferable when moving from a supertype to a subtype. The TREAT
function also executes more efficiently than the CAST function.

See also
● “Using the TREAT expression for subtypes” [SQL Anywhere Server - Spatial Data Support]
● “CAST function [Data type conversion]” on page 159

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
Execute the following in Interactive SQL to create a table and load two values into it:
DROP TABLE IF EXISTS treatExample;
CREATE TABLE treatExample( pk INT PRIMARY KEY, geo ST_Geometry );
INSERT INTO treatExample VALUES(0, NEW ST_Point(3,4) );
INSERT INTO treatExample VALUES(1, NEW ST_MultiPoint( new ST_Point( 5,
6 ) ) );

The following query returns an error. See “Type '%1' has no method named '%2' (near '%3')” [Error
Messages].
SELECT geo.ST_X() FROM treatExample T WHERE pk = 0;

The following query succeeds:


SELECT TREAT( geo AS ST_Point ).ST_X() FROM treatExample WHERE pk = 0;

The following query returns an error. See “Type '%1' has no method named '%2' (near '%3')” [Error
Messages].
SELECT TREAT( geo AS ST_Point ).ST_X() FROM treatExample T WHERE pk = 0;

366 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

The following query succeeds because a CAST statement is used instead of a TREAT statement:
SELECT CAST( geo AS ST_Point ) FROM treatExample WHERE pk = 1;

TRIM function [String]


Removes leading and trailing blanks from a string.

Syntax
TRIM( string-expression )

Parameters
● string-expression The string to be trimmed.

Returns
● VARCHAR
● NVARCHAR
● LONG VARCHAR
● LONG NVARCHAR

Remarks
This function supports NCHAR inputs and/or outputs.

See also
● “LTRIM function [String]” on page 267
● “RTRIM function [String]” on page 330
● “String functions” on page 142

Standards and compatibility


● SQL/2008 The TRIM function is a SQL/2008 core feature.

SQL Anywhere does not support the additional parameters trim specification and trim character, as
defined in SQL/2008. The SQL Anywhere implementation of TRIM corresponds to a TRIM
specification of BOTH.

For the other TRIM specifications defined by the SQL/2008 standard (LEADING and TRAILING),
SQL Anywhere supplies the LTRIM and RTRIM functions respectively.

Example
The following statement returns the value chocolate with no leading or trailing blanks.
SELECT TRIM( ' chocolate ' );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 367


SQL functions

TRUNCNUM function [Numeric]


Truncates a number at a specified number of places after the decimal point.

Syntax
{ TRUNCNUM | TRUNCATE }( numeric-expression, integer-expression )

Parameters
● numeric-expression The number to be truncated. This argument may be of type NUMERIC or
DOUBLE.

● integer-expression A positive integer specifies the number of significant digits to the right of the
decimal point at which to round. A negative value specifies the number of significant digits to the left
of the decimal point at which to round.

Returns
NUMERIC or DOUBLE

Remarks
You should use the TRUNCNUM function, not the TRUNCATE function, when truncating numbers.

Use of the TRUNCATE function is not recommended because the word truncate is a keyword, and
therefore requires you to either set the quoted_identifier option to OFF, or put quotes around the word
TRUNCATE.

See also
● “ROUND function [Numeric]” on page 327
● “quoted_identifier option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 600.

SELECT TRUNCNUM( 655, -2 );

The following statement: returns the value 655.340.

SELECT TRUNCNUM( 655.348, 2 );

TSEQUAL function [System] (deprecated)


Compares two TIMESTAMP values and returns whether they are the same.

368 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Syntax
TSEQUAL ( timestamp-expression-1, timestamp-expression-2 )

Parameters
● timestamp-expression-1 A TIMESTAMP value.

● timestamp-expression-2 A TIMESTAMP value.

Returns
BIT

Remarks
The TSEQUAL function can only be used in a WHERE clause and is most commonly used as part of an
UPDATE statement.

Although the TSEQUAL function can be used to compare two ordinary TIMESTAMP values, the
purpose of TSEQUAL is to determine whether or not a row has been modified by another connection by
comparing two special Transact-SQL TIMESTAMP values.

In a single-row UPDATE statement using TSEQUAL, if timestamp-expression-1 is equal to timestamp-


expression-2 and one of these values refers to a column declared with DEFAULT TIMESTAMP and the
other refers to the value of the column when the row was last fetched, then the row has not changed since
it was fetched and TSEQUAL returns TRUE. If the row was changed by another user, its timestamp has
been modified and the TSEQUAL function returns FALSE. If the TSEQUAL function returns FALSE in
this situation, the UPDATE is not performed. The application can determine that no rows were updated by
examining the number of rows affected, for example by using @@rowcount. If no rows were affected, the
application can assume that the row was modified by another user and that it needs to be re-fetched.

See also
● “The data type of a TIMESTAMP column” [SQL Anywhere Server - SQL Usage]
● “TIMESTAMP special value” on page 69
● “The special Transact-SQL TIMESTAMP column and data type” [SQL Anywhere Server - SQL
Usage]
● “UPDATE statement” on page 948

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Suppose you create a TIMESTAMP column Products.LastUpdated to store the timestamp for the last time
the row was updated. The following example uses the TSEQUAL function to change a row value. An
update is applied to the row only when the row has not been changed since it was last fetched.
SELECT LastUpdated into old_ts_value
FROM Products
WHERE ID = '300';
UPDATE Products
SET Color = 'Yellow'

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 369


SQL functions

WHERE ID = '300'
AND TSEQUAL( LastUpdated, old_ts_value );

UCASE function [String]


Converts all characters in a string to uppercase.

Syntax
UCASE( string-expression )

Parameters
● string-expression The string to be converted to uppercase.

Returns
CHAR, VARCHAR, LONG VARCHAR, NCHAR, NVARCHAR, or LONG NVARCHAR
corresponding to the data type of the argument.

Remarks
This function is identical to the UPPER function.

See also
● “UPPER function [String]” on page 372
● “LCASE function [String]” on page 257
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension. The UPPER function is SQL/2008 compliant.

Example
The following statement returns the value CHOCOLATE.
SELECT UCASE( 'ChocoLate' );

UNICODE function [String]


Returns an integer containing the Unicode code point of the first character in the string, or NULL if the
first character is not a valid encoding.

Syntax
UNICODE( nchar-string-expression )

Parameters
● nchar-string-expression The NCHAR string whose first character is to be converted to an
integer.

370 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Returns
INT

See also
● “CONNECTION_EXTENDED_PROPERTY function [String]” on page 169
● “NCHAR function [String]” on page 278
● “TO_CHAR function [String]” on page 360
● “TO_NCHAR function [String]” on page 361
● “UNISTR function [String]” on page 371

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example returns the integer 65536:
SELECT UNICODE(UNISTR( '\u010000data' ));

UNISTR function [String]


Converts a string containing characters and Unicode escape sequences to an NCHAR string.

Syntax
UNISTR( string-expression )

Parameters
● string-expression The string to be converted.

Returns
● NVARCHAR
● LONG NVARCHAR

Remarks
The UNISTR function allows the use of Unicode characters that cannot be represented in the CHAR
character set used by the SQL statement. For example, in an English environment, the UNISTR function
could be used to include Chinese characters.

The UNISTR function offers similar functionality to the N'' constant, however the UNISTR function
allows Unicode characters and characters from the CHAR character set, whereas the N'' constant only
allows characters from the CHAR character set.

The string-expression contains characters and Unicode escape sequences. The Unicode escape sequences
are of the form \uXXXX or \uXXXXXX, where each X is a hexadecimal digit. The UNISTR function
converts each character and each Unicode escape sequence to the corresponding Unicode character.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 371


SQL functions

If a 6-digit Unicode escape sequence is used, its value must not exceed 10FFFF, the largest Unicode code
point. A sequence such as \u234567 is not a 6-digit Unicode escape sequence. It is the 4-digit sequence
\u2345 followed by the characters 6 and 7.

If two adjacent Unicode escape sequences form a UTF-16 surrogate pair, they are combined into one
Unicode character in the output.

See also
● “CONNECTION_EXTENDED_PROPERTY function [String]” on page 169
● “NCHAR function [String]” on page 278
● “TO_CHAR function [String]” on page 360
● “TO_NCHAR function [String]” on page 361
● “UNICODE function [String]” on page 370
● “Strings” on page 5

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example returns the string Hello.

SELECT UNISTR( 'Hel\u006c\u006F' );

The following example combines the UTF-16 surrogate pair D800-DF02 into the Unicode code point
10302.

SELECT UNISTR( '\uD800\uDF02' );

The example is equivalent to the previous one.

SELECT UNISTR( '\u010302' );

UPPER function [String]


Converts all characters in a string to uppercase.

Syntax
UPPER( string-expression )

Parameters
● string-expression The string to be converted to uppercase.

Returns
CHAR, VARCHAR, LONG VARCHAR, NCHAR, NVARCHAR, or LONG NVARCHAR
corresponding to the data type of the argument.

372 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Remarks
This function is identical to the UCASE function.

See also
● “UCASE function [String]” on page 370
● “LCASE function [String]” on page 257
● “LOWER function [String]” on page 266
● “String functions” on page 142

Standards and compatibility


● SQL/2008 The UPPER function is a core feature of the SQL/2008 standard.

Example
The following statement returns the value CHOCOLATE.

SELECT UPPER( 'ChocoLate' );

USER_ID function [System]


Returns the numeric user ID for the specified user name.

Syntax
USER_ID( [ user-name ] )

Parameters
● user-name The user name for the user ID you are searching for.

Returns
INTEGER

Remarks
If you do not specify user-name, the ID of the current user is returned.

See also
● “USER_NAME function [System]” on page 374
● “SUSER_ID function [System]” on page 356

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the GROUPO user ID.

SELECT USER_ID( 'GROUPO' );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 373


SQL functions

USER_NAME function [System]


Returns the user name for the specified user ID.

Syntax
USER_NAME( [ user-id ] )

Parameters
● user-id The user ID of the user you are searching for.

Returns
LONG VARCHAR

Remarks
If you do not specify user-id, the user name of the current user is returned.

See also
● “USER_ID function [System]” on page 373
● “SUSER_NAME function [System]” on page 357

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the user name for user ID 101.
SELECT USER_NAME( 101 );

UUIDTOSTR function [String]


Converts a unique identifier value (UUID, also known as GUID) to a string value.

Note
In databases created before version 9.0.2, the UNIQUEIDENTIFIER data type was defined as a user-
defined data type and the STRTOUUID and UUIDTOSTR functions were needed to convert between
binary and string representations of UUID values.

In databases created using version 9.0.2 or later, the UNIQUEIDENTIFIER data type was changed to a
native data type and SQL Anywhere carries out conversions as needed. You do not need to use
STRTOUUID and UUIDTOSTR functions with these versions.

For more information, see “UNIQUEIDENTIFIER data type” on page 118.

Syntax
UUIDTOSTR( uuid-expression )

374 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Parameters
● uuid-expression A unique identifier value.

Returns
VARCHAR

Remarks
Converts a unique identifier to a string value in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where
x is a hexadecimal digit. If the binary value is not a valid uniqueidentifier, NULL is returned.

This function is useful if you want to view a UUID value.

See also
● “NEWID function [Miscellaneous]” on page 279
● “STRTOUUID function [String]” on page 351
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement creates a table mytab with two columns. Column pk has a unique identifier data
type, and column c1 has an integer data type. It then inserts two rows with the values 1 and 2 respectively
into column c1.

CREATE TABLE mytab(


pk UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
c1 INT );
INSERT INTO mytab( c1 ) values ( 1 );
INSERT INTO mytab( c1 ) values ( 2 );

Executing the following SELECT statement returns all the data in the newly created table.

SELECT * FROM mytab;

You will see a two-column, two-row table. The value displayed for column pk will be binary values.

To convert the unique identifier values into a readable format, execute the following command:

SELECT UUIDTOSTR(pk), c1 FROM mytab;

The UUIDTOSTR function is not needed for databases created with version 9.0.2 or later.

VAR_POP function [Aggregate]


Computes the statistical variance of a population consisting of a numeric-expression, as a DOUBLE.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 375


SQL functions

Syntax 1
VAR_POP( numeric-expression )

Syntax 2
VAR_POP( numeric-expression ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● numeric-expression The expression whose population-based variance is calculated over a set of
rows. The expression is commonly a column name.

Returns
DOUBLE

Remarks
This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns a DOUBLE as the result.

The population-based variance (s2) of numeric-expression (x) is computed according to the following
formula:

s2 = (1/N) * SUM( xI - mean( x ) )2

This variance does not include rows where numeric-expression is NULL. It returns NULL for a group
containing no rows.

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “Aggregate functions” on page 133
● “WINDOW clause” on page 961

Standards and compatibility


● SQL/2008 The VAR_POP function comprises part of optional SQL /2008 language feature T621,
"Enhanced numeric functions". When used as window function, VAR_POP comprises part of optional
SQL foundation feature T611, "Elementary OLAP operations".

The ability to specify DISTINCT over an expression that is not a column reference comprises part of
optional SQL language feature F561, "Full value expressions". SQL Anywhere also supports SQL/

376 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

2008 language feature F441, "Extended set function support", which permits operands of aggregate
functions to be arbitrary expressions possibly including outer references to expressions in other query
blocks that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the VAR_POP function, combined with an outer
reference. For an example, see “AVG function [Aggregate]” [UltraLite - Database Management and
Reference].

Example
The following statement lists the average and variance in the number of items per order in different time
periods:
SELECT YEAR( ShipDate ) AS Year,
QUARTER( ShipDate ) AS Quarter,
AVG( Quantity ) AS Average,
VAR_POP( quantity ) AS Variance
FROM SalesOrderItems
GROUP BY Year, Quarter
ORDER BY Year, Quarter;

Year Quarter Average Variance

2000 1 25.775148 203.9021...

2000 2 27.050847 225.8109...

... ... ... ...

VAR_SAMP function [Aggregate]


Computes the statistical variance of a sample consisting of a numeric-expression, as a DOUBLE.

Syntax 1
VAR_SAMP( numeric-expression )

Syntax 2
VAR_SAMP( numeric-expression ) OVER ( window-spec )

window-spec : see Syntax 2 instructions in the Remarks section below

Parameters
● numeric-expression The expression whose sample-based variance is calculated over a set of
rows. The expression is commonly a column name.

Returns
DOUBLE

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 377


SQL functions

Remarks
This function converts its argument to DOUBLE, performs the computation in double-precision floating-
point arithmetic, and returns a DOUBLE as the result.

The variance (s2) of numeric-expression (x) is computed according to the following formula, which
assumes a normal distribution:

s2 = (1/( N - 1 )) * SUM( xI - mean( x ) )2

This variance does not include rows where numeric-expression is NULL. It returns NULL for a group
containing either 0 or 1 rows.

Syntax 2 represents usage as a window function in a SELECT statement. As such, elements of window-
spec can be specified either in the function syntax (inline), or in conjunction with a WINDOW clause in
the SELECT statement. See the window-spec definition for the WINDOW clause.

For more information about using window functions in SELECT statements, including working examples,
see “Window functions” [SQL Anywhere Server - SQL Usage].

For more information about specifying a window specification in an OVER clause, see “Window
definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server - SQL Usage].

See also
● “Aggregate functions” on page 133
● “VARIANCE function [Aggregate]” on page 380
● “WINDOW clause” on page 961

Standards and compatibility


● SQL/2008 The VAR_SAMP function comprises part of optional SQL /2008 language feature
T621, "Enhanced numeric functions". When used as window function, VAR_SAMP comprises part of
optional SQL foundation feature T611, "Elementary OLAP operations". The VARIANCE syntax is a
vendor extension.

The ability to specify DISTINCT over an expression that is not a column reference comprises part of
optional SQL language feature F561, "Full value expressions". SQL Anywhere also supports SQL/
2008 language feature F441, "Extended set function support", which permits operands of aggregate
functions to be arbitrary expressions possibly including outer references to expressions in other query
blocks that are not column references.

SQL Anywhere does not support optional SQL/2008 feature F442, "Mixed column references in set
functions". SQL Anywhere does not permit the arguments of an aggregate function to include both a
column reference from the query block containing the VAR_SAMP function, combined with an outer
reference. For an example, see “AVG function [Aggregate]” [UltraLite - Database Management and
Reference].

Example
The following statement lists the average and variance in the number of items per order in different time
periods:

378 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

SELECT YEAR( ShipDate ) AS Year,


QUARTER( ShipDate ) AS Quarter,
AVG( Quantity ) AS Average,
VAR_SAMP( quantity ) AS Variance
FROM SalesOrderItems
GROUP BY Year, Quarter
ORDER BY Year, Quarter;

Year Quarter Average Variance

2000 1 25.775148 205.1158...

2000 2 27.050847 227.0939...

... ... ... ...

VAREXISTS function [Miscellaneous]


Returns 1 if a user-defined variable has been created or declared with a given name. Returns 0 if no such
variable has been created.

Syntax
VAREXISTS( variable-name-string )

Parameters
● variable-name-string The variable name to be tested, as a string.

Returns
INT

See also
● “CREATE VARIABLE statement” on page 660
● “DECLARE statement” on page 673
● “IF statement” on page 769

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following IF statement creates a variable with a name start_time if one is not already created or
declared. The variable can then be used safely.
IF VAREXISTS( 'start_time' ) = 0 THEN
CREATE VARIABLE start_time TIMESTAMP;
END IF;
SET start_time = current timestamp;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 379


SQL functions

VARIANCE function [Aggregate]


An alias for VAR_SAMP.

See also
● “VAR_SAMP function [Aggregate]” on page 377

WATCOMSQL function [Miscellaneous]


Takes a Transact-SQL statement and rewrites it in the Watcom SQL dialect. This can be useful when
converting existing Adaptive Server Enterprise stored procedures into Watcom SQL syntax.

Syntax
WATCOMSQL( sql-statement-string )

Parameters
● sql-statement-string The SQL statement that the function rewrites into the Watcom SQL dialect.

Returns
LONG VARCHAR

See also
● “SQLDIALECT function [Miscellaneous]” on page 343
● “TRANSACTSQL function [Miscellaneous]” on page 365

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the string 'SELECT Surname as last_name FROM
Employees'.
SELECT WATCOMSQL( 'SELECT last_name = Surname FROM Employees' ) FROM dummy;

WEEKS function [Date and time]


The WEEKS function manipulates a TIMESTAMP, or returns the number of weeks between two
TIMESTAMP values. See the Remarks section below.

Syntax 1
WEEKS( timestamp-expression )

380 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Syntax 2
WEEKS( timestamp-expression, timestamp-expression )

Syntax 3
WEEKS( timestamp-expression, integer-expression )

Parameters
● timestamp-expression A date and time value of type TIMESTAMP.

● integer-expression The number of weeks to be added to timestamp-expression. If integer-


expression is negative, the appropriate number of weeks is subtracted from timestamp-expression. If
you supply an integer-expression, timestamp-expression must be explicitly cast as a DATE or
TIMESTAMP.

Returns
INTEGER with Syntax 1 or Syntax 2.

TIMESTAMP with Syntax 3.

Remarks
Given a single date (Syntax 1), the WEEKS function returns the number of weeks since 0000-02-29.

Given two dates (Syntax 2), the WEEKS function returns the number of weeks between them. The
WEEKS function is similar to the DATEDIFF function, however the method used to calculate the number
of weeks between two dates is not the same and can return a different result. The return value for WEEKS
is determined by dividing the number of days between the two dates by seven, and then rounding down.
However, DATEDIFF uses number of week boundaries in its computation. This can cause the values
returned from the two functions to be different. For example, if the first date is a Friday and the second
date is the following Monday, the WEEKS function returns a difference of 0, but the DATEDIFF function
returns a difference of 1. While neither method is better than the other, you should consider the difference
when choosing between WEEKS and DATEDIFF.

For more information about the DATEDIFF function, see “DATEDIFF function [Date and time]”
on page 189.

Given a date and an integer (Syntax 3), the WEEKS function adds the integer number of weeks to
timestamp-expression. With Syntax 3, you must explicitly cast timestamp-expression as a TIME, DATE,
or TIMESTAMP data type. If timestamp-expression is a TIME value, the current date is assumed. Instead
of Syntax 3, use the DATEADD function.

For more information about the DATEADD function, see “DATEADD function [Date and time]”
on page 188.

See also
For information about casting data types, see “CAST function [Data type conversion]” on page 159.

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 381


SQL functions

Example
The following statement returns the value 8, signifying that 2008-09-13 10:07:12 is eight weeks after
2008-07-13 06:07:12.
SELECT WEEKS( '2008-07-13 06:07:12', '2008-09-13 10:07:12' );

The following statement returns the value 104792, signifying that the date is 104792 weeks after
0000-02-29.
SELECT WEEKS( '2008-07-13 06:07:12' );

The following statement returns the TIMESTAMP value 2008-06-16 21:05:07.0, indicating the date and
time five weeks after 2008-05-12 21:05:07.
SELECT WEEKS( CAST( '2008-05-12 21:05:07' AS TIMESTAMP ), 5);

WRITE_CLIENT_FILE function [String]


Creates and writes to a file on the client computer.

Syntax
WRITE_CLIENT_FILE( filename, blob-expression [, 'A' ] )

Parameters
● filename The name of the file on the client computer. The name is resolved on the client computer
relative to the current working directory of the client application.

● blob-expression A binary string to be written to filename on the client computer.

● A By default, if the file already exists, it is overwritten. If you want the data to be appended to
existing data, specify 'A'. If the file does not already exist, and you specify 'A', the file is still created.

Returns
INT

Remarks
The database server converts filename from the database character set to the client character set. On the
client computer, filename is then converted to the operating system character set.

Since the data is a binary string, if you want the data to be in a particular character set, or compressed, or
encrypted, you must perform these operations on the data before sending it to the WRITE_CLIENT_FILE
function.

Reading of the file is performed by the client software library and the transfer of data is done using the
command sequence communication protocol.

Permissions
When writing to a file on a client computer:

382 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

● WRITECLIENTFILE authority is required.

● The client application must have write permissions on the computer being written to.

● The allow_write_client_file database option must be enabled.

● The write_client_file secured feature must be enabled.

See also
● “WRITECLIENTFILE authority” [SQL Anywhere Server - Database Administration]
● “allow_write_client_file option” [SQL Anywhere Server - Database Administration]
● “-sf dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “Access to data on client computers” [SQL Anywhere Server - SQL Usage]
● “WRITECLIENTFILE authority” [SQL Anywhere Server - Database Administration]
● “UNLOAD statement” on page 937
● “CSCONVERT function [String]” on page 183
● “DECOMPRESS function [String]” on page 203
● “DECRYPT function [String]” on page 204

Standards and compatibility


● SQL/2008 Vendor extension.

XMLAGG function [Aggregate]


Generates a forest of XML elements from a collection of XML values.

Syntax
XMLAGG( expression [ ORDER BY order-by-expression ] )

Parameters
● expression An XML value. The content is escaped unless the data type is XML. The order-by-
expression orders the elements returned by the function.

● order-by-expression An expression used to order the XML elements according to the value of
this expression.

When an ORDER BY clause contains constants, they are interpreted by the optimizer and then
replaced by an equivalent ORDER BY clause. For example, the optimizer interprets ORDER BY 'a' as
ORDER BY expression.

A query block containing more than one aggregate function with valid ORDER BY clauses can be
executed if the ORDER BY clauses can be logically combined into a single ORDER BY clause. For
example, the following clauses:
ORDER BY expression1, 'a', expression2

ORDER BY expression1, 'b', expression2, 'c', expression3

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 383


SQL functions

are subsumed by the clause:

ORDER BY expression1, expression2, expression3

Returns
XML

Remarks
Any values that are NULL are omitted from the result. If all inputs are NULL, or there are no rows, the
result is NULL. If you require a well-formed XML document, you must ensure that your query is written
so that the generated XML has a single root element.

Data in BINARY, LONG BINARY, IMAGE, and VARBINARY columns is automatically returned in
base64-encoded format when you execute a query that contains XMLAGG.

For an example of a query that uses the XMLAGG function with an ORDER BY clause, see “Use of the
XMLAGG function” [SQL Anywhere Server - SQL Usage].

See also
● “Use of the XMLAGG function” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 XMLAGG is part of optional SQL/2008 language feature X034. The optional ORDER
BY clause for the XMLAGG function comprises optional SQL/2008 language feature X035.

Example
The following statement generates an XML document that shows the orders placed by each customer.

SELECT XMLELEMENT( NAME "order",


XMLATTRIBUTES( ID AS order_id ),
( SELECT XMLAGG(
XMLELEMENT(
NAME "Products",
XMLATTRIBUTES( ProductID, Quantity AS
"quantity_shipped" ) ) )
FROM SalesOrderItems soi
WHERE soi.ID = so.ID
)
) AS products_ordered
FROM SalesOrders so
ORDER BY so.ID;

XMLCONCAT function [String]


Produces a forest of XML elements.

Syntax
XMLCONCAT( xml-value [, ... ])

384 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Parameters
● xml-value The XML values to be concatenated.

Returns
XML

Remarks
Generates a forest of XML elements. In an unparsed XML document, a forest refers to the multiple root
nodes within the document. NULL values are omitted from the result. If all the values are NULL, then
NULL is returned. The XMLCONCAT function does not check whether the argument has a prolog. If you
require a well-formed XML document, you must ensure that your query is written so that a single root
element is generated.

Element content is always escaped unless the data type is XML. Data in BINARY, LONG BINARY,
IMAGE, and VARBINARY columns is automatically returned in base64-encoded format when you
execute a query that contains a XMLCONCAT function.

See also
● “Use of the XMLCONCAT function” [SQL Anywhere Server - SQL Usage]
● “XMLELEMENT function [String]” on page 385
● “XMLFOREST function [String]” on page 388
● “String functions” on page 142

Standards and Compatibility


● SQL/2008 XMLCONCAT comprises part of the optional SQL/2008 language feature X020.

Example
The following query generates <CustomerID>, <cust_fname>, and <cust_lname> elements for each
customer.
SELECT XMLCONCAT( XMLELEMENT ( NAME CustomerID, ID ),
XMLELEMENT( NAME cust_fname, GivenName ),
XMLELEMENT( NAME cust_lname, Surname )
) AS "Customer Information"
FROM Customers
WHERE ID < 120;

XMLELEMENT function [String]


Produces an XML element within a query.

Syntax
XMLELEMENT( { NAME element-name-expression } | string-expression
[, XMLATTRIBUTES ( attribute-value-expression [ AS attribute-name ],... ) ]
[, element-content-expression,... ]
)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 385


SQL functions

Parameters
● element-name-expression An identifier. For each row, an XML element with the same name as
the identifier is generated.

● attribute-value-expression An attribute of the element. This optional argument allows you to


specify an attribute value for the generated element. This argument specifies the attribute name and
content. If the attribute-value-expression is a column name, then the attribute name defaults to the
column name. You can change the attribute name by specifying the attribute-name argument.

● element-content-expression The content of the element. This can be any string expression. You
can specify an unlimited number of element-content-expression arguments and they are concatenated
together. For example, the following SELECT statement returns the value <x>abcdef</x>:
SELECT XMLELEMENT( NAME x, 'abc', 'def' );

Returns
XML

Remarks
NULL element values and NULL attribute values are omitted from the result. The letter case for both
element and attribute names is taken from the query.

Element content is always escaped unless the data type is XML. Invalid element and attribute names are
also quoted. For example, consider the following statement:
SELECT XMLELEMENT('H1', f_get_page_heading() );

If the function f_get_page_heading is defined as RETURNS LONG VARCHAR or RETURNS


VARCHAR(1000), then the result is HTML encoded:
CREATE FUNCTION f_get_page_heading() RETURNS LONG VARCHAR
BEGIN
RETURN ('<B>My Heading</B>');
END;

The above SELECT statement returns the following:


<H1>&lt;B&gt;My Heading&lt;/B&gt;</H1>

If the function is declared as RETURNS XML, then the above SELECT statement returns the following:
<H1><B>My Heading</B></H1>

For more information about quoting and the XMLELEMENT function, see “Invalid names and SQL/
XML” [SQL Anywhere Server - SQL Usage].

XMLELEMENT functions can be nested to create a hierarchy. If you want to return different elements at
the same level of the document hierarchy, use the XMLFOREST function.

For more information, see “XMLFOREST function [String]” on page 388.

Data in BINARY, LONG BINARY, IMAGE, and VARBINARY columns is automatically returned in
base64-encoded format when you execute a query that contains the XMLELEMENT function.

386 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

See also
● “Use of the XMLELEMENT function” [SQL Anywhere Server - SQL Usage]
● “XMLCONCAT function [String]” on page 384
● “XMLFOREST function [String]” on page 388
● “String functions” on page 142

Standards and compatibility


● SQL/2008 XMLELEMENT constitutes part of optional SQL/2008 language feature X031.
Omitting the NAME keyword and using a string expression as the first argument is a vendor
extension. SQL Anywhere does not support the optional OPTION clause with the XMLELEMENT
function.

Example
The following example produces an <item_name> element for each product in the result set, where the
product name is the content of the element.
SELECT ID, XMLELEMENT( NAME item_name, p.Name )
FROM Products p
WHERE ID > 400;

The following example returns <A HREF="http://www.ianywhere.com/"


TARGET="_top">iAnywhere web site</A>:
SELECT XMLELEMENT(
'A',
XMLATTRIBUTES( 'http://www.ianywhere.com/'
AS "HREF", '_top' AS "TARGET"),
'iAnywhere web site'
);

The following example returns <table><tbody><tr align="center"


valign="top"><td>Cell 1 info</td><td>Cell 2 info</td></tr></tbody></
table>:
SELECT XMLELEMENT( name "table",
XMLELEMENT( name "tbody",
XMLELEMENT( name "tr",
XMLATTRIBUTES('center' AS "align", 'top' AS "valign"),
XMLELEMENT( name "td", 'Cell 1 info' ),
XMLELEMENT( name "td", 'Cell 2 info' )
)
)
);

The following example returns'<x>abcdef</x>','<custom_element>abcdef</


custom_element>':
CREATE VARIABLE @my_element_name VARCHAR(200);
SET @my_element_name = 'custom_element';
SELECT XMLELEMENT( NAME x, 'abc', 'def' ),
XMLELEMENT( @my_element_name,'abc', 'def' );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 387


SQL functions

XMLFOREST function [String]


Generates a forest of XML elements.

Syntax
XMLFOREST( element-content-expression [ AS element-name ],... )

Parameters
● element-content-expression A string. An element is generated for each element-content-
expression argument that is specified. The element-content-expression value becomes the content of
the element. For example, if you specify the EmployeeID column from the Employees table for this
argument, then an <EmployeeID> element containing an EmployeeID value is generated for each
value in the table.

Specify the element-name argument if you want to assign a name other than the element-content-
expression to the element, otherwise the element name defaults to the element-content-expression
name.

Returns
XML

Remarks
Produces a forest of XML elements. In the unparsed XML document, a forest refers to the multiple root
nodes within the document. When all the arguments to the XMLFOREST function are NULL, a NULL
value is returned. If only some values are NULL, the NULL values are omitted from the result. Element
content is always quoted unless the data type is XML. You cannot specify attributes using the
XMLFOREST function. Use the XMLELEMENT function if you want to specify attributes for generated
elements.

For more information about the XMLELEMENT function, see “XMLELEMENT function [String]”
on page 385.

Element names are escaped unless the data type is XML.

If you require a well-formed XML document, you must ensure that your query is written so that a single
root element is generated.

Data in BINARY, LONG BINARY, IMAGE, and VARBINARY columns is automatically returned in
base64-encoded format when you execute a query that contains XMLFOREST.

See also
● “Use of the XMLFOREST function” [SQL Anywhere Server - SQL Usage]
● “XMLELEMENT function [String]” on page 385
● “XMLCONCAT function [String]” on page 384
● “String functions” on page 142

388 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Standards and compatibility


● SQL/2008 XMLFOREST constitutes part of optional SQL/2008 language feature X032. SQL
Anywhere does not support the optional XMLNAMESPACES clause, or the OPTION clause, with the
XMLFOREST function.

Example
The following statement produces an XML element for the first and last name of each employee.

SELECT EmployeeID,
XMLFOREST( GivenName, Surname )
AS "Employee Name"
FROM Employees;

XMLGEN function [String]


Generates an XML value based on an XQuery constructor.

Syntax
XMLGEN( xquery-constructor, content-expression [ AS variable-name ],... )

Parameters
● xquery-constructor An XQuery constructor. The XQuery constructor is an item defined in the
XQuery language. It gives a syntax for constructing XML elements based on XQuery expressions.
The xquery-constructor argument must be a well-formed XML document with one or more variable
references. A variable reference is enclosed in curly braces and must be prefixed with a $ and have no
surrounding white space. For example:

SELECT XMLGEN( '<a>{$x}</a>', 1 AS x );

● content-expression A variable. You can specify multiple content-expression arguments. The


optional variable-name argument is used to name the variable. For example:

SELECT XMLGEN( '<emp EmployeeID="{$EmployeeID}"><StartDate>{$x}</


StartDate></emp>',
EmployeeID, StartDate
AS x )
FROM Employees;

Returns
XML

Remarks
Computed constructors as defined in the XQuery specification are not supported by the XMLGEN
function.

When you execute a query that contains an XMLGEN function, data in BINARY, LONG BINARY,
IMAGE, and VARBINARY columns is automatically returned in base64-encoded format.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 389


SQL functions

Element content is always escaped unless the data type is XML. Illegal XML element and attribute names
are also escaped.

For information about escaping and the XMLGEN function, see “Invalid names and SQL/XML” [SQL
Anywhere Server - SQL Usage].

See also
● “Use of the XMLGEN function” [SQL Anywhere Server - SQL Usage]
● “String functions” on page 142

Standards and compatibility


● SQL/2008 Vendor extension. XMLGEN provides similar functionality to the SQL/2008
XMLDOCUMENT function.

Example
The following example generates <emp>, <Surname>, <GivenName>, and <StartDate> elements for each
employee.
SELECT XMLGEN( '<emp EmployeeID="{$EmployeeID}">
<Surname>="{$Surname}"</Surname>
<GivenName>="{$GivenName}"</GivenName>
<StartDate>="{$StartDate}"</StartDate>
</emp>',
EmployeeID,
Surname,
GivenName,
StartDate
) AS employee_list
FROM Employees;

YEAR function [Date and time]


Returns the year component of the TIMESTAMP argument.

Syntax
YEAR( timestamp-expression )

Parameters
● timestamp-expression A TIMESTAMP value.

Returns
SMALLINT

Remarks
The value returned is the years component of the given TIMESTAMP value, returned as a SMALLINT.

Standards and compatibility


● SQL/2008 Vendor extension.

390 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

Example
The following example returns the value 2001.

SELECT YEAR( '2001-09-12' );

YEARS function [Date and time]


The YEARS function manipulates a TIMESTAMP, or returns the number of years between two
TIMESTAMP values. See the Remarks section below.

Syntax 1
YEARS( timestamp-expression )

Syntax 2
YEARS( timestamp-expression, timestamp-expression )

Syntax 2
YEARS( timestamp-expression, integer-expression )

Parameters
● timestamp-expression A date and time value of type TIMESTAMP.

● integer-expression The number of years (as a SMALLINT value) to be added to timestamp-


expression. If integer-expression is negative, the appropriate number of years is subtracted from
timestamp-expression. If you supply an integer-expression, the timestamp-expression must be
explicitly cast as a DATE, TIME, or TIMESTAMP value. If timestamp-expression is a TIME, the
current year is assumed.

For information about casting data types, see “CAST function [Data type conversion]” on page 159.

Returns
SMALLINT with Syntax 1 or Syntax 2.

TIMESTAMP with Syntax 3.

Remarks
The value of YEARS is computed by counting the number of first days of the year between the two dates.

See also
● “DATEDIFF function [Date and time]” on page 189
● “DATEADD function [Date and time]” on page 188

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 391


SQL functions

Example
The following statements both return -4.

SELECT YEARS( '1998-07-13 06:07:12',


'1994-03-13 08:07:13' );

SELECT DATEDIFF( year,


'1998-07-13 06:07:12',
'1994-03-13 08:07:13' );

The following statements return 1998.

SELECT YEARS( '1998-07-13 06:07:12' )


SELECT DATEPART( year, '1998-07-13 06:07:12' );

The following statements return the given date advanced 300 years.

SELECT YEARS( CAST( '1998-07-13 06:07:12' AS TIMESTAMP ), 300 )

SELECT DATEADD( year, 300, '1998-07-13 06:07:12' );

YMD function [Date and time]


Returns a date value corresponding to the given year, month, and day of the month. Arguments are
SMALLINT values from -32768 to 32767.

Syntax
YMD( smallint-expression1, smallint-expression2, smallint-expression3 )

Parameters
● smallint-expression1 The year.

● smallint-expression2 The number of the month. The year is adjusted if the month is outside the
range 1-12.

● smallint-expression3 The day number. The day can be any integer; the date is adjusted
accordingly.

Returns
DATE

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement returns the value 1998-06-12.

SELECT YMD( 1998, 06, 12 );

392 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Functions

If the values are outside their normal range, the date is adjusted accordingly. For example, the following
statement returns the DATE value 2000-03-01.
SELECT YMD( 1999, 15, 1 );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 393


394 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1
SQL statements
This section describes the conventions used in the SQL statement documentation.

Common elements in SQL syntax


This section lists language elements that are found in the syntax of many SQL statements.

● column-name An identifier that represents the name of a column.

● condition An expression that evaluates to TRUE, FALSE, or UNKNOWN.

● connection-name A string representing the name of an active connection.

● data-type A storage data type.

● expression An expression. A common example of an expression in syntax is a column name.

● filename A string containing a file name.

● hostvar A C language variable, declared as a host variable preceded by a colon.

● materialized-view-name An identifier that represents the name of a materialized view.

● 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.

● query-block A query block is a simple query expression, or a query expression with an ORDER
BY clause.

● query-expression A query expression can be a SELECT, UNION, INTERSECT, or EXCEPT


block (that is, a statement that does not contain an ORDER BY, WITH, FOR, FOR XML, or OPTION
clause), or any combination of such blocks.

● role-name An identifier representing the role name of a foreign key. In conceptual database
modeling, a verb or phrase that describes a relationship from one point of view. You can describe each
relationship with two roles. Examples of roles are "contains" and "is a member of."

● savepoint-name An identifier that represents the name of a savepoint.

● search-condition A condition that evaluates to TRUE, FALSE, or UNKNOWN.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 395


SQL statements

● special-value A special value.

● statement-label An identifier that represents the label of a loop or compound statement.

● statement-list A list of SQL statements, each ending with a semicolon.

● string-expression An expression that resolves to a string.

● table-list A list of table names, which may include correlation names.

● 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.

● window-name An identifier that represents a window name. Used in syntax related to window
definition (for example, the WINDOW clause, and window functions such as RANK).

See also
● “Savepoints within transactions” [SQL Anywhere Server - SQL Usage]
● “Variables” on page 72
● “Truth value search conditions” on page 54
● “Permissions acquired through ownership of an object” [SQL Anywhere Server - Database
Administration]
● “Materialized views” [SQL Anywhere Server - SQL Usage]
● “Host variables in embedded SQL” [SQL Anywhere Server - Programming]
● “Expressions” on page 12
● “SQL data types” on page 81
● “Strings” on page 5
● “SQL Anywhere database connections” [SQL Anywhere Server - Database Administration]
● “Control statements” [SQL Anywhere Server - SQL Usage]
● “Search conditions” on page 32
● “Special values” on page 58
● “FROM clause” on page 738
● “Key joins” [SQL Anywhere Server - SQL Usage]
● “Identifiers” on page 4

Syntax conventions
The following conventions are used in the SQL syntax descriptions:

● Keywords All SQL keywords appear in uppercase, like the SQL statement ALTER TABLE in the
following example:

ALTER TABLE [ owner.]table-name

396 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Syntax conventions

● Placeholders Items that must be replaced with appropriate identifiers or expressions appear in
italics, like the words owner and table-name in the following example:

ALTER TABLE [ owner.]table-name

● Clause order If the order of optional clauses is significant in SQL statement syntax, the clauses are
listed in the main body of the syntax in the order in which they should be listed, similar to the
following:

CREATE SYNCHRONIZATION SUBSCRIPTION [ subscription-name ]


TO publication-name
[ FOR ml-username, ... ]
...

In the case where the order of optional clauses is not significant in SQL statement syntax, the clauses
are listed separately like a list of options, similar to the following:

CREATE [ OR REPLACE ] SPATIAL REFERENCE SYSTEM


srs-name
[ srs-attribute [ srs-attribute ... ]

srs-attribute :
IDENTIFIED BY srs-id
| DEFINITION { definition-string | NULL }
...

● Optional portions Optional portions of a statement are enclosed by square brackets. For example:

RELEASE SAVEPOINT [ savepoint-name ]

These square brackets indicate that the savepoint-name is optional. The square brackets should not be
typed.

You might also see square brackets around a portions of keywords. For example, the following syntax
indicates that you can use either COMMIT TRAN or COMMIT TRANSACTION:

COMMIT TRAN[SACTION] ...

Likewise, the following syntax indicates that you can use either COMMIT or COMMIT WORK:

COMMIT [ WORK ]

● Repeating items An item that can be repeated is followed by the appropriate list separator and an
ellipsis (three dots), like column-constraint in the following example:

ADD column-definition [ column-constraint, ... ]

In this case, you can specify no column constraint, one, or more. If more than one is specified, they
must be separated by commas.

● 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 ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 397


SQL statements

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 } ]

In this case, if the QUOTES option is chosen, one of ON or OFF must be provided. The brackets and
braces should not be typed.

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.

● [T-SQL] The statement is implemented for compatibility with Adaptive Server Enterprise.
Sometimes 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/2008 standard is recommended unless
Transact-SQL compatibility is an issue.

● [external procedures] The statement is for use in calling external functions and procedures.

● [MobiLink] The statement is for use only in MobiLink clients.

● [SQL Remote] The statement can be used only in SQL Remote.

● [web services] The statement is for use in web services clients.

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 in both embedded SQL and stored procedures.

SQL statements
The following sections define the syntax information for all supported SQL statements.

ALLOCATE DESCRIPTOR statement [ESQL]


Allocates space for a SQL descriptor area (SQLDA).

398 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
ALLOCATE DESCRIPTOR descriptor-name
[ WITH MAX { integer | hostvar } ]

descriptor-name : identifier

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.

Remarks
Allocates space for a descriptor area (SQLDA). You must declare the following in your C code before
using this statement:
struct sqlda * descriptor_name

Permissions
None.

Side effects
None.

See also
● “DEALLOCATE DESCRIPTOR statement [ESQL]” on page 665
● “The SQL descriptor area (SQLDA)” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 ALLOCATE DESCRIPTOR is part of optional SQL language feature B031 "Basic
dynamic SQL" of the SQL/2008 standard.

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;
if( !db_init( &sqlca ) ) {
return 1;
}
db_string_connect( &sqlca,

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 399


SQL statements

"UID=dba;PWD=sql;DBF=d:\\DB Files\\sample.db");
EXEC SQL ALLOCATE DESCRIPTOR sqlda1 WITH MAX 25;
EXEC SQL PREPARE :stmt FROM
'SELECT * FROM Employees';
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;
}

ALTER DATABASE statement


Upgrades the database, turns jConnect support for a database on or off, calibrates the database, changes
the transaction log and transaction log mirror file names, or forces a mirror server to take ownership of a
database.

Syntax 1 - Upgrading components or restoring objects


ALTER DATABASE UPGRADE
[ PROCEDURE ON ]
[ JCONNECT { ON | OFF } ]

Syntax 2 - Performing calibration


ALTER DATABASE {
CALIBRATE [ SERVER ]
| CALIBRATE DBSPACE dbspace-name
| CALIBRATE DBSPACE TEMPORARY
| CALIBRATE GROUP READ
| CALIBRATE PARALLEL READ
| RESTORE DEFAULT CALIBRATION
}

400 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax 3 - Changing transaction log and transaction log mirror names


ALTER DATABASE dbfile
ALTER [ TRANSACTION ] LOG {
{ ON [ log-name ] [ MIRROR mirror-name ] | OFF }
[ KEY key ]

Syntax 4 - Changing ownership of a database


ALTER DATABASE
{ dbname FORCE START
| SET PARTNER FAILOVER }

Syntax 5 - Changing checksum settings


ALTER DATABASE dbfile
CHECKSUM OFF

Parameters
PROCEDURE clause Drop and re-create all dbo- and sys-owned procedures in the database.

JCONNECT clause To allow the jConnect JDBC driver access to system catalog information, specify
JCONNECT ON. This clause installs the system objects that provide jConnect support. Specify
JCONNECT OFF if you want to exclude the jConnect system objects. You can still use JDBC, as long as
you do not access system information. JCONNECT is ON by default.

CALIBRATE [ SERVER ] clause Calibrate all dbspaces except for the temporary dbspace. This
clause also performs the work done by CALIBRATE PARALLEL READ.

CALIBRATE DBSPACE clause Calibrate the specified dbspace.

CALIBRATE DBSPACE TEMPORARY clause Calibrate the temporary dbspace.

CALIBRATE GROUP READ clause Perform group read calibration on the temporary dbspace.
Writes large work tables to the temporary dbspace and uses different group read sizes to time the reading
of the files. If adding space to the temporary table exceeds the limit for the connection, or if the cache is
not large enough to allow calibration with the largest memory size, calibration fails and an error message
is returned.

CALIBRATE PARALLEL READ clause Calibrate the parallel I/O capabilities of devices for all
dbspace files. The CALIBRATE [ SERVER ] clause also performs this calibration.

RESTORE DEFAULT CALIBRATION clause Restore the Disk Transfer Time (DTT) model to the
built-in default values that are based on typical hardware and configuration settings.

ALTER [TRANSACTION] LOG clause Change the file name of the transaction log or transaction log
mirror file. If MIRROR mirror-name is not specified, the clause sets a file name 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.

If MIRROR mirror-name is specified, the clause sets a file name 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.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 401


SQL statements

You can also use this clause to turn off the transaction or transaction log mirror. For example, ALTER
DATABASE ALTER LOG OFF.

KEY clause Specify the encryption key to use for the transaction log or transaction log mirror. When
using the ALTER [ TRANSACTION ] LOG clause on a strongly encrypted database, you must specify
the encryption key.

dbname FORCE START clause Force a database server that is currently acting as the mirror server
to take ownership of the database. This clause can be executed from within a procedure or event, and must
be executed while connected to the utility database on the mirror server.

SET PARTNER FAILOVER clause Initiate a database mirroring failover from the primary server to
the mirror server. This statement must be executed while connected to the database on the primary server,
and can be executed from within a procedure or event. When executed, any existing connections to the
database are closed, including the connection that executed the statement. If the statement is contained in
a procedure or event, other statements that follow it may not be executed.

CHECKSUM clause Disables global checksums for the database. By default, new databases have
global checksums enabled, while version 11 and earlier databases do not have global checksums enabled.

Regardless of the setting of this clause, the database server always enables write checksums for databases
running on storage devices such as removable drives, and databases running on Windows Mobile to help
provide early detection if the database file becomes corrupt. It also calculates checksums for critical pages
during validation activities.

For databases that do not have global checksums enabled, you can enable write checksums by using the -
wc options.

Remarks
● Syntax 1 You can use the ALTER DATABASE UPGRADE statement as an alternative to the
Upgrade utility to upgrade or update a database. This applies to maintenance releases as well. After
executing this statement, you should restart the database. In general, changes in databases between
minor versions are limited to additional database options and minor system table and procedure
changes. The ALTER DATABASE UPGRADE statement upgrades the system tables to the current
version and adds any new database options. If necessary, it also drops and recreates all system
procedures. You can force a rebuild of the system procedures by specifying the PROCEDURE ON
clause.

An error message is returned if you execute an ALTER DATABASE UPGRADE statement on a


database that is currently being mirrored.

You can also use the ALTER DATABASE UPGRADE statement to restore settings and system
objects to their original installed state.

Features that require a physical reorganization of the database file are not made available by executing
an ALTER DATABASE UPGRADE statement. Such features include index enhancements and
changes in data storage. To obtain the benefits of these enhancements, you must unload and reload
your database.

402 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Caution
It is strongly recommended that you back up your database files before attempting to upgrade your
database. If the upgrade process fails, then the partially upgraded database is marked as invalid and is
no longer usable. Attempting to start a database after a failed upgrade results in an error indicating that
the database file is not valid.

To use the jConnect JDBC driver to access system catalog information, specify JCONNECT ON (the
default). If you want to exclude the jConnect system objects, specify JCONNECT OFF. Setting
JCONNECT OFF does not remove jConnect support from a database. You can still use JDBC, as long
as you do not access system catalog information. If you subsequently download a more recent version
of jConnect, you can upgrade the version in the database by (re)executing the ALTER DATABASE
UPGRADE JCONNECT ON statement.

● Syntax 2 Use Syntax 2 to perform recalibration of the I/O cost model used by the optimizer. This
operation updates the Disk Transfer Time (DTT) model, which is a mathematical model of the disk
I/O used by the cost model. When you recalibrate the I/O cost model, the database server is
unavailable for other use. In addition, it is essential that all other activities on the computer are idle.
Recalibrating the database server is an expensive operation and may take some time to complete. It is
recommended that you leave the default in place.

When using the CALIBRATE PARALLEL READ clause, parallel calibration is not performed on
dbspace files with fewer than 10000 pages. Even though the database server automatically suspends
all of its activity during calibration operations, parallel calibration should be done when there are no
processes consuming significant resources on the same computer. After calibration, you can retrieve
the maximum estimated number of parallel I/O operations allowed on a dbspace file using the
IOParallelism extended database property.

To eliminate repetitive, time-consuming recalibration activities when there is a large number of


similar hardware installations, you can re-use a calibration by unloading it and then applying it
(loading it) into another database using the sa_unload_cost_model and sa_load_cost_model system
procedures, respectively.

● Syntax 3 You can use the ALTER DATABASE statement to change the transaction log and
transaction log mirror names associated with a database file. The database must not be running to
make these changes. These changes are the same as those made by the Transaction Log (dblog) utility.
You can execute this statement while connected to the utility database or another database, depending
on the setting of the -gu option. If you are changing the transaction log or transaction log mirror of an
encrypted database, you must specify a key. You cannot stop using the transaction log if the database
is using auditing. Once you turn off auditing, you can stop using the transaction log. This syntax is not
supported in procedures, triggers, events, or batches.

You can use the BACKUP DATABASE statement to rename the transaction log for a running
database. For example:
BACKUP DATABASE DIRECTORY 'directory-name'
TRANSACTION LOG ONLY
TRANSACTION LOG RENAME;

● Syntax 4 ALTER DATABASE...FORCE START must be executed from the mirror server, not the
primary server. Attempting to execute an ALTER DATABASE...FORCE START statement for a

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 403


SQL statements

database that is not being mirrored or is currently active and owned by this server results in an error.
Also, if the primary server is still connected to the mirror server, an error is given.

● Syntax 5 This clause can only be used to disable checksums for a database.

Permissions
For Syntax 1 and 2, you must have DBA authority, and must be the only connection to the database.
ALTER DATABASE UPGRADE is not supported on Windows Mobile.

For Syntax 3, you must have file permissions on the directories where the transaction log is located, and
the database must not be running.

For Syntax 4, you must have the permissions specified by the -gk server option.

For Syntax 5, you must have DBA authority.

Side effects
Automatic commit

See also
● “CREATE DATABASE statement” on page 508
● “CREATE STATISTICS statement” on page 625
● “BACKUP statement” on page 477
● “Upgrade utility (dbupgrad)” [SQL Anywhere Server - Database Administration]
● “Transaction Log utility (dblog)” [SQL Anywhere Server - Database Administration]
● “DB_EXTENDED_PROPERTY function [System]” on page 197
● “-gk dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “-gu dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “-wc dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “-wc dbeng12/dbsrv12 database option” [SQL Anywhere Server - Database Administration]
● “sa_validate system procedure” on page 1157
● “sa_unload_cost_model system procedure” on page 1154
● “sa_load_cost_model system procedure” on page 1070
● “Forcing a database server to become the primary server” [SQL Anywhere Server - Database
Administration]
● “Failover on the primary server” [SQL Anywhere Server - Database Administration]
● “Database mirroring” [SQL Anywhere Server - Database Administration]
● “Database rebuilds” [SQL Anywhere Server - SQL Usage]
● “Upgrading databases in a database mirroring system” [SQL Anywhere 12 - Changes and Upgrading]
● “DB_EXTENDED_PROPERTY function [System]” on page 197
● “Installing jConnect system objects into a database” [SQL Anywhere Server - Programming]
● “Corruption detection using checksums” [SQL Anywhere Server - Database Administration]
● “jConnect on Windows Mobile” [SQL Anywhere Server - Database Administration]
● “Validation utility (dbvalid)” [SQL Anywhere Server - Database Administration]
● “VALIDATE statement” on page 955

Standards and compatibility


● SQL/2008 Vendor extension.

404 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

● Transact-SQL The ALTER DATABASE statement is supported by Adaptive Server Enterprise.


However, the statement's clauses supported by Adaptive Server Enterprise are disjoint from those
clauses supported by SQL Anywhere.

Example
The following example disables jConnect support:

ALTER DATABASE UPGRADE JCONNECT OFF;

The following example sets the transaction log file name associated with demo.db to mynewdemo.log:

ALTER DATABASE 'demo.db'


ALTER LOG ON 'mynewdemo.log';

ALTER DBSPACE statement


Pre-allocates space for a dbspace or for the transaction log, or updates the catalog when a dbspace file is
renamed or moved.

Syntax
ALTER DBSPACE { dbspace-name | TRANSLOG | TEMPORARY }
{ ADD number [ add-unit ]
| RENAME filename }

add-unit :
PAGES
| KB
| MB
| GB
| TB

Parameters
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.

The syntax ALTER DBSPACE dbspace-name TRANSLOG RENAME filename is not supported.

TEMPORARY clause You supply the special dbspace name TEMPORARY to add space to temporary
dbspaces. When space is added to a temporary dbspace, the additional space materializes in the
corresponding temporary file immediately. Pre-allocating space to the temporary dbspace of a database
can improve performance during execution complex queries that use large work tables.

ADD clause An ALTER DBSPACE statement with the ADD clause preallocates disk space for a
dbspace. It extends the corresponding database file by the specified size, in units of pages, kilobytes (KB),
megabytes (MB), gigabytes (GB), or terabytes (TB). If you do not specify a unit, PAGES is the default.
The page size of a database is fixed when the database is created.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 405


SQL statements

If space is not preallocated, database files are extended by about 256 KB at a time for page sizes of 2 KB,
4 KB, and 8 KB, and by about 32 pages for other page sizes, when the space is needed. Pre-allocating
space can improve performance for loading large amounts of data and also serves to keep the database
files more contiguous within the file system.

You can use this clause to add space to any of the predefined dbspaces (system, temporary, temp,
translog, and translogmirror).

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 SQL Anywhere finds
the new file when the database is started. The filename parameter can be a string literal, or a variable.

Cloud note: For tenant databases in a cloud, when you specify the location of a dbspace, you can
specify only a file name. You cannot specify a directory path.

The name change takes effect as follows:

○ If the dbspace was already open before the statement was executed (that is, you have not yet renamed
the actual file), it remains accessible; however, the name stored in the catalog is updated. After the
database is stopped, you must rename the file to match what you provided using the RENAME clause,
otherwise the file name won't match the dbspace name in the catalog and the database server is unable
to open the dbspace the next time the database is started.

○ If the dbspace was not open when the statement was executed, the database server attempts to open it
after updating the catalog. If the dbspace can be opened, it becomes accessible. No error is returned if
the dbspace cannot be opened.
To determine if a dbspace is open, execute the statement below. If the result is NULL, the dbspace is
not open.
SELECT DB_EXTENDED_PROPERTY('FileSize','dbspace-name');

Using ALTER DBSPACE with RENAME on the main dbspace, system, has no effect. The RENAME
clause is not supported for changing the name of the transaction log file. You can use the BACKUP
DATABASE statement to rename the transaction log for a running database. For example:
BACKUP DATABASE DIRECTORY 'directory-name'
TRANSACTION LOG ONLY
TRANSACTION LOG RENAME;

Remarks
Each database is held in one or more files. A dbspace is an additional file with a logical name associated
with each database file, and used to hold more data than can be held in the main database file alone.
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 SYSDBSPACE system view. 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 SQL Anywhere
where to find the main database file. The main database file holds the system tables. SQL Anywhere
looks in these system tables to find the location of the other dbspaces, and then opens each of the other
dbspaces. You can specify which dbspace new tables are created in by setting the default_dbspace option.

406 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Permissions
DBA authority and be the only connection to the database.

Side effects
Automatic commit.

See also
● “CREATE DBSPACE statement” on page 515
● “BACKUP statement” on page 477
● “SYSDBSPACE system view” on page 1202
● “default_dbspace option” [SQL Anywhere Server - Database Administration]
● “Predefined dbspaces” [SQL Anywhere Server - Database Administration]
● “Database file types” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example increases the size of the system dbspace by 200 pages:
ALTER DBSPACE system
ADD 200;

The following example increases the size of the system dbspace by 400 MB:
ALTER DBSPACE system
ADD 400 MB;

The following example changes the file name associated with the system_2 dbspace:
ALTER DBSPACE system_2
RENAME 'e:\db\dbspace2.db';

ALTER DOMAIN statement


Renames a user-defined domain or data type.

Syntax
ALTER { DOMAIN | DATATYPE } user-type
RENAME new-name

Remarks
When you execute this statement, the name of the user-defined domain or data type is updated in the
ISYSUSERTYPE system table.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 407


SQL statements

Note
Any procedures, triggers, views, or events that refer to the user-defined domain or data type must be
recreated, or else they continue to refer to the old name.

Permissions
Must have DBA authority or be the database user who created the domain.

Side effects
Automatic commit.

See also
● “SYSUSERTYPE system view” on page 1256
● “CREATE DOMAIN statement” on page 519
● “Domains” on page 120
● “Domains” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension. The ALTER DOMAIN statement is optional SQL feature F711 of the
SQL/2008 standard. However, in the standard, ALTER DOMAIN can specify modified DEFAULT or
CHECK constraint clauses for an existing domain. Neither of these operations are supported in SQL
Anywhere. Feature F711 does not support the renaming of a domain.

Example
The following example renames the Address domain to MailingAddress:
ALTER DOMAIN Address RENAME MailingAddress;

ALTER EVENT statement


Changes the definition of an event or its associated handler for automating predefined actions, or alters
the definition of scheduled actions. You can also use this statement to hide the definition of an event
handler.

Syntax 1 - Altering an event


ALTER EVENT [ owner.]event-name
[ AT { CONSOLIDATED | REMOTE | ALL } ]
[ { DELETE TYPE
| TYPE event-type
| WHERE { trigger-condition | NULL }
| { ADD | ALTER | DELETE } SCHEDULE schedule-spec } ]
[ ENABLE | DISABLE ]
[ [ ALTER ] HANDLER compound-statement | DELETE HANDLER ]

event-type :
BackupEnd
| Connect
| ConnectFailed

408 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

| DatabaseStart
| DBDiskSpace
| Deadlock
| "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

Syntax 2 - Hiding the definition of an event handler


ALTER EVENT event-name SET HIDDEN

Parameters
AT clause Use this clause to change the specification regarding the databases at which the event is
handled.

DELETE TYPE clause Use this clause to remove an association of the event with an event type.

ADD | ALTER | DELETE SCHEDULE clause Use this clause to change the definition of a schedule.
Only one schedule can be altered in any one ALTER EVENT statement.

WHERE clause Use this clause to change the trigger condition under which an event is fired. The
WHERE NULL option deletes a condition.

START TIME clause Use this clause to specify the start time and, optionally, the end time, for the
event. The start-time and end-time parameters are strings (for example, '12:34:56'). Variables and
expressions are not allowed (for example, NOW()).

START DATE clause Use this clause to specify the start date for the event. The start-date parameter
is a string. Variables and expressions are not allowed (for example, TODAY()).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 409


SQL statements

SET HIDDEN clause Use this clause to hide the definition of an event handler. Specifying the SET
HIDDEN clause results in the permanent obfuscation of the event handler definition stored in the action
column of the ISYSEVENT system table.

Remarks
This statement allows you to alter an event definition created with CREATE EVENT. Possible uses
include the following:

● hiding the definition of an event handler

● defining and testing an event handler without a trigger condition or schedule during a development
phase, and then adding the conditions for execution using ALTER EVENT once the event handler is
completed

If you need to alter an event, you can disable it while it is running by executing an ALTER
EVENT...DISABLE statement. To disable an event in Sybase Central, right-click the event and clear the
Enabled option. Disabling the event does not interrupt current event handler execution; the event handler
continues to execute until completion. When the event handler completes, it is not restarted until you re-
enable it. You can alter and then re-enable the definition. To determine what events are running, execute
the following statement:
SELECT *
FROM dbo.sa_conn_info()
WHERE CONNECTION_PROPERTY( 'EventName',Number ) = 'event-name';

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “System events” [SQL Anywhere Server - Database Administration]
● “SYSEVENT system view” on page 1204
● “BEGIN statement” on page 484
● “CREATE EVENT statement” on page 526

Standards and compatibility


● SQL/2008 Vendor extension.

ALTER EXTERNAL ENVIRONMENT statement


Specifies the location of an external environment such as Java, PHP, or Perl.

Syntax
ALTER EXTERNAL ENVIRONMENT environment-name
LOCATION location-string

410 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

environment-name :
JAVA
| PERL
| PHP
| CLR
| C_ESQL32
| C_ESQL64
| C_ODBC32
| C_ODBC64
| DBMLSYNC

Parameters
environment-name Use environment-name to specify the external environment you are altering.

LOCATION clause Use the LOCATION clause to specify the location on the database server
computer where the executable/binary for the external environment can be found. It includes the
executable/binary name. This path can either be fully qualified or relative. If the path is relative, then the
executable/binary must be in a location where the server can find it.

Remarks
The location of dbmlsync utility can be set using this statement. If, during synchronization, the dbmlsync
executable image cannot be located using the database server's PATH environment variable, then use this
statement to record the location of the executable.

Permissions
DBA authority.

Side effects
None

See also
● “SQL Anywhere external environment support” [SQL Anywhere Server - Programming]
● “START EXTERNAL ENVIRONMENT statement” on page 911
● “STOP EXTERNAL ENVIRONMENT statement” on page 919
● “INSTALL EXTERNAL OBJECT statement” on page 785
● “REMOVE EXTERNAL OBJECT statement” on page 851
● “SYSEXTERNENV system view” on page 1206
● “SYSEXTERNENVOBJECT system view” on page 1206

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example specifies the location of the Perl executable for use when using Perl as an external
environment.
ALTER EXTERNAL ENVIRONMENT PERL
LOCATION 'c:\\Perl64\\bin\\perl.exe';

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 411


SQL statements

ALTER FUNCTION statement


Modifies a function.

Syntax 1 - Change the definition of a function


ALTER FUNCTION [ owner.]function-name function-definition

function-definition : CREATE FUNCTION syntax

Syntax 2 - Obfuscate a function definition


ALTER FUNCTION [ owner.]function-name
SET HIDDEN

Syntax 3 - Recompile a function


ALTER FUNCTION [ owner.]function-name
RECOMPILE

Remarks
You must include the entire new function in the ALTER FUNCTION statement.

● Syntax 1 The ALTER FUNCTION statement is identical in syntax to the CREATE FUNCTION
statement except for the first word.

With ALTER FUNCTION, existing permissions on the function remain unmodified. Conversely, if
you execute DROP FUNCTION followed by CREATE FUNCTION, execute permissions are
reassigned.

● Syntax 2 Use SET HIDDEN to obfuscate the definition of the associated function and cause it to
become unreadable. The function can be unloaded and reloaded into other databases.

If SET HIDDEN is used, debugging using the debugger does not show the function definition, nor is it
available through procedure profiling.

Note
This setting is irreversible. It is strongly recommended that you retain the original function definition
outside of the database.

● Syntax 3 Use the RECOMPILE syntax to recompile a user-defined SQL function. When you
recompile a function, the definition stored in the catalog is re-parsed and the syntax is verified. The
preserved source for a function is not changed by recompiling. When you recompile a function, the
definitions obfuscated by the SET HIDDEN clause remain obfuscated and unreadable.

Permissions
Must be the owner of the function or have DBA authority.

Side effects
Automatic commit.

412 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “CREATE FUNCTION statement” on page 548
● “CREATE FUNCTION statement [External call]” on page 535
● “CREATE FUNCTION statement [Web service]” on page 541
● “ALTER PROCEDURE statement” on page 423
● “DROP FUNCTION statement” on page 695
● “Hiding the contents of procedures, functions, triggers, events, and views” [SQL Anywhere Server -
SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension. ALTER FUNCTION is optional SQL language feature F381 of the
SQL/2008 standard. However, in the SQL standard, ALTER FUNCTION cannot be used to re-define
a PSM function definition. SQL/2008 does not include support for SET HIDDEN or RECOMPILE.

Example
In this example, MyFunction is created and altered. The SET HIDDEN clause obfuscates the function
definition and makes it unreadable.
CREATE FUNCTION MyFunction(
firstname CHAR(30),
lastname CHAR(30) )
RETURNS CHAR(61)
BEGIN
DECLARE name CHAR(61);
SET name = firstname || ' ' || lastname;
RETURN (name);
ALTER FUNCTION MyFunction SET HIDDEN;
END;

ALTER INDEX statement


Renames an index, primary key, or foreign key, or changes the clustered nature of an index.

Syntax
ALTER { INDEX index-name
| [ INDEX ] FOREIGN KEY role-name
| [ INDEX ] PRIMARY KEY }
ON [ owner.]object-name { REBUILD | rename-clause | cluster-clause } }

object-name : table-name | materialized-view-name

rename-clause : RENAME { AS | TO } new-index-name

cluster-clause : CLUSTERED | NONCLUSTERED

Parameters
rename-clause Specify the new name for the index, primary key, or foreign key.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 413


SQL statements

When you rename the underlying index for a foreign or primary key, the corresponding RI constraint
name for the index is not changed. However, the foreign key role name, if applicable, is the same as the
index name and is changed. Use the ALTER TABLE statement to rename the RI constraint name, if
necessary.

cluster-clause Specify whether the index should be changed to CLUSTERED or NONCLUSTERED.


Only one index on a table can be clustered.

REBUILD clause Use this clause to rebuild an index, instead of dropping and recreating it.

Remarks
The ALTER INDEX statement carries out two tasks:

● It can be used to rename an index, primary key, or foreign key.

● It can be used to change an index type from nonclustered to clustered, or vice versa.
The ALTER INDEX statement can be used to change the clustering specification of the index, but does
not reorganize the data. As well, only one index per table or materialized view can be clustered.

ALTER INDEX cannot be used to change an index on a local temporary table. An attempt to do so results
in an Index not found error.

This statement cannot be executed when there are cursors opened with the WITH HOLD clause that use
either statement or transaction snapshots.

Permissions
Must own the table, or have REFERENCES permissions on the table or materialized view, or have DBA
authority.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL. Closes all cursors for
the current connection. If ALTER INDEX REBUILD is specified, a checkpoint is performed.

See also
● “CREATE INDEX statement” on page 553
● “ALTER TABLE statement” on page 451
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement renames the index IX_product_name on the Products table to ixProductName:
ALTER INDEX IX_product_name ON Products
RENAME TO ixProductName;

The following statement changes IX_product_name to be a clustered index:

414 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

ALTER INDEX IX_product_name ON Products


CLUSTERED;

ALTER LOGIN POLICY statement


Alters an existing login policy.

Syntax
ALTER LOGIN POLICY policy-name policy-options

policy options :
policy-option [ policy-option ... ]

policy-option :
policy-option-name = policy-option-value

policy-option-value :
{ UNLIMITED
| DEFAULT
| legal-option-value }

Parameters
policy-name The name of the login policy. Specify root to modify the root login policy.

policy-option-name The name of the policy option.

policy-option-value The value assigned to the login policy option. If you specify UNLIMITED, no
limits are used. If you specify DEFAULT, the default limits are used.

Remarks
When a login policy is altered, changes are immediately applied to all users.

If you do not specify a policy option, values for the login policy are taken from the root login policy.

All new databases include a root login policy. You can modify the root login policy values, but you
cannot delete the policy. An overview of the default options for the root login policy is provided in the
table below.

Policy-option-name Description Default Applies to


value

password_life_time The maximum number of days before a Unlimi- All users, includ-
password must be changed. ted ing those with
DBA authority.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 415


SQL statements

Policy-option-name Description Default Applies to


value

password_grace_time The number of days before the password 0 All users, includ-
expires during which login is allowed, but ing those with
the default post_login procedure issues DBA authority.
warnings.

password_expi- If the value for this option is ON, the us- OFF All users, includ-
ry_on_next_login er's password expires after the next login. ing those with
DBA authority.

locked If the value for this option is ON, users OFF Users without
are not allowed to establish new connec- DBA authority.
tions. Users with DBA authority cannot
be locked. The reason_locked column of
the sa_get_user_status system procedure
returns a string generated by the database
server that shows why a user is locked.

max_connections The maximum number of concurrent con- Unlimi- Users without


nections allowed for a user. ted DBA authority.

max_failed_login_at- The maximum number of failed attempts Unlimi- All users, includ-
tempts since the last successful attempt to log in ted ing those with
before the user is locked. DBA authority.

DBA user ac-


counts are un-
locked after one
minute has passed
since the most re-
cent failed login
attempt.

max_days_since_login The maximum number of days that can Unlimi- Users without
elapse between two successive logins by ted DBA authority.
the same user.

max_non_dba_connec- The maximum number of concurrent con- Unlimi- Users without


tions nections that users without DBA authority ted DBA authority and
can make. This option is only supported only to the root
in the root login policy. login policy.

Permissions
DBA authority

416 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
None.

See also
● “Altering a login policy” [SQL Anywhere Server - Database Administration]
● “ALTER USER statement” on page 470
● “COMMENT statement” on page 499
● “CREATE LOGIN POLICY statement” on page 558
● “CREATE USER statement” on page 658
● “DROP LOGIN POLICY statement” on page 696
● “DROP USER statement” on page 715
● “Login policies” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example alters the Test1 login policy. This example changes the locked and
max_connections options. The locked value indicates that users with the policy cannot establish new
connections and the max_connections value limits the number of concurrent connections that are allowed.

ALTER LOGIN POLICY Test1


locked=ON
max_connections=5;

ALTER MATERIALIZED VIEW statement


Alters a materialized view.

Syntax
ALTER MATERIALIZED VIEW [ owner.]materialized-view-name {
SET HIDDEN
| { ENABLE | DISABLE }
| { ENABLE | DISABLE } USE IN OPTIMIZATION
| { ADD PCTFREE percent-free-space | DROP PCTFREE }
| [ NOT ] ENCRYPTED
| [ { IMMEDIATE | MANUAL } REFRESH ]
}

percent-free-space : integer

Parameters
SET HIDDEN clause Use the SET HIDDEN clause to obfuscate the definition of a materialized view.
This setting is irreversible.

ENABLE clause Use the ENABLE clause to enable a disabled materialized view, making it available
for the database server to use. This clause has no effect on a view that is already enabled. After using this

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 417


SQL statements

clause, you must refresh the view to initialize it, and recreate any text indexes that were dropped when the
view was disabled.

DISABLE clause Use the DISABLE clause to disable use of the view by the database server. When
you disable a materialized view, the database server drops the data and indexes for the view.

{ ENABLE | DISABLE } USE IN OPTIMIZATION clause Use this clause to specify whether you
want the materialized view to be available for the optimizer to use. If you specify DISABLE USE IN
OPTIMIZATION, the materialized view is used only when executing queries that explicitly reference the
view. The default is ENABLE USE IN OPTIMIZATION.

ADD PCTFREE clause Specify the percentage of free space you want to reserve on each page. The
free space is used if rows increase in size when the data is updated. If there is no free space on a page,
every increase in the size of a row on that page requires the row to be split across multiple pages, causing
row fragmentation and possible performance degradation.

The value of percent-free-space is an integer between 0 and 100. The value 0 specifies that no free space
is to be left on each page—each page is to be fully packed. A high value causes each row to be inserted
into a page by itself. If PCTFREE is not set, or is dropped, the default PCTFREE setting is applied
according to the database page size (200 bytes for a 4 KB page size, and 100 bytes for a 2 KB page size).

DROP PCTFREE clause Removes the PCTFREE setting currently in effect for the materialized view,
and applies the default PCTFREE according to the database page size.

[ NOT ] ENCRYPTED clause Specify whether to encrypt the materialized view data. By default,
materialized view data is not encrypted at creation time. To encrypt a materialized view, specify
ENCRYPTED. To decrypt a materialized view, specify NOT ENCRYPTED.

REFRESH clause Use the REFRESH clause to change the refresh type for the materialized view:

○ IMMEDIATE REFRESH Use the IMMEDIATE REFRESH clause to change a manual view to an
immediate view. The manual view must be valid and uninitialized to change the refresh type to
IMMEDIATE REFRESH. If the view is in an initialized state, execute a TRUNCATE statement to
change the state to uninitialized before executing the ALTER MATERIALIZED
VIEW...IMMEDIATE REFRESH.

○ MANUAL REFRESH Use the MANUAL REFRESH clause to change an immediate view to a
manual view.

Remarks
If you alter a materialized view owned by another user, you must qualify the name by including the owner
(for example, GROUPO.EmployeeConfidential). If you don't qualify the name, the database server looks
for a materialized view with that name owned by you and alters it. If there isn't one, it returns an error.

When you disable a materialized view (DISABLE clause), it is no longer available for the database server
to use for answering queries. As well, the data and indexes are dropped, and the refresh type changes to
manual. Any dependent regular views are also disabled.

The DISABLE clause requires exclusive access not only to the view being disabled, but to any dependent
views, since they are also disabled.

418 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Table encryption must already be enabled on the database to encrypt a materialized view (ENCRYPTED
clause). The materialized view is then encrypted using the encryption key and algorithm specified at
database creation time.

Permissions
To execute the ALTER MATERIALIZED VIEW statement you must own the view or have DBA
authority.

If you do not have DBA authority but want to alter a materialized view to be immediate (ALTER
MATERIALIZED VIEW...IMMEDIATE REFRESH), you must own the view and all the tables it
references.

The only operations a user can perform on a materialized view to change its data are refreshing,
truncating, and disabling. However, immediate views are automatically updated by the database server.
That is, once an immediate view is enabled and initialized, the database server maintains it automatically,
without additional permissions checking.

Side effects
Automatic commit.

See also
● “CREATE MATERIALIZED VIEW statement” on page 560
● “REFRESH MATERIALIZED VIEW statement” on page 843
● “DROP MATERIALIZED VIEW statement” on page 697
● “TRUNCATE statement” on page 933
● “sa_refresh_materialized_views system procedure” on page 1108
● “Materialized views” [SQL Anywhere Server - SQL Usage]
● “View dependencies” [SQL Anywhere Server - SQL Usage]
● “Restrictions when changing a materialized view from manual to immediate” [SQL Anywhere Server -
SQL Usage]
● “Enabling or disabling a materialized view” [SQL Anywhere Server - SQL Usage]
● “Encrypting or decrypting a materialized view” [SQL Anywhere Server - SQL Usage]
● “Hiding a materialized view” [SQL Anywhere Server - SQL Usage]
● “Whether to set refresh type to manual or immediate” [SQL Anywhere Server - SQL Usage]
● “Advanced: Status and properties for materialized views” [SQL Anywhere Server - SQL Usage]
● “Enabling or disabling optimizer use of a materialized view” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements creates the EmployeeConfid88 materialized view and then disables its use in
optimization:

CREATE MATERIALIZED VIEW EmployeeConfid88 AS


SELECT EmployeeID, Employees.DepartmentID, SocialSecurityNumber, Salary,
ManagerID,
Departments.DepartmentName, Departments.DepartmentHeadID

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 419


SQL statements

FROM Employees, Departments


WHERE Employees.DepartmentID=Departments.DepartmentID;
REFRESH MATERIALIZED VIEW EmployeeConfid88;
ALTER MATERIALIZED VIEW GROUPO.EmployeeConfid88 DISABLE USE IN OPTIMIZATION;

Caution
When you are done with this example, you should drop the materialized view you created. Otherwise, you
cannot make schema changes to its underlying tables, Employees and Departments, when trying out other
examples. You cannot alter the schema of a table that has enabled, dependent materialized view.

ALTER MIRROR SERVER statement


Note
Read-only scale-out and database mirroring each require a separate license. See “Separately licensed
components” [SQL Anywhere 12 - Introduction].

Modifies the attributes of a mirror server.

Syntax
ALTER MIRROR SERVER mirror-server-name
AS { PRIMARY | MIRROR | ARBITER | PARTNER | COPY }
[ { FROM SERVER parent-name [ OR SERVER server-name ] | USING AUTO PARENT } | ALTER
PARENT FROM mirror-server-name ]
[ server-option = { string | NULL } [ ... ] ]

parent-name :
server-name | PRIMARY

server-option :
connection_string
logfile
preferred
state_file

Parameters
● AS clause You can specify one of the following server types:

○ PRIMARY The mirror server with type PRIMARY defines a virtual or logical server, rather
than an actual database server. The name of this server is the alternate server name for the
database. The alternate server name can be used by applications to connect to the server currently
acting as the primary server. The server marked as PRIMARY also defines the connection string
used by mirror servers to connect to the server currently acting as primary, and it defines how new
copy nodes initially connect to the root server in a scale-out system. There can be only one
PRIMARY server for a database.

○ MIRROR The mirror server with type MIRROR defines a virtual or logical server, rather than
an actual database server. The name of this server is the alternate mirror server name for the

420 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

database. The alternate mirror server name can be used by applications to connect to the server
currently acting as the read-only mirror. There can be only one MIRROR server for a database.

○ ARBITER In a database mirroring system, the arbiter server assists in determining which of the
PARTNER servers takes ownership of the database. The arbiter server must be defined with a
connection string that can be used by the partner servers to connect to the arbiter. There can be
only one ARBITER server for a database.

○ PARTNER In a database mirroring system, servers defined as PARTNER are eligible to


become the primary server and take ownership of the database. You must define two PARTNER
servers for database mirroring, and both must have a connection string and a state file. The name
of the mirror server must correspond to the name of the database server, as specified by the -n
server option, and must match the value of the SERVER connection string parameter specified in
the connection_string mirror server option.

In a read-only scale-out system, you must define one PARTNER server. This server is the root
server, and runs the only copy of the database that allows both read and write operations.

○ COPY In a read-only scale-out system, this value specifies that the database server is a copy
node. All connections to the database on this server are read-only. The name of the mirror server
must correspond to the name of the database server, as specified by the -n server option, and must
match the value of the SERVER connection string parameter specified in the connection_string
mirror server option. You do not have to explicitly define copy nodes for the scale-out system; you
can choose to have the root node define the copy nodes when they connect.

● FROM SERVER clause You can only specify this clause for mirror servers of type COPY. This
clause constructs a tree of servers for a mirroring or scale-out system and indicates which servers the
copy nodes obtain transaction log pages from.

The parent can be specified using the name of the mirror server or PRIMARY. An alternate parent for
the copy node can be specified using the OR SERVER clause.

In a database mirroring system that has only two levels (partner and copy nodes), the copy nodes
obtain transaction log pages from the current primary or mirror server.

A copy node determines which server to connect to by using its mirror server definition that is stored
in the database. From its definition, it can locate the definition of its parent, and from its parent's
definition, it can obtain the connection string to connect to the parent.

You do not have to explicitly define copy nodes for the scale-out system: you can choose to have the
root node define the copy nodes when they connect.

● USING AUTO PARENT clause This clause causes the primary server to assign a parent for this
server.

● ALTER PARENT FROM clause This clause changes the parent for this mirror server, and assigns
all its siblings to be its children. The server name specified by the ALTER PARENT FROM clause is
used to verify that the current parent for this server matches the value specified. This is used to ensure
that only one of a collection of siblings is able to replace its parent if they all request the change
simultaneously.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 421


SQL statements

● server-option clause The following options are supported:

○ connection_string server option Specifies the connection string to be used to connect to the
server. A user ID and password are not required. The connection string for a mirror server should
not include a user ID or password because they are not used when one mirror server connects to
another mirror server.

For a list of connection parameters, see “Connection parameters” [SQL Anywhere Server -
Database Administration].

○ logfile server option Specifies the location of the file that contains one line per request that is
sent between mirror servers if database mirroring is used. This file is used only for debugging.

○ preferred server option Specifies whether the server is the preferred server in the mirroring
system. You can specify either YES or NO. The preferred server assumes the role of primary
server whenever possible. You specify this option when defining PARTNER servers.

○ state_file server option Specifies the location of the file used for maintaining state
information about the mirroring system. This option is required for database mirroring. A state file
must be specified for servers with type PARTNER. For arbiter servers, the location is specified as
part of the command to start the server.

Remarks
Cloud note: This statement is not supported on tenant databases in the cloud.

In a database mirroring system, the mirror server type can be PRIMARY, MIRROR, ARBITER, or
PARTNER.

In a read-only scale-out system, the mirror server type can be PRIMARY, PARTNER, or COPY.

Mirror server names for servers of type PARTNER, ARBITER, or COPY must match the names of the
database servers that will be part of the mirroring system (the name used with the -n server option). This
allows each database server to find its own definition and that of its parent.

Permissions
Must have DBA authority.

Side effects
Automatic commit.

422 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “How child copy nodes are added” [SQL Anywhere Server - Database Administration]
● “State information files” [SQL Anywhere Server - Database Administration]
● “Automatically assign the parent of a copy node” [SQL Anywhere Server - Database Administration]
● “Preferred database server” [SQL Anywhere Server - Database Administration]
● “Database mirroring” [SQL Anywhere Server - Database Administration]
● “SYSMIRRORSERVER system view” on page 1217
● “CREATE MIRROR SERVER statement” on page 564
● “COMMENT statement” on page 499
● “DROP MIRROR SERVER statement” on page 699

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example changes the parent of the scaleout_child copy node and assigns all its siblings to
be its children:
ALTER MIRROR SERVER "scaleout_child"
AS COPY
ALTER PARENT FROM scaleout_mirror
connection_string = 'server=scaleout_child;host=winxp-2:6878';

ALTER PROCEDURE statement


Modifies a procedure.

Syntax 1
ALTER PROCEDURE [ owner.]procedure-name procedure-definition

procedure-definition : See “CREATE PROCEDURE statement” on page 585.

Syntax 2
ALTER PROCEDURE [ owner.]procedure-name
SET HIDDEN

Syntax 3
ALTER PROCEDURE [ owner.]procedure-name
RECOMPILE

Remarks
The ALTER PROCEDURE statement must include the entire new procedure. You can use PROC as a
synonym for PROCEDURE.

● Syntax 1 The ALTER PROCEDURE statement is identical in syntax to the CREATE


PROCEDURE statement except for the first word. Both Watcom and Transact-SQL dialect
procedures can be altered through the use of ALTER PROCEDURE.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 423


SQL statements

With ALTER PROCEDURE, existing permissions on the procedure are not changed. If you execute
DROP PROCEDURE followed by CREATE PROCEDURE, execute permissions are reassigned.

● Syntax 2 Use SET HIDDEN to obfuscate the definition of the associated procedure and cause it to
become unreadable. The procedure can be unloaded and reloaded into other databases.

If SET HIDDEN is used, debugging using the debugger does not show the procedure definition, and
the definition is not available through procedure profiling.

You cannot combine Syntax 2 with Syntax 1.

Note
This setting is irreversible. It is recommended that you retain the original procedure definition outside
of the database.

● Syntax 3 Use the RECOMPILE syntax to recompile a stored procedure. When you recompile a
procedure, the definition stored in the catalog is re-parsed and the syntax is verified. For procedures
that generate a result set but do not include a RESULT clause, the database server attempts to
determine the result set characteristics for the procedure and stores the information in the catalog. This
can be useful if a table referenced by the procedure has been altered to add, remove, or rename
columns since the procedure was created.

The procedure definition is not changed by recompiling. You can recompile procedures with
definitions hidden with the SET HIDDEN clause, but their definitions remain hidden.

Permissions
Must be the owner of the procedure or have DBA authority.

Side effects
Automatic commit.

See also
● “CREATE PROCEDURE statement” on page 585
● “CREATE PROCEDURE statement [Web service]” on page 575
● “ALTER FUNCTION statement” on page 412
● “DROP PROCEDURE statement” on page 700
● “Hiding the contents of procedures, functions, triggers, events, and views” [SQL Anywhere Server -
SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension. ALTER PROCEDURE is optional SQL language feature F381 of the
SQL/2008 standard. However, in the SQL standard, ALTER PROCEDURE cannot be used to re-
define a stored procedure definition, and Transact-SQL dialect procedures are not supported. SQL/
2008 does not include support for SET HIDDEN or RECOMPILE.

424 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

ALTER PUBLICATION statement [MobiLink] [SQL Remote]


Alters a publication. In MobiLink, a publication identifies synchronized data in a SQL Anywhere remote
database. In SQL Remote, a publication identifies replicated data in both consolidated and remote
databases.

Syntax
ALTER PUBLICATION [ owner.]publication-name alterpub-clause, ...

alterpub-clause :
ADD article-definition
| ALTER article-definition
| { DELETE | DROP } TABLE [ owner.]table-name
| RENAME publication-name

article-definition :
TABLE table-name [ ( column-name, ... ) ]
[ WHERE search-condition ]
[ SUBSCRIBE BY expression ]
[ USING ( [PROCEDURE ] [ owner.][procedure-name ]
FOR UPLOAD { INSERT | DELETE | UPDATE }, ... ) ]

Remarks
This statement is applicable only to MobiLink and SQL Remote.

The contribution to a publication from one table is called an article. Changes can be made to a publication
by adding, modifying, or deleting articles, or by renaming the publication. If an article is modified, the
entire definition of the modified article must be entered.

It is recommended that you perform a successful synchronization of a publication immediately before you
alter it.

You cannot use the WHERE clause for publications that are defined as FOR DOWNLOAD ONLY or
WITH SCRIPTED UPLOAD.

The SUBSCRIBE BY clause applies to SQL Remote only.

The USING clause is for scripted upload only.

You set options for a MobiLink publication with the ADD OPTION clause in the ALTER
SYNCHRONIZATION SUBSCRIPTION statement or CREATE SYNCHRONIZATION
SUBSCRIPTION statement.

When altering a MobiLink publication, an article can only be dropped after the execution of a START
SYNCHRONIZATION SCHEMA CHANGE statement.

Permissions
Must have DBA authority, or be the owner of the publication. Requires exclusive access to all tables
referred to in the statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 425


SQL statements

Side effects
Automatic commit.

See also
● “CREATE PUBLICATION statement [MobiLink] [SQL Remote]” on page 592
● “DROP PUBLICATION statement [MobiLink] [SQL Remote]” on page 701
● SQL Anywhere MobiLink clients: “Publications” [MobiLink - Client Administration]
● UltraLite MobiLink clients: “UltraLite client synchronization design” [UltraLite - Database
Management and Reference]
● “Publications and articles” [SQL Remote]
● “ALTER SYNCHRONIZATION SUBSCRIPTION statement [MobiLink]” on page 447
● “CREATE SYNCHRONIZATION SUBSCRIPTION statement [MobiLink]” on page 629
● “ISYSSYNC system table” on page 976
● “START SYNCHRONIZATION SCHEMA CHANGE statement [MobiLink]” on page 916
● “Changes to avoid on a running system” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement adds the Customers table to the pub_contact publication.
ALTER PUBLICATION pub_contact
ADD TABLE Customers;

ALTER REMOTE MESSAGE TYPE statement [SQL Remote]


Changes the publisher's message system, or the publisher's address for a given message system, for a
message type that has been created.

Syntax
ALTER REMOTE MESSAGE TYPE message-system
ADDRESS address

message-system : FILE | FTP | SMTP

address : string

Parameters
message-system One of the message systems supported by SQL Remote. It must be one of the
following values: FILE, FTP, or SMTP.

address A string containing a valid address for the specified message system.

Remarks
The statement changes the publisher's address for a given message type.

426 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The Message Agent sends outgoing messages from a database by one of the supported message links. The
Extraction utility uses this address when it executes the GRANT CONSOLIDATE statement in the
remote database.

The address is the publisher's address under the specified message system. If it is an email system, the
address string must be a valid email address. If it is a file-sharing system, the address string is a
subdirectory of the directory specified by the SQLREMOTE environment variable, or of the current
directory if that is not set. You can override this setting on the GRANT CONSOLIDATE statement at the
remote database.

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “CREATE REMOTE MESSAGE TYPE statement [SQL Remote]” on page 596
● “GRANT CONSOLIDATE statement [SQL Remote]” on page 754
● “SQLREMOTE environment variable” [SQL Anywhere Server - Database Administration]
● “SQL Remote message systems” [SQL Remote]
● “Alter message types” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement changes the publisher's address for the FILE message link to new_addr.
ALTER REMOTE MESSAGE TYPE file
ADDRESS 'new_addr';

ALTER SEQUENCE statement


Alters a sequence.

Syntax
ALTER SEQUENCE [ owner.] sequence-name
[ RESTART WITH signed-integer ]
[ INCREMENT BY signed-integer ]
[ MINVALUE signed-integer | NO MINVALUE ]
[ MAXVALUE signed-integer | NO MAXVALUE ]
[ CACHE integer | NO CACHE ]
[ CYCLE | NO CYCLE ]

Parameters
RESTART WITH clause Restarts the named sequence with the specified value.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 427


SQL statements

INCREMENT BY clause Defines the amount the next sequence value is incremented from the last
value assigned. The default is 1. Specify a negative value to generate a descending sequence. An error is
returned if the INCREMENT BY value is 0.

MINVALUE clause Defines the smallest value generated by the sequence. The default is 1. An error is
returned if MINVALUE is greater than ( 2^63-1) or less than -(2^63-1). An error is also returned if
MINVALUE is greater than MAXVALUE.

MAXVALUE clause Defines the largest value generated by the sequence. The default is 2^63-1. An
error is returned if MAXVALUE is greater than 2^63-1 or less than -(2^63-1).

CACHE clause Specifies the number of preallocated sequence values that are kept in memory for
faster access. When the cache is exhausted, the sequence cache is repopulated and a corresponding entry
is written to the transaction log. At checkpoint time, the current value of the cache is forwarded to the
ISYSSEQUENCE system table. The default is 100.

CYCLE clause Specifies whether values should continue to be generated after the maximum or
minimum value is reached.

Remarks
If the named sequence cannot be located, an error message is returned.

Permissions
Must have DBA authority or be the owner of the sequence and have RESOURCE authority.

Side effects
None

See also
● “Use of a sequence to generate unique values” [SQL Anywhere Server - SQL Usage]
● “CREATE SEQUENCE statement” on page 599
● “DROP SEQUENCE statement” on page 702

Standards and compatibility


● SQL/2008 The ALTER SEQUENCE statement is part of optional SQL language feature T176 of
the SQL/2008 standard. The CACHE clause is a vendor extension.

Example
The following example sets a new maximum value for a sequence named Test:
ALTER SEQUENCE Test
MAXVALUE 1500;

ALTER SERVER statement


Modifies the attributes of a remote server.

428 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
ALTER SERVER server-name
[ CLASS server-class ]
[ USING connection-info ]
[ CAPABILITY cap-name { ON | OFF } ]
[ CONNECTION CLOSE [ CURRENT | ALL | connection-id ] ]

server-class :
SAODBC
| 'ASEODBC'
| 'DB2ODBC'
| 'IQODBC'
| 'MSSODBC'
| 'ORAODBC'
| 'MSACCESSODBC'
| 'MYSQLODBC'
| 'ULODBC'
| 'ADSODBC'
| 'ODBC'
| 'SAJDBC'
| 'ASEJDBC'
| 'IQJDBC'

connection-info :
computer-name:port-number[/dbname ] | data-source-name

Parameters
CLASS clause The CLASS clause is specified to change the server class.

USING clause The USING clause is specified to change the server connection information.

CAPABILITY clause The CAPABILITY clause turns a server capability ON or OFF. Server
capabilities are stored in the ISYSCAPABILITY system table. The names of these capabilities are
accessible via the SYSCAPABILITYNAME system view. The ISYSCAPABILITY system table and
SYSCAPABILITYNAME system view are not populated with data until the first connection to a remote
server is made. For subsequent connections, the database server's capabilities are obtained from the
ISYSCAPABILITY system 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.

CONNECTION CLOSE clause When a user creates a connection to a remote server, the remote
connection is not closed until the user disconnects from the local database. The CONNECTION CLOSE
clause allows you to explicitly close connections to a remote server. You may find this useful when a
remote connection becomes inactive or is no longer needed.

The following SQL statements are equivalent and close the current connection to the remote server:
ALTER SERVER server-name CONNECTION CLOSE;
ALTER SERVER server-name CONNECTION CLOSE CURRENT;

You can close both ODBC and JDBC connections to a remote server using this syntax. You do not need
DBA authority to execute either of these statements.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 429


SQL statements

You can also disconnect a specific remote ODBC connection by specifying a connection ID, or
disconnect all remote ODBC connections by specifying the ALL keyword. If you attempt to close a JDBC
connection by specifying the connection ID or the ALL keyword, an error occurs. When the connection
identified by connection-id is not the current local connection, the user must have DBA authority to be
able to close the connection.

Remarks
The ALTER SERVER statement modifies the attributes of a server. These changes do not take effect until
the next connection to the remote server.

Permissions
DBA authority.

Side effects
Automatic commit. The CONNECTION CLOSE clause does not cause an automatic commit.

See also
● “Server classes for remote data access” [SQL Anywhere Server - SQL Usage]
● “CREATE SERVER statement” on page 601
● “DROP SERVER statement” on page 703
● “Troubleshooting remote data access” [SQL Anywhere Server - SQL Usage]
● “SYSCAPABILITY system view” on page 1197
● “SYSCAPABILITYNAME system view” on page 1197

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example changes the server class of the Adaptive Server Enterprise server named ase_prod
so its connection to SQL Anywhere is ODBC-based. Its data source name is ase_prod.
ALTER SERVER ase_prod
CLASS 'ASEODBC'
USING 'ase_prod';

The following example changes a capability of server infodc.


ALTER SERVER infodc
CAPABILITY 'insert select' OFF;

The following example closes all connections to the remote server named rem_test.
ALTER SERVER rem_test
CONNECTION CLOSE ALL;

The following example closes the connection to the remote server named rem_test that has the connection
ID 142536.
ALTER SERVER rem_test
CONNECTION CLOSE 142536;

430 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

ALTER SERVICE statement [HTTP web service]


Alters an existing HTTP web service.

Syntax
ALTER SERVICE service-name
[ TYPE { 'RAW' | 'HTML' | 'JSON' | 'XML' } ]
[ URL [ PATH ] { ON | OFF | ELEMENTS } ]
[ common-attributes ]
[ AS { statement | NULL } ]

common-attributes :
[ AUTHORIZATION { ON | OFF } ]
[ ENABLE | DISABLE ]
[ METHODS 'method,...' ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]

method :
DEFAULT
| POST
| GET
| HEAD
| PUT
| DELETE
| NONE
|*

Parameters
service-name Web service names can be any sequence of alphanumeric characters or slash (/), hyphen
(-), underscore (_), period (.), exclamation mark (!), tilde (~), asterisk (*), apostrophe ('), left parenthesis
((), or right parenthesis ()), except that the service name must not begin or end with a slash (/) or contain
two or more consecutive slashes (for example, //).

You can name your service root, but this name has a special function.

TYPE clause Identifies the type of the service where each service defines a specific response format.
The type must be one of the listed service types. There is no default value.

○ 'RAW' The result set is sent to the client without any formatting. Utilization of this service requires
that all content markup is explicitly provided. Complex dynamic content containing current content
with markup, JavaScript and images can be generated on demand. The media type may be specified
by setting the Content-Type response header using the sa_set_http_header procedure. Setting the
Content-Type header to 'text/html' is good practice when generating HTML markup to ensure that all
browsers display the markup as HTML and not text/plain.

○ 'HTML' The result set is returned as an HTML representation of a table or view.

○ 'JSON' The result set is returned in JavaScript Object Notation (JSON). A JSON service does not
automatically process JSON input. It only presents data (in the response) in JSON format. JSON
accepts POST/PUT methods where application/x-www-form-urlencoded is supported. If for a

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 431


SQL statements

POST/PUT METHOD, Content-Type: application/json is specified, then the application may use
http_variable('body') to retrieve the JSON (request) content. SQL Anywhere does not parse the JSON
input automatically. It is up to the application to parse it. For more information about JSON, see
http://www.json.org/.

○ 'XML' The result set is returned as XML. If the result set is already XML, no additional formatting
is applied. Otherwise, it is automatically formatted as XML. As an alternative approach, a RAW
service could return a select using the FOR XML RAW clause having set a valid Content-Type such
as text/xml using sa_set_http_header procedure.

URL clause Determines whether URL paths are accepted and, if so, how they are processed.
Specifying URL PATH has the same effect as URL.

○ OFF Indicates that the service name in a URL request must not be followed by a path. OFF is the
default setting. For example, the following form is disallowed due to the path elements /aaa/bbb/
ccc.
http://host-name/service-name/aaa/bbb/ccc

Suppose that CREATE SERVICE echo URL PATH OFF was specified when creating the web
service. A URL similar to http://localhost/echo?id=1 produces the following values:
HTTP_VARIABLE('id') == 1,
HTTP_HEADER('@HTTPQUERYSTRING') == id=1

○ ON Indicates that the service name in a URL request can be followed by a path. The path value is
returned by querying a dedicated HTTP variable named URL. A service can be defined to explicitly
provide the URL parameter or it may be retrieved using the HTTP_VARIABLE function. For
example, the following form is allowed:
http://host-name/service-name/aaa/bbb/ccc

Suppose that CREATE SERVICE echo URL PATH ON was specified when creating the web
service. A URL similar to http://localhost/echo/one/two?id=1 produces the following
values:
HTTP_VARIABLE('id') == 1,
HTTP_VARIABLE('URL') == one/two,
HTTP_HEADER('@HTTPQUERYSTRING') == id=1

○ ELEMENTS Indicates that the service name in a URL request may be followed by a path. The path
is obtained in segments by specifying a single parameter keyword URL1, URL2, and so on. Each
parameter may be retrieved using the HTTP_VARIABLE or NEXT_HTTP_VARIABLE functions.
These iterator functions can be used in applications where a variable number of path elements can be
provided. For example, the following form is allowed:
http://host-name/service-name/aaa/bbb/ccc

Suppose that CREATE SERVICE echo URL PATH ELEMENTS was specified when creating the
web service. A URL similar to http://localhost/echo/one/two?id=1 produces the
following values:
HTTP_VARIABLE('id') == 1,
HTTP_VARIABLE('URL1') == one,

432 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

HTTP_VARIABLE('URL2') == two,
HTTP_HEADER('@HTTPQUERYSTRING') == id=1

Up to 10 elements can be obtained. A NULL value is returned if the corresponding element is not
supplied. In the above example, HTTP_VARIABLE('URL3') returns NULL because no
corresponding element was supplied.

For more information about URLs, see “Browsing an HTTP web server” [SQL Anywhere Server -
Programming] and “Accessing client-supplied HTTP variables and headers” [SQL Anywhere Server -
Programming].

AUTHORIZATION clause Determines whether users must specify a user name and password through
basic HTTP authorization when connecting to the service. The default value is ON. If authorization is
OFF, the AS clause is required for all services and a user must be specified with the USER clause. All
requests are run using that user's account and permissions. If AUTHORIZATION is ON, all users must
provide a user name and password. Optionally, you can limit the users that are permitted to use the service
by providing a user or group name with the USER clause. If the user name is NULL, all known users can
access the service. The AUTHORIZATION clause allows your web services to use database authorization
and permissions to control access to the data in your database.

When the authorization value is ON, an HTTP client connecting to a web service uses basic
authentication (RFC 2617) that obfuscates the user and password information using base-64 encoding. It
is recommended that you use the HTTPS protocol for increased security.

ENABLE and DISABLE clauses Determines whether the service is available for use. By default,
when a service is created, it is enabled. When creating or altering a service, you may include an ENABLE
or DISABLE clause. Disabling a service effectively takes the service off line. Later, it can be enabled
using ALTER SERVICE with the ENABLE clause. An HTTP request made to a disabled service
typically returns a 404 Not Found HTTP status.

METHODS clause Specifies the HTTP methods that are supported by the service. Valid values are
DEFAULT, POST, GET, HEAD, PUT, DELETE, and NONE. An asterisk (*) may be used as a short
form to represent the POST, GET, and HEAD methods which are default request types for the RAW,
HTML, and XML service types. Not all HTTP methods are valid for all the service types. The following
table summarizes the valid HTTP methods that can be applied to each service type:

Method value Applies to service Description

DEFAULT all Use DEFAULT to reset the set of default


HTTP methods for the given service type. It
cannot be included in a list with other method
values.

POST RAW, HTML, JSON, Enabled by default.


XML

GET RAW, HTML, JSON, Enabled by default.


XML

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 433


SQL statements

Method value Applies to service Description

HEAD RAW, HTML, JSON, Enabled by default.


XML

PUT RAW, HTML, JSON, Not enabled by default.


XML

DELETE RAW, HTML, JSON, Not enabled by default.


XML

NONE all Use NONE to disable access to a service.

* RAW, HTML, JSON, Same as specifying 'POST,GET,HEAD'.


XML

For example, you can use either of the following clauses to specify that a service supports all HTTP
method types:
METHODS '*,PUT,DELETE'
METHODS 'POST,GET,HEAD,PUT,DELETE'

To reset the list of request types for any service type to its default, you can use the following clause:
METHODS 'DEFAULT'

SECURE clause Specifies whether the service should be accessible on a secure or non-secure listener.
ON indicates that only HTTPS connections are accepted, and that connections received on the HTTP port
are automatically redirected to the HTTPS port. OFF indicates that both HTTP and HTTPS connections
are accepted, provided that the necessary ports are specified when starting the web server. The default
value is OFF.

USER clause Specifies a database user, or group of users, with permissions to execute the web service
request. A USER clause must be specified when the service is configured with AUTHORIZATION OFF
and should be specified with AUTHORIZATION ON. (the default) An HTTP request made to a service
requiring authorization results in a 401 Authorization Required HTTP response status. Based
on this response, the web browser prompts for a user ID and password.

Caution
It is strongly recommended that you specify a USER clause when authorization is enabled (default).
Otherwise, authorization is granted to all users.

The USER clause controls which database user accounts can be used to process service requests. Database
access permissions are restricted to the privileges assigned to the user of the service.

statement Specifies a command, such as a stored procedure call, to invoke when the service is
accessed.

An HTTP request to a non-DISH service with no statement specifies the SQL expression to execute
within its URL. Although authorization is required, this capability should not be used in production

434 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

systems because it makes the server vulnerable to SQL injections. When a statement is defined within the
service, the specified SQL statement is the only statement that can be executed through the service.

In a typical web service application, you use statement to call a function or procedure. You can pass host
variables as parameters to access client-supplied HTTP variables.

The following statement demonstrates a procedure call that passes two host variables to a procedure
named AuthenticateUser. This call presumes that a web client supplies the user_name and
user_password variables:
CALL AuthenticateUser ( :user_name, :user_password );

For more information about passing host variables to a function or procedure, see “Accessing client-
supplied HTTP variables and headers” [SQL Anywhere Server - Programming].

Remarks
The ALTER SERVICE statement modifies the attributes of a web service.

Permissions
DBA authority

Side effects
None.

See also
● “CREATE SERVICE statement [HTTP web service]” on page 605
● “DROP SERVICE statement” on page 704
● “Tutorial: Using SQL Anywhere to access a SOAP/DISH service” [SQL Anywhere Server -
Programming]
● “SYSWEBSERVICE system view” on page 1259
● “-xs dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “sa_set_http_header system procedure” on page 1134
● “SQL Anywhere as an HTTP web server” [SQL Anywhere Server - Programming]
● “Creating and customizing a root web service” [SQL Anywhere Server - Programming]
● “Developing web service applications in an HTTP web server” [SQL Anywhere Server -
Programming]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example demonstrates how to disable an existing web service using the ALTER SERVICE
statement:
CREATE SERVICE WebServiceTable
TYPE 'RAW'
AUTHORIZATION OFF
USER DBA
AS SELECT *

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 435


SQL statements

FROM SYS.SYSTAB;

ALTER SERVICE WebServiceTable DISABLE;

ALTER SERVICE statement [SOAP web service]


Alters an existing HTTP over SOAP or DISH service.

Syntax 1 - SOAP over HTTP services


ALTER SERVICE service-name
[ TYPE 'SOAP' ]
[ DATATYPE { ON | OFF | IN | OUT } ]
[ FORMAT { 'DNET' | 'CONCRETE' [ EXPLICIT { ON | OFF } ] | 'XML' | NULL } ]
[ common-attributes ]
[ AS statement ]

common-attributes :
[ AUTHORIZATION { ON | OFF } ]
[ ENABLE | DISABLE ]
[ METHODS 'method,...' ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]

method :
DEFAULT
| POST
| HEAD
| NONE

Syntax 2 - DISH services


ALTER SERVICE service-name
[ TYPE 'DISH' ]
[ GROUP { group-name | NULL } ]
[ FORMAT { 'DNET' | 'CONCRETE' [ EXPLICIT { ON | OFF } ]| 'XML' | NULL } ]
[ common-attributes ]

common-attributes :
[ AUTHORIZATION { ON | OFF } ]
[ ENABLE | DISABLE ]
[ METHODS 'method,...' ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]

method :
DEFAULT
| POST
| GET
| HEAD
| NONE
|*

436 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Parameters
The descriptions of the ALTER SERVICE clauses are identical to those of the CREATE SERVICE
statement.

Parameters
service-name Web service names can be any sequence of alphanumeric characters or slash (/), hyphen
(-), underscore (_), period (.), exclamation mark (!), tilde (~), asterisk (*), apostrophe ('), left parenthesis
((), or right parenthesis ()), except that the service name must not begin or end with a slash (/) or contain
two or more consecutive slashes (for example, //).

Unlike other services, you cannot use a slash (/) anywhere in a DISH service name.

You can name your service root, but this name has a special function.

TYPE clause Identifies the type of the service where each service defines a specific response format.
The type must be one of the listed service types. There is no default value.

○ 'SOAP' The result set is returned as an XML payload known as a SOAP envelope. The format of
the data may be further refined using by the FORMAT clause. A request to a SOAP service must be a
valid SOAP request, not just a general HTTP request. For more information about the SOAP
standards, see http://www.w3.org/TR/2000/NOTE-SOAP-20000508/.

○ 'DISH' A DISH service (Determine SOAP Handler) is a SOAP endpoint that references any SOAP
service within its GROUP context. It also exposes the interfaces to its SOAP services by generating a
WSDL (Web Services Description Language) for consumption by SOAP client toolkits.

GROUP clause A DISH service without a GROUP clause exposes all SOAP services defined within
the database. By convention, the SOAP service name can be composed of a GROUP and a NAME
element. The name is delimited from the group by the last slash character. For example, a SOAP service
name defined as 'aaa/bbb/ccc' is 'ccc', and the group is 'aaa/bbb'. Delimiting a DISH service using this
convention is invalid. Instead, a GROUP clause is applied to specify the group of SOAP services for
which it is to be the SOAP endpoint.

Note
Slashes are converted to underscores within the WSDL to produce valid XML. Use caution when using a
DISH service that does not specify a GROUP clause such that it exposes all SOAP services that may
contain slashes. Use caution when using groups in conjunction with SOAP service names that contain
underscores to avoid ambiguity.

DATATYPE clause Applies to SOAP services only. When DATATYPE OFF is specified, SOAP
input parameters and response data are defined as XMLSchema string types. In most cases, true data types
are preferred because it negates the need for the SOAP client to cast the data prior to computation.
Parameter data types are exposed in the schema section of the WSDL generated by the DISH service.
Output data types are represented as XML schema type attributes for each column of data.

The following values are permitted for the DATATYPE clause:

○ ON Generates data typing of input parameters and result set responses.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 437


SQL statements

○ OFF All input parameters and response data are typed as XMLSchema string (default).

○ IN Generates true data types for input parameters only. Response data types are XMLSchema
string.

○ OUT Generates true data types for responses only. Input parameters are typed as XMLSchema
string.

For more information about SOAP services, see “Tutorial: Using SQL Anywhere to access a SOAP/DISH
service” [SQL Anywhere Server - Programming].

For more information about mapping XMLSchema types to SQL data types, see “SOAP data types” [SQL
Anywhere Server - Programming].

FORMAT clause This clause specifies the output format when sending responses to SOAP client
applications.

The SOAP service format is dictated by the associated DISH service format specification when it is not
specified by the SOAP service. The default format is DNET.

SOAP requests should be directed to the DISH service (the SQL Anywhere SOAP endpoint) to leverage
common formatting rules for a group of SOAP services (SOAP operations). A SOAP service FORMAT
specification overrides that of a DISH service. The format specification of the DISH service is used when
a SOAP service does not define a FORMAT clause. If no FORMAT is provided by either service then the
default is 'DNET'.

The following formats are supported:

○ 'DNET' The output is in a System.Data.DataSet compatible format for consumption by .NET client
applications. (default)

○ 'CONCRETE' This output format is used to support client SOAP toolkits that are capable of
generating interfaces representing arrays of row and column objects but are not able to consume the
DNET format. Java and .NET clients can easily consume this output format.

The specific output format is exposed within the WSDL of a DISH service. For CONCRETE OFF or
as a last resort, a CONCRETE format for one or more SOAP services is represented as a
SimpleDataset. Examining the WSDL, a SimpleDataset is composed of an array of rows, which is
composed of an array of any number of columns. This is not an ideal representation because the
specific column names and data types are not specified. It is recommended that SOAP services define
a call to a stored procedure that, in turn, defines a RESULT clause. A DISH service exposing SOAP
services defined in this way can fully describe the result set when generating the WSDL.

By default, EXPLICIT ON is assumed and the WSDL contains a specific Dataset entry for each
SOAP service if the result set for a SOAP service can be described. Each entry name is prefixed by
the SOAP service name and an underscore. For example, a SOAP service named test produces a
test_Dataset object specification containing the XMLSchema definitions for each of its column
elements.

When EXPLICIT ON is specified (default), the WSDL describes an explicit DataSet element when
the following criteria are met:

438 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

● The CREATE SERVICE statement calls a stored procedure

● A RESULT clause describing the columns and data types is specified in the stored procedure

When EXPLICIT OFF is specified, the WSDL describes the SimpleDataset element. This
description does not provide the number of columns, column names, or data types.

○ 'XML' The output is generated in an XMLSchema string format. The response is an XML document
that requires further processing by the SOAP client to extract column data. This format is suitable for
SOAP clients that cannot generate intermediate interface objects that represent arrays of rows and
columns.

○ NULL A NULL type causes the SOAP or DISH service to use the default behavior. The format type
of an existing service is overwritten when using the NULL type in an ALTER SERVICE statement.

AUTHORIZATION clause Determines whether users must specify a user name and password through
basic HTTP authorization when connecting to the service. The default value is ON. If authorization is
OFF, the AS clause is required for SOAP services, and a user must be specified with the USER clause.
All requests are run using that user's account and permissions. If AUTHORIZATION is ON, all users
must provide a user name and password. Optionally, you can limit the users that are permitted to use the
service by providing a user or group name with the USER clause. If the user name is NULL, all known
users can access the service. The AUTHORIZATION clause allows your web services to use database
authorization and permissions to control access to the data in your database.

When the authorization value is ON, an HTTP client connecting to a web service uses basic
authentication (RFC 2617) which obfuscates the user and password information using base-64 encoding.
It is recommended that you use the HTTPS protocol for increased security.

ENABLE and DISABLE clauses Determines whether the service is available for use. By default,
when a service is created, it is enabled. When creating or altering a service, you may include an ENABLE
or DISABLE clause. Disabling a service effectively takes the service off line. Later, it can be enabled
using ALTER SERVICE with the ENABLE clause. An HTTP request made to a disabled service
typically returns a 404 Not Found HTTP status.

METHODS clause Specifies the HTTP methods that are supported by the service. Valid values are
DEFAULT, POST, GET, HEAD, and NONE. An asterisk (*) may be used as a short form to represent the
POST, GET, and HEAD methods. The default method types for SOAP services are POST and HEAD.
The default method types for DISH services are GET, POST, and HEAD. Not all HTTP methods are
valid for all the service types. The following table summarizes the valid HTTP methods that can be
applied to each service type:

Method value Applies to service Description

DEFAULT both Use DEFAULT to reset the set of default


HTTP methods for the given service type.
It cannot be included in a list with other
method values.

POST both Enabled by default for SOAP.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 439


SQL statements

Method value Applies to service Description

GET DISH only Enabled by default for DISH.

HEAD both Enabled by default for SOAP and DISH.

NONE both Use NONE to disable access to a service.


When applied to a SOAP service, the
service cannot be directly accessed by a
SOAP request. This enforce exclusive ac-
cess to a SOAP operation through a DISH
service SOAP endpoint.

It is recommended that you specify


METHOD NONE for each SOAP service.

* DISH only Same as specifying 'POST,GET,HEAD'.

For example, you can use the following clause to specify that a service supports all SOAP over HTTP
method types:

METHODS 'POST,HEAD'

To reset the list of request types for any service type to its default, you can use the following clause:

METHODS 'DEFAULT'

SECURE clause Specifies whether the service should be accessible on a secure or non-secure listener.
ON indicates that only HTTPS connections are accepted, and that connections received on the HTTP port
are automatically redirected to the HTTPS port. OFF indicates that both HTTP and HTTPS connections
are accepted, provided that the necessary ports are specified when starting the web server. The default
value is OFF.

USER clause Specifies a database user, or group of users, with permissions to execute the web service
request. A USER clause must be specified when the service is configured with AUTHORIZATION OFF
and should be specified with AUTHORIZATION ON (the default). An HTTP request made to a service
requiring authorization results in a 401 Authorization Required HTTP response status. Based
on this response, the web browser prompts for a user ID and password.

Caution
It is strongly recommended that you specify a USER clause when authorization is enabled (the default).
Otherwise, authorization is granted to all users.

The USER clause controls which database user accounts can be used to process service requests. Database
access permissions are restricted to the privileges assigned to the user of the service.

statement Specifies a command, such as a stored procedure call, to invoke when the service is
accessed.

440 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

A DISH service is the only service that must either define a null statement, or not define a statement. A
SOAP service must define a statement. Any other SERVICE can have a NULL statement, but only if it is
configured with AUTHORIZATION ON.

An HTTP request to a non-DISH service with no statement specifies the SQL expression to execute
within its URL. Although authorization is required, this capability should not be used in production
systems because it makes the server vulnerable to SQL injections. When a statement is defined within the
service, the specified SQL statement is the only statement that can be executed through the service.

In a typical web service application, you use statement to call a function or procedure. You can pass host
variables as parameters to access client-supplied HTTP variables.

The following statement demonstrates a procedure call that passes two host variables to a procedure
named AuthenticateUser. This call presumes that a web client supplies the user_name and
user_password variables:
CALL AuthenticateUser ( :user_name, :user_password );

For more information about passing host variables to a function or procedure, see “Accessing client-
supplied HTTP variables and headers” [SQL Anywhere Server - Programming].

Remarks
The ALTER SERVICE statement modifies the attributes of a web service.

Permissions
DBA authority

Side effects
None.

See also
● “CREATE SERVICE statement [SOAP web service]” on page 611
● “DROP SERVICE statement” on page 704
● “Tutorial: Using SQL Anywhere to access a SOAP/DISH service” [SQL Anywhere Server -
Programming]
● “SYSWEBSERVICE system view” on page 1259
● “-xs dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “SQL Anywhere as an HTTP web server” [SQL Anywhere Server - Programming]
● “Creating and customizing a root web service” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example demonstrates how to disable an existing web service using the ALTER SERVICE
statement:
CREATE SERVICE WebServiceTable
TYPE 'SOAP'

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 441


SQL statements

AUTHORIZATION OFF
USER DBA
AS SELECT *
FROM SYS.SYSTAB;

ALTER SERVICE WebServiceTable DISABLE;

ALTER SPATIAL REFERENCE SYSTEM statement


Changes the settings of an existing spatial reference system. See the Remarks section for considerations
before altering a spatial reference system.

Syntax
ALTER SPATIAL REFERENCE SYSTEM
srs-name=
[ srs-attribute [ srs-attribute ... ]

srs-name : string

srs-attribute :
SRID srs-id
| DEFINITION { definition-string | NULL }
| ORGANIZATION { organization-name IDENTIFIED BY organization-srs-id | NULL }
| TRANSFORM DEFINITION { transform-definition-string | NULL }
| LINEAR UNIT OF MEASURE linear-unit-name
| ANGULAR UNIT OF MEASURE { angular-unit-name | NULL }
| TYPE { ROUND EARTH | PLANAR }
| COORDINATE coordinate-name { UNBOUNDED | BETWEEN low-number AND high-number }
| ELLIPSOID SEMI MAJOR AXIS semi-major-axis-length { SEMI MINOR AXIS semi-minor-axis-length |
INVERSE FLATTENING inverse-flattening-ratio }
| SNAP TO GRID { grid-size | DEFAULT }
| TOLERANCE { tolerance-distance | DEFAULT }
| POLYGON FORMAT polygon-format
| STORAGE FORMAT storage-format

srs-id : integer

semi-major-axis-length : number

semi-minor-axis-length : number

inverse-flattening-ratio : number

grid-size : DOUBLE : usually between 0 and 1

tolerance-distance : number

axis-order : { 'x/y/z/m' | 'long/lat/z/m' | 'lat/long/z/m' }

polygon-format : { 'CounterClockWise' | 'Clockwise' | 'EvenOdd' }

storage-format : { 'Internal' | 'Original' | 'Mixed' }

442 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Parameters
Complete definitions for each of the clauses is provided in the CREATE SPATIAL REFERENCE
SYSTEM statement.

IDENTIFIED BY clause Use this clause to change the SRID number for the spatial reference system.

DEFINITION clause Use this clause to set, or override, default coordinate system settings.

ORGANIZATION clause Use this clause to specify information about the organization that created the
spatial reference system that the spatial reference system is based on.

TRANSFORM DEFINITION clause Use this clause to specify a description of the transform to use for
the spatial reference system. Currently, only the PROJ.4 transform is supported.

The transform definition is used by the ST_Transform method when transforming data between spatial
reference systems. Some transforms may still be possible even if there is no transform-definition-string
defined.

COORDINATE clause Use this clause to specify the bounds on the spatial reference system's
dimensions. coordinate-name is the name of the coordinate system used by the spatial reference system.
For non-geographic types coordinate-name can be x, y, or m. For geographic types, coordinate-name can
be LATITUDE, LONGITUDE, z, or m.

LINEAR UNIT OF MEASURE clause Use this clause to specify the linear unit of measure for the
spatial reference system. The value you specify must match a linear unit of measure defined in the
ST_UNITS_OF_MEASURE system view.

ANGULAR UNIT OF MEASURE clause Use this clause to specify the angular unit of measure for the
spatial reference system. The value you specify must match an angular unit of measure defined in the
ST_UNITS_OF_MEASURE system table.

TYPE clause Use the TYPE clause to control how the spatial reference system interprets lines between
points. For geographic spatial reference systems, the TYPE clause can specify either ROUND EARTH
(the default) or PLANAR. For non-geographic spatial reference systems, the type must be PLANAR.

ELLIPSOID clause Use the ellipsoid clause to specify the values to use for representing the Earth as
an ellipsoid for spatial reference systems of type ROUND EARTH. If the DEFINITION clause is present,
it can specify ellipsoid definition. If the ELLIPSOID clause is specified, it overrides this default ellipsoid.

SNAP TO GRID clause For flat-Earth (planar) spatial reference systems, use the SNAP TO GRID
clause to define the size of the grid SQL Anywhere uses when performing calculations. Specify SNAP
TO GRID DEFAULT to set the grid size to the default that the database server would use.

For round-Earth spatial reference systems, SNAP TO GRID must be set to 0.

TOLERANCE clause For flat-Earth (planar) spatial reference systems, use the TOLERANCE clause
to specify the precision to use when comparing points.

For round-Earth spatial reference systems, TOLERANCE must be set to 0.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 443


SQL statements

POLYGON FORMAT clause Use the POLYGON FORMAT clause to change the polygon
interpretation. The following values are supported:

○ 'CounterClockwise'
○ 'Clockwise'
○ 'EvenOdd'

The default polygon format is 'EvenOdd'.

STORAGE FORMAT clause Use the STORAGE FORMAT clause to control what is stored when
spatial data is loaded into the database. Possible values are:

○ 'Internal' SQL Anywhere stores only the normalized representation. Specify this when the original
input characteristics do not need to be reproduced. This is the default for planar spatial reference
systems (TYPE PLANAR).

Note
If you are using MobiLink to synchronize your spatial data, you should specify Mixed instead.
MobiLink tests for equality during synchronization, which requires the data in its original format.

○ 'Original' SQL Anywhere stores only the original representation. The original input characteristics
can be reproduced, but all operations on the stored values must repeat normalization steps, possibly
slowing down operations on the data.

○ 'Mixed' SQL Anywhere stores the internal version and, if it is different from the original version,
SQL Anywhere stores the original version as well. By storing both versions, the original
representation characteristics can be reproduced and operations on stored values do not need to repeat
normalization steps. However, storage requirements may increase significantly because potentially
two representations are being stored for each geometry.

Mixed is the default format for round-Earth spatial reference systems (TYPE ROUND EARTH).

Remarks
You cannot alter a spatial reference system if there is existing data that references it. For example, if you
have a column declared as ST_Point(SRID=8743), you cannot alter the spatial reference system with
SRID 8743. This is because many spatial reference system attributes, such as storage format, impact the
storage format of the data. If you have data that references the SRID, create a new spatial reference
system and transform the data to the new SRID.

Permissions
Must have DBA authority or be a member of the SYS_SPATIAL_ADMIN_ROLE group.

Side effects
None

444 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “CREATE SPATIAL REFERENCE SYSTEM statement” on page 616
● “DROP SPATIAL REFERENCE SYSTEM statement” on page 704
● “Using spatial data” [SQL Anywhere Server - Spatial Data Support]
● “ST_Transform method for type ST_Geometry” [SQL Anywhere Server - Spatial Data Support]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example changes the polygon format of a fictitious spatial reference system named
mySpatialRef to EvenOdd.
ALTER SPATIAL REFERENCE SYSTEM mySpatialRef
POLYGON FORMAT 'EvenOdd';

ALTER STATISTICS statement


Controls whether statistics are automatically updated on a column, or columns, in a table.

Syntax
ALTER STATISTICS
[ ON ] table [ ( column1 [ , column2 ... ] ) ]
AUTO UPDATE { ENABLE | DISABLE }

Parameters
ON The word ON is optional. Including it has no impact on the execution of the statement.

AUTO UPDATE clause Specify whether to enable or disable automatic updating of statistics for the
column(s).

Remarks
During normal execution of queries, DML statements, and LOAD TABLE statements, the database server
automatically maintains column statistics for use by the optimizer. The benefit of maintaining statistics
for some columns may not outweigh the overhead necessary to generate them. For example, if a column is
not queried often, or if it is subject to periodic mass changes that are eventually rolled back, there is little
value in continually updating its statistics. Use the ALTER STATISTICS statement to suppress the
automatic updating of statistics for these types of columns.

When automatic updating is disabled, you can still update the statistics for the column using the CREATE
STATISTICS and DROP STATISTICS statements. However, you should only update them if it has been
determined that it would have a positive impact on performance. Normally, column statistics should not
be disabled.

Permissions
DBA authority

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 445


SQL statements

Side effects
If automatic updating has been disabled, the statistics may become out of date. Re-enabling does not
immediately bring them up to date. Execute the CREATE STATISTICS statement to recreate them, if
necessary.

See also
● “CREATE STATISTICS statement” on page 625
● “DROP STATISTICS statement” on page 706

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example disables the automatic updating of statistics on the Street column in the Customers
table:
ALTER STATISTICS Customers ( Street ) AUTO UPDATE DISABLE;

ALTER SYNCHRONIZATION PROFILE statement


[MobiLink]
Changes a SQL Anywhere synchronization profile. Synchronization profiles are named collections of
synchronization options that can be used to control synchronization.

Syntax
ALTER SYNCHRONIZATION PROFILE name
MERGE string

Parameters
name The name of the synchronization profile to alter.

MERGE clause Use this clause to change existing, or add new, options to a synchronization profile.

string A string of one or more synchronization option value pairs, separated by semicolons. For
example, 'option1=value1;option2=value2'.

Remarks
Synchronization profiles define how a SQL Anywhere database synchronizes with the MobiLink server.

When MERGE is used in the ALTER SYNCHRONIZATION PROFILE statement, options specified in
the string are added to those already in the synchronization profile. If an option in the string already exists
in profile, then the value from the string replaces the value already stored in the profile.

For example, executing the following statements leaves the profile myProfile with the value
subscription=s2;verbosity=high;uploadonly=on.

446 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE SYNCHRONIZATION PROFILE myProfile 'subscription=p1;verbosity=high';


ALTER SYNCHRONIZATION PROFILE myProfile MERGE
'subscription=p2;uploadonly=on';

When setting extended options, use the following syntax:


ALTER SYNCHRONIZATION PROFILE myprofile MERGE
's=mysub;e={ctp=tcpip;adr=''host=localhost;port=2439''}';

Permissions
DBA authority.

Side effects
Automatic commit.

See also
● “CREATE SYNCHRONIZATION PROFILE statement [MobiLink]” on page 628
● “DROP SYNCHRONIZATION PROFILE statement [MobiLink]” on page 709

Standards and compatibility


● SQL/2008 Vendor extension.

ALTER SYNCHRONIZATION SUBSCRIPTION statement


[MobiLink]
Alters the properties of a synchronization subscription in a SQL Anywhere remote database.

Syntax
ALTER SYNCHRONIZATION SUBSCRIPTION
{ subscription-name | TO publication-name [ FOR ml-username, ... ] }

alter-clause :
RENAME new-subscription-name
| TYPE network-protocol
| ADDRESS protocol-options
| ADD OPTION option=value, ...
| ALTER OPTION option=value, ...
| DELETE { ALL OPTION | OPTION option, ... }
| SET SCRIPT VERSION=script-version

subscription-name : identifier

publication-name : identifier

ml-username : identifier

new-subscription-name : identifier

network-protocol : http | https | tls | tcpip

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 447


SQL statements

protocol-options : string

value : string | integer

option : identifier

script-version : string

Parameters
TO clause This clause specifies the name of a publication.

If the TO clause is used without a FOR clause, you cannot use the RENAME or SET SCRIPT VERSION
clauses.

FOR clause This clause specifies one or more MobiLink user names.

Omit the FOR clause to set the protocol type, protocol options, and extended options for a publication.

If the TO clause is used without a FOR clause, you cannot use the RENAME or SET SCRIPT VERSION
clauses.

RENAME clause This clause specifies a new name for the subscription.

If the TO clause is used without a FOR clause, you cannot use the RENAME clause.

TYPE clause This clause specifies the network protocol to use for synchronization. The default
protocol is tcpip.

ADDRESS clause This clause specifies network protocol options, including the location of the
MobiLink server.

Cloud note: You can specify NULL for the protocol-option value for cloud tenant databases.

ADD OPTION, ALTER OPTION, DELETE OPTION, and DELETE ALL OPTION clauses These
clauses allow you to add, alter, delete, or delete all extended options. You can specify only one option in
each clause. No option is specified for Delete All.

The values for each option cannot contain the characters " = " or " , " or " ; ".

SET SCRIPT VERSION clause This clause specifies the script version to use during synchronization.
You can alter the script version without making a schema change.

If the TO clause is used without a FOR clause, you cannot use the SET SCRIPT VERSION clause.

Cloud note: You can specify NULL for the script-version value for cloud tenant databases.

448 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
The network-protocol, protocol-options, and options can be set in several places.

This statement causes options and other information to be stored in the SQL Anywhere ISYSSYNC
system table. Anyone with DBA authority for the database can view the information, which could include
passwords and encryption certificates. To avoid this potential security issue, you can specify the
information on the dbmlsync command line.

Permissions
DBA authority and exclusive access to all tables referred to in the publication.

Side effects
Automatic commit.

See also
● “CREATE PUBLICATION statement [MobiLink] [SQL Remote]” on page 592
● “DROP PUBLICATION statement [MobiLink] [SQL Remote]” on page 701
● “CREATE SYNCHRONIZATION SUBSCRIPTION statement [MobiLink]” on page 629
● SQL Anywhere MobiLink clients: “Synchronization subscription creation” [MobiLink - Client
Administration]
● UltraLite MobiLink clients: “UltraLite client synchronization design” [UltraLite - Database
Management and Reference]
● “ISYSSYNC system table” on page 976
● “MobiLink client network protocol options” [MobiLink - Client Administration]
● “MobiLink SQL Anywhere client extended options” [MobiLink - Client Administration]
● “CommunicationType (ctp) extended option” [MobiLink - Client Administration]
● “dbmlsync syntax” [MobiLink - Client Administration]
● “Priority order” [MobiLink - Client Administration]
● “Script versions” [MobiLink - Server Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example changes the address of the MobiLink server for the sales subscription:
ALTER SYNCHRONIZATION SUBSCRIPTION sales
TYPE TCPIP
ADDRESS 'host=10.11.12.132;port=2439';

ALTER SYNCHRONIZATION USER statement [MobiLink]


Alters the properties of a MobiLink user in a SQL Anywhere remote database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 449


SQL statements

Syntax
ALTER SYNCHRONIZATION USER ml-username
[ TYPE network-protocol ]
[ ADDRESS protocol-options ]
[ ADD OPTION option=value, ... ]
[ ALTER OPTION option=value, ... ]
[ DELETE { ALL OPTION | OPTION option } ]

ml-username : identifier

network-protocol : http | https | tls | tcpip

protocol-options : string

value : string | integer

Parameters
TYPE clause This clause specifies the network protocol to use for synchronization. The default
protocol is tcpip.

ADDRESS clause This clause specifies protocol-options in the form keyword=value, separated by
semicolons. Which settings you supply depends on the communication protocol you are using (TCP/IP,
TLS, HTTP, or HTTPS).

Cloud note: You can specify NULL for the protocol-option value for cloud tenant databases.

ADD OPTION, ALTER OPTION, DELETE OPTION, and DELETE ALL OPTION clauses These
clauses allow you to add, modify, delete, or delete all extended options. You may specify only one option
in each clause. No option is specified for Delete All.

Remarks
The network-protocol, protocol-options, and options can be set in several places.

This statement causes options and other information to be stored in the SQL Anywhere ISYSSYNC
system table. Anyone with DBA authority for the database can view the information, which could include
passwords and encryption certificates. To avoid this potential security issue, you can specify the
information on the dbmlsync command line.

Permissions
DBA authority. Requires exclusive access to all tables referred to in the publication.

Side effects
Automatic commit.

450 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “dbmlsync syntax” [MobiLink - Client Administration]
● “CREATE SYNCHRONIZATION USER statement [MobiLink]” on page 631
● “CommunicationType (ctp) extended option” [MobiLink - Client Administration]
● “DROP SYNCHRONIZATION USER statement [MobiLink]” on page 710
● “MobiLink users” [MobiLink - Client Administration]
● “ISYSSYNC system table” on page 976
● “MobiLink SQL Anywhere client extended options” [MobiLink - Client Administration]
● “Priority order” [MobiLink - Client Administration]
● “MobiLink client network protocol options” [MobiLink - Client Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

ALTER TABLE statement


Modifies a table definition or disables dependent views.

Syntax 1 - Altering an existing table


ALTER TABLE [owner.]table-name { alter-clause, ... }

alter-clause :
ADD create-clause
| ALTER column-name column-alteration
| ALTER [ CONSTRAINT constraint-name ] CHECK ( condition )
| DROP drop-object
| RENAME rename-object
| table-alteration

create-clause :
column-name [ AS ] column-data-type [ new-column-attribute ... ]
| table-constraint
| PCTFREE integer

column-alteration :
{ column-data-type | alterable-column-attribute } [ alterable-column-attribute ... ]
| SET COMPUTE ( compute-expression )
| ADD [ constraint-name ] CHECK ( condition )
| DROP { DEFAULT | COMPUTE | CHECK | CONSTRAINT constraint-name }

drop-object :
column-name
| CHECK
| CONSTRAINT constraint-name
| UNIQUE [ CLUSTERED ] ( index-columns-list )
| FOREIGN KEY fkey-name
| PRIMARY KEY

rename-object :
new-table-name

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 451


SQL statements

| column-name TO new-column-name
| CONSTRAINT constraint-name TO new-constraint-name

table-alteration :
PCTFREE DEFAULT
| [ NOT ] ENCRYPTED

new-column-attribute :
[ NOT ] NULL
| DEFAULT default-value
| COMPRESSED
| INLINE { inline-length | USE DEFAULT }
| PREFIX { prefix-length | USE DEFAULT }
| [ NO ] INDEX
| IDENTITY
| COMPUTE ( expression )
| column-constraint

table-constraint :
[ CONSTRAINT constraint-name ] {
CHECK ( condition )
| UNIQUE [ CLUSTERED | NONCLUSTERED ] ( column-name [ ASC | DESC ], ... )
| PRIMARY KEY [ CLUSTERED | NONCLUSTERED ] ( column-name [ ASC | DESC ], ... )
| foreign-key
}

column-constraint :
[ CONSTRAINT constraint-name ] {
CHECK ( condition )
| UNIQUE [ CLUSTERED | NONCLUSTERED ] [ ASC | DESC ]
| PRIMARY KEY [ CLUSTERED | NONCLUSTERED ] [ ASC | DESC ]
| REFERENCES table-name [ ( column-name ) ]
[ MATCH [ UNIQUE ] { SIMPLE | FULL } ]
[ actions ][ CLUSTERED | NONCLUSTERED ]
| NOT NULL
}

alterable-column-attribute :
[ NOT ] NULL
| DEFAULT default-value
| [ CONSTRAINT constraint-name ] CHECK { NULL | ( condition ) }
| [ NOT ] COMPRESSED
| INLINE { inline-length | USE DEFAULT }
| PREFIX { prefix-length | USE DEFAULT }
| [ NO ] INDEX

default-value :
special-value
| string
| global variable
| [ - ] number
| ( constant-expression )
| ( sequence-expression )
| built-in-function( constant-expression )
| AUTOINCREMENT
| GLOBAL AUTOINCREMENT [ ( partition-size ) ]

452 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

special-value :
CURRENT DATABASE
| CURRENT DATE
| CURRENT TIME
| [ CURRENT ] TIMESTAMP
| CURRENT PUBLISHER
| CURRENT REMOTE USER
| [ CURRENT ] USER
| [ CURRENT ] UTC TIMESTAMP
| LAST USER
| NULL

foreign-key :
[ NOT NULL ] FOREIGN KEY [ role-name ]
[ ( column-name [ ASC | DESC ], ... )
REFERENCES table-name
[ ( pkey-column-list ) ]
[ MATCH [ UNIQUE] { SIMPLE | FULL } ]
[ actions ] [ CHECK ON COMMIT ] [ CLUSTERED ]
[ FOR OLAP WORKLOAD ]

actions :
[ ON UPDATE action ] [ ON DELETE action ]

action :
CASCADE | SET NULL | SET DEFAULT | RESTRICT

Syntax 2 - Disabling view dependencies


ALTER TABLE [owner.]table-name {
DISABLE VIEW DEPENDENCIES
}

Parameters
Adding clauses The following section explains the clauses used for adding columns or table
constraints to a table:

ADD column-name [ AS ] column-data-type [ new-column-attribute ... ] clause Use this clause


to add a new column to the table, specifying the data type and attributes for the column.

NULL and NOT NULL clauses Use this clause to specify whether to allow NULLs in the column. By
default, new columns allow NULL values. BIT type columns automatically have the NOT NULL
constraint applied when they are created, but you can declare a BIT type column to be nullable.

DEFAULT clause 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 value is specified, it is
equivalent to DEFAULT NULL.

Following is a list of possible values for DEFAULT:

● special-value You use one of several specials values in the DEFAULT clause.

● [ CURRENT ] 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 of day whenever the row is updated.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 453


SQL statements

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.

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.

You can automatically truncate TIMESTAMP values in SQL Anywhere based on the
default_timestamp_increment option. This is useful for maintaining compatibility with other database
software that records less precise timestamp values.

The global variable @@dbts returns a TIMESTAMP value representing the last value generated for a
column using DEFAULT TIMESTAMP.

● [ CURRENT ] UTC TIMESTAMP Provides a way of indicating when each row in the table was last
modified. When a column is declared with DEFAULT UTC TIMESTAMP, a default value is
provided for inserts, and the value is updated with the current Coordinated Universal Time (UTC)
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 UTC TIMESTAMP instead of DEFAULT UTC TIMESTAMP.

The behavior of this default is the same as TIMESTAMP and CURRENT TIMESTAMP except that
the date and time of day is in Coordinated Universal Time (UTC).

● string See “Strings” on page 5.

● global-variable See “Global variables” on page 75.

● constant-expression 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.

● sequence-expression You can set DEFAULT to the current value or next value from a sequence
in the database.

● AUTOINCREMENT When using AUTOINCREMENT, the column must be one of the integer data
types, or an exact numeric type.

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 that is larger than the current maximum value for the column, that value is inserted and then
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 column
value less than the maximum, subsequent rows without explicit assignment are still automatically
incremented with a value of one greater than the previous maximum.

You can find the most recently inserted value of the column by inspecting the @@identity global
variable.

454 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

AUTOINCREMENT values are maintained as signed 64-bit integers, corresponding to the data type
of the max_identity column in the SYSTABCOL system view. When the next value to be generated
exceeds the maximum value that can be stored in the column to which the AUTOINCREMENT is
assigned, NULL is returned. If the column has been declared to not allow NULLs, as is true for
primary key columns, a SQL error is generated.

The next value to use for a column can be reset using the sa_reset_identity procedure.

● GLOBAL AUTOINCREMENT This default is intended for use when multiple databases are used in
a MobiLink synchronization environment or SQL Remote replication.

This option is similar to AUTOINCREMENT, except that the domain is partitioned. Each partition
contains the same number of values. You assign each copy of the database a unique global database
identification number. SQL Anywhere supplies default values in a database only from the partition
uniquely identified by that database's number.

The partition size can be specified in parentheses immediately following the AUTOINCREMENT
keyword. The partition size can 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 232 =
4294967296; for columns of all other types, the default partition size is 216 = 65536. Since these
defaults may be inappropriate, especially if your column is not of type INT or BIGINT, it is best to
specify the partition size explicitly.

When using this default, the value of the public option global_database_id in each database must be
set to a unique, non-negative integer. This value uniquely identifies the database and indicates from
which partition default values are to be assigned. The range of allowed values is np + 1 to p(n + 1),
where n is the value of the public option global_database_id and p is the partition size. For example, if
you define the partition size to be 1000 and set global_database_id to 3, then the range is from 3001 to
4000.

If the previous value is less than p(n + 1), the next default value is one greater than the previous
largest value in the column. If the column contains no values, the first default value is np + 1. Default
column values are not affected by values in the column outside the current partition; that is, by
numbers less than np + 1 or greater than p(n + 1). Such values may be present if they have been
replicated from another database via MobiLink or SQL Remote.

You can find the most recently inserted value of the column by inspecting the @@identity global
variable.

GLOBAL AUTOINCREMENT values are maintained as signed 64-bit integers, corresponding to the
data type of the max_identity column in the SYSTABCOL system view. When the supply of values
within the partition has been exhausted, NULL is returned. If the column has been declared to not
allow NULLs, as is true for primary key columns, a SQL error is generated. 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. To detect that the supply of unused values is low and handle this condition, create an
event of type GlobalAutoincrement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 455


SQL statements

Because the public option global_database_id cannot be set to a negative value, the values chosen are
always positive. The maximum identification number is restricted only by the column data type and
the partition size.

If the public option global_database_id is set to the default value of 2147483647, a NULL value is
inserted into the column. If NULL values are not permitted, attempting to insert the row causes an
error.

The next value to use for a column can be reset using the sa_reset_identity procedure.

● LAST USER LAST USER is the user ID of the user who last modified the row.

LAST USER can be used as a default value in columns with character data types.

On INSERT, this default has the same effect as CURRENT USER.

On UPDATE, if a column with a default of LAST USER is not explicitly modified, it is changed to
the name of the current user.

When used in conjunction with DEFAULT TIMESTAMP or DEFAULT UTC TIMESTAMP, a


default of LAST USER can be used to record (in separate columns) both the user and the date and
time a row was last changed.

column-constraint clause Use this clause to add a constraint to the column. With the exception of
CHECK constraints, when a new constraint is added, the database server validates existing values to
confirm that they satisfy the constraint. CHECK constraints are enforced only for operations that occur
after the table alteration is complete. Possible column constraints include:

● CHECK clause This constraint 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.

If you need to create a CHECK constraint that involves a relationship between two or more columns
in the table (for example, column A must be less than column B), define a table constraint instead.

● UNIQUE clause Use this subclause to specify that values in the column must be unique, and
whether to create a clustered or nonclustered index.

● PRIMARY KEY clause Use this subclause to make the column a primary key, and specify whether
to use a clustered index.

● REFERENCES clause Use this subclause to add or alter a reference to another table, to specify
how matches are handled, and to specify whether to use a clustered index.

● MATCH clause Use this subclause to control what is considered a match when using a multi-
column foreign key. It also allows you to specify uniqueness for the key, thereby eliminating the need
to declare uniqueness separately.

● NULL and NOT NULL clauses Use this clause to specify whether to allow NULL values in the
column. By default, NULLs are allowed.

COMPRESSED clause Use this clause to compress the column.

456 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

INLINE and PREFIX clauses The INLINE clause specifies the maximum BLOB size, in bytes, to
store within the row. BLOBs smaller than or equal to the value specified by the INLINE clause are stored
within the row. BLOBs that exceed the value specified by the INLINE clause are stored outside the row in
table extension pages. Also, a copy of some bytes from the beginning of the BLOB may be kept in the
row when a BLOB is larger than the INLINE value. Use the PREFIX clause to specify how many bytes
are kept in the row. The PREFIX clause can improve the performance of requests that need the prefix
bytes of a BLOB to determine if a row is accepted or rejected.

The prefix data for a compressed column is stored uncompressed, so if all the data required to satisfy a
request is stored in the prefix, no decompression is necessary.

If neither INLINE nor PREFIX is specified, or if USE DEFAULT is specified, default values are applied
as follows:

● For character data type columns, such as CHAR, NCHAR, and LONG VARCHAR, the default value
of INLINE is 256, and the default value of PREFIX is 8.

● For binary data type columns, such as BINARY, LONG BINARY, VARBINARY, BIT, VARBIT,
LONG VARBIT, BIT VARYING, and UUID, the default value of INLINE is 256, and the default
value of PREFIX is 0.

Note
It is strongly recommended that you use the default values unless there are specific circumstances that
require a different setting. The default values have been chosen to balance performance and disk space
requirements. For example, if you set INLINE to a large value, and all the BLOBs are stored inline,
row processing performance may degrade. If you set PREFIX too high, you increase the amount of disk
space required to store BLOBs since the prefix data is a duplicate of a portion of the BLOB.

If only one of the values is specified, the other value is automatically set to the largest amount that does
not conflict with the specified value. Neither the INLINE nor PREFIX value can exceed the database
page size. Also, there is a small amount of overhead reserved in a table page that cannot be used to
store row data. Therefore, specifying an INLINE value approximate to the database page size can result
in a slightly smaller number of bytes being stored inline.

INDEX and NO INDEX clauses When storing BLOBs (character or binary types only), specify
INDEX to create BLOB indexes on inserted values that exceed the internal BLOB size threshold
(approximately eight database pages). This is the default behavior.

BLOB indexes can improve performance when random access searches within the BLOBs are required.
However, for some types of BLOB values, such as images and multimedia files that will never require
random-access, performance can improve if BLOB indexing is turned off. To turn off BLOB indexing for
a column, specify NO INDEX.

Note
A BLOB index is not the same as a table index. A table index is created to index values in one or more
columns.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 457


SQL statements

IDENTITY is a Transact-SQL-compatible alternative to using DEFAULT


IDENTITY clause
AUTOINCREMENT. In SQL Anywhere, a column defined with IDENTITY is implemented as
DEFAULT AUTOINCREMENT.

COMPUTE clause When a column is created using a COMPUTE clause, 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 whenever the row is modified. The COMPUTE
expression should not return a non-deterministic value. For example, it should not include a special value
such as CURRENT TIMESTAMP, or a non-deterministic function. If a COMPUTE expression returns a
non-deterministic value, then it cannot be used to match an expression in a query.

The COMPUTE clause is ignored for remote tables.

Any UPDATE statement that attempts to change the value of a computed column fires any triggers
associated with the column.

ADD table-constraint clause Use this clause to add a table constraint. Table constraints place limits
on what data columns in the table can hold. When adding or altering table constraints, the optional
constraint name allows you to modify or drop individual constraints. Following is a list of the table
constraints you can add.

● UNIQUE Use this subclause to specify that values in the columns specified in column-list must be
unique, and, optionally, whether to use a clustered index.

● PRIMARY KEY Use this subclause to add or alter the primary key for the table, and specify
whether to use a clustered index. The table must not already have a primary key that was created by
the CREATE TABLE statement or another ALTER TABLE statement.

● foreign-key Use this subclause to add a foreign key as a constraint. If you use a subclause other
than ADD FOREIGN KEY with the ALTER TABLE statement on a table with dependent
materialized views, the ALTER TABLE statement fails. For all other clauses, you must disable the
dependent materialized views and then re-enable them when your changes are complete.

You can specify a MATCH subclause to control what is considered a match when using a multi-
column foreign key. It also allows you to specify uniqueness for the key, thereby eliminating the need
to declare uniqueness separately.

ADD PCTFREE clause Specify the percentage of free space you want to reserve in each table page.
The free space is used if rows increase in size when the data is updated. If there is no free space in a table
page, every increase in the size of a row on that page requires the row to be split across multiple table
pages, causing row fragmentation and possible performance degradation. A free space percentage of 0
specifies that no free space is to be left on each page—each page is to be fully packed. A high free space
percentage causes each row to be inserted into a page by itself. If PCTFREE is not set, or is dropped, the
default PCTFREE value is applied according to the database page size (200 bytes for a 4 KB or larger
page size). The value for PCTFREE is stored in the ISYSTAB system table. When PCTFREE is set, all
subsequent inserts into table pages use the new value, but rows that were already inserted are not affected.
The value persists until it is changed. The PCTFREE specification can be used for base, global temporary,
or local temporary tables.

458 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Altering clauses The following section explains the clauses used for altering the definition for a
column or table:

ALTER column-name column-alteration clause Use this clause to change attributes for the
specified column. If a column is contained in a unique constraint, a foreign key, or a primary key, you can
change only the default for the column. However, for any other change, you must delete the key or
constraint before the column can be modified.

column-data-type clause Use this clause to alter the length or data type of the column. If necessary,
the data in the modified column is converted to the new data type. If a conversion error occurs, the
operation will fail and the table is left unchanged. You cannot reduce the size of a column. For example,
you cannot change a column from a VARCHAR(100) to a VARCHAR(50).

[ NOT ] NULL clause Use this clause to change whether NULLs are allowed in the column. If NOT
NULL is specified, and the column value is NULL in any of the existing rows, then the operation fails
and the table is left unchanged.

CHECK NULL Use this clause to delete all check constraints for the column.

DEFAULT clause Use this clause to change the default value for the column.

DEFAULT NULL clause Use this clause to remove the default value for the column.

[ CONSTRAINT constraint-name ] CHECK { NULL | ( condition ) } clause Use this clause to add
a CHECK constraint on the column.

If you need to create a CHECK constraint that involves a relationship between two or more columns in
the table (for example, column A must be less than column B), define a table constraint instead.

[ NOT ] COMPRESSED clause Use this clause to change whether the column is compressed.

INLINE and PREFIX clauses The INLINE clause specifies the maximum BLOB size, in bytes, to
store within the row. BLOBs smaller than or equal to the value specified by the INLINE clause are stored
within the row. BLOBs that exceed the value specified by the INLINE clause are stored outside the row in
table extension pages. Also, a copy of some bytes from the beginning of the BLOB may be kept in the
row when a BLOB is larger than the INLINE value. Use the PREFIX clause to specify how many bytes
are kept in the row. The PREFIX clause can improve the performance of requests that need the prefix
bytes of a BLOB to determine if a row is accepted or rejected.

The prefix data for a compressed column is stored uncompressed, so if all the data required to satisfy a
request is stored in the prefix, no decompression is necessary.

If neither INLINE nor PREFIX is specified, or if USE DEFAULT is specified, default values are applied
as follows:

● For character data type columns, such as CHAR, NCHAR, and LONG VARCHAR, the default value
of INLINE is 256, and the default value of PREFIX is 8.

● For binary data type columns, such as BINARY, LONG BINARY, VARBINARY, BIT, VARBIT,
LONG VARBIT, BIT VARYING, and UUID, the default value of INLINE is 256, and the default
value of PREFIX is 0.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 459


SQL statements

Note
It is strongly recommended that you use the default values unless there are specific circumstances that
require a different setting. The default values have been chosen to balance performance and disk space
requirements. For example, if you set INLINE to a large value, and all the BLOBs are stored inline,
row processing performance may degrade. If you set PREFIX too high, you increase the amount of disk
space required to store BLOBs since the prefix data is a duplicate of a portion of the BLOB.

If only one of the values is specified, the other value is automatically set to the largest amount that does
not conflict with the specified value. Neither the INLINE nor PREFIX value can exceed the database
page size. Also, there is a small amount of overhead reserved in a table page that cannot be used to
store row data. Therefore, specifying an INLINE value approximate to the database page size can result
in a slightly smaller number of bytes being stored inline.

INDEX and NO INDEX clauses When storing BLOBs (character or binary types only), specify
INDEX to create BLOB indexes on inserted values that exceed the internal BLOB size threshold
(approximately eight database pages). This is the default behavior.

BLOB indexes can improve performance when random access searches within the BLOBs are required.
However, for some types of BLOB values, such as images and multimedia files that will never require
random-access, performance can improve if BLOB indexing is turned off. To turn off BLOB indexing for
a column, specify NO INDEX.

Note
A BLOB index is not the same as a table index. A table index is created to index values in one or more
columns.

SET COMPUTE clause When a column is created using a COMPUTE clause, 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 whenever the row is modified. The COMPUTE
expression should not return a non-deterministic value. For example, it should not include a special value
such as CURRENT TIMESTAMP, or a non-deterministic function. If a COMPUTE expression returns a
non-deterministic value, then it cannot be used to match an expression in a query.

The COMPUTE clause is ignored for remote tables.

Any UPDATE statement that attempts to change the value of a computed column fires any triggers
associated with the column.

ALTER CONSTRAINT constraint-name CHECK clause Use this clause to alter a named check
constraint for the table.

If you want to alter the constraint to specify a relationship between two or more columns in the table (for
example, column A must be less than column B), you must define a table constraint instead.

Dropping clauses The following section explains the DROP clauses:

DROP DEFAULT Drops the default value set for the table or specified column. Existing values do not
change.

460 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

DROP COMPUTE Removes the COMPUTE attribute for the specified column. This statement does
not change any existing values in the table.

DROP CHECK Drops all CHECK constraints for the table or specified column. DELETE CHECK is
also accepted.

DROP CONSTRAINT constraint-name Drops the named constraint for the table or specified
column. DELETE CONSTRAINT is also accepted.

DROP column-name Drops the specified column from the table. DELETE column-name is also
accepted. If the column is contained in any index, unique 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.

DROP UNIQUE ( column-name ... ) Drop the unique constraints on the specified column(s). Any
foreign keys referencing this unique constraint are also deleted. DELETE UNIQUE ( column-name ... ) is
also accepted.

DROP FOREIGN KEY fkey-name Drop the specified foreign key. DELETE FOREIGN KEY fkey-
name is also accepted.

DROP PRIMARY KEY Drop the primary key. All foreign keys referencing the primary key for this
table are also deleted. DELETE PRIMARY KEY is also accepted.

Renaming clauses The following section explains the clauses used for renaming parts of a column or
table definition:

RENAME new-table-name Change the name of the table to new-table-name. Any applications using
the old table name must be modified, as necessary.

RENAME column-name TO new-column-name Change the name of the column to the new-
column-name. Any applications using the old column name must be modified, as necessary.

RENAME CONSTRAINT constraint-name TO new-constraint-name Change the name of the


constraint to the new-constraint-name.

ALTER TABLE...RENAME CONSTRAINT constraint-name TO new-constraint-name, when used for


an RI constraint, only renames the constraint, not the underlying index or, if applicable, the foreign key
role name. If you want to rename the underlying index or the role name, use the ALTER INDEX
statement.

table-alteration clauses Use this clause to alter the following table attributes.

PCTFREE DEFAULT Use this clause to change the percent free setting for the table to the default (200
bytes for a 4 KB, and up, page size).

[ NOT ] ENCRYPTED Use this clause to change whether the table is encrypted. To encrypt a table,
table encryption must already be enabled on the database. The table is encrypted using the encryption key
and algorithm specified at database creation time.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 461


SQL statements

After encrypting a table, any data for that table that was in temporary files or the transaction log before
encryption still exists in unencrypted form. To address this, restart the database to remove the temporary
files. Run the Backup utility (dbbackup) with the -o option, or use the BACKUP statement, to back up the
transaction log and start a new one.

When table encryption is enabled, table pages for the encrypted table, associated index pages, temporary
file pages, and transaction log pages containing transactions on encrypted tables are encrypted.

DISABLE VIEW DEPENDENCIES clause Use this clause to disable dependent regular views.
Dependent materialized views are not disabled; you must disable each dependent materialized view by
executing an ALTER MATERIALIZED VIEW...DISABLE statement.

Remarks
The ALTER TABLE statement changes table attributes (column definitions, constraints, and so on) in an
existing table.

The database server keeps track of object dependencies in the database. Alterations to the schema of a
table may impact dependent views. Also, if there are materialized views that are dependent on the table
you are attempting to alter, you must first disable them using the ALTER MATERIALIZED
VIEW...DISABLE 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 database server does not process
other requests referencing the table while the statement is being processed.

If you alter a column that a text index defined as IMMEDIATE REFRESH is built on, the text index is
immediately rebuilt. If the text index is defined as AUTO REFRESH or MANUAL REFRESH, the text
index is rebuilt the next time it is refreshed.

When you execute an ALTER TABLE statement, the database server attempts to restore column
permissions on dependent views that are automatically recompiled. Permissions on columns that no
longer exist in the recompiled views are lost.

Permissions
Must be one of the following:

● The owner of the table.

● A user with DBA authority.

● A user who has been 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.

Cannot be used within a snapshot transaction.

462 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
Automatic commit.

A checkpoint is carried out at the beginning of the ALTER TABLE operation, and further checkpoints are
suspended until the ALTER operation completes.

Once you alter a column or table, any stored procedures, views, or other items that refer to the altered
column may no longer work.

If you change the declared length or type of a column, or drop a column, the statistics for that column are
dropped.

See also
● “Events” [SQL Anywhere Server - Database Administration]
● “sa_reset_identity system procedure” on page 1112
● “Choosing between sequences and AUTOINCREMENT values” [SQL Anywhere Server - SQL
Usage]
● “Reloading tables with AUTOINCREMENT columns” [SQL Anywhere 12 - Changes and Upgrading]
● “ALTER MATERIALIZED VIEW statement” on page 417
● “BACKUP statement” on page 477
● “ALTER INDEX statement” on page 413
● “CREATE TABLE statement” on page 633
● “DROP TABLE statement” on page 711
● “MATCH clause, CREATE TABLE statement” on page 641
● “Backup utility (dbbackup)” [SQL Anywhere Server - Database Administration]
● “SQL data types” on page 81
● “Table alteration” [SQL Anywhere Server - SQL Usage]
● “The special IDENTITY column” [SQL Anywhere Server - SQL Usage]
● “Special values” on page 58
● “Table and column constraints” [SQL Anywhere Server - SQL Usage]
● “Use of a sequence to generate unique values” [SQL Anywhere Server - SQL Usage]
● “allow_nulls_by_default option” [SQL Anywhere Server - Database Administration]
● “Enabling table encryption in the database” [SQL Anywhere Server - Database Administration]
● “Clustered indexes” [SQL Anywhere Server - SQL Usage]
● “View dependencies” [SQL Anywhere Server - SQL Usage]
● “Enabling table encryption in the database” [SQL Anywhere Server - Database Administration]
● “Update column statistics” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 ALTER TABLE is a core feature. In the SQL/2008 standard, ADD COLUMN and
DROP COLUMN are supported as core features, as are ADD CONSTRAINT and DROP
CONSTRAINT. ALTER [COLUMN] is SQL feature F381, as is the ability to add, modify, or drop a
DEFAULT value for a column. In SQL/2008, altering the data type of a column is performed by
specifying the SET DATA TYPE clause, which is SQL language feature F382. Conversely, SQL
Anywhere supports modifying a column's data type through the ALTER clause directly.

Other clauses supported by SQL Anywhere, including ALTER CONSTRAINT, RENAME,


PCTFREE, ENCRYPTED, and DISABLE MATERIALIZED VIEW, are vendor extensions. Support

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 463


SQL statements

for extensions to column definitions, and column and table constraint definitions, are vendor
extensions to SQL/2008 or are specific optional features of SQL/2008.

● Transact-SQL ALTER TABLE is supported by Adaptive Server Enterprise. Adaptive Server


Enterprise supports the ADD COLUMN and DROP COLUMN clauses, in addition to ADD
CONSTRAINT and DROP CONSTRAINT. Adaptive Server Enterprise uses MODIFY rather than
the keyword ALTER for the ALTER clause. Adaptive Server Enterprise uses the REPLACE clause
for altering a column's DEFAULT value. In Adaptive Server Enterprise, ALTER TABLE is also used
to enable/disable triggers for a specific table, a feature that is not supported in SQL Anywhere.

Example
The following example adds a new timestamp column, TimeStamp, to the Customers table.
ALTER TABLE Customers
ADD TimeStamp AS TIMESTAMP DEFAULT TIMESTAMP;

The following example drops the new timestamp column, TimeStamp that you added in the previous
example.
ALTER TABLE Customers
DROP TimeStamp;

The Street column in the Customers table can currently hold up to 35 characters. To allow it to hold up to
50 characters, execute the following:
ALTER TABLE Customers
ALTER Street CHAR(50);

The following example adds a column to the Customers table, assigning each customer a sales contact.
ALTER TABLE Customers
ADD SalesContact INTEGER
REFERENCES Employees ( EmployeeID )
ON UPDATE CASCADE
ON DELETE SET NULL;

This foreign key is constructed with cascading updates and is set to 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.

The following example creates a foreign key, FK_SalesRepresentative_EmployeeID2, on the


SalesOrders.SalesRepresentative column, linking it to Employees.EmployeeID:
ALTER TABLE GROUPO.SalesOrders
ADD CONSTRAINT FK_SalesRepresentative_EmployeeID2
FOREIGN KEY ( SalesRepresentative )
REFERENCES GROUPO.Employees (EmployeeID);

The following example adds a column where the default is AUTOINCREMENT. In this example, all
existing customer rows are modified to have a nullable AUTOINCREMENT column with the column
value assigned, but the database server does not guarantee which row is assigned which value:
ALTER TABLE Customers
ADD Surrogate_key INTEGER DEFAULT AUTOINCREMENT;

464 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

ALTER TEXT CONFIGURATION statement


Alters a text configuration object.

Syntax
ALTER TEXT CONFIGURATION [ owner.]config-name
STOPLIST stoplist-string
| DROP STOPLIST
| { MINIMUM | MAXIMUM } TERM LENGTH integer
| TERM BREAKER { GENERIC [ EXTERNAL NAME external-call ] | NGRAM }
| PREFILTER EXTERNAL NAME external-call
| DROP PREFILTER
| SAVE OPTION VALUES [ FROM CONNECTION ]
}

external-call : '[ operating-system: ]library-function-name@library-name[;...]'

operating-system : UNIX

Parameters
STOPLIST clause Use this clause to create or replace the list of terms to ignore when building a text
index. Using this text configuration object, terms specified in this list are also ignored in a query. Separate
stoplist terms with spaces. For example, STOPLIST 'because about therefore only'.
Stoplist terms cannot contain whitespace.

Samples of stoplists for different languages are located in %SQLANYSAMP12%\SQLAnywhere\SQL.

Stoplist terms should not contain non-alphanumeric characters. The stoplist length must be less than 8000
bytes.

Carefully consider whether you want to put terms in your stoplist.

DROP STOPLIST clause Use this clause to drop the stoplist for a text configuration object.

MINIMUM TERM LENGTH clause The value specified in the MINIMUM TERM LENGTH clause is
ignored when using NGRAM text indexes.

The minimum length, in characters, of a term to include in the text index. Terms that are shorter than this
setting are ignored when building or refreshing the text index. The value of this option must be greater
than 0. If you set this option to be higher than MAXIMUM TERM LENGTH, the value of MAXIMUM
TERM LENGTH is automatically adjusted to be the same as the new MINIMUM TERM LENGTH
value.

MAXIMUM TERM LENGTH clause With NGRAM text indexes, use the MAXIMUM TERM
LENGTH clause to set the size of the n-grams into which strings are broken.

With GENERIC text indexes, use the MAXIMUM TERM LENGTH clause to set the maximum length, in
characters, of a term to include in the text index. Terms that are longer than this setting are ignored when
building or refreshing the text index. The value of MAXIMUM TERM LENGTH must be less than or
equal to 60. If you set this option to be lower than MINIMUM TERM LENGTH, the value of MINIMUM

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 465


SQL statements

TERM LENGTH is automatically adjusted to be the same as the new MAXIMUM TERM LENGTH
value.

TERM BREAKER clause The name of the algorithm to use for separating column values into terms.
The choices are GENERIC (the default) or NGRAM.

○ GENERIC For GENERIC, you can use the built-in GENERIC term breaker algorithm by
specifying TERM BREAKER GENERIC, or you can specify an external algorithm using the TERM
BREAKER GENERIC EXTERNAL NAME clause.

The built-in GENERIC algorithm treats any string of one or more alphanumerics, separated by non-
alphanumerics, as a term.

Specify the TERM BREAKER GENERIC EXTERNAL NAME clause to specify an entry point to a
term breaker function in an external library. This is useful if you have custom requirements for how
you want terms broken up before they are indexed or queried (for example, if you want an apostrophe
to be considered as part of a term and not as a term breaker).

external-call can specify more than one function and/or library, and can include the file extension of
the library, which is typically .dll on Windows, and .so on Unix. In the absence of the file extension,
the database server defaults to the platform-specific file extension for libraries. For example,
EXTERNAL NAME 'TermBreakFunct1@myTBlib;Unix:TermBreakFunct2@myTBlib'
calls the TermBreakFunct1 function from myTBlib.dll on Windows, and the TermBreakFunct2
function from myTBlib.so on Unix.

○ NGRAM The built-in NGRAM algorithm breaks strings into n-grams. An n-gram is an n-character
substring of a larger string. The NGRAM term breaker is required for fuzzy (approximate) matching,
or for documents that do not use whitespace or non-alphanumeric characters to separate terms, if no
external term breaker is specified.

PREFILTER EXTERNAL NAME clause Specify the PREFILTER EXTERNAL NAME clause to
specify an entry point to a prefilter function in an external library. This is useful if text data needs to be
extracted from binary data (for example, PDF). It is also useful if the text you want to index contains
formatting information and/or images that you want to strip out before indexing the data (for example,
HTML).

external-call can specify more than one function and/or library, and can include the file extension of the
library, which is typically .dll on Windows, and .so on Unix. In the absence of the file extension, the
database server defaults to the platform-specific file extension for libraries. For example, PREFILTER
EXTERNAL NAME
'PrefilterFunct1@myPreFilterlib;Unix:PrefilterFunct2@myPreFilterlib'
calls the PrefilterFunct1 function from myPreFilterlib.dll on Windows, and the PrefilterFunct2 function
from myPreFilterlib.so on Unix.

DROP PREFILTER clause Use the DROP PREFILTER clause to drop use of the specified
prefiltering library for the text configuration object. This means that prefiltering is no longer performed
when the database server builds indexes that use this text configuration object.

SAVE OPTION VALUES clause When a text configuration object is created, the current date_format,
time_format, timestamp_format, and timestamp_with_time_zone_format database options reflect how

466 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

DATE, TIME, and TIMESTAMP columns are saved with the text configuration object. Use the SAVE
OPTION VALUES clause to update the option values saved for the text configuration object to reflect the
options currently in effect for the connection.

Remarks
Before changing the term length settings, read about the impact of various settings on what gets indexed
and how query terms are interpreted.

Text indexes are dependent on a text configuration object. Before using this statement you must truncate
dependent AUTO or MANUAL REFRESH text indexes, and drop any IMMEDIATE REFRESH text
indexes.

To view the settings for text configuration objects, query the SYSTEXTCONFIG system view.

Permissions
When changing or dropping the external prefilter or term breaker, DBA authority is required (being the
owner of the text configuration object is not enough).

For all other cases, you can be the owner of the text configuration object, or have DBA authority.

Side effects
Automatic commit

See also
● “Altering a text configuration object” [SQL Anywhere Server - SQL Usage]
● “Viewing information about a text index in the database (Sybase Central)” [SQL Anywhere Server -
SQL Usage]
● “What to specify when creating or altering text configuration objects” [SQL Anywhere Server - SQL
Usage]
● “Tutorial: Performing a full text search on a GENERIC text index” [SQL Anywhere Server - SQL
Usage]
● “Tutorial: Performing a fuzzy full text search” [SQL Anywhere Server - SQL Usage]
● “CREATE TEXT CONFIGURATION statement” on page 647
● “DROP TEXT CONFIGURATION statement” on page 712
● “sa_char_terms system procedure” on page 1009
● “sa_nchar_terms system procedure” on page 1094
● “sa_refresh_text_indexes system procedure” on page 1109
● “sa_text_index_stats system procedure” on page 1149
● “SYSTEXTCONFIG system view” on page 1248

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements create a text configuration object, maxTerm16, and then change the maximum
term length to 16:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 467


SQL statements

CREATE TEXT CONFIGURATION maxTerm16 FROM default_char;


ALTER TEXT CONFIGURATION maxTerm16
MAXIMUM TERM LENGTH 16;

The following statement adds a stoplist to the maxTerm16 configuration object:


ALTER TEXT CONFIGURATION maxTerm16
STOPLIST 'because about therefore only';

The following statement configures an external term breaker for the myTextConfig text configuration
object. Both the Windows and Unix interfaces are specified.
ALTER TEXT CONFIGURATION myTextConfig
TERM BREAKER GENERIC
EXTERNAL NAME
'[email protected];Unix:my_termbreaker@libtermbreaker_r.so'

The following example configures an external prefilter for the myTextConfig text configuration object.
Both the Windows and Unix interfaces are specified.
ALTER TEXT CONFIGURATION myTextConfig
PREFILTER EXTERNAL NAME
'html_xml_filter@html_xml_filter.dll;UNIX:html_xml_filter@libhtml_xml_filter_
r.so';

The following example drops the external prefilter for the myTextConfig text configuration object.
ALTER TEXT CONFIGURATION myTextConfig DROP PREFILTER;

ALTER TEXT INDEX statement


Alters the definition of a text index.

Syntax
ALTER TEXT INDEX [ owner.]text-index-name
ON [ owner.]table-name
alter-clause

alter-clause :
rename-object
| refresh-alteration

rename-object :
RENAME { AS | TO } new-name

refresh-alteration :
{ MANUAL REFRESH
| AUTO REFRESH [ EVERY integer { MINUTES | HOURS } ] }

Parameters
RENAME clause Use the RENAME clause to rename the text index.

REFRESH clause Specify the REFRESH clause to set the refresh type for the text index.

468 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
Once a text index is created, you cannot change it to, or from, IMMEDIATE REFRESH. If either of these
changes is required, you must drop and recreate the text index.

Permissions
Must be the owner of the underlying table, or have DBA authority, or have REFERENCES permission.

This statement cannot be executed when there are cursors opened with the WITH HOLD clause that use
either statement or transaction snapshots.

Side effects
Automatic commit

See also
● “CREATE TEXT INDEX statement” on page 649
● “ALTER TEXT INDEX statement” on page 468
● “DROP TEXT INDEX statement” on page 713
● “REFRESH TEXT INDEX statement” on page 846
● “TRUNCATE TEXT INDEX statement” on page 935
● “COMMENT statement” on page 499
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]
● “Viewing information about a text index in the database (Sybase Central)” [SQL Anywhere Server -
SQL Usage]
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Tutorial: Performing a full text search on a GENERIC text index” [SQL Anywhere Server - SQL
Usage]
● “Tutorial: Performing a fuzzy full text search” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The first statement creates a text index, txt_index_manual, defining it as MANUAL REFRESH. The
second statement alters the text index to refresh automatically every day. The third statement renames the
text index to txt_index_daily.
CREATE TEXT INDEX txt_index_manual ON MarketingInformation ( Description )
MANUAL REFRESH;
ALTER TEXT INDEX txt_index_manual ON MarketingInformation
AUTO REFRESH EVERY 24 HOURS;
ALTER TEXT INDEX txt_index_manual ON MarketingInformation
RENAME AS txt_index_daily;

ALTER TRIGGER statement


Replaces a trigger definition with a modified version. You must include the entire new trigger definition
in the ALTER TRIGGER statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 469


SQL statements

Syntax 1 - Change the definition of a trigger


ALTER TRIGGER trigger-name trigger-definition

trigger-definition : CREATE TRIGGER syntax

Syntax 2 - Obfuscate a trigger definition


ALTER TRIGGER trigger-name ON [owner.] table-name SET HIDDEN

Remarks
● Syntax 1 The ALTER TRIGGER statement is identical in syntax to the CREATE TRIGGER
statement except for the first word.

Either the Transact-SQL or Watcom SQL form of the CREATE TRIGGER syntax can be used.

● Syntax 2 You can use SET HIDDEN to obfuscate the definition of the associated trigger and cause
it to become unreadable. The trigger can be unloaded and reloaded into other databases. If SET
HIDDEN is used, debugging using the debugger does not show the trigger definition, nor is it
available through procedure profiling.

Note
The SET HIDDEN operation is irreversible.

Permissions
Must be the owner of the table on which the trigger is defined, or user DBA, or have ALTER permissions
on the table and RESOURCE authority.

Side effects
Automatic commit.

See also
● “CREATE TRIGGER statement” on page 651
● “CREATE TRIGGER statement [T-SQL]” on page 657
● “DROP TRIGGER statement” on page 714
● “Hiding the contents of procedures, functions, triggers, events, and views” [SQL Anywhere Server -
SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

ALTER USER statement


Alters user settings.

470 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax 1 - Change the definition of a database user


ALTER USER user-name [ IDENTIFIED BY password ]
[ LOGIN POLICY policy-name ]
[ FORCE PASSWORD CHANGE { ON | OFF } ]

Syntax 2 - Revert a user's login policy to the original values


ALTER USER user-name
[ RESET LOGIN POLICY ]

Parameters
user-name The name of the user.

IDENTIFIED BY clause The password of the user. A user without a password cannot connect to the
database.

policy-name The name of the login policy to assign the user. No change is made if the LOGIN
POLICY clause is not specified.

FORCE PASSWORD CHANGE clause Controls whether the user must specify a new password
when they log in. This setting overrides the password_expiry_on_next_login option setting in the user's
policy.

RESET LOGIN POLICY clause Reverts the settings of a user's login policy to the original values.
When you reset a login policy, a user can access an account that has been locked for exceeding a login
policy option limit such as max_failed_login_attempts or max_days_since_login.

Remarks

● User IDs cannot:

○ begin with white space, single quotes, or double quotes


○ end with white space
○ contain semicolons

● Passwords are case-sensitive and they cannot:

○ begin with white space, single quotes, or double quotes


○ end with white space
○ contain semicolons
○ be longer than 255 bytes in length

The verify_password_function option can be used to specify a function to implement password rules (for
example, passwords must include at least one digit). If a password verification function is used, you
cannot specify more than one user ID and password in the GRANT CONNECT statement.

If you set the password_expiry_on_next_login value to ON, the user's password expires immediately
when they next login even if they are assigned to the same policy. You can use the ALTER USER and
LOGIN POLICY clauses to force a user to change their password when they next login.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 471


SQL statements

Permissions
Any user can change their own password. All other changes require DBA authority.

Side effects
None.

See also
● “ALTER LOGIN POLICY statement” on page 415
● “COMMENT statement” on page 499
● “CREATE LOGIN POLICY statement” on page 558
● “CREATE USER statement” on page 658
● “DROP LOGIN POLICY statement” on page 696
● “DROP USER statement” on page 715
● “verify_password_function option” [SQL Anywhere Server - Database Administration]
● “Login policies” [SQL Anywhere Server - Database Administration]
● “Assigning a login policy to an existing user” [SQL Anywhere Server - Database Administration]
● “GRANT statement” on page 760

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement alters a user named SQLTester. The password is set to welcome. The SQLTester
user is assigned to the Test1 login policy and the password does not expire on the next login.
ALTER USER SQLTester IDENTIFIED BY welcome
LOGIN POLICY Test1
FORCE PASSWORD CHANGE off;

ALTER VIEW statement


Replaces a view definition with a modified version.

Syntax 1 - Change the definition of a view


ALTER VIEW
[ owner.]view-name [ ( column-name, ... ) ] AS select-statement
[ WITH CHECK OPTION ]

Syntax 2 - Change the attributes of a view


ALTER VIEW
[ owner.]view-name { SET HIDDEN | RECOMPILE | DISABLE | ENABLE }

Parameters
AS clause The SELECT statement on which the view is based. The SELECT statement must not refer
to local temporary tables. Also, query-expression can have a GROUP BY, HAVING, WINDOW, or
ORDER BY clause, and can contain UNION, EXCEPT, INTERSECT, or a common table expression.

472 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The semantics of queries dictates that the order of the rows returned is undefined unless the query
combines an ORDER BY clause with a TOP or FIRST clause in the SELECT statement. If an ORDER
BY clause is specified along with either a TOP or FIRST clause, then the query returns the top n rows, or
the first row, respectively.

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 view as defined by its query-expression.

SET HIDDEN clause Use the SET HIDDEN clause to obfuscate the definition of the view and cause
the view to become hidden from view, for example in Sybase Central. Explicit references to the view still
work.

Note
The SET HIDDEN operation is irreversible.

RECOMPILE clause Use the RECOMPILE clause to re-create the column definitions for the view.
This clause is identical in functionality to the ENABLE clause, except that it can be used on a view that is
not disabled. When a view is recompiled, the database server restores the column permissions based on
the column names specified in the new view definition. The existing permissions are lost when a column
no longer exists after the recompilation.

DISABLE clause Use the DISABLE clause to disable the view from use by the database server.

ENABLE clause Use the ENABLE clause to enable a disabled view. Enabling the view causes the
database server to re-create the column definitions for the view. Before you enable a view, you must
enable any views upon which it depends.

Remarks
If you execute an ALTER VIEW statement on a view that has one or more INSTEAD OF triggers, an
error is returned. You must drop the trigger before the view can be dropped or altered.

If you alter a view owned by another user, you must qualify the name by including the owner (for
example, GROUPO.ViewSalesOrders). If you don't qualify the name, the database server looks for a view
with that name owned by you and alters it. If there isn't one, it returns an error.

When you alter a view, existing permissions on the view are maintained, and do not have to be
reassigned. Instead of using the ALTER VIEW statement, you could also drop the view and recreate it
using the DROP VIEW and CREATE VIEW, respectively. However, if you do so, permissions on the
view need to be reassigned.

After completing the view alteration using Syntax 1, the database server recompiles the view. Depending
on the type of change you made, if there are dependent views, the database server attempts to recompile
them as well. If you have made a change that impacts a dependent view, you may need to alter the
definition for the dependent view as well.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 473


SQL statements

Caution
If the SELECT statement defining the view contained an asterisk (*), the number of the columns in the
view may change if columns have been added or deleted from the underlying tables. The names and data
types of the view columns may also change.

● Syntax 1 This syntax is used to alter the structure of the view. Unlike altering tables where your
change may be limited to individual columns, altering the structure of a view requires you to replace
the entire view definition with a new definition, much as you would for creating the view.

● Syntax 2 This syntax is used to change attributes for the view, such as whether the view definition
is hidden.

When you use SET HIDDEN, the view can be unloaded and reloaded into other databases. If SET
HIDDEN is used, debugging using the debugger does not show the view definition, nor is it be
available through procedure profiling. If you need to change the definition of a hidden view, you must
drop the view and create it again using the CREATE VIEW statement.

When you use the DISABLE clause, the view is no longer available for use by the database server for
answering queries. Disabling a view is similar to dropping it, except that the view definition remains
in the database. Disabling a view also disables any dependent views. Therefore, the DISABLE clause
requires exclusive access not only to the view being disabled, but also any dependent views, since
they are disabled too.

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 661
● “DROP VIEW statement” on page 716
● “CREATE MATERIALIZED VIEW statement” on page 560
● “ALTER MATERIALIZED VIEW statement” on page 417
● “Hiding the contents of procedures, functions, triggers, events, and views” [SQL Anywhere Server -
SQL Usage]
● “View dependencies” [SQL Anywhere Server - SQL Usage]
● “Views” [SQL Anywhere Server - SQL Usage]
● “Creating a regular view (Sybase Central)” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

474 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

ATTACH TRACING statement


Starts a diagnostic tracing session (starts sending diagnostic information to the diagnostic tables).

Syntax

ATTACH TRACING TO { LOCAL DATABASE | connect-string }


[ LIMIT { size | history } ]

connect-string : the connection string for the database

size : SIZE nnn { MB | GB }

history : HISTORY nnn { MINUTES | HOURS | DAYS }

nnn : integer

Parameters
● connect-string The connection string is required to connect to the database receiving the tracing
information. This parameter is only required when the database being profiled is different from the
database receiving the data.

The following connection parameters are allowed in connect-string: DBF, DBKEY, DBN, Host,
Server, LINKS, PWD, UID.

Specify the DBF relative to the database server that you want to connect to. If you do not specify a
different database server, then the database server to which you are currently connected attempts to
start the tracing database identified by the DBF connection parameter.

An error is returned if you specify the DBF parameter with the LINKS or Server connection
parameters.

● LIMIT clause The volume limit of data stored in the tracing database, either by size, or by length of
time.

Remarks
The ATTACH TRACING statement is used to start a tracing session for the database you want to profile.
You can only use it once a tracing level has been set. You can set the tracing level using Sybase Central,
or using the sa_set_tracing_level system procedure.

Once a session is started, tracing information is generated according to the tracing levels set in the
sa_diagnostic_tracing_level table. You can send the tracing data to tracing tables within the same
database that is being profiled by specifying LOCAL DATABASE. Alternatively, you can send the
tracing data to a separate tracing database by specifying a connection string (connect-string) to that
database. The tracing database must already exist, and you must have permissions to access it.

You can limit the amount of tracing data to store using the LIMIT SIZE or LIMIT HISTORY clauses.
Use the LIMIT SIZE clause when you want to limit the volume of tracing data to a certain size, as
measured in megabytes or gigabytes. Use the LIMIT HISTORY clause to limit the volume of tracing data

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 475


SQL statements

to a period of time, as measured in minutes, hours, or days. For example, HISTORY 8 DAYS limits the
amount of tracing data stored in the tracing database to 8 days' worth.

To start a tracing session, TCP/IP must be running on the database server(s) on which the tracing database
and production database are running.

Packets that contain potentially sensitive data are visible on the network interface, even when tracing to a
local database. For security purposes, you can specify encryption in the connection string.

To see the current tracing levels set for a database, look in the sa_diagnostic_tracing_level table.

To see where tracing data is being sent to, examine the SendingTracingTo database property.

Permissions
Must be connected to the database being profiled and must have DBA or PROFILE authority.

Side effects
None.

See also
● “DETACH TRACING statement” on page 687
● “REFRESH TRACING LEVEL statement” on page 848
● “-x dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “sa_diagnostic_tracing_level table” on page 991
● “sa_set_tracing_level system procedure” on page 1140
● “SendingTracingTo database property” [SQL Anywhere Server - Database Administration]
● “Connection parameters” [SQL Anywhere Server - Database Administration]
● “TCP/IP protocol” [SQL Anywhere Server - Database Administration]
● “Diagnostic tracing” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example sets the tracing level to 1 using the sa_set_tracing_level system procedure. Then it
starts a tracing session. Tracing data generated for the local database will be sent to the mytracingdb
tracing database on another computer, as shown by the specified connection string. A maximum of two
hours of tracing data will be maintained during the tracing session. Note that the ATTACH TRACING
statement example is all on one line.
CALL sa_set_tracing_level( 1 );
ATTACH TRACING TO
'uid=DBA;pwd=sql;server=remotedbsrv;dbn=mytracingdb;host=winxp-32'
LIMIT HISTORY 2 HOURS;

476 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

BACKUP statement
Backs up a database and transaction log.

Syntax 1 - Image backup


BACKUP DATABASE
DIRECTORY backup-directory
[ backup-option [ backup-option ... ]

backup-directory : { string | variable }

backup-option :
WAIT BEFORE START
| WAIT AFTER END
| DBFILE ONLY
| TRANSACTION LOG ONLY
| TRANSACTION LOG RENAME [ MATCH ]
| TRANSACTION LOG TRUNCATE
| ON EXISTING ERROR
| WITH COMMENT comment string
| HISTORY { ON | OFF }
| AUTO TUNE WRITERS { ON | OFF }
| WITH CHECKPOINT LOG { AUTO | COPY | NO COPY | RECOVER }

Syntax 2 - Archive backup


BACKUP DATABASE TO archive-root
[ backup-option [ backup-option ... ]

archive-root : { string | variable }

backup-option :
| WAIT BEFORE START
| WAIT AFTER END
| DBFILE ONLY
| TRANSACTION LOG ONLY
| TRANSACTION LOG RENAME [ MATCH ]
| TRANSACTION LOG TRUNCATE
| ATTENDED { ON | OFF }
| WITH COMMENT comment string
| HISTORY { ON | OFF }
| WITH CHECKPOINT LOG [ NO ] COPY
| MAX WRITE { number-of-writers | AUTO }
| FREE PAGE ELIMINATION { ON | OFF }

comment-string : string

number-of-writers : integer

Parameters
DIRECTORY clause The target location on disk for the backup files, relative to the database server's
current directory at startup. If the directory does not exist, it is created. Specifying an empty string as a
directory allows you to rename or truncate the transaction log without first making a copy of it. Do not
use this clause if you are using database mirroring.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 477


SQL statements

WAIT BEFORE START clause Use this clause to ensure that the rollback log for each connection in
the backup copy of the database is empty. Use this clause with the WITH CHECKPOINT LOG NO
COPY clause to verify that the backup copy of the database does not contain any information required for
recovery.

If you use the WAIT BEFORE START and WITH CHECKPOINT LOG NO COPY clauses to complete
a backup, you can start the backup copy of the database in read-only mode and validate it. By enabling
validation of the backup database, you can avoid making an additional copy of the database.

When this clause is specified, the backup is delayed until there are no active transactions. All other
activity on the database is prevented and a checkpoint is performed to ensure that the backup copy of the
database does not require recovery. When the checkpoint is complete, other activity on the database
resumes.

WAIT AFTER END clause When renaming or truncating the transaction log you can specify the
WAIT AFTER END clause to ensure that all transactions are completed before the log is renamed or
truncated. If you specify this clause, the backup waits for other connections to commit or rollback any
open transactions before finishing. This clause should be used with caution because new, incoming
transactions may cause the backup to wait indefinitely.

DBFILE ONLY clause When you specify the DBFILE ONLY clause, backup copies of the main
database file and all associated dbspaces are made, but the transaction log is not copied. You cannot use
the DBFILE ONLY clause with the TRANSACTION LOG RENAME or TRANSACTION LOG
TRUNCATE clauses.

TRANSACTION LOG ONLY clause You can specify the TRANSACTION LOG ONLY clause to
create a backup copy of the transaction log, without copying the other database files.

TRANSACTION LOG RENAME [ MATCH ] clause This clause causes the database server to rename
the current transaction log at the completion of the backup. If the MATCH keyword is omitted, the
backup copy of the transaction log has the same name as the current transaction log for the database. If
you supply the MATCH keyword, the backup copy of the transaction log is given a name of the form
YYMMDDnn.log, to match the renamed copy of the current transaction log. Using the MATCH keyword
enables the same statement to be executed several times without writing over old data.

The transaction log can be renamed without completing a backup by specifying an empty directory name
with the TRANSACTION LOG ONLY clause. For example:
BACKUP DATABASE DIRECTORY ''
TRANSACTION LOG ONLY
TRANSACTION LOG RENAME;

TRANSACTION LOG TRUNCATE clause If this clause is used, the current transaction log is
truncated and restarted at the completion of the backup. Do not use this clause if you are using database
mirroring.

The transaction log can be truncated without completing a backup by specifying an empty directory name
with the TRANSACTION LOG ONLY clause. For example:
BACKUP DATABASE DIRECTORY ''
TRANSACTION LOG ONLY
TRANSACTION LOG TRUNCATE;

478 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

archive-root clause 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. The number automatically
appended to the end of the archive file name is incremented each time you execute an archive backup.

The backslash ( \ ) is an escape character in SQL strings, so each backslash must be doubled.

ON EXISTING ERROR clause This clause applies only to image backups. By default, existing files
are overwritten when you execute a BACKUP DATABASE statement. If this clause is used, an error
occurs if any of the files to be created by the backup already exist.

ATTENDED clause 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 DATABASE
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.

WITH COMMENT clause This clause records a comment in the backup history file. For archive
backups, the comment is also recorded in the archive file.

HISTORY clause By default, each backup operation appends a line to the backup.syb file. You can
prevent updates to the backup.syb file by specifying HISTORY OFF. You may want to prevent the file
from being updated if any of the following conditions apply:

○ your backups occur frequently


○ there is no procedure to periodically archive or delete the backup.syb file
○ disk space is very limited

AUTO TUNE WRITERS clause When the backup starts, one thread is dedicated to writing the backup
files to the backup directory. However, if the backup directory is on a device that can handle an increased
writer load (such as a RAID array), then overall backup performance can be improved by increasing the
number of threads acting as writers. If this clause is ON (the default), the database server periodically
examines the read and write performance from all the devices taking part in the backup. If the overall
backup speed can be improved by creating another writer, then the database server creates another writer.

WITH CHECKPOINT LOG clause This clause specifies how the backup processes the database files
before writing them to the destination directory. The choice of whether to apply pre-images during a
backup, or copy the checkpoint log as part of the backup, has performance implications. The default
setting is AUTO for image backups and COPY for archive backups.

○ COPY clause This option cannot be used with the WAIT BEFORE START clause of the
BACKUP statement.

When you specify COPY, the backup reads the database files without applying any modified pages.
The entire checkpoint log and the system dbspace are copied to the backup directory. The next time
the database server is started, the database server automatically recovers the database to the state it
was in as of the checkpoint at the time the backup started.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 479


SQL statements

Because pages do not have to be written to the temporary file, using this option can provide better
backup performance, and reduce internal server contention for other connections that are operating
during a backup. However, since the checkpoint log contains original images of modified pages, it
grows in the presence of database updates. With copy specified, the backed-up copy of the database
files may be larger than the database files at the time the backup started. The COPY option should be
used if disk space in the destination directory is not an issue.

○ NO COPY clause When you specify NO COPY, the checkpoint log is not copied as part of the
backup. This option causes modified pages to be saved in the temporary file so that they can be
applied to the backup as it progresses. The backup copies of the database files will be the same size as
the database when the backup operation commenced.

This option results in smaller backed up database files, but the backup may proceed more slowly, and
possibly decrease performance of other operations in the database server. It is useful in situations
where space on the destination drive is limited.

○ RECOVER clause When you specify RECOVER, the database server copies the checkpoint log
(as with the COPY option), but applies the checkpoint log to the database when the backup is
complete. This restores the backed up database files to the same state (and size) that they were in at
the start of the backup operation. This option is useful if space on the backup drive is limited (it
requires the same amount of space as the COPY option for backing up the checkpoint log, but the
resulting file size is smaller).

○ AUTO clause When you specify AUTO, the database server checks the amount of available disk
space on the volume hosting the backup directory. If there is at least twice as much disk space
available as the size of the database at the start of the backup, then this option behaves as if copy were
specified. Otherwise, it behaves as NO COPY. AUTO is the default behavior.

MAX WRITE clause For archive backups, by default one thread is dedicated to writing the backup
files. If the backup directory is on a device that can handle an increased writer load (such as a RAID
array), then overall backup performance can be improved by increasing the number of threads acting as
writers.

If AUTO is specified, one output stream is created for each reader thread. The value n specifies the
maximum number of output streams that can be created, up to the number of reader threads. The default
value for this clause is 1. If you are backing up to tape, only one writer can be used.

The first stream, stream 0, produces files named myarchive.X, where X is a number that starts at 1 and
continues incrementing to the number of files required. All of the other streams produce files named
myarchive.Y.Z, where Y is the stream number (starting at 1), and Z is a number that starts at 1 and
continues incrementing to the number of files required.

FREE PAGE ELIMINATION clause By default, archive backups skip some free pages, which can
result in smaller and potentially faster backups. Free page elimination has no effect on the back up of
transaction log files because transaction log files do not contain free pages. Databases with large
transaction log files may not benefit as much from free page elimination as databases with small
transaction log files.

When you back up a strongly-encrypted database with free page elimination turned on, you must specify
the encryption key when restoring the database. When you back up a strongly-encrypted database with

480 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

free page elimination turned off, you do not need to specify the encryption key when restoring the
database.

As of version 12, you cannot restore archive backups created with version 11 or earlier database servers.

Remarks
The BACKUP statement performs a server-side backup. To perform a client-side backup, use the
dbbackup utility.

Each backup operation, whether image or archive, updates a history file called backup.syb. This file
records the BACKUP and RESTORE operations that have been performed on a database server. For
information about how the location of the backup.syb file is determined, see “SALOGDIR environment
variable” [SQL Anywhere Server - Database Administration].

To create a backup that can be started on a read-only server without having to go through recovery, you
must use both the WAIT BEFORE START and WITH CHECKPOINT LOG NO COPY clauses. The
WAIT BEFORE START clause ensures that the rollback log is empty, and the WITH CHECKPOINT
LOG NO COPY clause ensures that the checkpoint log is empty. If either of these files is missing, then
recovery is required. You can use WITH CHECKPOINT LOG RECOVER as an alternative to the WAIT
BEFORE START and WITH CHECKPOINT LOG NO COPY clauses if you do not need to recover the
database you backed up.

● Syntax 1 - Image backup An image backup creates copies of each of the database files, in the
same way as the Backup utility (dbbackup). By default, the Backup utility makes the backup on the
client computer, but you can specify the -s option to create the backup on the database server when
using the Backup utility. For the BACKUP DATABASE statement, however, the backup can only be
made on the database server.

Optionally, only the database file(s) or transaction log can be saved. The transaction log may also be
renamed or truncated after the backup has completed.

Alternatively, you can specify an empty string as a directory to rename or truncate the log without
copying it first. This is useful in a replication environment where space is a concern. You can use this
feature with an event handler on transaction log size to rename the transaction log when it reaches a
given size, and with the delete_old_logs option to delete the transaction log when it is no longer
needed.

To restore from an image backup, copy the saved files back to their original locations and reapply the
transaction logs.

● Syntax 2 - Archive backup 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 tape is ejected at the end of the backup.

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 DATABASE statement.

If a RESTORE DATABASE statement references an archive file containing only a transaction log,
the statement must specify a file name for the location of the restored database file, even if that file

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 481


SQL statements

does not exist. For example, to restore from an archive that only contains a transaction log to the
directory C:\MYNEWDB, the RESTORE DATABASE statement is:
RESTORE DATABASE 'c:\mynewdb\my.db' FROM archive-root

Caution
Backup copies of the database and transaction log must not be changed in any way. If there were no
transactions in progress during the backup, or if you specified BACKUP DATABASE WITH
CHECKPOINT LOG RECOVER or WITH CHECKPOINT LOG NO COPY, you can check the
validity of the backup database using read-only mode or by validating a copy of the backup database.

However, if transactions were in progress, or if you specified BACKUP DATABASE WITH


CHECKPOINT LOG COPY, the database server must perform recovery on the database when you
start it. Recovery modifies the backup copy, which is not desirable.

During the execution of this statement, you can request progress messages.

You can also use the Progress connection property to determine how much of the statement has been
executed.

Permissions
Must have DBA, REMOTE DBA, or BACKUP authority.

Side effects
Causes a checkpoint.

See also
● “Database recovery with multiple transaction logs” [SQL Anywhere Server - Database
Administration]
● “Progress connection property” [SQL Anywhere Server - Database Administration]
● “progress_messages option” [SQL Anywhere Server - Database Administration]
● “Backup utility (dbbackup)” [SQL Anywhere Server - Database Administration]
● “Image backups” [SQL Anywhere Server - Database Administration]
● “Strings” on page 5
● “RESTORE DATABASE statement” on page 855
● “KEY CLAUSE, RESTORE DATABASE statement” on page 856
● “Backup and data recovery” [SQL Anywhere Server - Database Administration]
● “Database mirroring and transaction log files” [SQL Anywhere Server - Database Administration]
● “EXECUTE IMMEDIATE statement [SP]” on page 719
● “Parallel database backups” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

● Windows Mobile Only the BACKUP DATABASE DIRECTORY syntax (syntax 1) is supported
on Windows Mobile.

482 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Example
Back up the current database and the transaction log, each to a different file, and rename 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';

Rename the transaction log without making a copy:


BACKUP DATABASE DIRECTORY ''
TRANSACTION LOG ONLY
TRANSACTION LOG RENAME;

Execute the BACKUP DATABASE statement with a dynamically-constructed directory name:


CREATE EVENT NightlyBackup
SCHEDULE
START TIME '23:00' EVERY 24 HOURS
HANDLER
BEGIN
DECLARE dest LONG VARCHAR;
DECLARE day_name CHAR(20);

SET day_name = DATENAME( WEEKDAY, CURRENT DATE );


SET dest = 'd:\\backups\\' || day_name;
BACKUP DATABASE DIRECTORY dest
TRANSACTION LOG RENAME;
END;

BEGIN SNAPSHOT statement


Starts a snapshot at a specified period in time for use with snapshot isolation transactions.

Syntax
BEGIN SNAPSHOT

Remarks
By default, when a transaction begins, the database server defers creating the snapshot until the
application causes the first row of a table to be fetched. You can use the BEGIN SNAPSHOT statement to
start the snapshot earlier within the transaction. The database server creates a snapshot when the BEGIN
SNAPSHOT statement is executed by a snapshot transaction.

The statement fails and returns an error when either of the following conditions is met:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 483


SQL statements

● support for snapshots transactions has not been enabled for the database.

● a snapshot has already been started for the current transaction.

This statement is also useful for non-snapshot transactions because it allows them to start a snapshot that
can be used later in the transaction for a statement-level snapshot operation.

Permissions
None.

Side effects
None.

See also
● “allow_snapshot_isolation option” [SQL Anywhere Server - Database Administration]
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

BEGIN statement
Specifies a compound statement.

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

exception-case :
WHEN exception-name [, ... ] THEN statement-list
| WHEN OTHERS THEN statement-list

variable-declaration and exception-declaration : See “DECLARE statement” on page 673.

cursor-declaration : See “DECLARE CURSOR statement [ESQL] [SP]” on page 666.

temporary-table-declaration : See “DECLARE LOCAL TEMPORARY TABLE


statement” on page 672.

484 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Parameters
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.

ATOMIC clause An atomic statement is a statement that is executed completely or not at all. For
example, an UPDATE statement that updates thousands of rows might encounter an error after updating
many rows. If the statement does not complete, all changes revert back to their original state. Similarly, if
you specify that the BEGIN statement is atomic, the statement is executed either in its entirety or not at
all.

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 of the compound statement are visible to the exception handlers for the statement.
Local declarations are not visible to other procedures that are called from within a compound statement.

Remarks
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.

Permissions
None.

Side effects
None.

See also
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]
● “Error and warning handling” [SQL Anywhere Server - SQL Usage]
● “Exception handling and atomic compound statements” [SQL Anywhere Server - SQL Usage]
● “Exception handlers” [SQL Anywhere Server - SQL Usage]
● “Atomic compound statements” [SQL Anywhere Server - SQL Usage]
● “CONTINUE statement” on page 507
● “SIGNAL statement [SP]” on page 906
● “RESIGNAL statement [SP]” on page 854
● “RAISERROR statement” on page 838
● “BEGIN statement [TSQL]” on page 486

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 485


SQL statements

Standards and compatibility


● SQL/2008 BEGIN, which identifies a compound statement, comprises part of optional SQL
language feature P002 in SQL/2008.

Example
The body of a procedure or trigger is a compound statement.
CREATE PROCEDURE TopCustomer (OUT TopCompany CHAR(35), OUT TopValue INT)
BEGIN
DECLARE err_notfound EXCEPTION FOR
SQLSTATE '02000';
DECLARE curThisCust CURSOR FOR
SELECT CompanyName, CAST(
sum( SalesOrderItems.Quantity *
Products.UnitPrice ) AS INTEGER) VALUE
FROM Customers
LEFT OUTER JOIN SalesOrders
LEFT OUTER JOIN SalesOrderItems
LEFT OUTER JOIN Products
GROUP BY CompanyName;
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;

The example below declares the following variables:

● v1 as an INT with the initial setting of 5.


● v2 and v3 as CHAR(10), both with an initial value of abc.
BEGIN
DECLARE v1 INT = 5
DECLARE v2, v3 CHAR(10) = 'abc'
// ...
END

BEGIN statement [TSQL]


Specifies a compound statement.

486 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
BEGIN
statement-list
END

statement-list :
sql-statement
| variable-declaration
| cursor-declaration
| temporary-table-declaration

variable-declaration : See “DECLARE statement” on page 673.

cursor-declaration : See “DECLARE CURSOR statement [ESQL] [SP]” on page 666.

temporary-table-declaration : See “DECLARE LOCAL TEMPORARY TABLE


statement” on page 672.

Parameters
statement-list A list of statements and declarations.

Remarks
A BEGIN statement allows one or more SQL statements to be grouped together and treated as a unit, and
starts with the keyword BEGIN and ends with the keyword END.

Error handling is different for Transact-SQL compound statements.

Permissions
None.

Side effects
None.

See also
● “Error handling in Transact-SQL procedures” [SQL Anywhere Server - SQL Usage]
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]
● “BEGIN statement” on page 484
● “CONTINUE statement” on page 507
● “GOTO statement [T-SQL]” on page 754
● “RAISERROR statement” on page 838
● “Transact-SQL-compatible databases” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 BEGIN, which identifies a compound statement, comprises part of optional SQL
language feature P002 in SQL/2008.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 487


SQL statements

Example
The example below declares the following variables:

● v1 as an INT with the initial setting of 5.


● v2 and v3 as CHAR(10), both with an initial value of abc.

BEGIN
DECLARE v1 INT = 5
DECLARE v2, v3 CHAR(10) = 'abc'
// ...
END

BEGIN TRANSACTION statement [T-SQL]


Begins a user-defined transaction.

Syntax
BEGIN TRAN[SACTION] [ transaction-name ]

Remarks
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 SQL 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/2008 compatible chained mode only commits a transaction when an
explicit COMMIT is executed or when a statement that carries out an autocommit (such as a data
definition statement) is executed.

You can control the mode by setting the chained database option. The default setting for ODBC and
embedded SQL connections in SQL Anywhere is On, in which case SQL 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 manipulation 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 setting of the chained option within a transaction.

488 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Caution
When calling a stored procedure, you should ensure that it operates correctly under the required
transaction mode.

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.

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 executed.

When Adaptive Server Enterprise starts a transaction implicitly, the @@trancount variable is set to 1.
SQL Anywhere does not set the @@trancount value to 1 when a transaction is started implicitly. Instead,
the SQL 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.

For transactions starting with a BEGIN TRANSACTION statement, @@trancount has a value of 1 in
both SQL 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 2 in both SQL Anywhere, and Adaptive Server Enterprise
after the BEGIN TRANSACTION statement.

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.

Permissions
None.

Side effects
None.

See also
● “COMMIT statement” on page 501
● “ROLLBACK statement” on page 865
● “SAVEPOINT statement” on page 870
● “isolation_level option” [SQL Anywhere Server - Database Administration]
● “chained option” [SQL Anywhere Server - Database Administration]
● “Savepoints within transactions” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL BEGIN TRANSACTION is 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
in the database server messages window.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 489


SQL statements

PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
COMMIT
PRINT @@trancount
COMMIT
PRINT @@trancount

BREAK statement [T-SQL]


Exits a compound statement or loop.

Syntax
BREAK

Remarks
The BREAK statement is a control statement that allows you to leave a loop. Execution resumes at the
first statement after the loop.

Permissions
None.

Side effects
None.

See also
● “WHILE statement [T-SQL]” on page 960
● “CONTINUE statement” on page 507
● “BEGIN statement” on page 484
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]

Standards and compatibility


● SQL/2008 Transact-SQL extension.

Example
In this example, 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:
WHILE ( SELECT AVG( UnitPrice ) FROM Products ) < $30
BEGIN
UPDATE Products
SET UnitPrice = UnitPrice + 2
IF ( SELECT MAX(UnitPrice) FROM Products ) > $50
BREAK
END

490 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CALL statement
Invokes a procedure.

Syntax 1
[variable = ] CALL procedure-name ( [ expression, ... ] )

Syntax 2
[variable = ] CALL procedure-name ( [ parameter-name = expression, ... ] )

Remarks
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 value is copied
back.

The argument list can be specified by position or by using keyword format. By position, the arguments
match up with the corresponding parameter in the parameter list for the procedure (DEFAULT can be
used for an optional parameter). 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. 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.

Subqueries and spatial method calls are not allowed as arguments to a stored procedure in a CALL
statement.

Procedures can return an integer value (for example, as a status indicator) 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, ... )

If the procedure being called returns an INT and the value is NULL, then the error status value, 0, is
returned instead. There is no way to differentiate between this case and the case of an actual value of 0
being returned.

Note
Use of this statement to invoke a function is deprecated. If you have a function you want to call, consider
using an assignment statement to invoke the function and assign its result to a variable. For example:

DECLARE varname INT;


SET varname=test( );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 491


SQL statements

Permissions
Must be the owner of the procedure, have EXECUTE permission for the procedure, or have DBA
authority.

Side effects
None.

See also
● “CREATE FUNCTION statement” on page 548
● “CREATE FUNCTION statement [External call]” on page 535
● “CREATE FUNCTION statement [Web service]” on page 541
● “CREATE PROCEDURE statement” on page 585
● “CREATE PROCEDURE statement [External call]” on page 567
● “CREATE PROCEDURE statement [Web service]” on page 575
● “GRANT statement” on page 760
● “EXECUTE statement [T-SQL]” on page 724
● “Result sets” [SQL Anywhere Server - SQL Usage]
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]

Standards and compatibility


● SQL/2008 Core feature. The use of the RETURN statement to return a value from a stored
procedure is a vendor extension; SQL/2008 supports return values only for SQL-invoked functions,
not for procedures. Default values for stored procedure arguments are not supported in SQL/2008.

Example
Call the ShowCustomers procedure. This procedure has no parameters, and returns a result set.
CALL ShowCustomers();

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(SalesOrders.ID)
INTO Orders
FROM Customers
KEY LEFT OUTER JOIN SalesOrders
WHERE Customers.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

492 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CASE statement
Selects an execution path based on multiple cases.

Syntax 1
CASE value-expression
WHEN [ constant | NULL ] THEN statement-list ...
[ WHEN [ constant | NULL ] THEN statement-list ] ...
[ ELSE statement-list ]
END [ CASE ]

Syntax 2
CASE
WHEN [ search-condition | NULL] THEN statement-list ...
[ WHEN [ search-condition | NULL] THEN statement-list ] ...
[ ELSE statement-list ]
END [ CASE ]

Remarks
Syntax 1 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. The value-expression is an expression that
takes on a single value, which may be a string, a number, a date, or other SQL data type. 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.

If the value-expression can be null, use the ISNULL function to replace the NULL value-expression with
a different expression.

Syntax 2 With this form, the statements are executed for the first satisfied search-condition in the
CASE statement. The ELSE clause is executed if none of the search-conditions are met.

If the expression can be NULL, use the following syntax for the first search-condition:
WHEN search-condition IS NULL THEN statement-list

Note
Do not confuse the syntax of the CASE statement with that of the CASE expression.

Permissions
None.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 493


SQL statements

See also
● “ISNULL function [Miscellaneous]” on page 253
● “Unknown values: NULL” [SQL Anywhere Server - SQL Usage]
● “BEGIN statement” on page 484
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]
● “CASE expressions” on page 16
● “CASE statement [T-SQL]” on page 495

Standards and compatibility


● SQL/2008 The CASE statement is part of language feature P002 (Computational completeness) of
the SQL/2008 standard. The use of END alone, rather than END CASE, is a vendor extension.

● Transact-SQL The CASE statement is supported by Adaptive Server Enterprise.

Example
The following procedure using a case statement classifies the products listed in the Products table of the
SQL Anywhere sample database into one of shirt, hat, shorts, or unknown.
CREATE PROCEDURE ProductType (IN product_ID INT, OUT type CHAR(10))
BEGIN
DECLARE prod_name CHAR(20);
SELECT Name INTO prod_name FROM Products
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 example uses Syntax 2 to generate a message about product quantity within the SQL
Anywhere sample database.
CREATE PROCEDURE StockLevel (IN product_ID INT)
BEGIN
DECLARE qty INT;
SELECT Quantity INTO qty FROM Products
WHERE ID = product_ID;
CASE
WHEN qty < 30 THEN
MESSAGE 'Order Stock' TO CLIENT;
WHEN qty > 100 THEN
MESSAGE 'Overstocked' TO CLIENT;
ELSE
MESSAGE 'Sufficient stock on hand' TO CLIENT;
END CASE;
END;

494 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CASE statement [T-SQL]


Selects an execution path based on multiple cases.

Syntax 1
CASE value-expression
WHEN [ constant | NULL ] THEN statement-list ...
[ WHEN [ constant | NULL ] THEN statement-list ] ...
[ ELSE statement-list ]
END

Syntax 2
CASE
WHEN [ search-condition | NULL] THEN statement-list ...
[ WHEN [ search-condition | NULL] THEN statement-list ] ...
[ ELSE statement-list ]
END

Remarks
Syntax 1 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. The value-expression is an expression that
takes on a single value, which may be a string, a number, a date, or other SQL data type. 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.

If the value-expression can be null, use the ISNULL function to replace the NULL value-expression with
a different expression.

Syntax 2 With this form, the statements are executed for the first satisfied search-condition in the
CASE statement. The ELSE clause is executed if none of the search-conditions are met.

If the expression can be NULL, use the following syntax for the first search-condition:
WHEN search-condition IS NULL THEN statement-list

Note
Do not confuse the syntax of the CASE statement with that of the CASE expression.

Permissions
None.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 495


SQL statements

See also
● “ISNULL function [Miscellaneous]” on page 253
● “BEGIN statement” on page 484
● “CASE expressions” on page 16
● “Unknown values: NULL” [SQL Anywhere Server - SQL Usage]
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]

Standards and compatibility


● SQL/2008 The CASE statement is part of language feature P002 (Computational completeness) of
the SQL/2008 standard. The SQL standard requires END CASE to terminate the CASE statement,
rather than END alone.

● Transact-SQL Compatible with Adaptive Server Enterprise.

Example
The following procedure using a case statement classifies the products listed in the Products table of the
SQL Anywhere sample database into one of shirt, hat, shorts, or unknown.
CREATE PROCEDURE DBA.ProductType( @product_ID INTEGER,@TYPE CHAR(10)
OUTPUT ) AS
BEGIN
DECLARE @prod_name CHAR(20)
SELECT Name INTO @prod_name FROM Products
WHERE ID = @product_ID
IF @prod_name
= 'Tee Shirt'
SET @TYPE = 'Shirt'
ELSE IF @prod_name
= 'Sweatshirt'
SET @TYPE = 'Shirt'
ELSE IF @prod_name
= 'Baseball Cap'
SET @TYPE = 'Hat'
ELSE IF @prod_name
= 'Visor'
SET @TYPE = 'Hat'
ELSE IF @prod_name
= 'Shorts'
SET @TYPE = 'Shorts'
ELSE
SET @TYPE = 'UNKNOWN'
END;

The following example uses Syntax 2 to generate a message about product quantity within the SQL
Anywhere sample database.
CREATE PROCEDURE DBA.StockLevel( @product_ID INTEGER ) AS
BEGIN
DECLARe @qty INTEGER
SELECT Quantity INTO @qty FROM Products
WHERE ID = @product_ID
IF @qty < 30
MESSAGE 'Order Stock' TO CLIENT
ELSE IF @qty > 100
MESSAGE 'Overstocked' TO CLIENT

496 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

ELSE
MESSAGE 'Sufficient stock on hand' TO CLIENT
END;

CHECKPOINT statement
Checkpoints the database.

Syntax
CHECKPOINT

Remarks
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 to issue the CHECKPOINT statement.

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
● “Backup and data recovery” [SQL Anywhere Server - Database Administration]
● “Checkpoint logs” [SQL Anywhere Server - Database Administration]
● “checkpoint_time option” [SQL Anywhere Server - Database Administration]
● “recovery_time option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL The CHECKPOINT statement is supported by Adaptive Server Enterprise.

CLEAR statement [Interactive SQL]


Closes any open result sets in Interactive SQL.

Syntax
CLEAR

Remarks
Closes any open result sets and leaves the contents of the SQL Statements pane unchanged

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 497


SQL statements

Permissions
None.

Side effects
Closes the cursor associated with the data being cleared.

See also
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

CLOSE statement [ESQL] [SP]


Closes a cursor.

Syntax
CLOSE cursor-name

cursor-name : identifier | hostvar

Remarks
This statement closes the named cursor.

Permissions
The cursor must have been previously opened.

Side effects
None.

See also
● “OPEN statement [ESQL] [SP]” on page 821
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “PREPARE statement [ESQL]” on page 833

Standards and compatibility


● SQL/2008 Core feature. When used in embedded SQL, the CLOSE statement is part of optional
language feature B031 (Basic dynamic SQL).

● Transact-SQL Supported by Adaptive Server Enterprise.

Example
The following examples close cursors in embedded SQL.

498 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

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 CompanyName, CAST( sum(SalesOrderItems.Quantity *
Products.UnitPrice) AS INTEGER) VALUE
FROM Customers
LEFT OUTER JOIN SalesOrders
LEFT OUTER JOIN SalesOrderItems
LEFT OUTER JOIN Products
GROUP BY CompanyName;
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

COMMENT statement
Stores a comment for a database object in the system tables.

Syntax
COMMENT ON {
COLUMN [ owner.]table-name.column-name
| DBSPACE dbspace-name
| EVENT [ owner.]event-name
| EXTERNAL ENVIRONMENT environment-name
| EXTERNAL [ ENVIRONMENT ] OBJECT object-name
| FOREIGN KEY [ owner.]table-name.role-name
| INDEX [ [ owner.] table.]index-name
| INTEGRATED LOGIN integrated-login-id
| JAVA CLASS java-class-name
| JAVA JAR java-jar-name
| KERBEROS LOGIN "client-Kerberos-principal"
| LOGIN POLICY policy-name
| MATERIALIZED VIEW [ owner.]materialized-view-name
| MIRROR SERVER mirror-server-name
| PRIMARY KEY ON [ owner.]table-name

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 499


SQL statements

| PROCEDURE [ owner.]procedure-name
| SEQUENCE sequence-name
| SERVICE web-service-name
| SPATIAL REFERENCE SYSTEM srs-name
| SPATIAL UNIT OF MEASURE uom-identifier
| TABLE [ owner.]table-name
| TEXT CONFIGURATION [ owner.]text-config-name
| TEXT INDEX text-index-name ON [ owner.]table-name
| TRIGGER [ [ owner.]tablename.]trigger-name
| USER userid
| VIEW [ owner.]view-name
}
IS comment

comment : string | NULL

environment-name :
JAVA
| PERL
| PHP
| CLR
| C_ESQL32
| C_ESQL64
| C_ODBC32
| C_ODBC64

Remarks
The COMMENT statement allows you to set a remark (comment) for an object in the database. The
COMMENT statement updates remarks listed in the ISYSREMARKS system table. You can remove a
comment 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.

You cannot add comments for local temporary tables.

If you use the Database Documentation Wizard to document your SQL Anywhere database, you have
the option to include the comments for procedures, functions, triggers, events, and views in the output.

Permissions
Must either be the owner of the database object being commented, or have DBA authority.

Side effects
Automatic commit.

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL Not supported by Adaptive Server Enterprise.

Example
The following examples show how to add and remove a comment.

1. Add a comment to the Employees table.

500 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

COMMENT
ON TABLE Employees
IS 'Employee information';

2. Remove the comment from the Employees table.

COMMENT
ON TABLE Employees
IS NULL;

To view the comment set for an object, use a SELECT statement similar to the following. This example
retrieves the comment set for the ViewSalesOrders view in the SQL Anywhere sample database.

SELECT remarks
FROM SYSTAB t, SYSREMARK r
WHERE t.object_id = r.object_id
AND t.table_name = 'ViewSalesOrders';

See also
● “Documenting a database” [SQL Anywhere Server - Database Administration]

COMMIT statement
Makes changes to the database permanent, or terminates a user-defined transaction.

Syntax 1
COMMIT [ WORK ]

Syntax 2
COMMIT TRAN[SACTION] [ transaction-name ]

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.

For more information about transaction nesting in Adaptive Server Enterprise and SQL Anywhere, see
“BEGIN TRANSACTION statement [T-SQL]” on page 488.

You can use a set of options to control the detailed behavior of the COMMIT statement. See:

○ “cooperative_commit_timeout option” [SQL Anywhere Server - Database Administration]


○ “cooperative_commits option” [SQL Anywhere Server - Database Administration]
○ “delayed_commits option” [SQL Anywhere Server - Database Administration]
○ “delayed_commit_timeout option” [SQL Anywhere Server - Database Administration]
○ “Permanent data changes” [SQL Anywhere Server - SQL Usage]

You can use the Commit connection property to return the number of commits on the current connection.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 501


SQL statements

Remarks
● Syntax 1 The COMMIT statement ends a transaction and makes all changes made during this
transaction permanent in the database.

All data definition statements automatically perform a commit. 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 behavior
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 option, the database
server delays integrity checking until the COMMIT statement is executed.

The use of COMMIT alone is equivalent to COMMIT WORK.

● 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.

Syntax 2 is a Transact-SQL extension.

In Interactive SQL, you can also execute a COMMIT by:

● Pressing Ctrl+Shift+C.

● Clicking SQL » Commit.

In Interactive SQL, executing a COMMIT from the SQL menu or the keyboard shortcut does not modify
the contents of the SQL Statements pane; however, the Results tab in the Results pane is cleared.

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.

If the database is not using a transaction log, each COMMIT operation causes an implicit checkpoint.

502 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “wait_for_commit option” [SQL Anywhere Server - Database Administration]
● “auto_commit option [Interactive SQL]” [SQL Anywhere Server - Database Administration]
● “commit_on_exit option [Interactive SQL]” [SQL Anywhere Server - Database Administration]
● “Executing COMMIT and ROLLBACK statements in Interactive SQL” [SQL Anywhere Server -
Database Administration]
● “SAVEPOINT statement” on page 870
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “BEGIN TRANSACTION statement [T-SQL]” on page 488
● “PREPARE TO COMMIT statement” on page 835
● “ROLLBACK statement” on page 865

Standards and compatibility


● SQL/2008 Syntax 1 is a core feature. Syntax 2 is a Transact-SQL extension.

Example
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

CONFIGURE statement [Interactive SQL]


Opens the Interactive SQL Options window.

Syntax
CONFIGURE

Remarks
The CONFIGURE statement opens the Interactive SQL Options window. This window displays the
current settings of all Interactive SQL options. It does not display or allow you to modify database
options. You can configure Interactive SQL settings in this window.

Permissions
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 503


SQL statements

Side effects
None.

See also
● “Customizing Interactive SQL” [SQL Anywhere Server - Database Administration]
● “SET OPTION statement” on page 886
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

CONNECT statement [ESQL] [Interactive SQL]


Establishes a connection to a database.

Syntax 1 - Shared memory connections


CONNECT
[ TO database-server-name ]
[ DATABASE database-name ]
[ AS connection-name ]
[ USER ] userid [ IDENTIFIED BY password ]

database-server-name, database-name, connection-name, userid, password :


{ identifier | string | hostvar }

Syntax 2 - TCP/IP connections


CONNECT USING connect-string

connect-string : { identifier | string | hostvar }

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.

For Syntax 2, a connect-string is a list of parameter settings of the form keyword=value, separated by
semicolons, and must be enclosed in single quotes.

Remarks
The CONNECT statement establishes a connection to the database identified by database-name running
on the database server identified by database-server-name. This statement is not supported in procedures,
triggers, events, or batches.

504 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax 1 is only supported for shared memory connections to database servers running on the same
computer. If you want to connect to a local database server using TCP/IP or to a database server running
on a different computer, you must use Syntax 2.

● Embedded SQL behavior In embedded SQL, if no database-server-name is specified, the default


local database server is assumed (the first database server started). If no database-name is specified,
the first database on the given server is assumed.

The WHENEVER statement, SET SQLCA, and some DECLARE statements do not generate code
and 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.

Note
For SQL Anywhere, only Syntax 1 is valid with embedded SQL. For UltraLite, both Syntax 1 and
Syntax 2 can be used with embedded 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 );


CONNECT DBA IDENTIFIED BY sql;
CREATE TABLE t2 (c1 int );

No other database statements are allowed until a successful CONNECT statement has been executed.

When Interactive SQL is run in windowed mode, you are prompted for any missing connection
parameters.

When Interactive SQL is running in command-prompt mode (-nogui is specified when you start
Interactive SQL from a command line) or batch mode, or if you execute CONNECT without an AS
clause, an unnamed connection is opened. If there is another unnamed connection already opened, the
old one is automatically closed. Otherwise, existing connections are not closed when you execute a
CONNECT statement.

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.

When connecting to Interactive SQL, specifying CONNECT [ USER ] userid is the same as executing
a SETUSER WITH OPTION userid statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 505


SQL statements

In Interactive SQL, the connection information (including the database name, your user ID, and the
database server) appears in the title bar above the SQL Statements pane. If you are not connected to a
database, Not Connected appears in the title bar.

Note
Both Syntax 1 and Syntax 2 are valid with Interactive SQL except that Interactive SQL does not
support the hostvar argument.

Permissions
None.

Side effects
None.

See also
● “GRANT statement” on page 760
● “DISCONNECT statement [ESQL] [Interactive SQL]” on page 688
● “SET CONNECTION statement [Interactive SQL] [ESQL]” on page 881
● “SETUSER statement” on page 904
● “Troubleshooting connections” [SQL Anywhere Server - Database Administration]
● “Connection parameters” [SQL Anywhere Server - Database Administration]
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Syntax 1 is optional language feature F771 of the SQL/2008 standard. Syntax 2 is a
vendor extension.

● Transact-SQL Both Syntax 1 and Syntax 2 are supported by Adaptive Server Enterprise.

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";

The following examples assume that the SQL Anywhere sample database has already been started.

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 user DBA from Interactive SQL.


CONNECT
TO demo12

506 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

USER DBA
IDENTIFIED BY sql;

Connect to the sample database using a connection string, from Interactive SQL.
CONNECT
USING 'UID=DBA;PWD=sql;DBN=demo';

Once you connect to the sample database, the database name, your user ID, and the database server name
appear in the title bar as: demo (DBA) on demo12.

CONTINUE statement
Restarts a loop.

Syntax
CONTINUE [ statement-label ]

Remarks
The CONTINUE statement is a control statement that allows you to restart a loop. Execution continues at
the first statement in the loop. When CONTINUE appears within a set of Watcom-SQL statements,
statement-label must be specified.

When CONTINUE appears within a set of statements using Transact-SQL, statement-label must not be
used.

Permissions
None.

Side effects
None.

See also
● “LOOP statement” on page 810
● “WHILE statement [T-SQL]” on page 960
● “FOR statement” on page 733
● “BEGIN statement” on page 484
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL CONTINUE without a statement label is supported by Adaptive Server Enterprise.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 507


SQL statements

Example
The following fragment shows how the CONTINUE statement is used to restart a loop. This example
displays the odd numbers between 1 and 10.
BEGIN
DECLARE i INT;
SET i = 0;
lbl:
WHILE i < 10 LOOP
SET i = i + 1;
IF mod( i, 2 ) = 0 THEN
CONTINUE lbl
END IF;
MESSAGE 'The value ' || i || ' is odd.' TO CLIENT;
END LOOP lbl;
END

CREATE DATABASE statement


Creates a database.

Syntax
CREATE DATABASE db-filename-string [ create-option ... ]

create-option :
[ ACCENT { RESPECT | IGNORE | FRENCH } ]
[ ASE [ COMPATIBLE ] ]
[ BLANK PADDING { ON | OFF } ]
[ CASE { RESPECT | IGNORE } ]
[ CHECKSUM { ON | OFF } ]
[ COLLATION collation-label[ ( collation-tailoring-string ) ] ]
[ DATABASE SIZE size { KB | MB | GB | PAGES | BYTES } ]
[ DBA USER userid ]
[ DBA PASSWORD password ]
[ ENCODING encoding-label ]
[ ENCRYPTED [ TABLE ] { algorithm-key-spec | OFF } ]
[ JCONNECT { ON | OFF } ]
[ PAGE SIZE page-size ]
[ NCHAR COLLATION nchar-collation-label[ ( collation-tailoring-string ) ] ]
[ [ TRANSACTION ] { LOG OFF | LOG ON [ log-filename-string ]
[ MIRROR mirror-filename-string ] } ]

page-size :
2048 | 4096 | 8192 | 16384 | 32768

algorithm-key-spec :
ON
| [ ON ] KEY key [ ALGORITHM AES-algorithm ]
| [ ON ] ALGORITHM AES-algorithm KEY key
| [ ON ] ALGORITHM 'SIMPLE'

AES-algorithm :
'AES' | 'AES256' | 'AES_FIPS' | 'AES256_FIPS'

508 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

key : quoted string

Parameters
CREATE DATABASE The file names (db-filename-string, log-filename-string, and mirror-filename-
string) are strings containing operating system file names. As literal strings, they must be enclosed in
single quotes.

○ 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 from being interpreted as new line characters (\n) or as hexadecimal
numbers (\x), according to the rules for strings in SQL.
It is always safer to escape the backslash character. For example:
CREATE DATABASE 'c:\\databases\\my_db.db'
LOG ON 'e:\\logdrive\\my_db.log';

○ If you do not specify a path, or a relative path, the database file is created relative to the working
directory of the database server. If you specify no path for a transaction log file, the file is created in the
same directory as the database file. It is recommended that you store the database files and the
transaction log on separate disks on the computer.

○ If you provide no file extension, a file is created with extension .db for databases, .log for the
transaction log, and .mlg for the transaction log mirror.

You cannot specify utility_db for db-filename-string. This name is reserved for the utility database.

ACCENT clause This clause is used to specify accent sensitivity for the database. Support for this
clause is deprecated. Use the collation tailoring options provided for the COLLATION and NCHAR
COLLATION clauses to specify accent sensitivity.

The ACCENT clause applies only when using the UCA (Unicode Collation Algorithm) for the collation
specified in the COLLATION or NCHAR COLLATION clause. ACCENT RESPECT causes the UCA
string comparison to respect accent differences between letters. For example, e is less than é. ACCENT
FRENCH is similar to ACCENT RESPECT, except that accents are compared from right to left,
consistent with the rules of the French language. ACCENT IGNORE causes string comparisons to ignore
accents. For example, e is equal to é.

If accent sensitivity is not specified when the database is created, the default accent sensitivity for
comparisons and sorting is insensitive, with one exception; for Japanese databases created with a UCA
collation, the default accent sensitivity is sensitive.

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
(version 4 and earlier of this software). These views conflict with the Adaptive Server Enterprise
compatibility views dbo.syscolumns and dbo.sysindexes.

BLANK PADDING clause SQL Anywhere compares all strings as if they are varying length and
stored using the VARCHAR domain. This includes string comparisons involving fixed length CHAR or
NCHAR columns. In addition, SQL Anywhere never trims or pads values with trailing blanks when the
values are stored in the database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 509


SQL statements

By default, SQL Anywhere treats blanks as significant characters. For example, the value 'a ' (the
character 'a' followed by a blank) is not equivalent to the single-character string 'a'. Inequality
comparisons also treat a blank as any other character in the collation.

If blank padding is enabled (specifying BLANK PADDING ON), the semantics of string comparisons
more closely follow the ANSI/ISO SQL standard. With blank-padding enabled, SQL Anywhere ignores
trailing blanks in any comparison.

In the example above, an equality comparison of 'a ' to 'a' in a blank-padded database returns TRUE. With
a blank-padded database, fixed-length string values are padded with blanks when they are fetched by an
application. Whether the application receives a string truncation warning on such an assignment is
controlled by the ansi_blanks connection option.

CASE clause This clause is used to specify case sensitivity for the database. Support for this clause is
deprecated. Use the collation tailoring options provided for the COLLATION and NCHAR COLLATION
clauses to specify case sensitivity.

CASE RESPECT causes case-sensitive string comparisons for all CHAR and NCHAR data types.
Comparisons using UCA consider the case of a letter only if the base letters and accents are all equal. For
all other collations, uppercase and lowercase letters are distinct; for example, a is less than A, which is
less than b, and so on. CASE IGNORE causes case-insensitive string comparisons. Uppercase and
lowercase letters are considered to be exactly equal.

If case sensitivity is not specified when the database is created, default case sensitivity for comparisons
and sorting is insensitive, with one exception; for Japanese databases created with a UCA collation,
default case sensitivity is sensitive.

CASE RESPECT is provided for compatibility with the ISO/ANSI SQL standard. Identifiers in the
database are always case insensitive, even in case-sensitive databases.

CHECKSUM clause Checksums are used to determine whether a database page has been modified on
disk. When you create a database with global checksums enabled, a checksum is calculated for each page
just before it is written to disk. The next time the page is read from disk, the page's checksum is
recalculated and compared to the checksum stored on the page. If the checksums are different, then the
page has been modified on disk and an error occurs. Databases created with global checksums enabled
can also be validated using checksums. You can check whether a database was created with global
checksums enabled by executing the following statement:
SELECT DB_PROPERTY ( 'Checksum' );

This query returns ON if global checksums are turned on, otherwise, it returns OFF. Global checksums
are turned on by default, so if the CHECKSUM clause is omitted, ON is applied.

Regardless of the setting of this clause, the database server always enables write checksums for databases
running on storage devices such as removable drives, and databases running on Windows Mobile to help
provide early detection if the database file becomes corrupt. It also calculates checksums for critical pages
during validation activities.

For databases that do not have global checksums enabled, you can enable write checksums by using the -
wc options.

510 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

COLLATION clause The collation specified by the COLLATION clause is used for sorting and
comparison of character data types (CHAR, VARCHAR, and LONG VARCHAR). The collation
provides character comparison and ordering information for the encoding (character set) being used. If the
COLLATION clause is not specified, SQL Anywhere chooses a collation based on the operating system
language and encoding.

The collation can be chosen from the list of collations that use the SQL Anywhere Collation Algorithm
(SACA), or it can be the Unicode Collation Algorithm (UCA). If UCA is specified, you should also
specify the ENCODING clause.

It is important to choose your collation carefully. It cannot be changed after the database has been created.

Optionally, you can specify collation tailoring options (collation-tailoring-string) for additional control
over the sorting and comparing of characters. These options take the form of keyword=value pairs,
assembled in parentheses, following the collation name. For example, ... CHAR COLLATION
'UCA(locale=es;case=respect;accent=respect)'.

DATABASE SIZE clause Use this optional clause to set the initial size of the database file. You can
use KB, MB, GB, or PAGES to specify units of kilobytes, megabytes, gigabytes, or pages respectively.

Specifying the file size at creation time is a way of pre-allocating space for the file. This helps reduce the
risk of running out of space on the drive the database is located on. As well, it can help improve
performance by increasing the amount of data that can be stored in the database before the database server
needs to grow the database, which can be a time-consuming operation.

DBA USER clause Use this clause to specify a DBA user for the database. When you use this clause,
you can no longer connect to the database as the default DBA user. If you do not specify this clause, the
default DBA user ID is created.

DBA PASSWORD clause You can specify a different password for the DBA database user. If you do
not specify this clause, the default password (sql) is used for the DBA user.

○ User IDs cannot:

● begin with white space, single quotes, or double quotes


● end with white space
● contain semicolons

○ Passwords are case-sensitive and they cannot:

● begin with white space, single quotes, or double quotes


● end with white space
● contain semicolons
● be longer than 255 bytes in length

ENCODING clause Most collations specified in the COLLATION clause dictate both the encoding
(character set) and ordering. For those collations, the ENCODING clause should not be specified.
However, if the value specified in the COLLATION clause is UCA (Unicode Collation Algorithm), use
the ENCODING clause to specify a locale-specific encoding and get the benefits of the UCA for

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 511


SQL statements

comparison and ordering. The ENCODING clause may specify UTF-8 or any single-byte encoding for
CHAR data types. ENCODING may not specify a multibyte encoding other than UTF-8.

If you choose the UCA collation, you can optionally specify collation tailoring options.

If COLLATION is set to UCA and ENCODING is not specified, then SQL Anywhere uses UTF-8.

ENCRYPTED or ENCRYPTED TABLE clause Encryption makes stored data unreadable. Use the
ENCRYPTED keyword (without TABLE) when you want to encrypt the entire database. Use the
ENCRYPTED TABLE clause when you only want to enable table encryption. Enabling table encryption
means that the tables that are subsequently created or altered using the ENCRYPTED clause are
encrypted using the settings you specified at database creation.

There are two levels of database and table encryption: simple and strong. Simple encryption is equivalent
to obfuscation. The data is unreadable, but someone with cryptographic expertise could decipher the data.
Strong encryption makes the data is unreadable and virtually undecipherable.

For simple encryption, specify ENCRYPTED ON ALGORITHM SIMPLE, or ENCRYPTED


ALGORITHM SIMPLE, or specify the ENCRYPTED ON clause without specifying an algorithm or key.

For strong encryption, specify ENCRYPTED ON ALGORITHM with a 128-bit or 256-bit AES
algorithm, and the KEY clause to specify an encryption key. It is recommended that you choose a value
for your key that is at least 16 characters long, contains a mix of uppercase and lowercase, and includes
numbers, letters, and special characters.

On Windows Mobile, the AES_FIPS and AES256_FIPS algorithms are only supported with ARM
processors.

Caution
For strongly encrypted databases, be sure to store a copy of the key in a safe location. If you lose the
encryption key there is no way to access the data, even with the assistance of technical support. The
database must be discarded and you must create a new database.

You can also create an encrypted copy of an existing database using the CREATE ENCRYPTED
DATABASE statement.

JCONNECT clause To allow the jConnect JDBC driver access to system catalog information, specify
JCONNECT ON. This clause installs the system objects that provide jConnect support. Specify
JCONNECT OFF if you want to exclude the jConnect system objects. You can still use JDBC, as long as
you do not access system information. JCONNECT is ON by default.

PAGE SIZE clause The page size for a database can be 2048, 4096, 8192, 16384, or 32768 bytes. The
default page size is 4096 bytes. Large databases generally obtain performance benefits from a larger page
size, but there can be additional overhead associated with large page sizes.

For example:
CREATE DATABASE 'c:\\databases\\my_db.db'
PAGE SIZE 4096;

512 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Note
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 option.

NCHAR COLLATION clause The collation specified by the NCHAR COLLATION clause is used for
sorting and comparison of national character data types (NCHAR, NVARCHAR, and LONG
NVARCHAR). The collation provides character ordering information for the UTF-8 encoding (character
set) used for national characters. If the NCHAR COLLATION clause is not specified, SQL Anywhere
uses the Unicode Collation Algorithm (UCA). The only other allowed collation is UTF8BIN, which
provides a binary ordering of all characters whose encoding is greater than 0x7E.

Optionally, you can specify collation tailoring options (collation-tailoring-string) for additional control
over the sorting and comparing of characters. These options take the form of keyword=value pairs,
assembled in a quoted string, following the collation name. For example, ... NCHAR COLLATION
'UCA(locale=es;case=respect;accent=respect)'. If you specify the ACCENT or CASE
clause and a collation tailoring string that contains settings for case and accent, the values of the
ACCENT and CASE clauses are used as defaults only.

Note
When you specify the UCA collation, all collation tailoring options are supported. For all other collations,
only the case sensitivity tailoring option is supported.

Databases created with collation tailoring options cannot be started using a pre-10.0.1 database server.

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, and in data replication.

The MIRROR clause of the TRANSACTION clause allows you to provide a file name if you want to use
a transaction log mirror. 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, SQL Anywhere does not
use a transaction log mirror.

Remarks
Cloud note: This statement is not supported on tenant databases in the cloud.

Creates a database file with the supplied name and attributes. The database is stored as an operating
system file. This statement is not supported in procedures, triggers, events, or batches.

Permissions
The permissions required to execute this statement are set on the server command line, using the -gu
option. The default setting requires DBA authority.

The account under which the database server is running must have write permissions on the directories
where files are created.

Side effects
An operating system file is created.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 513


SQL statements

See also
● “ALTER DATABASE statement” on page 400
● “DROP DATABASE statement” on page 690
● “Initialization utility (dbinit)” [SQL Anywhere Server - Database Administration]
● “DatabaseKey (DBKEY) connection parameter” [SQL Anywhere Server - Database Administration]
● “The transaction log” [SQL Anywhere Server - Database Administration]
● “Validation utility (dbvalid)” [SQL Anywhere Server - Database Administration]
● “Corruption detection using checksums” [SQL Anywhere Server - Database Administration]
● “VALIDATE statement” on page 955
● “CREATE ENCRYPTED DATABASE statement” on page 521
● “Table encryption” [SQL Anywhere Server - Database Administration]
● “Utility databases” [SQL Anywhere Server - Database Administration]
● “ansi_blanks option” [SQL Anywhere Server - Database Administration]
● “-gp dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “-wc dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “-wc dbeng12/dbsrv12 database option” [SQL Anywhere Server - Database Administration]
● “sa_validate system procedure” on page 1157
● “Collation tailoring options” [SQL Anywhere Server - Database Administration]
● “Collation considerations” [SQL Anywhere Server - Database Administration]
● “Supported and alternate collations” [SQL Anywhere Server - Database Administration]
● “Strong encryption” [SQL Anywhere Server - Database Administration]
● “jConnect on Windows Mobile” [SQL Anywhere Server - Database Administration]
● “International languages and character sets” [SQL Anywhere Server - Database Administration]
● “Recommended character sets and collations” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL The CREATE DATABASE statement is supported by Adaptive Server Enterprise,


though with different clauses.

Examples
The following statement creates a database file named mydb.db in the C:\ directory.
CREATE DATABASE 'C:\\mydb.db'
TRANSACTION LOG ON
CASE IGNORE
PAGE SIZE 4096
ENCRYPTED OFF
BLANK PADDING OFF;

The following statement creates a database using code page 1252 and uses the UCA for both CHAR and
NCHAR data types. Accents and case are respected during comparison and sorting.
CREATE DATABASE 'c:\\uca.db'
COLLATION 'UCA'
ENCODING 'CP1252'
NCHAR COLLATION 'UCA'
ACCENT RESPECT
CASE RESPECT;

The following statement creates a database, myencrypteddb.db, that is encrypted using simple encryption:

514 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE DATABASE 'myencrypteddb.db'


ENCRYPTED ON;

The following statement creates a database, mystrongencryptdb.db, that is encrypted using the key
gh67AB2 (strong encryption):
CREATE DATABASE 'mystrongencryptdb.db'
ENCRYPTED ON KEY 'gh67AB2';

The following statement creates a database, mytableencryptdb.db, with table encryption enabled using
simple encryption. Notice the keyword TABLE inserted after ENCRYPTED to indicate table encryption
instead of database encryption:
CREATE DATABASE 'mytableencryptdb.db'
ENCRYPTED TABLE ON;

The following statement creates a database, mystrongencrypttabledb.db, with table encryption enabled
using the key gh67AB2 (strong encryption), and the AES_FIPS encryption algorithm:
CREATE DATABASE 'mystrongencrypttabledb.db'
ENCRYPTED TABLE ON KEY 'gh67AB2'
ALGORITHM 'AES_FIPS';

The following statement creates a database file named mydb.db that uses collation 1252LATIN1. The
NCHAR collation is set to UCA, with the locale set to es, and has case sensitivity and accent sensitivity
enabled:
CREATE DATABASE 'my2.db'
COLLATION '1252LATIN1(case=respect)'
NCHAR COLLATION 'UCA(locale=es;case=respect;accent=respect)';

CREATE DBSPACE statement


Defines a new database space and creates the associated database file.

Syntax
CREATE DBSPACE dbspace-name AS filename

Parameters
dbspace-name Specify a name for the dbspace. This is not the actual database file name, which you
specify using filename. dbspace-name is an internal name you can refer to, for example in statements and
procedures. You cannot use the following names for a dbspace because they are reserved for predefined
dbspaces: system, temporary, temp, translog, and translogmirror.

An error is returned if you specify a value that contains a period (.).

filename Specify a name for the database file, including, optionally, the path to the file. If no path is
specified, the database file is created in the same location (directory) as the main database file. If you
specify a different location, the path is relative to the database server. The backslash ( \ ) is an escape
character in SQL strings, so each backslash must be doubled.

The filename parameter must be either a string literal or a variable.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 515


SQL statements

Cloud note: For tenant databases in a cloud, when you specify the location of a dbspace, you can
specify only a file name. You cannot specify a directory path.

Remarks
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 in addition to the main file.

Each object, such as a table or index, is contained entirely within one dbspace. The IN clause of the
CREATE statement specifies the dbspace into which an object is placed. Objects are put into the system
database file by default. You can also specify which dbspace tables are created in by setting the
default_dbspace option before you create the tables.

Permissions
DBA authority.

Side effects
Automatic commit. Automatic checkpoint.

See also
● “DROP DBSPACE statement” on page 692
● “default_dbspace option” [SQL Anywhere Server - Database Administration]
● “Strings” on page 5
● “Predefined dbspaces” [SQL Anywhere Server - Database Administration]
● “Additional dbspaces considerations” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following CREATE DBSPACE statement creates a dbspace called libbooks. The database file name
for the dbspace is library.db, located in the c:\ directory. A subsequent CREATE TABLE statement
creates a table called LibraryBooks in the libbooks dbspace.
CREATE DBSPACE libbooks
AS 'c:\\library.db';
CREATE TABLE LibraryBooks (
title char(100),
author char(50),
isbn char(30),
) IN libbooks;

516 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE DECRYPTED DATABASE statement


Creates a decrypted copy of an existing database, including all transaction logs and dbspaces.

Syntax
CREATE DECRYPTED DATABASE newfile
FROM oldfile
[ KEY key ]

Parameters
FROM clause Use this clause to specify the name of the database to copy (oldfile).

KEY clause Use this clause to specify the encryption key needed to decrypt the database. You do not
specify the KEY clause if the existing database was encrypted with simple encryption, which does not
require a key.

Remarks
The CREATE DECRYPTED DATABASE statement produces a new database file (newfile), and does
not replace or remove the original database file (oldfile).

All encrypted tables in oldfile are not encrypted in newfile, and table encryption is not enabled.

Note
For databases created with SQL Anywhere 12 or later, the ISYSCOLSTAT, ISYSUSER, and
ISYSEXTERNLOGIN system tables always remain encrypted to protect the data from unauthorized
access.

If oldfile uses a transaction log or transaction log mirror, the files are renamed newfile.log and
newfile.mlg, respectively.

If oldfile contains dbspace files, a D (decrypted) is added to the file name. For example, when you execute
the CREATE DECRYPTED DATABASE statement, if oldfile is mydbspace.dbs, newfile becomes
mydbspace.dbsD.

You cannot execute this statement on a database that requires recovery. This statement is not supported in
procedures, triggers, events, or batches.

Permissions
DBA authority.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 517


SQL statements

See also
● “Database encryption and decryption” [SQL Anywhere Server - Database Administration]
● “CREATE ENCRYPTED DATABASE statement” on page 521
● “CREATE ENCRYPTED FILE statement” on page 524
● “CREATE DECRYPTED FILE statement” on page 518

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The first statement below creates an AES256-encrypted copy of the demo.db called demoEncrypted.db,.
The second statement creates a decrypted copy of demoEncrypted.db called demoDecrypted.db.
CREATE ENCRYPTED DATABASE 'demoEncrypted.db'
FROM 'demo.db'
KEY 'Sd8f6654*Mnn'
ALGORITHM 'AES256';
CREATE DECRYPTED DATABASE 'demoDecrypted.db'
FROM 'demoEncrypted.db'
KEY 'Sd8f6654*Mnn';

CREATE DECRYPTED FILE statement


Creates a decrypted copy of a strongly encrypted database, and can be used to create decrypted copies of
transaction logs, transaction log mirrors, and dbspaces.

Syntax
CREATE DECRYPTED FILE newfile
FROM oldfile KEY key

Parameters
FROM clause Lists the file name of the encrypted file.

KEY clause Lists the key required to access the encrypted file.

Remarks
Use this statement when your database requires recovery and you need to create a decrypted copy of the
database for support reasons. You must also use this statement to decrypt any database-related files such
as the transaction log, transaction log mirror, or dbspaces.

The original database file must be strongly encrypted using an encryption key. The resulting file is an
exact copy of the encrypted file, without encryption and therefore requiring no encryption key.

If a database is decrypted using this statement, the corresponding transaction log file (and any dbspaces)
must also be decrypted to use the database.

If a database requiring recovery is decrypted, its transaction log file must also be decrypted and recovery
on the new database is necessary. The name of the transaction log file remains the same in this process, so

518 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

if the database and transaction log file are renamed, then you need to run dblog -t on the resulting
database.

You cannot use this statement on a database that has table encryption enabled. If you have tables you
want to decrypt, use the NOT ENCRYPTED clause of the ALTER TABLE statements to decrypt them.

Note
For databases created with SQL Anywhere 12 or later, the ISYSCOLSTAT, ISYSUSER, and
ISYSEXTERNLOGIN system tables always remain encrypted to protect the data from unauthorized
access to the database file.

This statement is not supported in procedures, triggers, events, or batches.

Permissions
DBA authority.

Side effects
None.

See also
● “ALTER TABLE statement” on page 451
● “CREATE ENCRYPTED FILE statement” on page 524
● “CREATE DECRYPTED DATABASE statement” on page 517
● “CREATE ENCRYPTED DATABASE statement” on page 521

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example decrypts the contacts database and creates a new unencrypted database called
contacts2.
CREATE DECRYPTED FILE 'contacts2.db'
FROM 'contacts.db'
KEY 'Sd8f6654*Mnn';

CREATE DOMAIN statement


Creates a domain in a database.

Syntax
CREATE { DOMAIN | DATATYPE } [ AS ] domain-name data-type
[ [ NOT ] NULL ]
[ DEFAULT default-value ]
[ CHECK ( condition ) ]

domain-name : identifier

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 519


SQL statements

data-type : built-in data type, with precision and scale

Parameters
DOMAIN | DATATYPE clause It is recommended that you use CREATE DOMAIN, rather than
CREATE DATATYPE, because CREATE DOMAIN is defined in the SQL/2008 standard.

NULL clause This clause allows you to specify the nullability of a domain. When a domain is used to
define a column, nullability is determined as follows:

○ Nullability specified in the column definition.

○ Nullability specified in the domain definition.

○ If the nullability was not explicitly specified in either the column definition or the domain definition,
then the setting of the allow_nulls_by_default option is used.

CHECK clause When creating a domain with a CHECK constraint, you can use a variable name
prefixed with the @ sign in the CHECK constraint's search condition. When the data type is used in the
definition of a column, such a variable is replaced by the column name. This allows a domain's CHECK
constraint to be applied to each table column defined with that domain.

Remarks
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
domain. Any conditions or values explicitly specified in the column definition override those specified for
the domain.

To drop the domain from the database, use the DROP DOMAIN statement. You must be either the owner
of the domain, or have DBA authority, to drop a domain.

Permissions
RESOURCE authority.

Side effects
Automatic commit.

520 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “allow_nulls_by_default option” [SQL Anywhere Server - Database Administration]
● “DROP DOMAIN statement” on page 692
● “SQL data types” on page 81

Standards and compatibility


● SQL/2008 Domain support is optional SQL language feature F251 in the SQL/2008 standard.

Examples
The following statement creates a domain named address, which holds a 35-character string, and which
may be NULL.
CREATE DOMAIN address CHAR( 35 ) NULL;

The following statement creates a domain named ID, which does not allow NULLS, and which is
autoincremented by default.
CREATE DOMAIN ID INT
NOT NULL
DEFAULT AUTOINCREMENT;

The following statement creates a domain named PhoneNumber, which uses a regular expression within a
CHECK constraint to ensure that the string has a properly-formatted North American phone number of 12
characters, consisting of a 3-digit area code, 3-digit exchange, and 4-digit number separated by either
dashes or a blank.
CREATE DOMAIN PhoneNumber CHAR(12) NULL
CHECK( @PhoneNumber REGEXP '([2-9][0-9]{2}-[2-9][0-9]{2}-[0-9]{4})|([2-9]
[0-9]{2}\s[2-9][0-9]{2}\s[0-9]{4})');

CREATE ENCRYPTED DATABASE statement


Creates an encrypted copy of an existing database, including all transaction logs and dbspaces.

Syntax 1 - Create an encrypted copy of a database


CREATE ENCRYPTED DATABASE newfile
FROM oldfile
[ KEY newkey ]
[ ALGORITHM algorithm ]
[ OLD KEY oldkey ]

algorithm :
'SIMPLE'
| 'AES'
| 'AES256'
| 'AES_FIPS'
| 'AES256_FIPS'

Syntax 2 - Create a copy of a database with table encryption enabled


CREATE ENCRYPTED TABLE DATABASE newfile
FROM oldfile

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 521


SQL statements

[ KEY newkey ]
[ ALGORITHM algorithm ]
[ OLD KEY oldkey ]

Parameters
CREATE ENCRYPTED DATABASE clause Use this clause to specify a name for the new encrypted
database.

CREATE ENCRYPTED TABLE DATABASE clause Use this clause to specify a name for the new
database. The new database is not encrypted, but has table encryption enabled.

FROM clause Use this clause to specify the name of the original database (oldfile).

KEY clause If algorithm-key is anything other than SIMPLE, use this clause to specify the encryption
key for newfile.

OLD KEY clause Use this clause to specify the encryption key for oldfile. This clause is only required
if oldfile is encrypted with anything other than SIMPLE encryption.

ALGORITHM clause Use this clause to specify the encryption algorithm to use for newfile. If you
specify a KEY clause but do not specify the ALGORITHM clause, AES (128-bit encryption) is used by
default. If you specify SIMPLE for algorithm, you do not specify a KEY clause.

Remarks
You can also use this statement to create a copy of a database and enable table encryption in the copy.

oldfile can be an unencrypted database, an encrypted database, or a database with table encryption
enabled.

Syntax 1 takes an existing database, oldfile, and creates an encrypted copy of it, newfile.

Syntax 2 takes an existing database, oldfile, and creates a copy of it, newfile, with table encryption
enabled. When you use this syntax, any tables encrypted in oldfile are encrypted in newfile as well. If no
tables were encrypted in oldfile, but you want to encrypt them, you can execute an ALTER
TABLE...ENCRYPTED statement on each table you want to encrypt.

Neither syntax replaces or removes oldfile.

If oldfile uses transaction log or transaction log mirror files, they are renamed newfile.log and newfile.mlg
respectively.

If oldfile contains dbspace files, an E (for encrypted) is added to the file name. For example, when you
execute the CREATE ENCRYPTED DATABASE statement, the file mydbspace.dbs is changed to
mydbspace.dbsE.

You can use this statement to change the encryption algorithm and key for a database. However, the
CREATE ENCRYPTED DATABASE statement produces a new file (newfile), and does not replace or
remove the previous version of the file (oldfile).

522 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE ENCRYPTED DATABASE and CREATE ENCRYPTED TABLE DATABASE cannot be


executed against a database that requires recovery. These statements are not supported in procedures,
triggers, events, or batches.

You can also encrypt an existing database or change an existing encryption key by unloading and
reloading the database using the dbunload -an option with either -ek or -ep.

You can also create an encrypted database, or a database with table encryption enabled, using the
CREATE DATABASE statement.

Note
Not all platforms support FIPS-certified encryption. For a list of supported platforms, see http://
www.sybase.com/detail?id=1002288.

Permissions
DBA authority.

Side effects
None.

See also
● “Using the Unload utility to rebuild databases” [SQL Anywhere Server - SQL Usage]
● “Database encryption and decryption” [SQL Anywhere Server - Database Administration]
● “Table encryption” [SQL Anywhere Server - Database Administration]
● “Using simple encryption” [SQL Anywhere Server - Database Administration]
● “Strong encryption” [SQL Anywhere Server - Database Administration]
● “CREATE DECRYPTED DATABASE statement” on page 517
● “CREATE ENCRYPTED FILE statement” on page 524
● “CREATE DECRYPTED FILE statement” on page 518
● “CREATE DATABASE statement” on page 508
● “ALTER TABLE statement” on page 451
● “Initialization utility (dbinit)” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example creates an encrypted copy of the sample database called demoEnc.db. The new
database is encrypted with AES256 encryption.

CREATE ENCRYPTED DATABASE 'demoEnc.db'


FROM 'demo.db'
KEY 'Sd8f6654*Mnn'
ALGORITHM 'AES256';

The following example creates a copy of the sample database called demoTableEnc.db. Table encryption
is enabled on the new database. Since a key was specified with no algorithm, AES encryption is used.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 523


SQL statements

CREATE ENCRYPTED TABLE DATABASE 'demoTableEnc.db'


FROM 'demo.db'
KEY 'Sd8f6654';

CREATE ENCRYPTED FILE statement


Creates a strongly encrypted copy of a database file, transaction log, transaction log mirror, or dbspace.

Syntax
CREATE ENCRYPTED FILE newfile
FROM oldfile
{ KEY key | KEY key OLD KEY oldkey }
[ ALGORITHM {
'AES'
| 'AES256'
| 'AES_FIPS'
| 'AES256_FIPS' } ]

Parameters
FROM clause Specifies the name of the existing file (oldfile) on which to execute the CREATE
ENCRYPTED FILE statement.

KEY clause Specifies the encryption key to use.

OLD KEY clause Specifies the current key with which the file is encrypted.

ALGORITHM clause Specifies the algorithm used to encrypt the file. If you do not specify an
algorithm, AES (128-bit encryption) is used by default.

Remarks
Use this statement when your database requires recovery and you need to create an encrypted copy of the
database for support reasons. You must also use this statement to encrypt any database-related files such
as the transaction log, transaction log mirror, or dbspace files.

You cannot be connected to the database you are creating the encrypted file for. You must be connected
to a different database.

When encrypting the database-related files, you must specify the same algorithm and key for all files
related to the database.

If oldfile has dbspaces or transaction log files associated with it and you encrypt those too, you must
ensure that the new name and location of those files is stored with the new database. To do so:

● run dblog -t on the new database to change the name and location of the transaction log

● run dblog -m on the new database to change the name and location of the transaction log mirror

● execute an ALTER DBSPACE statement on the new database to change the location and name of the
dbspace files

524 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

You can use this statement to change the encryption algorithm and key for a database. However, the
CREATE ENCRYPTED FILE statement produces a new file (newfile), and does not replace or remove
the previous version of the file (oldfile).

The name of the transaction log file remains the same in this process, so if the database and transaction
log file are renamed, then you need to run dblog -t on the resulting database.

You can also encrypt an existing database or change an existing encryption key by unloading and
reloading the database using the dbunload -an option with either -ek or -ep.

If you have a database on which table encryption is enabled, you cannot encrypt the database using this
statement. However, you can use this statement to change the key used for table encryption. To encrypt a
database that has table encryption enabled, use the CREATE ENCRYPTED DATABASE statement.

This statement is not supported in procedures, triggers, events, or batches.

Note
Not all platforms support FIPS-certified encryption. For a list of supported platforms, see http://
www.sybase.com/detail?id=1002288.

Permissions
Must be a user with DBA authority.

On Windows Mobile, the AES_FIPS and AES256_FIPS algorithms are only supported with ARM
processors.

Side effects
None.

See also
● “CREATE ENCRYPTED DATABASE statement” on page 521
● “Database encryption and decryption” [SQL Anywhere Server - Database Administration]
● “CREATE ENCRYPTED DATABASE statement” on page 521
● “CREATE DECRYPTED FILE statement” on page 518
● “CREATE DECRYPTED DATABASE statement” on page 517
● “Unload utility (dbunload)” [SQL Anywhere Server - Database Administration]
● “Transaction Log utility (dblog)” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example encrypts the contacts database and creates a new database called contacts2 that is
encrypted with AES_FIPS encryption.
CREATE ENCRYPTED FILE 'contacts2.db'
FROM 'contacts.db'
KEY 'Sd8f6654*Mnn'
ALGORITHM 'AES_FIPS';

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 525


SQL statements

The following example encrypts the contacts database and the contacts transaction log file, renaming the
both files. You must run dblog -ek Sd8f6654*Mnn -t contacts2.log contacts.db,
since the transaction log has been renamed and the database file still points to the old log.
CREATE ENCRYPTED FILE 'contacts2.db'
FROM 'contacts.db'
KEY 'Sd8f6654*Mnn';
CREATE ENCRYPTED FILE 'contacts2.log'
FROM 'contacts.db'
KEY 'Sd8f6654*Mnn';

The following example encrypts the contacts database and the contacts transaction log file, leaving the
original transaction log file name untouched. In this case, you do not need to run dblog, since the name of
the file remains the same.
CREATE ENCRYPTED FILE 'newpath\contacts.db'
FROM 'contacts.db'
KEY 'Sd8f6654*Mnn';
CREATE ENCRYPTED FILE 'newpath\contacts.log'
FROM 'contacts.log'
KEY 'Sd8f6654*Mnn';

To change the encryption key for a database, first create a copy of the database file using the new key, as
shown in this statement:
CREATE ENCRYPTED FILE 'newcontacts.db'
FROM 'contacts.db'
KEY 'newkey' OLD KEY 'oldkey';

Once you have created the encrypted file, delete contacts.db and then rename newcontacts.db to be
contacts.db.

CREATE EVENT statement


Defines an event and its associated handler for automating predefined actions, and to define scheduled
actions.

Syntax
CREATE EVENT [ owner.]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

526 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

| DatabaseStart
| DBDiskSpace
| Deadlock
| "Disconnect"
| GlobalAutoincrement
| GrowDB
| GrowLog
| GrowTemp
| LogDiskSpace
| MirrorFailover
| MirrorServerDisconnect
| 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 : identifier

schedule-name : identifier

day-of-week : string

day-of-month : integer

value : integer

period : integer

start-time : time

end-time : time

start-date : date

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.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 527


SQL statements

TYPE clause You can specify the TYPE clause with an optional WHERE clause, or specify the
SCHEDULE.

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 transaction log
mirror, and reports based on the least available space.

Disk space event types are not supported on Windows Mobile.

The TempDiskSpace event type checks the amount of temporary disk space.

If the appropriate event handlers have been defined (DBDiskSpace, LogDiskSpace, or


TempDiskSpace), the database server checks the available space on each device associated with a
database file every 30 seconds. Similarly, if an event has been defined to handle the system event type
ServerIdle, the database server notifies the handler when no requests have been processed during the
previous 30 seconds.

You can specify the -fc option when starting the database server to implement a callback function
when the database server encounters a file system full condition.

○ GlobalAutoincrement event type The event fires on each insert when the number of remaining
values for a GLOBAL AUTOINCREMENT is less than 1% 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, based on the table
and number of remaining values which are supplied as parameters to this event.

You can use the event_condition function with RemainingValues as an argument for this event type.

○ ServerIdle event type If the database contains an event handler for the ServerIdle type, the
database server checks for server activity every 30 seconds.

○ Database mirroring event types The MirrorServerDisconnect event fires when a connection
from the primary database server to the mirror server or arbiter server is lost, and the MirrorFailover
event fires whenever a server takes ownership of the database.

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.

528 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

You can use multiple AND conditions to make up the WHERE clause, but you cannot use OR conditions
or other conditions.

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. You must provide a schedule-name when there is more than one schedule;
the schedule-name is optional if you provide only a single schedule.

A scheduled event is recurring if its definition includes EVERY or ON; if neither of these reserved words
is used, the event executes at most once. An attempt to create a non-recurring scheduled event for which
the start time has passed generates an error. 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 clause The first scheduled time for each day on which the event is scheduled. The
start-time parameter is a string, and cannot be a variable or an expression such as NOW(). If a START
DATE is specified, the START TIME refers to that date and each subsequent dat (if the schedule
includes EVERY or ON). If no START DATE is specified, the START TIME is on the current day
(unless the time has passed) and each subsequent day (if the schedule includes EVERY or ON). The
clause START TIME start-time is equivalent to BETWEEN start-time AND '23:59:59'.

● BETWEEN...AND clause A range of times during the day outside which no scheduled times
occur. The start-time and end-time parameters are strings, and cannot be variables or expressions such
as NOW(). If a START DATE is specified, the scheduled times do not occur until that date.

● EVERY clause 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 clause A list of days on which the scheduled events occur. The default is every day if EVERY
is specified. Days can be specified as days of the week or days of the month.

Days of the week are Mon, Tues, and so on. You may also use the full forms of the day, such as
Monday. You must use the full forms of the day names if the language you are using is not English, is
not the language requested by the client in the connection string, and is not the language which
appears in the database server messages window.

Days of the month are integers from 0 to 31. A value of 0 represents the last day of any month.

● START DATE clause The date on which scheduled events are to start occurring. This value is a
string, and cannot be a variable or an expression such as TODAY(). The default is the current date.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 529


SQL statements

Each time a scheduled event handler is completed, the following actions are taken to calculate the next
scheduled time and date for the event:

1. If the EVERY clause is used, find whether the next scheduled time falls on the current day, and is
before the end time specified by the BETWEEN...AND clause, if it was specified. 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 and use the START TIME for that date, or the beginning of the BETWEEN...AND
range.

● ENABLE | DISABLE clause 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 This clause should be used only in the following circumstance: in a SQL Remote setup,
use the AT clause against your remote or consolidated databases to restrict the databases at which the
event is handled.

If you do not use the AT clause when creating events for SQL Remote, all databases execute the
event. When executed on a consolidated database, this statement does not affect remote databases that
have already been extracted.

● HANDLER clause Each event has one handler.

Remarks
Events can be used for:

● Scheduling actions The database server executes actions on a timed schedule. You can use this
capability to complete scheduled tasks such as backups, validity checks, and queries used to add data
to reporting tables.

● Event handling actions The database server executes actions when a predefined event occurs.
You can use this capability to complete scheduled tasks such as restrict disk space when a disk fills
beyond a specified percentage. Event handler actions are committed if errors are not detected during
execution, and rolled back if errors are detected.

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 want to 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 message log.

After each execution of an event handler, a COMMIT occurs if no errors occurred. A ROLLBACK occurs
if there was an error.

530 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

When event handlers are triggered, the database 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.

Permissions
DBA authority.

Event handlers execute on a separate connection, with the permissions of the event owner. To execute
with authority 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.

See also
● “BEGIN statement” on page 484
● “ALTER EVENT statement” on page 408
● “COMMENT statement” on page 499
● “DROP EVENT statement” on page 693
● “TRIGGER EVENT statement” on page 932
● “EVENT_PARAMETER function [System]” on page 217
● “EVENT_CONDITION function [System]” on page 215
● “-fc dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “System events” [SQL Anywhere Server - Database Administration]
● “Trigger conditions for events” [SQL Anywhere Server - Database Administration]
● “Database server action logging” [SQL Anywhere Server - Database Administration]
● “Database mirroring system events” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
Instruct the database server to perform an automatic backup to tape using the first tape drive, every day at
1 A.M.
CREATE EVENT DailyBackup
SCHEDULE daily_backup
START TIME '1:00AM' EVERY 24 HOURS
HANDLER
BEGIN
BACKUP DATABASE TO '\\\\.\\tape0'
ATTENDED OFF
END;

Instruct the database server to perform an automatic backup of the transaction log only, every hour,
Monday to Friday between 8 A.M. and 6 P.M.
CREATE EVENT HourlyLogBackup
SCHEDULE hourly_log_backup

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 531


SQL statements

BETWEEN '8:00AM' AND '6:00PM'


EVERY 1 HOURS ON
('Monday','Tuesday','Wednesday','Thursday','Friday')
HANDLER
BEGIN
BACKUP DATABASE DIRECTORY 'c:\\database\\backup'
TRANSACTION LOG ONLY
TRANSACTION LOG RENAME
END;

Determine when an event is next scheduled to run:

SELECT DB_EXTENDED_PROPERTY( 'NextScheduleTime', 'HourlyLogBackup');

CREATE EXISTING TABLE statement


Creates 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 | variable-name

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

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 behavior
allows file names and extensions to be used in the database and owner fields. For example, the following
statement maps the table a1 to the Microsoft Access file mydbfile.mdb:

CREATE EXISTING TABLE a1


AT 'access;d:\mydbfile.mdb;;a1';

When the proxy table is used, variable-name is replaced with the contents of the SQL variable variable-
name that must be of the type CHAR, VARCHAR, or LONG VARCHAR. For more information about
using variables in the AT clause, see Example 2 in “Creating directory access servers (Sybase Central)”
[SQL Anywhere Server - SQL Usage].

Remarks
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 SQL Anywhere. This establishes the remote table as

532 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

a visible entity to SQL Anywhere users. SQL Anywhere verifies that the table exists at the external
location before it creates the table.

If the object does not exist (either as a 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 ISYSIDX system table. This information 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, SQL Anywhere derives the column list from the metadata it
obtains from the remote table. If column-definitions are specified, SQL Anywhere verifies the column-
definitions. Column names, data types, lengths, the identity property, and null properties are checked for
the following:

● Column names must match identically (although case is ignored).

● 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/or 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.

Permissions
Must have RESOURCE authority. To create a table for another user, you must have DBA authority.

Not supported on Windows Mobile.

Side effects
Automatic commit.

See also
● “CREATE TABLE statement” on page 633
● “Proxy table locations” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL Supported by Adaptive Server Enterprise. The format of location-string is


implementation-defined.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 533


SQL statements

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. SQL 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_employees for the Employees table at the remote SQL Anywhere Server,
demo12.
CREATE EXISTING TABLE rda_employees
AT 'demo12...Employees';

CREATE EXTERNLOGIN statement


Assigns 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 ] ]

Parameters
login-name specifies the local user login name. When using integrated logins, the login-name is the
database user to which the Windows user or group 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. Values for the REMOTE LOGIN clause are restricted to 128 bytes.

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.

If you omit the IDENTIFIED BY clause, the password is sent to the remote server as NULL. However, if
you specify IDENTIFIED BY "" (an empty string), then the password sent is the empty string.

Remarks
By default, SQL 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 REMOTE LOGIN clause is required only when the remote server requires a user ID and password
for the connection. Having an external login without a remote login allows the DBA to control who can

534 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

access the remote server and tells the remote access layer that logging in to the remote server does not
require a user ID and password. For example, the directory access server class requires an external login
for restricting access to the directory server, but remote login is not needed because the directory server
does not perform user ID and password validation.

The password is stored internally in encrypted form. The remote-server must be known to the local server
by an entry in the ISYSSERVER table.

Sites with automatic password expiration should plan for periodic updates of passwords for external
logins.

CREATE EXTERNLOGIN cannot be used from within a transaction.

Permissions
Only users with DBA authority can add or modify an external login for login-name.

Not supported on Windows Mobile.

Side effects
Automatic commit.

See also
● “DROP EXTERNLOGIN statement” on page 694
● “CREATE SERVER statement” on page 601
● “Creating external logins” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Map the local user named DBA to the user sa with password Plankton when connecting to the server
sybase1.
CREATE EXTERNLOGIN DBA
TO sybase1
REMOTE LOGIN sa
IDENTIFIED BY Plankton;

CREATE FUNCTION statement [External call]


Creates an interface to a native or external function.

Syntax
CREATE [ OR REPLACE ] FUNCTION [ owner.]function-name
( [ parameter, ... ] )
RETURNS data-type
[ SQL SECURITY { INVOKER | DEFINER } ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 535


SQL statements

[ [ NOT ] DETERMINISTIC ]
EXTERNAL NAME external-call [ LANGUAGE environment-name ]

parameter :
[ IN ] parameter-name data-type [ DEFAULT expression ]

environment-name :
C_ESQL32
| C_ESQL64
| C_ODBC32
| C_ODBC64
| CLR
| JAVA
| PERL
| PHP

Parameters
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. However, function parameters are IN by default.

When functions are executed, not all parameters need to be specified. If a DEFAULT value is provided in
the CREATE FUNCTION statement, missing parameters are assigned the default values. If an argument
is not provided by the caller and no default is set, an error is given.

OR REPLACE clause Specifying OR REPLACE creates a new function, or replaces an existing


function with the same name. This clause changes the definition of the function, but preserves existing
permissions. You cannot use the OR REPLACE clause with temporary functions.

RETURNS clause Use the RETURNS clause to specify the data type for the result of the function.

SQL SECURITY clause The SQL SECURITY clause defines whether the function is executed as the
INVOKER (the user who is calling the function), or as the DEFINER (the user who owns the function).
The default is DEFINER. For external calls, this clause establishes the ownership context for unqualified
object references in the external environment.

When SQL SECURITY INVOKER is specified, more memory is used because annotation must be done
for each user that calls the function. Also, when SQL SECURITY INVOKER is specified, name
resolution is done as the invoker as well. Therefore, care should be taken to qualify all object names
(tables, procedures, and so on) with their appropriate owner. For example, suppose user1 creates the
following function:
CREATE FUNCTION user1.myFunc()
RETURNS INT
SQL SECURITY INVOKER
BEGIN
DECLARE res INT;
SELECT COUNT(*) INTO res FROM table1;
RETURN res;
END;

If user2 attempts to run this function and a table user2.table1 does not exist, a table lookup error results.
Additionally, if a user2.table1 does exist, that table is used instead of the intended user1.table1. To
prevent this situation, qualify the table reference in the statement (user1.table1, instead of just table1).

536 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

[ NOT ] DETERMINISTIC clause Use this clause to indicate whether functions are deterministic or
non-deterministic. If this clause is omitted, then the deterministic behavior of the function is unspecified
(the default).

If a function is declared as DETERMINISTIC, it should return the same value every time it is invoked
with the same set of parameters.

If a function is declared as NOT DETERMINISTIC, then it is not guaranteed to return the same value for
the same set of parameters. A function declared as NOT DETERMINISTIC is re-evaluated each time it is
called in a query. This clause must be used when it is known that the function result for a given set of
parameters can vary.

Also, functions that have side effects such as modifying the underlying data should be declared as NOT
DETERMINISTIC. For example, a function that generates primary key values and is used in an
INSERT...SELECT statement should be declared NOT DETERMINISTIC:
CREATE FUNCTION keygen( increment INTEGER )
RETURNS INTEGER
NOT DETERMINISTIC
BEGIN
DECLARE keyval INTEGER;
UPDATE counter SET x = x + increment;
SELECT counter.x INTO keyval FROM counter;
RETURN keyval
END
INSERT INTO new_table
SELECT keygen(1), ...
FROM old_table;

Functions can be declared as DETERMINISTIC if they always return the same value for given input
parameters.

EXTERNAL NAME native-call clause

native-call :
[operating-system:]function-name@library; ...

operating-system : Unix

Note
The EXTERNAL NAME clause is not supported for TEMPORARY functions.

A function using the EXTERNAL NAME clause with no LANGUAGE attribute defines an interface to a
native function written in a programming language such as C. The native function is loaded by the
database server into its address space.

The library name can include the file extension, which is typically .dll on Windows and .so on Unix. In
the absence of the extension, the software appends the platform-specific default file extension for
libraries. The following is a formal example.
CREATE FUNCTION mystring( IN instr LONG VARCHAR )
RETURNS LONG VARCHAR
EXTERNAL NAME '[email protected];Unix:[email protected]';

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 537


SQL statements

A simpler way to write the above EXTERNAL NAME clause, using platform-specific defaults, is as
follows:
CREATE FUNCTION mystring( IN instr LONG VARCHAR )
RETURNS LONG VARCHAR
EXTERNAL NAME 'mystring@mylib';

When called, the library containing the function is loaded into the address space of the database server.
The native function will execute as part of the server. In this case, if the function causes a fault, then the
database server will be terminated. Because of this, loading and executing functions in an external
environment using the LANGUAGE attribute is recommended. If a function causes a fault in an external
environment, the database server will continue to run.

EXTERNAL NAME c-call LANGUAGE {C_ESQL32 | C_ESQL64 | C_ODBC32 | C_ODBC64 }


clause To call a compiled native C function in an external environment instead of within the database
server, the stored procedure or function is defined with the EXTERNAL NAME clause followed by the
LANGUAGE attribute specifying one of C_ESQL32, C_ESQL64, C_ODBC32, or C_ODBC64.

When the LANGUAGE attribute is specified, then the library containing the function is loaded by an
external process and the external function will execute as part of that external process. In this case, if the
function causes a fault, then the database server will continue to run.

The following is a sample function definition.


CREATE FUNCTION ODBCinsert(
IN ProductName CHAR(30),
IN ProductDescription CHAR(50)
)
RETURNS INT
EXTERNAL NAME '[email protected]'
LANGUAGE C_ODBC32;

EXTERNAL NAME clr-call LANGUAGE CLR clause To call a .NET function in an external
environment, the function interface is defined with an EXTERNAL NAME clause followed by the
LANGUAGE CLR attribute.

A CLR stored procedure or function behaves the same as a SQL stored procedure or function except that
the code for the procedure or function is written in a .NET language such as C# or Visual Basic, and the
execution of the procedure or function takes place outside the database server (that is, within a
separate .NET executable).

The following is a sample function definition.


CREATE FUNCTION clr_interface(
IN p1 INT,
IN p2 UNSIGNED SMALLINT,
IN p3 LONG VARCHAR)
RETURNS INT
EXTERNAL NAME 'CLRlib.dll::CLRproc.Run( int, ushort, string )'
LANGUAGE CLR;

EXTERNAL NAME perl-call LANGUAGE PERL clause To call a Perl function in an external
environment, the function interface is defined with an EXTERNAL NAME clause followed by the
LANGUAGE PERL attribute.

538 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

A Perl stored procedure or function behaves the same as a SQL stored procedure or function except that
the code for the procedure or function is written in Perl and the execution of the procedure or function
takes place outside the database server (that is, within a Perl executable instance).

The following is a sample function definition.


CREATE FUNCTION PerlWriteToConsole( IN str LONG VARCHAR)
RETURNS INT
EXTERNAL NAME '<file=PerlConsoleExample>
WriteToServerConsole( $sa_perl_arg0 )'
LANGUAGE PERL;

EXTERNAL NAME php-call LANGUAGE PHP clause To call a PHP function in an external
environment, the function interface is defined with an EXTERNAL NAME clause followed by the
LANGUAGE PHP attribute.

A PHP stored procedure or function behaves the same as a SQL stored procedure or function except that
the code for the procedure or function is written in PHP and the execution of the procedure or function
takes place outside the database server (that is, within a PHP executable instance).

The following is a sample function definition.


CREATE FUNCTION PHPPopulateTable()
RETURNS INT
EXTERNAL NAME '<file=ServerSidePHPExample> ServerSidePHPSub()'
LANGUAGE PHP;

EXTERNAL NAME java-call LANGUAGE JAVA clause To call a Java method in an external
environment, the function interface is defined with an EXTERNAL NAME clause followed by the
LANGUAGE JAVA attribute.

A Java-interfacing stored procedure or function behaves the same as a SQL stored procedure or function
except that the code for the procedure or function is written in Java and the execution of the procedure or
function takes place outside the database server (that is, within a Java VM).

The following is a sample function definition.


CREATE FUNCTION HelloDemo( IN name LONG VARCHAR )
RETURNS INT
EXTERNAL NAME 'Hello.main([Ljava/lang/String;)V'
LANGUAGE JAVA;

Remarks
The CREATE FUNCTION statement creates a function in the database. Users with DBA authority can
create functions for other users by specifying an owner. A function is invoked as part of a SQL
expression.

When referencing a temporary table from multiple functions, a potential issue can arise if the temporary
table definitions are inconsistent and statements referencing the table are cached.

Permissions
Must have RESOURCE authority, unless creating a temporary function.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 539


SQL statements

Must have DBA authority for external functions or to create a function for another user.

Side effects
Automatic commit.

See also
● “ALTER FUNCTION statement” on page 412
● “CALL statement” on page 491
● “CREATE FUNCTION statement” on page 548
● “CREATE FUNCTION statement [Web service]” on page 541
● “CREATE PROCEDURE statement [External call]” on page 567
● “DROP FUNCTION statement” on page 695
● “GRANT statement” on page 760
● “SQL Anywhere external environment support” [SQL Anywhere Server - Programming]
● “SQL Anywhere external call interface” [SQL Anywhere Server - Programming]
● “The ESQL and ODBC external environments” [SQL Anywhere Server - Programming]
● “The CLR external environment” [SQL Anywhere Server - Programming]
● “The Java external environment” [SQL Anywhere Server - Programming]
● “The PHP external environment” [SQL Anywhere Server - Programming]
● “The PERL external environment” [SQL Anywhere Server - Programming]
● “SQL data types” on page 81
● “References to temporary tables within procedures” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 CREATE FUNCTION for an external language environment is a core feature of the
SQL/2008 standard, though some of its components supported in SQL Anywhere are optional SQL/
2008 language features. A subset of these features include:

○ The SQL SECURITY clause is optional language feature T324.

○ The ability to pass a LONG VARCHAR, LONG NVARCHAR, or LONG BINARY value to a SQL
function is language feature T041.

○ Support for LANGUAGE JAVA is optional SQL/2008 language feature J621.

○ The ability to create or modify a schema object within an external function, using statements such
as CREATE TABLE or DROP TRIGGER, is language feature T653.

○ The ability to use a dynamic-SQL statement within an external function, including statements such
as CONNECT, EXECUTE IMMEDIATE, PREPARE, and DESCRIBE, is language feature T654.

Several clauses of the CREATE FUNCTION statement are vendor extensions. These include:

○ Support for C_ESQL32, C_ESQL64, C_ODBC32, C_ODBC64, CLR, PERL, and PHP in the
LANGUAGES clause are vendor extensions.

○ The format of external-call is implementation-defined.

○ The optional DEFAULT clause for a specific routine parameter is a vendor extension.

540 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ The optional OR REPLACE clause is a vendor extension.

● Transact-SQL CREATE FUNCTION for an external routine is supported by Adaptive Server


Enterprise. Adaptive Server Enterprise only supports LANGUAGE JAVA as the external
environment (SQL/2008 language feature J621) for an external function.

CREATE FUNCTION statement [Web service]


Creates a web client function that makes an HTTP or SOAP over HTTP request.

Syntax
CREATE [ OR REPLACE ] FUNCTION [ owner.]function-name ( [ parameter, ... ] )
RETURNS data-type
URL url-string
[ HEADER header-string ]
[ SOAPHEADER soap-header-string ]
[ TYPE {
'HTTP[ :{ GET | POST[:MIME-type ] | PUT[:MIME-type ] | DELETE | HEAD } ]' |
'SOAP[:{ RPC | DOC } ]' } ]
[ NAMESPACE namespace-string ]
[ CERTIFICATE certificate-string ]
[ CLIENTPORT clientport-string ]
[ PROXY proxy-string ]
[ SET protocol-option-string ]

url-string :
' { HTTP | HTTPS | HTTPS_FIPS }://[user:password@]hostname[:port][/path]'

parameter :
[ IN ] parameter-name data-type [ DEFAULT expression ]

Parameters
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. However, function parameters are IN by default.

When functions are executed, not all parameters need to be specified. If a DEFAULT value is provided in
the CREATE FUNCTION statement, missing parameters are assigned the default values. If an argument
is not provided by the caller and no default is set, an error is given.

OR REPLACE clause Specifying OR REPLACE creates a new function, or replaces an existing


function with the same name. This clause changes the definition of the function, but preserves existing
permissions. You cannot use the OR REPLACE clause with temporary functions.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 541


SQL statements

RETURNS clause Specify one of the following to define the return type for the SOAP or HTTP
function:

○ CHAR
○ VARCHAR
○ LONG VARCHAR
○ TEXT
○ NCHAR
○ NVARCHAR
○ LONG NVARCHAR
○ NTEXT
○ XML
○ BINARY
○ VARBINARY
○ LONG BINARY

The value returned is the body of the HTTP response. No HTTP header information is included. If more
information is required, such as status information, use a procedure instead of a function.

The data type does not affect how the HTTP response is processed.

URL clause Use the URL clause only when defining an HTTP or SOAP web services client function.
The URL clause specifies the URI of the web service. The optional user name and password parameters
provide a means of supplying the credentials needed for HTTP basic authentication. HTTP basic
authentication base-64 encodes the user and password information and passes it in the Authentication
header of the HTTP request.

Specifying HTTPS_FIPS forces the system to use the FIPS-certified libraries. If HTTPS_FIPS is
specified, but no FIPS-certified libraries are present, libraries that are not FIPS-certified are used instead.

For functions of type HTTP:GET, query parameters can be specified within the URL clause in addition to
being automatically generated from parameters passed to a procedure.
URL 'http://localhost/service?parm=1

HEADER clause When creating HTTP web service client functions, use this clause to add or modify
HTTP request header entries. Only printable ASCII characters can be specified for HTTP headers, and
they are case-insensitive.

SOAPHEADER clause When declaring a SOAP web service as a function, use this clause to specify
one or more SOAP request header entries. A SOAP header can be declared as a static constant, or can be
dynamically set using the parameter substitution mechanism (declaring IN, OUT, or INOUT parameters
for hd1, hd2, and so on). A web service function can define one or more IN mode substitution parameters,
but cannot define an INOUT or OUT substitution parameter.

TYPE clause The TYPE clause specifies the format used when making the web service request.
SOAP:RPC is used when SOAP is specified or no TYPE clause is included. HTTP:POST is used when
HTTP is specified.

The TYPE clause allows the specification of a MIME-type for HTTP:GET, HTTP:POST, and HTTP:PUT
types. The MIME-type specification is used to set the Content-Type request header and set the mode of

542 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

operation to allow only a single call parameter to populate the body of the request. Only zero or one
parameter may remain when making a web service stored function call after parameter substitutions have
been processed. Calling a web service function with a NULL value or no parameter (after substitutions)
results in a request with no body and a content-length of zero. Parameter names and values (multiple
parameters are permitted) are URL encoded within the body of the HTTP request.

Some typical MIME-types include:

○ text/plain
○ text/html
○ text/xml

The keywords for the TYPE clause have the following meanings:

○ HTTP:GET By default, this type uses the application/x-www-form-urlencoded MIME-type for


encoding parameters specified in the URL.

For example, the following request is produced when a client submits a request from the URL
http://localhost/WebServiceName?arg1=param1&arg2=param2:
GET /WebServiceName?arg1=param1&arg2=param2 HTTP/1.1
// <End of Request - NO BODY>

○ HTTP:POST By default, this type uses the application/x-www-form-urlencoded MIME-type for


encoding parameters specified in the body of a POST request. URL parameters are stored in the body.

For example, the following request is produced when a client submits a request from the URL
http://localhost/WebServiceName?arg1=param1&arg2=param2:
POST /WebServiceName HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 19

arg1=param1&arg2=param2
// <End of Request>

○ HTTP:PUT HTTP:PUT is similar to HTTP:POST, but the HTTP:PUT type does not have a default
media type.

The following example demonstrates how to configure a general purpose client procedure that uploads
data to a SQL Anywhere server running the put_data.sql sample:
ALTER PROCEDURE CPUT("data" LONG VARCHAR, resnm LONG VARCHAR, mediatype
LONG VARCHAR)
URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:PUT:!mediatype';

CALL CPUT('hello world', 'hello', 'text/plain' );

○ HTTP:DELETE A web service client procedure can be configured to delete a resource located on a
server. Specifying the media type is optional.

The following example demonstrates how to configure a general purpose client procedure that deletes
a resource from a SQL Anywhere server running the put_data.sql sample:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 543


SQL statements

ALTER PROCEDURE CDEL(resnm LONG VARCHAR, mediatype LONG VARCHAR)


URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:DELETE:!mediatype';

CALL CDEL('hello', 'text/plain' );

○ HTTP:HEAD The head method is identical to a GET method but the server does not return a body.
A media type can be specified.
ALTER PROCEDURE CHEAD(resnm LONG VARCHAR)
URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:HEAD';

CALL CHEAD( 'hello' );

○ SOAP:RPC This type sets the Content-Type to 'text/xml'. SOAP operations and parameters are
encapsulated in SOAP envelope XML documents.

○ SOAP:DOC This type sets the Content-Type to 'text/xml'. It is similar to the SOAP:RPC type but
allows you to send richer data types. SOAP operations and parameters are encapsulated in SOAP
envelope XML documents.

Specifying a MIME-type for the TYPE clause automatically sets the Content-Type header to that MIME-
type.

NAMESPACE clause Applies to SOAP client functions only. This clause identifies the method
namespace usually required for both SOAP:RPC and SOAP:DOC requests. The SOAP server handling
the request uses this namespace to interpret the names of the entities in the SOAP request message body.
The namespace can be obtained from the WSDL (Web Services Description Language) of the SOAP
service available from the web service server. The default value is the function's URL, up to but not
including, the optional path component.

CERTIFICATE clause To make a secure (HTTPS) request, a client must have access to the certificate
used by the HTTPS server. The necessary information is specified in a string of semicolon-separated key/
value pairs. You can use the file key to specify the file name of the certificate, or you can use the
certificate key to specify the server certificate in a string. You cannot specify a file and certificate key
together. The following keys are available:

Key Abbreviation Description

file The file name of the certificate.

certificate cert The certificate itself.

company co The company specified in the certificate.

unit The company unit specified in the certifi-


cate.

name The common name specified in the certif-


icate.

544 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Certificates are required only for requests that are directed to an HTTPS server, or for requests that can be
redirected from a non-secure to a secure server. Only PEM formatted certificates are supported.

CLIENTPORT clause Identifies the port number on which the HTTP client function communicates
using TCP/IP. It is provided for and recommended only for connections across firewalls, as firewalls filter
according to the TCP/UDP port. You can specify a single port number, ranges of port numbers, or a
combination of both; for example, CLIENTPORT '85,90-97'.

PROXY clause Specifies the URI of a proxy server. For use when the client must access the network
through a proxy. This clause indicates that the function is to connect to the proxy server and send the
request to the web service through it.

SET clause Specifies protocol-specific behavior options for HTTP and SOAP. The following list
describes the supported SET options. CHUNK and VERSION apply to the HTTP protocol, and
OPERATION applies to the SOAP protocol. Parameter substitution is supported for this clause.

○ 'HTTP(CH[UNK]=option)' (HTTP or SOAP) This option allows you to specify whether to use
chunking. Chunking allows HTTP messages to be broken up into several parts. Possible values are
ON (always chunk), OFF (never chunk), and AUTO (chunk only if the contents, excluding auto-
generated markup, exceeds 8196 bytes). For example, the following SET clause enables chunking:
SET 'HTTP(CHUNK=ON)'

If the CHUNK option is not specified, the default behavior is AUTO. If a chunked request fails in
AUTO mode with a status of 505 HTTP Version Not Supported, or with 501 Not
Implemented, or with 411 Length Required, the client retries the request without chunked
transfer-coding.

Set the CHUNK option to OFF (never chunk) if the HTTP server does not support chunked transfer-
coded requests.

Since CHUNK mode is a transfer encoding supported starting in HTTP version 1.1, setting CHUNK
to ON requires that the version (VER) be set to 1.1, or not be set at all, in which case 1.1 is used as the
default version.

○ ' HTTP(VER[SION]=ver)' (HTTP or SOAP) This option allows you to specify the version of HTTP
protocol that is used for the format of the HTTP message. For example, the following SET clause sets
the HTTP version to 1.1:
SET 'HTTP(VERSION=1.1)'

Possible values are 1.0 and 1.1. If VERSION is not specified:

● if CHUNK is set to ON, 1.1 is used as the HTTP version

● if CHUNK is set to OFF, 1.0 is used as the HTTP version

● if CHUNK is set to AUTO, either 1.0 or 1.1 is used, depending on whether the client is sending in
CHUNK mode

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 545


SQL statements

○ 'REDIR(COUNT=count, STATUS=status-list)' (HTTP or SOAP) The HTTP response status


codes such as 302 Found and 303 See Other are used to redirect web applications to a new URI,
particularly after an HTTP POST has been performed. For example, a client request could be:
GET /people/alice HTTP/1.1
Host: www.example.com
Accept: text/html, application/xhtml+xml
Accept-Language: en, de

The web server response could be:


HTTP/1.1 302 Found
Location: http://www.example.com/people/alice.en.html

In response, the client would send another HTTP request to the new URI. The REDIR option allows
you to control the maximum number of redirections allowed and which HTTP response status codes
to automatically redirect.

For example, SET 'REDIR(count=3, status=301,307)' allows a maximum limit of 3 re-


directions and permits redirection for 301 and 307 statuses. If one of the other redirection status codes
such as 302 or 303 is received, an error is issued (SQLCODE -983).

The default redirection limit count is 5. By default, an HTTP client procedure will automatically
redirect in response to all HTTP redirection status codes (301, 302, 303, 307). To disallow all
redirection status codes, use SET REDIR(COUNT=0). In this mode, a redirection response does not
result in an error (SQLCODE -983). Instead, a result set is returned with the HTTP status and
response headers. This permits a caller to conditionally reissue the request based on the URI contained
in the Location header.

A web service procedure specifying a POST HTTP method which receives a 303 See Other
status issues a redirect request using the GET HTTP method.

The Location header can contain either an absolute path or a relative path. The HTTP client
procedure handles either. The header can also include query parameters and these are forwarded to the
redirected location. For example, if the header contained parameters such as the following, the
subsequent GET or a POST includes these parameters.
Location: alternate_service?a=1&b=2

In the above example, the query parameters are a=1&b=2.

○ 'SOAP(OP[ERATION]=soap-operation-name)' (SOAP only) This option allows you to specify


the name of the SOAP operation, if it is different from the name of the procedure you are creating.
The value of OPERATION is analogous to the name of a remote procedure call. For example, if you
wanted to create a procedure called accounts_login that calls a SOAP operation called login, you
would specify something like the following:
CREATE FUNCTION accounts_login(
name LONG VARCHAR,
pwd LONG VARCHAR )
SET 'SOAP(OPERATION=login)';

If the OPERATION option is not specified, the name of the SOAP operation must match the name of
the procedure you are creating.

546 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The following statement shows how several protocol-option settings are combined in the same SET
clause:

CREATE FUNCTION accounts_login(


name LONG VARCHAR,
pwd LONG VARCHAR )
SET 'HTTP ( CHUNK=ON; VERSION=1.1 ), SOAP( OPERATION=login )'
...

Remarks
The CREATE FUNCTION statement creates a web services function in the database. A function can be
created for another user by specifying an owner name.

Parameter values are passed as part of the request. The syntax used depends on the type of request. For
HTTP:GET, the parameters are passed as part of the URL; for HTTP:POST requests, the values are
placed in the body of the request. Parameters to SOAP requests are always bundled in the request body.

Permissions
RESOURCE authority.

DBA authority for external functions, including Java functions.

Side effects
Automatic commit.

See also
● “SQL data types” on page 81
● “Tutorial: Using SQL Anywhere to access a SOAP/DISH service” [SQL Anywhere Server -
Programming]
● “HTTP and SOAP request structures” [SQL Anywhere Server - Programming]
● “HTTP request header management” [SQL Anywhere Server - Programming]
● “ALTER FUNCTION statement” on page 412
● “CREATE FUNCTION statement” on page 548
● “CREATE FUNCTION statement [External call]” on page 535
● “CREATE PROCEDURE statement” on page 585
● “CREATE PROCEDURE statement [Web service]” on page 575
● “DROP FUNCTION statement” on page 695
● “RETURN statement” on page 858
● “Variables supplied to web services” [SQL Anywhere Server - Programming]
● “Tutorial: Working with MIME types in a RAW service” [SQL Anywhere Server - Programming]
● “SQL Anywhere as an HTTP web server” [SQL Anywhere Server - Programming]
● “Web client application development” [SQL Anywhere Server - Programming]
● “remote_idle_timeout option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL Not supported by Adaptive Server Enterprise.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 547


SQL statements

Examples
The following statement creates a function named cli_test1 that returns images from the get_picture
service running on localhost:

CREATE FUNCTION cli_test1( image LONG VARCHAR )


RETURNS LONG BINARY
URL 'http://localhost/get_picture'
TYPE 'HTTP:GET';

The following statement issues an HTTP request with the URL http://localhost/get_picture?
image=widget:

SELECT cli_test1( 'widget' );

The following statement uses a substitution parameter to allow the request URL to be passed as an input
parameter. The SET clause is used to turn off CHUNK mode transfer-encoding.

CREATE FUNCTION cli_test2( image LONG VARCHAR, myurl LONG VARCHAR )


RETURNS LONG BINARY
URL '!myurl'
TYPE 'HTTP:GET'
SET 'HTTP(CH=OFF)'
HEADER 'ASA-ID';

The following statement issues an HTTP request with the URL http://localhost/get_picture?
image=widget:

CREATE VARIABLE a_binary LONG BINARY


a_binary = cli_test2('widget', 'http://localhost/get_picture');
SELECT a_binary;

CREATE FUNCTION statement


Creates a user-defined SQL function in the database.

Syntax
CREATE [ OR REPLACE | TEMPORARY ] FUNCTION [ owner.]function-name
( [ parameter, ... ] )
RETURNS data-type
[ SQL SECURITY { INVOKER | DEFINER } ]
[ ON EXCEPTION RESUME ]
[ [ NOT ] DETERMINISTIC ]
compound-statement | AS tsql-compound-statement

parameter :
[ IN ] parameter-name data-type [ DEFAULT expression ]

tsql-compound-statement :
sql-statement
sql-statement
...

548 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Parameters
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. However, function parameters are IN by default.

When functions are executed, not all parameters need to be specified. If a DEFAULT value is provided in
the CREATE FUNCTION statement, missing parameters are assigned the default values. If an argument
is not provided by the caller and no default is set, an error is given.

OR REPLACE clause Specifying CREATE OR REPLACE FUNCTION creates a new function, or


replaces an existing function with the same name. When a function is replaced, the definition of the
function is changed but the existing permissions are preserved.

You cannot use the OR REPLACE clause with temporary functions.

TEMPORARY keyword Specifying CREATE TEMPORARY FUNCTION means that the function is
visible only by the connection that created it, and that it is automatically dropped when the connection is
dropped. Temporary functions can also be explicitly dropped. You cannot perform ALTER, GRANT, or
REVOKE on them, and, unlike other functions, temporary functions are not recorded in the catalog or
transaction log.

Temporary functions execute with the permissions of their creator (current user) or specified owner. You
can specify an owner for a temporary function when:

○ the temporary function is created within a permanent stored procedure

○ the owner of the temporary function and permanent stored procedure is the same

To drop the owner of a temporary function, you must drop the temporary function first.

Temporary functions can be created and dropped when connected to a read-only database.

You cannot use the OR REPLACE clause with temporary functions.

RETURNS clause Use the RETURNS clause to specify the data type for the result of the function.

SQL SECURITY clause The SQL SECURITY clause defines whether the function is executed as the
INVOKER (the user who is calling the function), or as the DEFINER (the user who owns the function).
The default is DEFINER.

ON EXCEPTION RESUME clause Use Transact-SQL-like error handling.

[ NOT ] DETERMINISTIC clause Use this clause to indicate whether functions are deterministic or
non-deterministic. If this clause is omitted, then the deterministic behavior of the function is unspecified
(the default).

If a function is declared as DETERMINISTIC, it should return the same value every time it is invoked
with the same set of parameters.

If a function is declared as NOT DETERMINISTIC, then it is not guaranteed to return the same value for
the same set of parameters. A function declared as NOT DETERMINISTIC is re-evaluated each time it is

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 549


SQL statements

called in a query. This clause must be used when it is known that the function result for a given set of
parameters can vary.

Also, functions that have side effects such as modifying the underlying data should be declared as NOT
DETERMINISTIC. For example, a function that generates primary key values and is used in an
INSERT...SELECT statement should be declared NOT DETERMINISTIC:
CREATE FUNCTION keygen( increment INTEGER )
RETURNS INTEGER
NOT DETERMINISTIC
BEGIN
DECLARE keyval INTEGER;
UPDATE counter SET x = x + increment;
SELECT counter.x INTO keyval FROM counter;
RETURN keyval
END
INSERT INTO new_table
SELECT keygen(1), ...
FROM old_table;

Functions can be declared as DETERMINISTIC if they always return the same value for given input
parameters.

compound-statement A set of SQL statements bracketed by BEGIN and END, and separated by
semicolons.

tsql-compound-statement A batch of Transact-SQL statements.

Remarks
The CREATE FUNCTION statement creates a function in the database. A function can be created for
another user by specifying an owner name. Subject to permissions, a function can be used in exactly the
same way as other non-aggregate functions.

When SQL SECURITY INVOKER is specified, more memory is used because annotation must be done
for each user that calls the procedure. Also, when SQL SECURITY INVOKER is specified, name
resolution is done as the invoker as well. Therefore, care should be taken to qualify all object names
(tables, procedures, and so on) with their appropriate owner.

All functions are treated as deterministic unless they are declared NOT DETERMINISTIC. Deterministic
functions return a consistent result for the same parameters, and are free of side effects. That is, the
database server assumes that two successive calls to the same function with the same parameters returns
the same result, and does not have any unwanted side-effects on the query's semantics.

If a function returns a result set, it cannot also set output parameters or return a return value.

Permissions
Must have RESOURCE authority, unless creating a temporary function.

External functions, including Java functions, must have DBA authority.

Side effects
Automatic commit, even for temporary functions.

550 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “ALTER FUNCTION statement” on page 412
● “CREATE FUNCTION statement [External call]” on page 535
● “CREATE FUNCTION statement [Web service]” on page 541
● “BEGIN statement” on page 484
● “CREATE PROCEDURE statement” on page 585
● “DROP FUNCTION statement” on page 695
● “RETURN statement” on page 858
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]
● “SQL data types” on page 81
● “Transact-SQL batches” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 CREATE FUNCTION is a core feature of the SQL/2008 standard, though some of its
components supported in SQL Anywhere are optional SQL language features. A subset of these
features include:

○ The SQL SECURITY clause is optional language feature T324.

○ The ability to pass a LONG VARCHAR, LONG NVARCHAR, or LONG BINARY value to a SQL
function is language feature T041.

○ The ability to create or modify a schema object within a SQL function, using statements such as
CREATE TABLE or DROP TRIGGER, is language feature T651.

○ The ability to use a dynamic-SQL statement within a SQL function, including statements such as
EXECUTE IMMEDIATE, PREPARE, and DESCRIBE, is language feature T652.

Several clauses of the CREATE FUNCTION statement are vendor extensions. These include:

○ The TEMPORARY clause.

○ The ON EXCEPTION RESUME clause.

○ The optional DEFAULT clause for a specific routine parameter.

○ The specification of a Transact-SQL function using the AS clause.

○ The optional OR REPLACE clause.

● Transact-SQL CREATE FUNCTION is supported by Adaptive Server Enterprise. Adaptive


Server Enterprise does not support the optional IN keyword for function parameters.

Examples
The following function concatenates a firstname string and a lastname string.
CREATE FUNCTION fullname(
firstname CHAR(30),
lastname CHAR(30) )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 551


SQL statements

RETURNS CHAR(61)
BEGIN
DECLARE name CHAR(61);
SET name = firstname || ' ' || lastname;
RETURN (name);
END;

The following example replaces the fullname function created in the first example. After replacing the
function, the local variable name is removed:
CREATE OR REPLACE FUNCTION fullname(
firstname CHAR(30),
lastname CHAR(30) )
RETURNS CHAR(61)
BEGIN
RETURN ( firstname || ' ' || lastname );
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 ( GivenName, Surname )
FROM Employees;

fullname (GivenName, Surname)

Fran Whitney

Matthew Cobb

Philip Chin

Julie Jordan

...

The following function uses Transact-SQL syntax:


CREATE FUNCTION DoubleIt( @Input INT )
RETURNS INT
AS
BEGIN
DECLARE @Result INT
SELECT @Result = @Input * 2
RETURN @Result
END;

552 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The statement SELECT DoubleIt( 5 ) returns a value of 10.

CREATE INDEX statement


Creates an index on a specified table or materialized view.

Syntax 1 - Creating an index on a table


CREATE [ VIRTUAL ] [ UNIQUE ] [ CLUSTERED ] INDEX [ IF NOT EXISTS ] index-name
ON [ owner.]table-name
( column-name [ ASC | DESC ], ...
| function-name ( argument, ... ] ) AS column-name )
| [ WITH NULLS NOT DISTINCT ]
[ { IN | ON } dbspace-name ]
[ FOR OLAP WORKLOAD ]

Syntax 2 - Creating an index on a materialized view


CREATE [ VIRTUAL ] [ UNIQUE ] [ CLUSTERED ] INDEX [ IF NOT EXISTS ] index-name
ON [ owner.]materialized-view-name
( column-name [ ASC | DESC ], ...)
| [ WITH NULLS NOT DISTINCT ]
[ { IN | ON } dbspace-name ]
[ FOR OLAP WORKLOAD ]

Parameters

VIRTUAL clause The VIRTUAL keyword is primarily for use by the Index Consultant. A virtual
index mimics the properties of a real physical index during the evaluation of execution plans by the Index
Consultant and when the PLAN function is used. You can use virtual indexes together with the PLAN
function to explore the performance impact of an index, without the often time-consuming and resource-
consuming effects of creating a real index.

Virtual indexes are not visible to other connections, and are dropped when the connection is closed.
Virtual indexes are not used when evaluating plans for the actual execution of queries, and so do not
interfere with performance.

Virtual indexes have a limit of four columns.

UNIQUE clause The UNIQUE attribute ensures that there will not be two rows in the table or
materialized view with identical values in all the columns in the index. If you specify UNIQUE, but do
not specify WITH NULLS NOT DISTINCT, each index key must be unique or contain a NULL in at
least one column. For example, two entries ('a', NULL) and ('a', NULL) are each considered unique.

If you specify UNIQUE...WITH NULLS NOT DISTINCT, then the index key must be unique regardless
of the NULL values. For example, two entries ('a', NULL) and ('a', NULL) are considered equal, not
unique.

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

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 553


SQL statements

primary key or a unique constraint, but not a unique index, because it can include multiple instances of
NULL.

It is recommended that you do not use approximate data types such as FLOAT and DOUBLE for primary
keys or for columns in unique constraints. Approximate numeric data types are subject to rounding errors
after arithmetic operations.

Spatial columns cannot be included in a unique index.

CLUSTERED clause The CLUSTERED attribute causes rows to be stored in an approximate key
order corresponding to the index. While the database server makes an attempt to preserve key order, total
clustering is not guaranteed.

If a clustered index exists, the LOAD TABLE statement inserts rows in the order of the index key, and the
INSERT statement attempts to put new rows on the same page as the one containing adjacent rows, as
defined by the key order.

IF NOT EXISTS clause When the IF NOT EXISTS attribute is specified and the named index already
exists, no changes are made and an error is not returned.

ASC | DESC clause Columns are sorted in ascending (increasing) order unless descending (DESC) is
explicitly specified. An index is 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 is used only if the index was created with the same ascending and
descending attributes.

function-name The function-name clause creates an index on a function. This clause cannot be used
on declared temporary tables or materialized views.

This form of the CREATE INDEX statement is a convenience method that carries out the following
operations:

1. Adds a computed column named column-name to the table. The column is defined with a COMPUTE
clause that is the specified function, along with any specified arguments. See the COMPUTE clause
of the CREATE TABLE statement for restrictions on the type of function that can be specified. The
data type of the column is based on the result type of the function.

2. Populates the computed column for the existing rows in the table.

3. Creates an index on the column.

Dropping the index does not cause the associated computed column to be dropped.

IN | ON clause By default, the index is placed in the same database file as its table or materialized
view. 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, or for
performance improvements that might be achieved by using multiple disk devices.

If the new index can share the physical index with an existing logical index, the IN clause is ignored.

554 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

WITH NULLS NOT DISTINCT clause This clause can only be specified if you are declaring the index
to be UNIQUE and allows you to specify that NULLs in index keys are not unique. For more information,
see the UNIQUE clause.

FOR OLAP WORKLOAD clause When you specify FOR OLAP WORKLOAD, the database server
performs certain optimizations and gathers statistics on the key to help improve performance for OLAP
workloads. Performance improvements are most noticeable when the optimization_workload is set to
OLAP.

Remarks
Syntax 1 is for use with tables; Syntax 2 is for use with materialized views.

Indexes can improve database performance. SQL Anywhere uses physical and logical indexes. A physical
index is the actual indexing structure as it is stored on disk. A logical index is a reference to a physical
index. If you create an index that is identical in its physical attributes to an existing index, the database
server creates a logical index that shares the existing physical index. In general, indexes created by users
are considered logical indexes. The database server creates physical indexes as required to implement
logical indexes, and can share the same physical index among several logical indexes.

The CREATE INDEX statement creates a sorted index on the specified columns of the named table or
materialized view. 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), alter it (ALTER INDEX), delete it
(DROP INDEX), or in a hint to the optimizer.

● 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 or materialized view.

● Indexes on views You can create indexes on materialized views, but not on regular views.

● Index name space The name of each index must be unique for a given table or materialized view.

● Exclusive use CREATE INDEX is prevented whenever the statement affects a table or
materialized view currently being used by another connection. CREATE INDEX can be time
consuming and the database server will not process requests referencing the same table while the
statement is being processed.

● Automatically created indexes SQL Anywhere automatically creates indexes for primary key,
foreign key, and unique constraints. These automatically created indexes are held in the same database
file as the table.

This statement cannot be executed when there are cursors opened with the WITH HOLD clause that use
either statement or transaction snapshots.

Permissions
Must be the owner of the table or materialized view, or have either DBA authority or REFERENCES
permission.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 555


SQL statements

Side effects
Automatic commit. Creating an index on a function (an implicit computed column) also causes a
checkpoint.

Column statistics are updated (or created if they do not exist).

See also
● “DROP INDEX statement” on page 695
● “CREATE STATISTICS statement” on page 625
● “optimization_workload option” [SQL Anywhere Server - Database Administration]
● “Advanced: Logical and physical indexes” [SQL Anywhere Server - SQL Usage]
● “Indexes” [SQL Anywhere Server - SQL Usage]
● “Obtaining Index Consultant recommendations for a query” [SQL Anywhere Server - SQL Usage]
● “Index Consultant” [SQL Anywhere Server - SQL Usage]
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]
● “Clustered indexes” [SQL Anywhere Server - SQL Usage]
● “Computed columns” [SQL Anywhere Server - SQL Usage]
● “OLAP support” [SQL Anywhere Server - SQL Usage]
● “SQL Anywhere size and number limitations” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Create a two-column index on the Employees table.
CREATE INDEX employee_name_index
ON Employees
( Surname, GivenName );

Create an index on the SalesOrderItems table for the ProductID column.


CREATE INDEX item_prod
ON SalesOrderItems
( ProductID );

Use the SORTKEY function to create an index on the Description column of the Products table, sorted
according to a Russian collation. As a side effect, the statement adds a computed column desc_ru to the
table.
CREATE INDEX ix_desc_ru
ON Products (
SORTKEY( Description, 'rusdict' )
AS desc_ru );

CREATE LOCAL TEMPORARY TABLE statement


Creates a local temporary table within a procedure that persists after the procedure completes and until it
is either explicitly dropped, or until the connection terminates.

556 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
CREATE LOCAL TEMPORARY TABLE table-name
( { column-definition [ column-constraint ... ] | table-constraint | pctfree }, ... )
[ ON COMMIT { DELETE | PRESERVE } ROWS | NOT TRANSACTIONAL ]

pctfree : PCTFREE percent-free-space

percent-free-space : integer

Parameters
ON COMMIT clause By default, the rows of a temporary table are deleted on a COMMIT. You can
use the ON COMMIT clause to preserve rows on a COMMIT.

NOT TRANSACTIONAL clause The NOT TRANSACTIONAL clause provides performance


improvements in some circumstances because operations on non-transactional temporary tables do not
cause entries to be made in the rollback log. For example, NOT TRANSACTIONAL may be useful if
procedures that use the temporary table are called repeatedly with no intervening COMMITs or
ROLLBACKs.

Remarks
In a procedure, use the CREATE LOCAL TEMPORARY TABLE statement, instead of the DECLARE
LOCAL TEMPORARY TABLE statement, when you want to create a table that persists after the
procedure completes. Local temporary tables created using the CREATE LOCAL TEMPORARY
TABLE statement remain until they are either explicitly dropped, or until the connection closes.

Tables created using CREATE LOCAL TEMPORARY TABLE do not appear in the SYSTABLE view
of the system catalog.

Local temporary tables created in IF statements using CREATE LOCAL TEMPORARY TABLE also
persist after the IF statement completes.

Permissions
None.

Side effects
None.

See also
● “CREATE TABLE statement” on page 633
● “DECLARE LOCAL TEMPORARY TABLE statement” on page 672
● “Compound statements” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 CREATE LOCAL TEMPORARY TABLE is part of optional language feature F531 of
the SQL/2008 standard. The PCTFREE and NOT TRANSACTIONAL clauses are vendor extensions.
The column and constraint definitions defined by the statement may also include vendor extension
syntax. In SQL/2008, the standard stipulates that tables created via the CREATE LOCAL

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 557


SQL statements

TEMPORARY TABLE statement appear in the system catalog; this is not the case with SQL
Anywhere.

● Transact-SQL CREATE LOCAL TEMPORARY TABLE is not supported by Adaptive Server


Enterprise. In Sybase Adaptive Server Enterprise, one creates a temporary table using the CREATE
TABLE statement with a table name that begins with the special character #.

Example
The following example creates a local temporary table called TempTab:
CREATE LOCAL TEMPORARY TABLE TempTab ( number INT )
ON COMMIT PRESERVE ROWS;

CREATE LOGIN POLICY statement


Creates a login policy.

Syntax
CREATE LOGIN POLICY policy-name policy-options

policy options :
policy-option [ policy-option ... ]

policy-option :
policy-option-name = policy-option-value

policy-option-value :
{ UNLIMITED | legal-option-value }

Parameters
policy-name The name of the login policy.

policy-option-name The name of the login policy option. If you do not specify an option, the value
from the root login policy is applied.

policy-option-value The value assigned to the login policy option. If you specify UNLIMITED, no
limits are imposed.

Remarks
If you do not specify a policy option, values for the login policy are taken from the root login policy.

All new databases include a root login policy. You can modify the root login policy values, but you
cannot delete the policy. An overview of the default options for the root login policy is provided in the
table below.

558 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Policy-option-name Description Default Applies to


value

password_life_time The maximum number of days before a Unlimi- All users, includ-
password must be changed. ted ing those with
DBA authority.

password_grace_time The number of days before the password 0 All users, includ-
expires during which login is allowed, but ing those with
the default post_login procedure issues DBA authority.
warnings.

password_expi- If the value for this option is ON, the us- OFF All users, includ-
ry_on_next_login er's password expires after the next login. ing those with
DBA authority.

locked If the value for this option is ON, users OFF Users without
are not allowed to establish new connec- DBA authority.
tions. Users with DBA authority cannot
be locked. The reason_locked column of
the sa_get_user_status system procedure
returns a string generated by the database
server that shows why a user is locked.

max_connections The maximum number of concurrent con- Unlimi- Users without


nections allowed for a user. ted DBA authority.

max_failed_login_at- The maximum number of failed attempts Unlimi- All users, includ-
tempts since the last successful attempt to log in ted ing those with
before the user is locked. DBA authority.

DBA user ac-


counts are un-
locked after one
minute has passed
since the most re-
cent failed login
attempt.

max_days_since_login The maximum number of days that can Unlimi- Users without
elapse between two successive logins by ted DBA authority.
the same user.

max_non_dba_connec- The maximum number of concurrent con- Unlimi- Users without


tions nections that users without DBA authority ted DBA authority and
can make. This option is only supported only to the root
in the root login policy. login policy.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 559


SQL statements

Permissions
DBA authority

Side effects
None.

See also
● “ALTER LOGIN POLICY statement” on page 415
● “ALTER USER statement” on page 470
● “COMMENT statement” on page 499
● “CREATE USER statement” on page 658
● “DROP LOGIN POLICY statement” on page 696
● “DROP USER statement” on page 715
● “Login policies” [SQL Anywhere Server - Database Administration]
● “Creating a new login policy” [SQL Anywhere Server - Database Administration]
● “Assigning a login policy to an existing user” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example creates the Test1 login policy. This example has an unlimited password life and
allows the user a maximum of 5 attempts to enter a correct password before the account is locked.
CREATE LOGIN POLICY Test1
password_life_time=UNLIMITED
max_failed_login_attempts=5;

CREATE MATERIALIZED VIEW statement


Creates a materialized view.

Syntax
CREATE MATERIALIZED VIEW
[ owner.]materialized-view-name [ ( alt-column-names, ... ) ]
[ IN dbspace-name ]
AS select-statement
[ CHECK { IMMEDIATE | MANUAL } REFRESH ]

alt-column-names :
( column-name [,...] )

Parameters
alt-column-names clause Use this clause to specify alternate names for the columns in the
materialized view. If you specify alternate columns names, the number of columns listed in alt-column-
names must match the number of columns in select-statement. If you do not specify alternate column
names, the names are set to those in select-statement.

560 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

IN clause Use this clause to specify the dbspace in which to create the materialized view. If this clause
is not specified, then the materialized view is created in the dbspace specified by the default_dbspace
option. Otherwise, the system dbspace is used.

AS clause Use this clause to specify, in the form of a SELECT statement, the data to use to populate
the materialized view. A materialized view definition can only reference base tables; it cannot reference
views, other materialized views, or temporary tables. select-statement must contain column names or have
an alias name specified. If you specify alt-column-names, those names are used instead of the aliases
specified in select-statement.

Column names in the SELECT statement must be specified explicitly; you cannot use the SELECT *
construct. For example, you cannot specify CREATE MATERIALIZED VIEW matview AS
SELECT * FROM table-name. Also, you should fully qualify objects names in the select-statement.

CHECK clause Use this clause to validate the statement without actually creating the view. When you
specify the CHECK clause:

○ The database server performs the normal language checks that would be carried out if CREATE
MATERIALIZED VIEW was executed without the clause, and any errors generated are returned as
usual.

○ The database server does not perform the actual creation of the view. This means that certain errors that
would occur at creation time are not generated. For example, an error indicating that the specified view
name already exists is not generated. This allows you to use the CHECK clause to test intended
changes to the definition of the view, without a conflict with the naming of the view.

○ If CHECK IMMEDIATE REFRESH is used then the database server verifies that the syntax is valid
for an immediate view and returns any errors.

○ No changes are made to the database, and nothing is recorded in the transaction log.

○ There is an implicit commit at the beginning of statement execution and a rollback at the end to release
all locks obtained during execution.

See also
● “Materialized views restrictions” [SQL Anywhere Server - SQL Usage]
● “Additional dbspaces considerations” [SQL Anywhere Server - Database Administration]

Remarks
When you create a materialized view, it is a manual view and uninitialized. That is, it has a manual
refresh type, and it has not been refreshed (populated with data). To initialize the view, execute a
REFRESH MATERIALIZED VIEW statement, or use the sa_refresh_materialized_views system
procedure.

You can encrypt a materialized view, change its PCTFREE setting, change its refresh type, and enable or
disable its use by the optimizer. However, you must create the materialized view first, and then use the
ALTER MATERIALIZED VIEW to change these settings. The default values for materialized views at
creation time are:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 561


SQL statements

● NOT ENCRYPTED

● ENABLE USE IN OPTIMIZATION

● PCTFREE is set according to the database page size: 200 bytes for a 4 KB page size, and 100 bytes for
a 2 KB page size

● MANUAL REFRESH

Several database and server options must be in effect to create a materialized view.

The sa_recompile_views system procedure does not affect materialized views.

See also
● “Materialized views restrictions” [SQL Anywhere Server - SQL Usage]
● “REFRESH MATERIALIZED VIEW statement” on page 843

Permissions
You must have RESOURCE authority and SELECT permission on the tables in the materialized view
definition. To create a materialized view for another user, you must also have DBA authority.

Side effects
While executing, the CREATE MATERIALIZED VIEW statement places exclusive locks, without
blocking, on all tables referenced by the materialized view. If one of the referenced tables cannot be
locked, the statement fails and an error is returned.

See also
● “Materialized views” [SQL Anywhere Server - SQL Usage]
● “Advanced: Status and properties for materialized views” [SQL Anywhere Server - SQL Usage]
● “ALTER MATERIALIZED VIEW statement” on page 417
● “DROP MATERIALIZED VIEW statement” on page 697
● “REFRESH MATERIALIZED VIEW statement” on page 843
● “CREATE VIEW statement” on page 661
● “sa_refresh_materialized_views system procedure” on page 1108

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example creates a materialized view containing confidential information about employees
in the SQL Anywhere sample database. You must subsequently execute a REFRESH MATERIALIZED
VIEW statement to initialize the view for use, as shown in the example.
CREATE MATERIALIZED VIEW EmployeeConfid2 AS
SELECT EmployeeID, Employees.DepartmentID,
SocialSecurityNumber, Salary, ManagerID,
Departments.DepartmentName, Departments.DepartmentHeadID
FROM Employees, Departments
WHERE Employees.DepartmentID=Departments.DepartmentID;
REFRESH MATERIALIZED VIEW EmployeeConfid2;

562 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE MESSAGE statement [T-SQL]


Adds a user-defined message to the ISYSUSERMESSAGE system table for use by PRINT and
RAISERROR statements.

Syntax
CREATE MESSAGE message-number AS message-text

message-number : integer

message-text : string

Parameters
message-number 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.

Remarks
CREATE MESSAGE associates a message number with a message string. The message number can be
used in PRINT and RAISERROR statements.

Permissions
Must have RESOURCE authority

Side effects
Automatic commit.

See also
● “PRINT statement [T-SQL]” on page 836
● “RAISERROR statement” on page 838
● “DROP MESSAGE statement” on page 698
● “SYSUSERMESSAGE system view” on page 1256

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 563


SQL statements

● Transact-SQL CREATE MESSAGE supplies the functionality provided by the sp_addmessage


system procedure in Adaptive Server Enterprise.

CREATE MIRROR SERVER statement


Note
Read-only scale-out and database mirroring each require a separate license. See “Separately licensed
components” [SQL Anywhere 12 - Introduction].

Creates or replaces a mirror server that is being used for database mirroring or read-only scale-out.

Syntax
CREATE [ OR REPLACE ] MIRROR SERVER mirror-server-name
AS { PRIMARY | MIRROR | ARBITER | PARTNER | COPY }
[ { FROM SERVER parent-name [ OR SERVER server-name ] | USING AUTO PARENT } ]
[ server-option = string [ ... ] ]

parent-name :
server-name | PRIMARY

server-option :
connection_string
logfile
preferred
state_file

Parameters
● OR REPLACE clause CREATE MIRROR SERVER creates the mirror server. An error is
returned if a mirror server with the specified name already exists in the database.

Specifying OR REPLACE creates a mirror server if the server does not already exist in the database,
and replaces it if it does exist. An error is returned if you attempt to replace a mirror server while it is
in use.

● AS clause You can specify one of the following server types:

○ PRIMARY The mirror server with type PRIMARY defines a virtual or logical server, rather
than an actual database server. The name of this server is the alternate server name for the
database. The alternate server name can be used by applications to connect to the server currently
acting as the primary server. The server marked as PRIMARY also defines the connection string
used by mirror servers to connect to the server currently acting as primary, and it defines how new
copy nodes initially connect to the root server in a scale-out system. There can be only one
PRIMARY server for a database.

○ MIRROR The mirror server with type MIRROR defines a virtual or logical server, rather than
an actual database server. The name of this server is the alternate mirror server name for the
database. The alternate mirror server name can be used by applications to connect to the server
currently acting as the read-only mirror. There can be only one MIRROR server for a database.

564 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ ARBITER In a database mirroring system, the arbiter server assists in determining which of the
PARTNER servers takes ownership of the database. The arbiter server must be defined with a
connection string that can be used by the partner servers to connect to the arbiter. There can be
only one ARBITER server for a database.

○ PARTNER In a database mirroring system, servers defined as PARTNER are eligible to


become the primary server and take ownership of the database. You must define two PARTNER
servers for database mirroring, and both must have a connection string and a state file. The name
of the mirror server must correspond to the name of the database server, as specified by the -n
server option, and must match the value of the SERVER connection string parameter specified in
the connection_string mirror server option.

In a read-only scale-out system, you must define one PARTNER server. This server is the root
server, and runs the only copy of the database that allows both read and write operations.

○ COPY In a read-only scale-out system, this value specifies that the database server is a copy
node. All connections to the database on this server are read-only. The name of the mirror server
must correspond to the name of the database server, as specified by the -n server option, and must
match the value of the SERVER connection string parameter specified in the connection_string
mirror server option. You do not have to explicitly define copy nodes for the scale-out system; you
can choose to have the root node define the copy nodes when they connect.

● FROM SERVER clause You can only specify this clause for mirror servers of type COPY. This
clause constructs a tree of servers for a mirroring or scale-out system and indicates which servers the
copy nodes obtain transaction log pages from.

The parent can be specified using the name of the mirror server or PRIMARY. An alternate parent for
the copy node can be specified using the OR SERVER clause.

In a database mirroring system that has only two levels (partner and copy nodes), the copy nodes
obtain transaction log pages from the current primary or mirror server.

A copy node determines which server to connect to by using its mirror server definition that is stored
in the database. From its definition, it can locate the definition of its parent, and from its parent's
definition, it can obtain the connection string to connect to the parent.

You do not have to explicitly define copy nodes for the scale-out system: you can choose to have the
root node define the copy nodes when they connect.

● OR SERVER clause Use the OR SERVER clause to specify an alternate parent for the copy node.

● USING AUTO PARENT clause This clause causes the primary server to assign a parent for this
server.

● server-option clause The following options are supported:

○ connection_string server option Specifies the connection string to be used to connect to the
server. A user ID and password are not required. The connection string for a mirror server should
not include a user ID or password because they are not used when one mirror server connects to
another mirror server.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 565


SQL statements

For a list of connection parameters, see “Connection parameters” [SQL Anywhere Server -
Database Administration].

○ logfile server option Specifies the location of the file that contains one line per request that is
sent between mirror servers if database mirroring is used. This file is used only for debugging.

○ preferred server option Specifies whether the server is the preferred server in the mirroring
system. You can specify either YES or NO. The preferred server assumes the role of primary
server whenever possible. You specify this option when defining PARTNER servers.

○ state_file server option Specifies the location of the file used for maintaining state
information about the mirroring system. This option is required for database mirroring. A state file
must be specified for servers with type PARTNER. For arbiter servers, the location is specified as
part of the command to start the server.

Remarks
Cloud note: This statement is not supported on tenant databases in the cloud.

In a database mirroring system, the mirror server type can be PRIMARY, MIRROR, ARBITER, or
PARTNER.

In a read-only scale-out system, the mirror server type can be PRIMARY, PARTNER, or COPY.

Mirror server names for servers of type PARTNER, ARBITER, or COPY must match the names of the
database servers that are part of the mirroring system (the name used with the -n server option). This
allows each database server to find its own definition and that of its parent. Also, all copy node servers
must have unique server names.

To use a copy node as the arbiter for the database it is copying in a database mirroring system, create the
arbiter server with a name that does not match the server name of any of the database servers in the high
availability system. In this configuration, the name of the arbiter is used as a placeholder in the mirror
server definition to hold the connection string for the arbiter.

Permissions
Must have DBA authority.

Side effects
Automatic commit.

566 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “SYSMIRRORSERVER system view” on page 1217
● “Database mirroring” [SQL Anywhere Server - Database Administration]
● “SQL Anywhere read-only scale-out” [SQL Anywhere Server - Database Administration]
● “SET MIRROR OPTION statement” on page 883
● “ALTER MIRROR SERVER statement” on page 420
● “COMMENT statement” on page 499
● “DROP MIRROR SERVER statement” on page 699
● “How child copy nodes are added” [SQL Anywhere Server - Database Administration]
● “State information files” [SQL Anywhere Server - Database Administration]
● “Preferred database server” [SQL Anywhere Server - Database Administration]
● “Automatically assign the parent of a copy node” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension

Example
The following statement creates a mirror server that can be used as the primary server in a database
mirroring system:
CREATE MIRROR SERVER "scaleout_primary"
AS PRIMARY
connection_string =
'server=scaleout_primary;host=winxp-2:6871,winxp-3:6872';

The following statement creates a mirror server that can be used as the mirror server in a database
mirroring system:
CREATE MIRROR SERVER "scaleout_mirror"
AS MIRROR
connection_string = 'server=scaleout_mirror;host=winxp-2:6871,winxp-3:6872';

The following statement creates a mirror server that can be used as the arbiter in a database mirroring
system:
CREATE MIRROR SERVER "scaleout_arbiter"
AS ARBITER
connection_string = 'server=scaleout_arbiter;host=winxp-4:6870';

The following statement creates a mirror server that can be used as a partner server in a database
mirroring system:
CREATE MIRROR SERVER "scaleout_server1"
AS PARTNER
connection_string = 'server=scaleout_server1;HOST=winxp-2:6871'
state_file = 'c:\server1\server1.state';

CREATE PROCEDURE statement [External call]


Creates an interface to a native or external procedure.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 567


SQL statements

Syntax
CREATE [ OR REPLACE ] PROCEDURE [ owner.]procedure-name
( [ parameter[, ... ] ] )
[ RESULT ( result-column [, ... ] ) | NO RESULT SET ]
[ DYNAMIC RESULT SETS integer-expression ]
[ SQL SECURITY { INVOKER | DEFINER } ]
{ EXTERNAL NAME 'native-call'
| EXTERNAL NAME 'c-call' LANGUAGE { C_ESQL32 | C_ESQL64 | C_ODBC32 | C_ODBC64 }
| EXTERNAL NAME 'clr-call' LANGUAGE CLR
| EXTERNAL NAME 'perl-call' LANGUAGE PERL
| EXTERNAL NAME 'php-call' LANGUAGE PHP
| EXTERNAL NAME 'java-call' LANGUAGE JAVA }

parameter :
[ parameter-mode ] parameter-name data-type [ DEFAULT expression ]
| SQLCODE
| SQLSTATE

parameter-mode :
IN
| OUT
| INOUT

native-call :
[ operating-system:]function-name@library

result-column :
column-name data-type

c-call :
[ operating-system:]function-name@library; ...

clr-call :
dll-name::function-name( param-type-1[, ... ] )

perl-call :
<file=perl-file> $sa_perl_return = perl-subroutine( $sa_perl_arg0[, ... ] )

php-call :
<file=php-file> print php-func( $argv[1][, ... ] )

java-call :
[ package-name.]class-name.method-name method-signature

operating-system :
Unix

method-signature :
( [ field-descriptor, ... ] ) return-descriptor

field-descriptor and return-descriptor :


{Z
|B
|S
|I
|J

568 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

|F
|D
|C
|V
| [descriptor
| Lclass-name;
}

Parameters
You can create permanent stored procedures that call external or native procedures written in a variety of
programming languages. You can use PROC as a synonym for PROCEDURE.

OR REPLACE clause Specifying OR REPLACE creates a new procedure, or replaces an existing


procedure with the same name. This clause changes the definition of the procedure, but preserves existing
permissions. An error is returned if you attempt to replace a procedure that is already in use.

Parameters Parameter names must conform to the rules for other database identifiers such as column
names. They must be a valid SQL data type.

Parameters can be prefixed with one of the keywords IN, OUT, or INOUT. If you do not specify one of
these values, parameters are INOUT by default. 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 OUT parameters that output the SQLSTATE or SQLCODE
value when the procedure ends. The SQLSTATE and SQLCODE special values can 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.

Specifying OR REPLACE (CREATE OR REPLACE PROCEDURE) creates a new procedure, or


replaces an existing procedure with the same name. This clause changes the definition of the procedure,
but preserves existing permissions. An error is returned if you attempt to replace a procedure that is
already in use.

You cannot create TEMPORARY external call procedures.

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

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 569


SQL statements

information is returned by the embedded SQL DESCRIBE or by ODBC SQLDescribeCol when a CALL
statement is being described.

Embedded SQL (LANGUAGE C_ESQL32, LANGUAGE C_ESQL64) or ODBC (LANGUAGE


C_ODBC32, LANGUAGE C_ODBC64) external procedures can return 0 or 1 result sets.

Perl or PHP (LANGUAGE PERL, LANGUAGE PHP) external procedures cannot return result sets.
Procedures that call native functions loaded by the database server cannot return result sets.

CLR or Java (LANGUAGE CLR, LANGUAGE JAVA) external procedures can return 0, 1, or more
result sets.

Some procedures can produce 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 GivenName
FROM Employees
ELSE
SELECT Surname, GivenName
FROM Employees
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, to get the proper shape of result set. The CURSOR cursor-
name clause on the DESCRIBE statement is required.

○ ODBC, OLE DB, ADO.NET Variable result-set procedures can be used by applications using these
interfaces. The proper description of the result sets is carried out by the driver or provider.

○ 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.

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.

NO RESULT SET clause Declares that no result set is returned by this procedure. This declaration
can lead to a performance improvement.

DYNAMIC RESULT SETS clause Use this clause with LANGUAGE CLR and LANGUAGE JAVA
calls. The DYNAMIC RESULT SETS clause is used to specify the number of dynamic result sets that

570 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

will be returned by the procedure. When a RESULT clause is specified and the DYNAMIC RESULT
SETS clause is not specified, it is assumed that the number of dynamic result sets is 1. When neither the
RESULT clause nor the DYNAMIC RESULT SETS clause is specified, no result set is expected and an
error will result if a result set is generated.

The C_ESQL32, C_ESQL64, C_ODBC32, and C_ODBC64 external environments can also return result
sets (like CLR and JAVA), but they are restricted to only one dynamic result set.

Note that procedures that call into Perl or PHP (LANGUAGE PERL, LANGUAGE PHP) external
functions cannot return result sets. Procedures that call native functions loaded by the database server
cannot return result sets.

SQL SECURITY clause The SQL SECURITY clause defines whether the procedure is executed as
the INVOKER (the user who is calling the procedure), or as the DEFINER (the user who owns the
procedure). The default is DEFINER. For external calls, this clause establishes the ownership context for
unqualified object references in the external environment.

When SQL SECURITY INVOKER is specified, more memory is used because annotation must be done
for each user that calls the procedure. Also, when SQL SECURITY INVOKER is specified, name
resolution is done as the invoker as well. Therefore, care should be taken to qualify all object names
(tables, procedures, and so on) with their appropriate owner. For example, suppose user1 creates the
following procedure:
CREATE PROCEDURE user1.myProcedure()
RESULT( columnA INT )
SQL SECURITY INVOKER
BEGIN
SELECT columnA FROM table1;
END;

If user2 attempts to run this procedure and a table user2.table1 does not exist, a table lookup error results.
Additionally, if a user2.table1 does exist, that table is used instead of the intended user1.table1. To
prevent this situation, qualify the table reference in the statement (user1.table1, instead of just table1).

EXTERNAL NAME clause A procedure using the EXTERNAL NAME clause with no LANGUAGE
attribute defines an interface to a native function written in a programming language such as C. The native
function is loaded by the database server into its address space.

The library name can include the file extension, which is typically .dll on Windows and .so on Unix. In
the absence of the extension, the software appends the platform-specific default file extension for
libraries. The following is a formal example.
CREATE PROCEDURE mystring( IN instr LONG VARCHAR )
EXTERNAL NAME '[email protected];Unix:[email protected]';

A simpler way to write the above EXTERNAL NAME clause, using platform-specific defaults, is as
follows:
CREATE PROCEDURE mystring( IN instr LONG VARCHAR )
EXTERNAL NAME 'mystring@mylib';

When called, the library containing the function is loaded into the address space of the database server.
The native function will execute as part of the server. In this case, if the function causes a fault, then the

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 571


SQL statements

database server will be terminated. Because of this, loading and executing functions in an external
environment using the LANGUAGE attribute is recommended. If a function causes a fault in an external
environment, the database server will continue to run.

For syntaxes that support operating-system, if you do not specify operating-system, then it is assumed that
the procedure runs on all platforms. If you specify Unix for one of the calls, then it is assumed that the
other call is for Windows.

● EXTERNAL NAME 'c-call' LANGUAGE { C_ESQL32 | C_ESQL64 | C_ODBC32 | C_ODBC64 }


clause To call a compiled native C function in an external environment instead of within the
database server, the stored procedure or function is defined with the EXTERNAL NAME clause
followed by the LANGUAGE attribute specifying one of C_ESQL32, C_ESQL64, C_ODBC32, or
C_ODBC64.

When the LANGUAGE attribute is specified, then the library containing the function is loaded by an
external process and the external function will execute as part of that external process. In this case, if
the function causes a fault, then the database server will continue to run.

The following is a sample procedure definition.


CREATE PROCEDURE ODBCinsert(
IN ProductName CHAR(30),
IN ProductDescription CHAR(50)
)
NO RESULT SET
EXTERNAL NAME '[email protected]'
LANGUAGE C_ODBC32;

● EXTERNAL NAME clr-call LANGUAGE CLR clause To call a .NET function in an external
environment, the procedure interface is defined with an EXTERNAL NAME clause followed by the
LANGUAGE CLR attribute.

A CLR stored procedure or function behaves the same as a SQL stored procedure or function except
that the code for the procedure or function is written in a .NET language such as C# or Visual Basic,
and the execution of the procedure or function takes place outside the database server (that is, within a
separate .NET executable).

The following is a sample procedure definition.


CREATE PROCEDURE clr_interface(
IN p1 INT,
IN p2 UNSIGNED SMALLINT,
OUT p3 LONG VARCHAR)
NO RESULT SET
EXTERNAL NAME 'CLRlib.dll::CLRproc.Run( int, ushort, out string )'
LANGUAGE CLR;

● EXTERNAL NAME perl-call LANGUAGE PERL clause To call a Perl function in an external
environment, the procedure interface is defined with an EXTERNAL NAME clause followed by the
LANGUAGE PERL attribute.

A Perl stored procedure or function behaves the same as a SQL stored procedure or function except
that the code for the procedure or function is written in Perl and the execution of the procedure or
function takes place outside the database server (that is, within a Perl executable instance).

572 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The following is a sample procedure definition.


CREATE PROCEDURE PerlWriteToConsole( IN str LONG VARCHAR)
NO RESULT SET
EXTERNAL NAME '<file=PerlConsoleExample>
WriteToServerConsole( $sa_perl_arg0 )'
LANGUAGE PERL;

● EXTERNAL NAME php-call LANGUAGE PHP clause To call a PHP function in an external
environment, the procedure interface is defined with an EXTERNAL NAME clause followed by the
LANGUAGE PHP attribute.

A PHP stored procedure or function behaves the same as a SQL stored procedure or function except
that the code for the procedure or function is written in PHP and the execution of the procedure or
function takes place outside the database server (that is, within a PHP executable instance).

The following is a sample procedure definition.


CREATE PROCEDURE PHPPopulateTable()
NO RESULT SET
EXTERNAL NAME '<file=ServerSidePHPExample> ServerSidePHPSub()'
LANGUAGE PHP;

● EXTERNAL NAME java-call LANGUAGE JAVA clause To call a Java method in an external
environment, the procedure interface is defined with an EXTERNAL NAME clause followed by the
LANGUAGE JAVA attribute.

A Java-interfacing stored procedure or function behaves the same as a SQL stored procedure or
function except that the code for the procedure or function is written in Java and the execution of the
procedure or function takes place outside the database server (that is, within a Java VM).

The following is a sample procedure definition.


CREATE PROCEDURE HelloDemo( IN name LONG VARCHAR )
NO RESULT SET
EXTERNAL NAME 'Hello.main([Ljava/lang/String;)V'
LANGUAGE JAVA;

Remarks
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.

If a stored procedure returns a result set, it cannot also set output parameters or return a return value.

When referencing a temporary table from multiple procedures, a potential issue can arise if the temporary
table definitions are inconsistent and statements referencing the table are cached.

Permissions
Must have RESOURCE authority, unless creating a temporary procedure.

Must have DBA authority for external procedures or to create a procedure for another user.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 573


SQL statements

Side effects
Automatic commit.

See also
● “References to temporary tables within procedures” [SQL Anywhere Server - SQL Usage]
● “ALTER PROCEDURE statement” on page 423
● “CALL statement” on page 491
● “CREATE FUNCTION statement” on page 548
● “CREATE FUNCTION statement [External call]” on page 535
● “CREATE PROCEDURE statement” on page 585
● “CREATE PROCEDURE statement [Web service]” on page 575
● “CREATE PROCEDURE statement [T-SQL]” on page 583
● “DROP PROCEDURE statement” on page 700
● “GRANT statement” on page 760
● “SQL data types” on page 81
● “The ESQL and ODBC external environments” [SQL Anywhere Server - Programming]
● “SQL Anywhere external call interface” [SQL Anywhere Server - Programming]
● “SQL Anywhere external environment support” [SQL Anywhere Server - Programming]
● “The PERL external environment” [SQL Anywhere Server - Programming]
● “The CLR external environment” [SQL Anywhere Server - Programming]
● “The PHP external environment” [SQL Anywhere Server - Programming]
● “The Java external environment” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 CREATE PROCEDURE for an external language environment is a core feature of the
SQL/2008 standard, though some of its components supported in SQL Anywhere are optional SQL/
2008 language features. A subset of these features include:

○ The SQL SECURITY clause is SQL/2008 optional language feature T324.

○ The ability to pass a LONG VARCHAR, LONG NVARCHAR, or LONG BINARY value to an
external procedure is SQL/2008 language feature T041.

○ The ability to create or modify a schema object within an external procedure, using statements such
as CREATE TABLE or DROP TRIGGER, is SQL/2008 language feature T653.

○ The ability to use a dynamic-SQL statement within an external procedure, including statements
such as CONNECT, EXECUTE IMMEDIATE, PREPARE, and DESCRIBE, is SQL/2008
language feature T654.

○ JAVA external procedures embody SQL/2008 language feature J621.

Several clauses of the CREATE PROCEDURE statement are vendor extensions. These include:

○ Support for C_ESQL32, C_ESQL64, C_ODBC32, C_ODBC64, CLR, PERL, and PHP in the
LANGUAGES clause are vendor extensions. The SQL/2008 standard supports "C" as an
environment-name as optional language feature B122.

○ The format of external-call is implementation-defined.

574 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ The RESULT and NO RESULT SET clauses are vendor extensions. The SQL/2008 standard uses
the RETURNS clause.

○ The optional DEFAULT clause for a specific routine parameter is a vendor extension.

○ The optional OR REPLACE clause is a vendor extension.

● Transact-SQL CREATE PROCEDURE for an external routine is supported by Adaptive Server


Enterprise. Adaptive Server Enterprise supports C-language and Java language external routines.

CREATE PROCEDURE statement [Web service]


Creates a user-defined web client procedure that makes HTTP or SOAP requests to an HTTP server.

Syntax
CREATE [ OR REPLACE ] PROCEDURE [ owner.]procedure-name ( [ parameter, ... ] )
[ RESULT ( attribute-column-name datatype, value-column-name datatype ) ]
URL url-string
[ TYPE { http-type-spec-string | soap-type-spec-string } ]
[ HEADER header-string ]
[ CERTIFICATE certificate-string ]
[ CLIENTPORT clientport-string ]
[ PROXY proxy-string ]
[ SET protocol-option-string ]
[ SOAPHEADER soap-header-string ]
[ NAMESPACE namespace-string ]

http-type-spec-string :
HTTP[: { GET
| POST[:MIME-type ]
| PUT[:MIME-type ]
| DELETE
| HEAD } ]

soap-type-spec-string :
SOAP[:{ RPC | DOC }

parameter :
parameter-mode parameter-name data-type [ DEFAULT expression ]

parameter-mode :
IN
| OUT
| INOUT

url-string :
{ HTTP | HTTPS | HTTPS_FIPS }://[user:password@]hostname[:port][/path]

protocol-option-string
[ http-option-list]
[, soap-option-list ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 575


SQL statements

http-option-list :
HTTP(
[ CH[UNK]={ ON | OFF | AUTO } ]
[; VER[SION]={ 1.0 | 1.1 } ]
)

soap-option-list :
SOAP(OP[ERATION]=soap-operation-name)

Parameters
You can create or replace a web services client procedure. You can use PROC as a synonym for
PROCEDURE.

For SOAP requests, the procedure name is used as the SOAP operation name by default. For more
information, see the SET clause.

Note
You cannot create TEMPORARY web services procedures.

OR REPLACE clause Specifying OR REPLACE creates a new procedure, or replaces an existing


procedure with the same name. This clause changes the definition of the procedure, but preserves existing
permissions. An error is returned if you attempt to replace a procedure that is already in use.

Parameters Parameter names must conform to the rules for other database identifiers such as column
names. They must be a valid SQL data type.

Only SOAP requests support the transmission of typed data such as FLOAT, INT, and so on. HTTP
requests support the transmission of strings only, so you are limited to CHAR types.

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.

Parameters can be prefixed with one of the keywords IN, OUT, or INOUT. If you do not specify one of
these values, parameters are INOUT by default. 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.

RESULT clause The RESULT clause is required in order to use the procedure in a SELECT
statement. The RESULT clause must return two columns. The first column contains HTTP response
header, status, and response body attributes, while the second column contains the values for these
attributes. The RESULT clause must specify two character data types. For example, VARCHAR or
LONG VARCHAR. If the RESULT clause is not specified, the default column names are Attribute and
Value and their data types are LONG VARCHAR.

576 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

URL clause Specifies the URI of the web service. The optional user name and password parameters
provide a means of supplying the credentials needed for HTTP basic authentication. HTTP basic
authentication base-64 encodes the user and password information and passes it in the Authentication
header of the HTTP request. When specified in this way, the user name and password are passed
unencrypted, as part of the URL.

For procedures of type HTTP:GET, query parameters can be specified within the URL clause in addition
to being automatically generated from parameters passed to a procedure.
URL 'http://localhost/service?parm=1

TYPE clause Specifies the format used when making the web service request. SOAP:RPC is used
when SOAP is specified or no TYPE clause is included. HTTP:POST is used when HTTP is specified.

The TYPE clause allows the specification of a MIME-type for HTTP:GET, HTTP:POST, and HTTP:PUT
types. The MIME-type specification is used to set the Content-Type request header and set the mode of
operation to allow only a single call parameter to populate the body of the request. Only zero or one
parameter may remain when making a web service stored procedure call after parameter substitutions
have been processed. Calling a web service procedure with a NULL value or no parameter (after
substitutions) results in a request with no body and a content-length of zero. Parameter names and values
(multiple parameters are permitted) are URL encoded within the body of the HTTP request.

Some typical MIME-types include:

○ text/plain
○ text/html
○ text/xml

The keywords for the TYPE clause have the following meanings:

○ 'HTTP:GET' By default, this type uses the application/x-www-form-urlencoded MIME-type for


encoding parameters specified in the URL.

For example, the following request is produced when a client submits a request from the URL,
http://localhost/WebServiceName?arg1=param1&arg2=param2:

GET /WebServiceName?arg1=param1&arg2=param2 HTTP/1.1


// <End of Request - NO BODY>

○ 'HTTP:POST' By default, this type uses the application/x-www-form-urlencoded MIME-type for


encoding parameters specified in the body of a POST request. URL parameters are stored in the body
of the request.

For example, the following request is produced when a client submits a request the URL, http://
localhost/WebServiceName?arg1=param1&arg2=param2:

POST /WebServiceName HTTP/1.1


Content-Type: application/x-www-form-urlencoded
Content-Length: 19
arg1=param1&arg2=param2
// <End of Request>

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 577


SQL statements

○ HTTP:PUT HTTP:PUT is similar to HTTP:POST, but the HTTP:PUT type does not have a default
media type.

The following example demonstrates how to configure a general purpose client procedure that uploads
data to a SQL Anywhere server running the %SQLANYSAMP12%\SQLAnywhere\HTTP\put_data.sql
sample:
ALTER PROCEDURE CPUT("data" LONG VARCHAR, resnm LONG VARCHAR, mediatype
LONG VARCHAR)
URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:PUT:!mediatype';

CALL CPUT('hello world', 'hello', 'text/plain' );

○ HTTP:DELETE A web service client procedure can be configured to delete a resource located on a
server. Specifying the media type is optional.

The following example demonstrates how to configure a general purpose client procedure that deletes
a resource from a SQL Anywhere server running the put_data.sql sample:
ALTER PROCEDURE CDEL(resnm LONG VARCHAR, mediatype LONG VARCHAR)
URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:DELETE:!mediatype';

CALL CDEL('hello', 'text/plain' );

○ HTTP:HEAD The head method is identical to a GET method but the server does not return a body.
A media type can be specified.
ALTER PROCEDURE CHEAD(resnm LONG VARCHAR)
URL 'http://localhost/resource/!resnm'
TYPE 'HTTP:HEAD';

CALL CHEAD( 'hello' );

○ 'SOAP:RPC' This type sets the Content-Type header to 'text/xml'. SOAP operations and
parameters are encapsulated in SOAP envelope XML documents.

○ 'SOAP:DOC' This type sets the Content-Type header to 'text/xml'. It is similar to the SOAP:RPC
type but allows you to send richer data types. SOAP operations and parameters are encapsulated in
SOAP envelope XML documents.

Specifying a MIME-type for the TYPE clause automatically sets the Content-Type header to that MIME-
type.

HEADER clause When creating HTTP web service client procedures, use this clause to add, modify,
or delete HTTP request header entries. The specification of headers closely resembles the format specified
in RFC2616 Hypertext Transfer Protocol—HTTP/1.1, and RFC822 Standard for ARPA Internet Text
Messages, including the fact that only printable ASCII characters can be specified for HTTP headers, and
they are case-insensitive.

Headers can be defined as header-name:value-name pairs. Each header must be delimited from its value
with a colon ( : ) and therefore cannot contain a colon. You can define multiple headers by delimiting
each pair with \n, \x0d\n, <LF> (line feed), or <CR><LF>. (carriage return followed by a line feed)

578 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Multiple contiguous white spaces within the header are converted to a single white space.

CERTIFICATE clause To make a secure (HTTPS) request, a client must have access to the certificate
used by the HTTPS server. The necessary information is specified in a string of semicolon-separated key/
value pairs. You can use the file key to specify the file name of the certificate, or you can use the
certificate key to specify the server certificate in a string. You cannot specify a file and certificate key
together. The following keys are available:

Key Abbreviation Description

file The file name of the certificate.

certificate cert The certificate itself.

company co The company specified in the certificate.

unit The company unit specified in the certificate.

name The common name specified in the certificate.

Certificates are required only for requests that are either directed to an HTTPS server, or can be redirected
from a non-secure to a secure server. Only PEM formatted certificates are supported.

CLIENTPORT clause Identifies the port number on which the HTTP client procedure communicates
using TCP/IP. It is provided for and recommended only for connections through firewalls that filter
"outgoing" TCP/IP connections. You can specify a single port number, ranges of port numbers, or a
combination of both; for example, CLIENTPORT '85,90-97'.

PROXY clause Specifies the URI of a proxy server. For use when the client must access the network
through a proxy. Indicates that the procedure is to connect to the proxy server and send the request to the
web service through it.

SET clause Specifies protocol-specific behavior options for HTTP and SOAP. The following list
describes the supported SET options. CHUNK and VERSION apply to the HTTP protocol, and
OPERATION applies to the SOAP protocol.

○ 'HTTP(CH[UNK]=option)' (HTTP or SOAP) This option allows you to specify whether to use
chunking. Chunking allows HTTP messages to be broken up into several parts. Possible values are
ON (always chunk), OFF (never chunk), and AUTO (chunk only if the contents, excluding auto-
generated markup, exceeds 8196 bytes). For example, the following SET clause enables chunking:
SET 'HTTP(CHUNK=ON)'

If the CHUNK option is not specified, the default behavior is AUTO. If a chunked request fails in
AUTO mode with a status of 505 HTTP Version Not Supported, or with 501 Not
Implemented, or with 411 Length Required, the client retries the request without chunked
transfer-coding.

Set the CHUNK option to OFF (never chunk) if the HTTP server does not support chunked transfer-
coded requests.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 579


SQL statements

Since CHUNK mode is a transfer encoding supported starting in HTTP version 1.1, setting CHUNK
to ON requires that the version (VER) be set to 1.1, or not be set at all, in which case 1.1 is used as the
default version.

○ ' HTTP(VER[SION]=ver)' (HTTP or SOAP) This option allows you to specify the version of HTTP
protocol that is used for the format of the HTTP message. For example, the following SET clause sets
the HTTP version to 1.1:
SET 'HTTP(VERSION=1.1)'

Possible values are 1.0 and 1.1. If VERSION is not specified:

● if CHUNK is set to ON, 1.1 is used as the HTTP version

● if CHUNK is set to OFF, 1.0 is used as the HTTP version

● if CHUNK is set to AUTO, either 1.0 or 1.1 is used, depending on whether the client is sending in
CHUNK mode

○ 'REDIR(COUNT=count, STATUS=status-list)' (HTTP or SOAP) The HTTP response status


codes such as 302 Found and 303 See Other are used to redirect web applications to a new URI,
particularly after an HTTP POST has been performed. For example, a client request could be:
GET /people/alice HTTP/1.1
Host: www.example.com
Accept: text/html, application/xhtml+xml
Accept-Language: en, de

The web server response could be:


HTTP/1.1 302 Found
Location: http://www.example.com/people/alice.en.html

In response, the client would send another HTTP request to the new URI. The REDIR option allows
you to control the maximum number of redirections allowed and which HTTP response status codes
to automatically redirect.

For example, SET 'REDIR(count=3, status=301,307)' allows a maximum limit of 3 re-


directions and permits redirection for 301 and 307 statuses. If one of the other redirection status codes
such as 302 or 303 is received, an error is issued (SQLCODE -983).

The default redirection limit count is 5. By default, an HTTP client procedure will automatically
redirect in response to all HTTP redirection status codes (301, 302, 303, 307). To disallow all
redirection status codes, use SET REDIR(COUNT=0). In this mode, a redirection response does not
result in an error (SQLCODE -983). Instead, a result set is returned with the HTTP status and
response headers. This permits a caller to conditionally reissue the request based on the URI contained
in the Location header.

A web service procedure specifying a POST HTTP method which receives a 303 See Other status
will issue a redirect request using the GET HTTP method.

The Location header can contain either an absolute path or a relative path. The HTTP client
procedure will handle either. The header can also include query parameters and these will be

580 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

forwarded to the redirected location. For example, if the header contained parameters such as the
following, the subsequent GET or a POST will include these parameters.
Location: alternate_service?a=1&b=2

In the above example, the query parameters are a=1&b=2.

○ ' SOAP(OP[ERATION]=soap-operation-name) (SOAP only) This option allows you to specify


the name of the SOAP operation, if it is different from the name of the procedure you are creating.
The value of OPERATION is analogous to the name of a remote procedure call. For example, if you
wanted to create a procedure called accounts_login that calls a SOAP operation called login, you
would specify something like the following:
CREATE PROCEDURE accounts_login(
name LONG VARCHAR,
pwd LONG VARCHAR )
SET 'SOAP(OPERATION=login)'

If the OPERATION option is not specified, the name of the SOAP operation must match the name of
the procedure you are creating.

The following statement shows how several protocol-option settings are combined in the same SET
clause:
CREATE PROCEDURE accounts_login(
name LONG VARCHAR,
pwd LONG VARCHAR )
SET 'HTTP ( CHUNK=ON; VERSION=1.1 ), SOAP( OPERATION=login )'
...

SOAPHEADER clause (SOAP format only) When declaring a SOAP web service as a procedure, use
this clause to specify one or more SOAP request header entries. A SOAP header can be declared as a
static constant, or can be dynamically set using the parameter substitution mechanism (declaring IN,
OUT, or INOUT parameters for hd1, hd2, and so on). A web service procedure can define one or more IN
mode substitution parameters, and a single INOUT or OUT substitution parameter.

The following example illustrates how a client can specify the sending of several header entries using
parameter substitution and receiving the response SOAP header data:
CREATE PROCEDURE soap_client
(INOUT hd1 LONG VARCHAR, IN hd2 LONG VARCHAR, IN hd3 LONG VARCHAR)
URL 'localhost/some_endpoint'
SOAPHEADER '!hd1!hd2!hd3';

NAMESPACE clause (SOAP format only) This clause identifies the method namespace usually
required for both SOAP:RPC and SOAP:DOC requests. The SOAP server handling the request uses this
namespace to interpret the names of the entities in the SOAP request message body. The namespace can
be obtained from the WSDL (Web Services Description Language) of the SOAP service available from
the web service server. The default value is the procedure's URL, up to but not including the optional path
component.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 581


SQL statements

Remarks
Parameter values are passed as part of the request. The syntax used depends on the type of request. For
HTTP:GET, the parameters are passed as part of the URL; for HTTP:POST requests, the values are
placed in the body of the request. Parameters to SOAP requests are always bundled in the request body.

Permissions
Must have RESOURCE authority.

Must have DBA authority to create a procedure for another user.

Side effects
Automatic commit.

See also
● “ALTER PROCEDURE statement” on page 423
● “CALL statement” on page 491
● “CREATE FUNCTION statement” on page 548
● “CREATE FUNCTION statement [Web service]” on page 541
● “CREATE PROCEDURE statement” on page 585
● “CREATE PROCEDURE statement [T-SQL]” on page 583
● “CREATE PROCEDURE statement [External call]” on page 567
● “DROP PROCEDURE statement” on page 700
● “SOAP structured data types” [SQL Anywhere Server - Programming]
● “HTTP and SOAP request structures” [SQL Anywhere Server - Programming]
● “HTTP request header management” [SQL Anywhere Server - Programming]
● “Tutorial: Using SQL Anywhere to access a SOAP/DISH service” [SQL Anywhere Server -
Programming]
● “Tutorial: Working with MIME types in a RAW service” [SQL Anywhere Server - Programming]
● “Variables supplied to web services” [SQL Anywhere Server - Programming]
● “GRANT statement” on page 760
● “SQL Anywhere as an HTTP web server” [SQL Anywhere Server - Programming]
● “Web client application development” [SQL Anywhere Server - Programming]
● “remote_idle_timeout option” [SQL Anywhere Server - Database Administration]
● “Substitution parameters used for clause values” [SQL Anywhere Server - Programming]
● “Web client application development” [SQL Anywhere Server - Programming]
● “ClientPort (CPORT) protocol option (client side only)” [SQL Anywhere Server - Database
Administration]
● “HTTP request failed. Status code '%1'” [Error Messages]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL Not supported by Adaptive Server Enterprise.

Example
The following example creates a web services client procedure named FtoC.

582 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE PROCEDURE FtoC( IN temperature FLOAT,


INOUT inoutheader LONG VARCHAR,
IN inheader LONG VARCHAR )
URL 'http://localhost:8082/FtoCService'
TYPE 'SOAP:DOC'
SOAPHEADER '!inoutheader!inheader';

CREATE PROCEDURE statement [T-SQL]


Creates 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 SQL
Anywhere.

CREATE [ OR REPLACE ]PROCEDURE [owner.]procedure_name


[ NO RESULT SET ]
[ [ ( ] @parameter-name data-type [ = default ] [ OUTPUT ], ... [ ) ] ]
[ WITH RECOMPILE ] AS statement-list

Parameters
OR REPLACE clause Specifying OR REPLACE creates a new procedure, or replaces an existing
procedure with the same name. This clause changes the definition of the procedure, but preserves existing
permissions. An error is returned if you attempt to replace a procedure that is already in use.

NO RESULT SET clause Declares that no result set is returned by this procedure. This is useful when
an external environment needs to know that a procedure does not return a result set.

WITH RECOMPILE clause This clause is accepted for Transact-SQL compatibility, but is ignored.
SQL 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.

Remarks
The following differences between Transact-SQL and SQL 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 INOUT by default or can
be specified as IN, OUT, or INOUT. Transact-SQL procedure parameters are INPUT parameters by
default. They can be specified as input/output with the addition of the OUTPUT keyword. There are
no output-only parameters in the Transact-SQL dialect.

When you use the Watcom SQL dialect to declare a parameter OUT, it is output-only. The mixing of
dialects is not recommended because it can cause problems when the procedure declaration is
unloaded and used to rebuild the database. If the procedure declaration is unloaded and used to rebuild
the database, the rebuilt procedure declaration is in the Transact-SQL dialect, the OUTPUT keyword
is used, and the parameter is input/output.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 583


SQL statements

● 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 Employees.Surname, Employees.GivenName
FROM Departments, Employees
WHERE Departments.DepartmentName = @deptname
AND Departments.DepartmentID = Employees.DepartmentID;

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 Employees.Surname, Employees.GivenName
FROM Departments, Employees
WHERE Departments.DepartmentName = deptname
AND Departments.DepartmentID = Employees.DepartmentID
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.

Permissions
Must have RESOURCE authority.

Side effects
Automatic commit.

See also
● “CREATE FUNCTION statement” on page 548
● “CREATE PROCEDURE statement” on page 585

Standards and compatibility


● SQL/2008 Transact-SQL extension.

● Transact-SQL SQL Anywhere supports a subset of the Adaptive Server Enterprise CREATE
PROCEDURE statement syntax.

Only Transact-SQL SQL procedures are supported in the SQL Anywhere Transact-SQL dialect. To
create an external procedure you must use Watcom SQL syntax. Adaptive Server Enterprise does not
support the NO RESULT SET clause. If the Transact-SQL WITH RECOMPILE optional clause is

584 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

supplied, it is ignored. SQL 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 Transact-SQL procedures are not supported in SQL Anywhere.

CREATE PROCEDURE statement


Creates a user-defined SQL procedure in the database.

Syntax
CREATE [ OR REPLACE | TEMPORARY ] PROCEDURE [ owner.]procedure-name
( [ parameter, ... ] )
[ RESULT ( result-column, ... ) | NO RESULT SET ]
[ SQL SECURITY { INVOKER | DEFINER } ]
[ ON EXCEPTION RESUME ]
compound-statement | AT location-string | variable-name

parameter :
parameter-mode parameter-name data-type [ DEFAULT expression ]
| SQLCODE
| SQLSTATE

parameter-mode :
IN
| OUT
| INOUT

result-column : column-name data-type

Parameters
You can create permanent stored procedures that call external or native procedures written in a variety of
programming languages. You can use PROC as a synonym for PROCEDURE.

OR REPLACE clause Specifying OR REPLACE creates a new procedure, or replaces an existing


procedure with the same name. This clause changes the definition of the procedure, but preserves existing
permissions. An error is returned if you attempt to replace a procedure that is already in use.

TEMPORARY clause Specifying CREATE TEMPORARY PROCEDURE means that the stored
procedure is visible only by the connection that created it, and that it is automatically dropped when the
connection is dropped. Temporary stored procedures can also be explicitly dropped. You cannot perform
ALTER, GRANT, or REVOKE on them, and, unlike other stored procedures, temporary stored
procedures are not recorded in the catalog or transaction log.

Temporary procedures execute with the permissions of their creator (current user), or specified owner.
You can specify an owner for a temporary procedure when:

○ the temporary procedure is created within a permanent stored procedure

○ the owner of the temporary and permanent procedure is the same

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 585


SQL statements

To drop the owner of a temporary procedure, you must drop the temporary procedure first.

Temporary stored procedures can be created and dropped when connected to a read-only database, and
they cannot be external procedures.

For example, the following temporary procedure drops the table called CustRank, if it exists. For this
example, the procedure assumes that the table name is unique and can be referenced by the procedure
creator without specifying the table owner:
CREATE TEMPORARY PROCEDURE drop_table( IN @TableName char(128) )
BEGIN
IF EXISTS ( SELECT * FROM SYS.SYSTAB WHERE table_name = @TableName )
THEN
EXECUTE IMMEDIATE 'DROP TABLE "' || @TableName || '"';
MESSAGE 'Table "' || @TableName || '" dropped' to client;
END IF;
END;
CALL drop_table( 'CustRank' );

Parameters Parameter names must conform to the rules for other database identifiers such as column
names. They must be a valid SQL data type.

Parameters can be prefixed with one of the keywords IN, OUT, or INOUT. If you do not specify one of
these values, parameters are INOUT by default. 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 OUT parameters that output the SQLSTATE or SQLCODE
value when the procedure ends. The SQLSTATE and SQLCODE special values can 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.

Specifying CREATE OR REPLACE PROCEDURE creates a new procedure, or replaces an existing


procedure with the same name. This clause changes the definition of the procedure, but preserves existing
permissions. You cannot use the OR REPLACE clause with temporary procedures. An error is returned if
the procedure being replaced is already in use. Open cursors for a connection are closed when a CREATE
OR REPLACE PROCEDURE statement is executed.

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

586 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

information is returned by the embedded SQL DESCRIBE or by ODBC SQLDescribeCol when a CALL
statement is being described.

Some procedures can produce 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 GivenName
FROM Employees
ELSE
SELECT Surname, GivenName
FROM Employees
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, to get the proper shape of result set. The CURSOR cursor-
name clause on the DESCRIBE statement is required.

○ ODBC, OLE DB, ADO.NET Variable result-set procedures can be used by applications using these
interfaces. The proper description of the result sets is carried out by the driver or provider.

○ Open Client applications Variable result-set procedures can be used by Open Client applications.

○ Web services Web services rely on the RESULTS clause of the stored procedure to determine the
number and types of the column in the result set. Web services do not support procedures that return
multiple result sets, nor do they support variable result sets through the use of EXECUTE
IMMEDIATE.

Note
If an EXECUTE IMMEDIATE statement that includes a WITH RESULT SET ON clause is used in the
procedure, and if the result set that is returned from the statement is the same as the result set that is
returned from the procedure, then only the first column of the EXECUTE IMMEDIATE statement's result
set is returned.

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.

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.

NO RESULT SET clause Declares that no result set is returned by this procedure. This is useful when
an external environment needs to know that a procedure does not return a result set.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 587


SQL statements

SQL SECURITY clause The SQL SECURITY clause defines whether the procedure is executed as
the INVOKER (the user who is calling the procedure), or as the DEFINER (the user who owns the
procedure). The default is DEFINER.

When SQL SECURITY INVOKER is specified, more memory is used because annotation must be done
for each user that calls the procedure. When SQL SECURITY INVOKER is specified, name resolution is
done as the invoker as well. Therefore, care should be taken to qualify all object names (tables,
procedures, and so on) with their appropriate owner. For example, suppose user1 creates the following
procedure:
CREATE PROCEDURE user1.myProcedure()
RESULT( columnA INT )
SQL SECURITY INVOKER
BEGIN
SELECT columnA FROM table1;
END;

If user2 attempts to run this procedure and a table user2.table1 does not exist, a table lookup error results.
Additionally, if a user2.table1 does exist, that table is used instead of the intended user1.table1. To
prevent this situation, qualify the table reference in the statement (user1.table1, instead of just table1).

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 (the default) the execution continues if the next
statement handles the error; otherwise, it exits.

Error-handling statements include the following:

○ IF
○ 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.

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 file names and
extensions to be used in the database and owner fields.

When the remote procedure is used, variable-name is replaced with the contents of the SQL variable
variable-name that must be of the type CHAR, VARCHAR, or LONG VARCHAR. For more information

588 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

about using variables in the AT clause, see Example 2 in “Creating directory access servers (Sybase
Central)” [SQL Anywhere Server - SQL Usage].

If a remote procedure can return a result set, even if it does not always return one, then the local procedure
definition must contain a RESULT clause.

Remarks
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.

If a stored procedure returns a result set, it cannot set output parameters or return a return value.

When referencing a temporary table from multiple procedures, a potential issue can arise if the temporary
table definitions are inconsistent and statements referencing the table are cached.

Permissions
Must have RESOURCE authority, unless creating a temporary procedure.

Must have DBA authority for external procedures or to create a procedure for another user.

Side effects
Automatic commit, even for temporary procedures.

See also
● “ALTER PROCEDURE statement” on page 423
● “BEGIN statement” on page 484
● “CALL statement” on page 491
● “CREATE FUNCTION statement” on page 548
● “CREATE PROCEDURE statement [External call]” on page 567
● “CREATE PROCEDURE statement [Web service]” on page 575
● “CREATE PROCEDURE statement [T-SQL]” on page 583
● “CREATE SERVER statement” on page 601
● “DROP PROCEDURE statement” on page 700
● “EXECUTE IMMEDIATE statement [SP]” on page 719
● “GRANT statement” on page 760
● “EXECUTE IMMEDIATE used in procedures, triggers, user-defined functions, and batches” [SQL
Anywhere Server - SQL Usage]
● “SQL data types” on page 81
● “on_tsql_error option” [SQL Anywhere Server - Database Administration]
● “Result sets” [SQL Anywhere Server - SQL Usage]
● “References to temporary tables within procedures” [SQL Anywhere Server - SQL Usage]
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]
● “Creating remote procedures (Sybase Central)” [SQL Anywhere Server - SQL Usage]
● “Remote procedure calls (RPCs)” [SQL Anywhere Server - SQL Usage]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 589


SQL statements

Standards and compatibility


● SQL/2008 CREATE PROCEDURE is a core feature of the SQL/2008 standard, but some of its
components supported in SQL Anywhere are optional SQL language features. A subset of these
features includes:

○ The SQL SECURITY clause is optional SQL/2008 language feature T324.

○ The ability to pass a LONG VARCHAR, LONG NVARCHAR, or LONG BINARY value to a SQL
procedure is SQL/2008 language feature T041.

○ The ability to create or modify a schema object within a SQL procedure, using statements such as
CREATE TABLE or DROP TRIGGER, is SQL/2008 language feature T651.

○ The ability to use a dynamic-SQL statement within a SQL procedure, including statements such as
EXECUTE IMMEDIATE, PREPARE, and DESCRIBE, is SQL/2008 language feature T652.

Several clauses of the CREATE PROCEDURE statement are vendor extensions. These include:

○ The TEMPORARY clause.

○ The ON EXCEPTION RESUME clause.

○ The AT clause.

○ The optional DEFAULT clause for a specific routine parameter.

○ The RESULT and NO RESULT SET clauses. The SQL/2008 standard uses the RETURNS
keyword.

○ The optional OR REPLACE clause.

● Transact-SQL CREATE PROCEDURE is supported by Adaptive Server Enterprise.

See also
● “CREATE PROCEDURE statement [T-SQL]” on page 583

Examples
The following procedure queries the Employees table and returns salaries that are within the specified
percent (percentage) of a specified salary (sal):
CREATE OR REPLACE PROCEDURE AverageEmployees( IN percentage NUMERIC( 5,3),
IN sal NUMERIC( 20, 3 ) )
RESULT( Department CHAR(40), GivenName person_name_t, Surname person_name_t,
Salary NUMERIC( 20, 3) )
BEGIN
DECLARE maxS NUMERIC( 20, 3 );
DECLARE minS NUMERIC( 20, 3 );
IF percentage >= 1 THEN
SET percentage = percentage / 100;
ELSEIF percentage < 0 THEN
SELECT 'Percentage error', 'Err','Err', -1;
RETURN;

590 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

END IF;

SELECT MIN( E.Salary ), MAX( E.Salary ) INTO minS, maxS


FROM Employees E;

IF sal < minS OR sal > maxS THEN


SELECT 'Salary out of bounds', 'Err', 'Err', -2;
RETURN;
END IF;

SELECT D.DepartmentName, E.GivenName, E.Surname, E.Salary


FROM Employees E JOIN Departments D ON E.DepartmentID = D.DepartmentID
WHERE E.Salary BETWEEN sal *( 1 - percentage ) AND sal * ( 1 +
percentage );
END;

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 Products
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 example replaces the ProductType procedure created in the previous example. After
replacing the procedure, the parameters for Tee Shirt and Sweatshirt are updated:
CREATE OR REPLACE PROCEDURE ProductType (IN product_ID INT, OUT type
CHAR(10))
BEGIN
DECLARE prod_name CHAR(20);
SELECT name INTO prod_name FROM Products
WHERE ID = product_ID;
CASE prod_name
WHEN 'Tee Shirt' THEN
SET type = 'T Shirt'
WHEN 'Sweatshirt' THEN
SET type = 'Long Sleeve 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;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 591


SQL statements

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 CompanyName,
CAST(SUM(SalesOrderItems.Quantity *
Products.UnitPrice) AS INTEGER) VALUE
FROM Customers
LEFT OUTER JOIN SalesOrders
LEFT OUTER JOIN SalesOrderItems
LEFT OUTER JOIN Products
GROUP BY CompanyName;
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;

CREATE PUBLICATION statement [MobiLink] [SQL


Remote]
Creates a publication. In MobiLink, a publication identifies synchronized data in a SQL Anywhere remote
database. In SQL Remote, publications identify replicated data in both consolidated and remote databases.

Syntax 1 (MobiLink general use)


CREATE PUBLICATION [ IF NOT EXISTS ] [ owner. ] publication-name
( article-definition, ... )

article-definition :
TABLE table-name [ ( column-name, ... ) ]
[ WHERE search-condition ]

Syntax 2 (MobiLink scripted upload)


CREATE PUBLICATION [ IF NOT EXISTS ] [ owner.]
WITH SCRIPTED UPLOAD
( article-definition, ... )

article-definition :
TABLE table-name [ ( column-name, ... ) ]

592 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

[ USING ( [ PROCEDURE ] [ owner.][procedure-name ]


FOR UPLOAD { INSERT | DELETE | UPDATE }, ... ) ]

Syntax 3 (MobiLink download-only publications)


CREATE PUBLICATION [ IF NOT EXISTS ] [ owner.] publication-name
FOR DOWNLOAD ONLY
( article-definition, ... )

article-definition : TABLE table-name [ ( column-name, ... ) ]

Syntax 4 (SQL Remote)


CREATE PUBLICATION [ IF NOT EXISTS ] [ owner.] publication-name
( article-definition, ... )

article-definition :
TABLE table-name [ ( column-name, ... ) ]
[ WHERE search-condition ]
[ SUBSCRIBE BY expression ]

Parameters
IF NOT EXISTS clause When the IF NOT EXISTS clause is specified and the named publication
already exists, no changes are made and an error is not returned.

article-definition Publications are built from articles. Each article identifies the rows and columns of a
single table that are included in the publication. A publication may not contain two articles that refer to
the same table.

If a list of column-names is included in an article, only those columns are included in the publication. If
no column-names are listed, all columns in the table are include in the publication. For MobiLink
synchronization, if column-names are listed then all columns in the primary key of the table must be
included in the list.

In Syntax 2, which is used for publications that perform scripted uploads, the article description also
registers the scripts that are used to define the upload.

In Syntax 3, which is used for download-only publications, the article specifies only the tables and
columns to be downloaded.

WHERE clause The WHERE clause lets you define the subset of rows in a table to be included in an
article.

In MobiLink applications, the WHERE clause affects the rows included in the upload. (The download is
defined by the download_cursor script.) In MobiLink SQL Anywhere remote databases, the WHERE
clause can only refer to columns included in the article, and cannot contain subqueries, variables, or non-
deterministic functions.

SUBSCRIBE BY clause In SQL Remote, one way of defining a subset of rows of a table to be
included in an article is to use a SUBSCRIBE BY clause. This clause allows many different subscribers to
receive different rows from a table in a single publication definition.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 593


SQL statements

Remarks
The CREATE PUBLICATION statement creates a publication in the database. A publication can be
created for another user by specifying an owner name.

In MobiLink, publications are required in SQL Anywhere remote databases, and are optional in UltraLite
databases. These publications and the subscriptions to them determine which data is uploaded to the
MobiLink server.

You set options for a MobiLink publication with the ADD OPTION clause in the CREATE
SYNCHRONIZATION SUBSCRIPTION statement or ALTER SYNCHRONIZATION
SUBSCRIPTION statement.

Syntax 2 creates a publication for scripted uploads. Use the USING clause to register the stored
procedures that you want to use to define the upload. For each table, you can use up to three stored
procedures: one each for inserts, deletes, and updates.

Syntax 3 creates a download-only publication that can be synchronized with no transaction log file. When
download-only publications are synchronized, downloaded rows may overwrite changes that were made
to those rows in the remote database.

In SQL Remote, publishing is a two-way operation, as data can be entered at both consolidated and
remote databases. In a SQL Remote installation, any consolidated database and all remote databases must
have the same publication defined. Running the SQL Remote Extraction utility from a consolidated
database automatically executes the correct CREATE PUBLICATION statement in the remote database.

Permissions
DBA authority and exclusive access to all tables referred to in the statement.

Side effects
Automatic commit.

594 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “ALTER PUBLICATION statement [MobiLink] [SQL Remote]” on page 425
● “DROP PUBLICATION statement [MobiLink] [SQL Remote]” on page 701
● “CREATE SYNCHRONIZATION SUBSCRIPTION statement [MobiLink]” on page 629
● “ALTER SYNCHRONIZATION SUBSCRIPTION statement [MobiLink]” on page 447
● SQL Anywhere MobiLink clients: “Publications” [MobiLink - Client Administration]
● UltraLite MobiLink clients: “CREATE PUBLICATION statement [UltraLite]” [UltraLite - Database
Management and Reference]
● SQL Remote: “Publications and articles” [SQL Remote]
● “Scripted upload” [MobiLink - Client Administration]
● “Download-only publications” [MobiLink - Client Administration]
● “ISYSSYNC system table” on page 976
● “Publications for scripted upload” [MobiLink - Client Administration]
● “Creating publications” [SQL Remote]
● “Publishing only some columns in a table” [SQL Remote]
● “Publishing only some rows using the SUBSCRIBE BY clause” [SQL Remote]
● “Publishing only some rows using a WHERE clause” [SQL Remote]
● “Publish only some rows in a table” [SQL Remote]
● “Replicate the primary key pool” [SQL Remote]
● “Overlap partitions” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement publishes all columns and rows of two tables.
CREATE PUBLICATION pub_contact (
TABLE Contacts,
TABLE Company
);

The following statement publishes only some columns of one table.


CREATE PUBLICATION pub_customer (
TABLE Customers ( ID, CompanyName, City )
);

The following statement publishes only the active customer rows by including a WHERE clause that tests
the Status column of the Customers table.
CREATE PUBLICATION pub_customer (
TABLE Customers ( ID, CompanyName, City, State, Status )
WHERE Status = 'active'
);

The following statement publishes only some rows by providing a subscribe-by value. This method can
be used only with SQL Remote.
CREATE PUBLICATION pub_customer (
TABLE Customers ( ID, CompanyName, City, State )
SUBSCRIBE BY State
);

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 595


SQL statements

The subscribe-by value is used as follows when you create a SQL Remote subscription.
CREATE SUBSCRIPTION TO pub_customer ( 'NY' )
FOR jsmith;

The following example creates a MobiLink publication that uses scripted uploads:
CREATE PUBLICATION pub WITH SCRIPTED UPLOAD (
TABLE t1 (a, b, c) USING (
PROCEDURE my.t1_ui FOR UPLOAD INSERT,
PROCEDURE my.t1_ud FOR UPLOAD DELETE,
PROCEDURE my.t1_uu FOR UPLOAD UPDATE
),
TABLE t2 AS my_t2 USING (
PROCEDURE my.t2_ui FOR UPLOAD INSERT
)
);

The following example creates a download-only publication:


CREATE PUBLICATION p1 FOR DOWNLOAD ONLY (
TABLE t1
);

CREATE REMOTE MESSAGE TYPE statement [SQL


Remote]
Identifies a message link and return address for outgoing messages from a database.

Syntax
CREATE REMOTE MESSAGE TYPE message-system
[ ADDRESS address-string ]

message-system :
FILE
| FTP
| SMTP

Parameters
message-system One of the message systems supported by SQL Remote. It must be one of the
following values: FILE, FTP, or SMTP.

address-string A string containing a valid address for the specified message system.

Remarks
The Message Agent sends outgoing messages from a database using one of the supported message links.
Return messages for users employing the specified link are sent to the specified address as long as the
remote database is created by the Extraction utility. The Message Agent starts links only if it has remote
users for those links.

The address is the publisher's address under the specified message system. If it is an email system, the
address string must be a valid email address. If it is a file-sharing system, the address string is a

596 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

subdirectory of the directory set in the SQLREMOTE environment variable, or of the current directory if
that is not set. You can override this setting on the GRANT CONSOLIDATE statement at the remote
database.

To remove the address, execute a CREATE REMOTE MESSAGE TYPE statement without an
ADDRESS clause.

The dbinit utility creates message types automatically, without an address. Unlike other CREATE
statements, the CREATE REMOTE MESSAGE TYPE statement does not give an error if the type exists;
instead it alters the type.

Permissions
DBA authority.

Side effects
Automatic commit.

See also
● “GRANT PUBLISH statement [SQL Remote]” on page 756
● “GRANT REMOTE statement [SQL Remote]” on page 758
● “GRANT CONSOLIDATE statement [SQL Remote]” on page 754
● “DROP REMOTE MESSAGE TYPE statement [SQL Remote]” on page 701
● “ALTER REMOTE MESSAGE TYPE statement [SQL Remote]” on page 426
● “SQL Remote message systems” [SQL Remote]
● “Creating message types” [SQL Remote]
● “The FILE message system” [SQL Remote]
● “The FTP message system” [SQL Remote]
● “The SMTP message system” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
When remote databases are extracted using the extraction utility, the following statement sets all
recipients of file message-system messages to send messages back to the company subdirectory.

The statement also instructs dbremote to look in the company subdirectory for incoming messages.
CREATE REMOTE MESSAGE TYPE file
ADDRESS 'company';

CREATE SCHEMA statement


Creates a collection of tables, views, and permissions for a database user.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 597


SQL statements

Syntax
CREATE SCHEMA
AUTHORIZATION userid
[ create-table-statement
| create-view-statement
| grant-statement
] ... ;

Remarks
The CREATE SCHEMA statement creates a schema. A schema is a collection of tables and views along
with 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 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 create more than one schema for a user, doing so is not recommended.

Permissions
Must have RESOURCE authority.

Side effects
Automatic commit.

See also
● “CREATE TABLE statement” on page 633
● “CREATE VIEW statement” on page 661
● “GRANT statement” on page 760

Standards and compatibility


● SQL/2008 CREATE SCHEMA is a core feature of the SQL/2008 standard. The ability to create
multiple schemas for a single user is SQL/2008 optional language feature F171. SQL Anywhere does
not support the use of REVOKE statements within the CREATE SCHEMA statement, and does not
allow their use within Transact-SQL batches or procedures.

● Transact-SQL Supported by Adaptive Server Enterprise, which supports GRANT and REVOKE
statements within the CREATE SCHEMA statement.

598 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Example
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. 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 );

CREATE SEQUENCE statement


Creates a sequence that can be used to generate primary key values that are unique across multiple tables,
and for generating default values for a table.

Syntax
CREATE [ OR REPLACE ] SEQUENCE [ owner.] sequence-name
[ INCREMENT BY signed-integer ]
[ START WITH signed-integer ]
[ MINVALUE signed-integer | NO MINVALUE ]
[ MAXVALUE signed-integer | NO MAXVALUE ]
[ CACHE integer | NO CACHE ]
[ CYCLE | NO CYCLE ]

Parameters
OR REPLACE clause Specifying OR REPLACE creates a new sequence, or replaces an existing
sequence with the same name. If you do not use the OR REPLACE clause, an error is returned if you
specify the name of a sequence that already exists for the current user.

INCREMENT BY clause Defines the amount the next sequence value is incremented from the last
value assigned. The default is 1. Specify a negative value to generate a descending sequence. An error is
returned if the INCREMENT BY value is 0.

START WITH clause Defines the starting sequence value. If you do not specify a value for the
START WITH clause, MINVALUE is used for ascending sequences and MAXVALUE is used for
descending sequences. An error is returned if the START WITH value is beyond the range specified by
MINVALUE or MAXVALUE.

MINVALUE clause Defines the smallest value generated by the sequence. The default is 1. An error is
returned if MINVALUE is greater than ( 2^63-1) or less than -(2^63-1). An error is also returned if
MINVALUE is greater than MAXVALUE.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 599


SQL statements

MAXVALUE clause Defines the largest value generated by the sequence. The default is 2^63-1. An
error is returned if MAXVALUE is greater than 2^63-1 or less than -(2^63-1).

CACHE clause Specifies the number of preallocated sequence values that are kept in memory for
faster access. When the cache is exhausted, the sequence cache is repopulated and a corresponding entry
is written to the transaction log. At checkpoint time, the current value of the cache is forwarded to the
ISYSSEQUENCE system table. The default is 100.

CYCLE clause Specifies whether values should continue to be generated after the maximum or
minimum value is reached.

The default is NO CYCLE, which returns an error once the maximum or minimum value is reached.

Remarks
A sequence is a database object that allows the automatic generation of numeric values. A sequence is not
bound to a specific or unique table column and is only accessible through the table column to which it is
applied.

Sequences can generate values in one of the following ways:

● Increment or decrement monotonically without bound


● Increment or decrement monotonically to a user-defined limit and stop
● Increment or decrement monotonically to a user-defined limit and cycle back to the beginning and
start again

You control the behavior when the sequence runs out of values using the CYCLE clause.

If a sequence is increasing and it exceeds the MAXVALUE, MINVALUE is used as the next sequence
value if CYCLE is specified. If a sequence is decreasing and it falls below MINVALUE, MAXVALUE is
used as the next sequence value if CYCLE is specified. If CYCLE is not specified, an error is returned.

Sequence values cannot be used with views or materialized view definitions.

Permissions
Must have RESOURCE authority.

Side effects
None

See also
● “ALTER SEQUENCE statement” on page 427
● “DROP SEQUENCE statement” on page 702
● “sequence-expression clause, SELECT statement” on page 878
● “Use of a sequence to generate unique values” [SQL Anywhere Server - SQL Usage]
● “Choosing between sequences and AUTOINCREMENT values” [SQL Anywhere Server - SQL
Usage]

600 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Standards and compatibility


● SQL/2008 Sequences comprise SQL/2008 language feature T176. SQL Anywhere does not allow
optional specification of the sequence data type—this behavior can be achieved with a CAST when
using the sequence.

In addition, the following are vendor extensions:

○ CACHE clause
○ OR REPLACE syntax
○ CURRVAL expression
○ Use of sequences in DEFAULT expressions

Example
The following example creates a sequence named Test that starts at 4, increments by 2, does not cycle,
and caches 15 values at a time:
CREATE SEQUENCE Test
START WITH 4
INCREMENT BY 2
NO MAXVALUE
NO CYCLE
CACHE 15;

CREATE SERVER statement


Creates a remote server.

Syntax 1
CREATE SERVER server-name
CLASS server-class-string
USING connection-info-string
[ READ ONLY ]

server-class-string :
'SAODBC'
| 'ASEODBC'
| 'DB2ODBC'
| 'IQODBC'
| 'MSSODBC'
| 'ORAODBC'
| 'MSACCESSODBC'
| 'MYSQLODBC'
| 'ULODBC'
| 'ADSODBC'
| 'ODBC'
| 'SAJDBC'
| 'ASEJDBC'
| 'IQJDBC'

connection-info-string :
{ host-name:port-number [/dbname ] | data-source-name | sqlanywhere-connection-string }

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 601


SQL statements

Syntax 2
CREATE SERVER server-name
CLASS 'DIRECTORY'
USING using-string

using-string :
'ROOT = path
[ ;SUBDIRS = n ]
[ ;READONLY = { YES | NO } ]'
[ ;CREATEDIRS = { YES | NO } ]'

Parameters
● CLASS clause Specifies the server class you want to use for a remote connection. Server classes
contain detailed server capability information. The DIRECTORY class is used in Syntax 2 to access a
directory on the local computer.

● USING clause In Syntax 1, the USING clause supplies a connection string for the database server.
The appropriate connection string depends on the driver being used, which in turn depends on the
server-class-string.

If an ODBC-based server class is used, the USING clause is an ODBC connection string that can
include 'dsn=data-source-name' to specify an ODBC data source name and/or
'driver=driver-name' to specify a driver binary on Unix or driver definition on Windows.

For SQL Anywhere remote servers (SAODBC server classes), the connection-info-string parameter
can be any valid SQL Anywhere connection string. You can use any SQL Anywhere connection
parameters. For example, if you have connection problems, you can include a LOG connection
parameter to troubleshoot the connection attempt.

The USING clause can also contain a local or global variable name enclosed in {}. For example, a
USING clause that contains 'dsn={@mydsn}' indicates that @mydsn is a SQL variable and that
the current contents of the @mydsn variable should be substituted when expanding the USING clause.

The SQL variable variable-name that must be of type CHAR, VARCHAR, or LONG VARCHAR.

For more information about using variables in the USING clause, see Example 2 in “Creating
directory access servers (Sybase Central)” [SQL Anywhere Server - SQL Usage].

If a JDBC-based server class is used, the USING clause is of the form host-name:port-number [/
dbname], where:

○ host-name The computer the remote server runs on.

○ port-number The TCP/IP port number the remote server listens on. The default port number
for SQL Anywhere is 2638.

○ dbname For SQL 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 specify another database by some other means (for example, in
the FORWARD TO statement).

602 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

In Syntax 2, the USING clause specifies the following values for the local directory:

● ROOT clause The path, relative to the database server, that is the root of the directory
access class. When you create a proxy table using the directory access server name, the proxy
table is relative to this root path.

● SUBDIRS clause A number between 0 and 10 that represents the number of levels of
directories within the root that the database server can access. If SUBDIRS is omitted or set to
0, then only the files in the root directory are accessible via the directory access server. You
can create proxy tables to any of the directories or subdirectories available via the directory
access server.

● READONLY clause Specifies whether the files accessed by the directory are READONLY
and cannot be modified. By default, this is set to NO.

● CREATEDIRS clause Specifies whether directories can be created using the directory
access server. The default is NO.

Remarks
When you create a remote server, it is added to the ISYSSERVER system table.

● Syntax 1 The CREATE SERVER statement defines a remote server.

The SAJDBC, ASEJDBC, and IQJDBC JDBC-based server classes are deprecated and should not be
used.

To bypass the ODBC driver manager when defining a SQL Anywhere remote server, use the syntax
below, followed by the remainder of the connection-info-string:
CREATE SERVER remote-server CLASS 'SAODBC' USING 'DRIVER=SQL Anywhere
Native;DSN=my-dsn';

This syntax allows remote data access to load the SQL Anywhere ODBC driver directly and is
supported by Windows and Unix. Loading the SQL Anywhere ODBC driver directly ensures that the
ODBC driver for the current server version is used. Also, if the SQL Anywhere ODBC driver is only
used for remote data access, it does not need to be registered.

Note
If the application also makes use of non-SQL Anywhere remote servers, or if there are SQL
Anywhere remote servers defined without using 'DRIVER=SQL Anywhere Native', then
remote data access still uses a driver manager for the other remote servers.

On Unix platforms you can also reference the ODBC driver manager using the supplied iAnywhere
Solutions ODBC driver. The syntax is as follows:
USING 'driver=SQL Anywhere 12;DSN=my-dsn'

● Syntax 2 The CREATE SERVER statement lets you create a directory access server that accesses
the local directory structure on the computer where the database server is running. You must create an
external login for each database user that needs to use the directory access server. On Unix, the

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 603


SQL statements

database server runs as a specific user, so file permissions are based on the permissions granted to the
database server user.

Permissions
DBA authority.

Not supported on Windows Mobile.

Side effects
Automatic commit.

See also
● “ALTER SERVER statement” on page 428
● “DROP SERVER statement” on page 703
● “ISYSSERVER system table” on page 975
● “CREATE EXTERNLOGIN statement” on page 534
● “CREATE EXISTING TABLE statement” on page 532
● “USING parameter in the CREATE SERVER statement” [SQL Anywhere Server - SQL Usage]
● “Connection parameters” [SQL Anywhere Server - Database Administration]
● “Server classes for remote data access” [SQL Anywhere Server - SQL Usage]
● “Directory access servers” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example creates a SQL Anywhere remote server named testsa, using the SQL Anywhere
ODBC driver.

CREATE SERVER testsa


CLASS 'SAODBC'
USING 'DRIVER=SQL Anywhere 12;DSN=remoteSA';

The following example directly loads the SQL Anywhere ODBC driver without using the ODBC driver
manager:

CREATE SERVER testsa


CLASS 'SAODBC'
USING 'DRIVER=SQL Anywhere Native;DSN=remoteSA';

The following example creates an Adaptive Server Enterprise (ASE) remote server named ase_prod using
the ASE ODBC driver.

CREATE SERVER ase_prod


CLASS 'ASEODBC'
USING 'DSN=remoteASE';

The following example creates a remote server for the Oracle server named oracle723. Its ODBC data
source name is oracle723.

604 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE SERVER oracle723


CLASS 'ORAODBC'
USING 'oracle723';

The following example creates a directory access server that only sees files within the directory c:\temp.
CREATE SERVER diskserver0
CLASS 'directory'
USING 'root=c:\temp';
CREATE EXTERNLOGIN DBA TO diskserver0;
CREATE EXISTING TABLE diskdir0 AT 'diskserver0;;;.';

-- Get a list of those files.


SELECT permissions, file_name, size FROM diskdir0;

The following example creates a directory access server that sees nine levels of directories.
-- Create a directory server that sees 9 levels of directories.
CREATE SERVER diskserver9
CLASS 'directory'
USING 'ROOT=c:\temp;SUBDIRS=9';
CREATE EXTERNLOGIN DBA TO diskserver9;
CREATE EXISTING TABLE diskdir9 AT 'diskserver9;;;.';

CREATE SERVICE statement [HTTP web service]


Creates a new HTTP web service.

Syntax
CREATE SERVICE service-name
TYPE { 'RAW' | 'HTML' | 'JSON' | 'XML' }
[ URL [PATH] { ON | OFF | ELEMENTS } ]
[ common-attributes ]
[ AS { statement | NULL } ]

common-attributes :
[ AUTHORIZATION { ON | OFF } ]
[ ENABLE | DISABLE ]
[ METHODS 'method,...' ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]

method :
DEFAULT
| POST
| GET
| HEAD
| PUT
| DELETE
| NONE
|*

Parameters
service-name Web service names can be any sequence of alphanumeric characters or slash (/), hyphen
(-), underscore (_), period (.), exclamation mark (!), tilde (~), asterisk (*), apostrophe ('), left parenthesis

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 605


SQL statements

((), or right parenthesis ()), except that the service name must not begin or end with a slash (/) or contain
two or more consecutive slashes (for example, //).

You can name your service root, but this name has a special function.

TYPE clause Identifies the type of the service where each service defines a specific response format.
The type must be one of the listed service types. There is no default value.

○ 'RAW' The result set is sent to the client without any formatting. Utilization of this service requires
that all content markup is explicitly provided. Complex dynamic content containing current content
with markup, JavaScript and images can be generated on demand. The media type may be specified
by setting the Content-Type response header using the sa_set_http_header procedure. Setting the
Content-Type header to 'text/html' is good practice when generating HTML markup to ensure that all
browsers display the markup as HTML and not text/plain.

○ 'HTML' The result set is returned as an HTML representation of a table or view.

○ 'JSON' The result set is returned in JavaScript Object Notation (JSON). A JSON service does not
automatically process JSON input. It only presents data (in the response) in JSON format. JSON
accepts POST/PUT methods where application/x-www-form-urlencoded is supported. If for a
POST/PUT METHOD, Content-Type: application/json is specified, then the application may use
http_variable('body') to retrieve the JSON (request) content. SQL Anywhere does not parse the JSON
input automatically. It is up to the application to parse it. For more information about JSON, see
http://www.json.org/.

○ 'XML' The result set is returned as XML. If the result set is already XML, no additional formatting
is applied. Otherwise, it is automatically formatted as XML. As an alternative approach, a RAW
service could return a select using the FOR XML RAW clause having set a valid Content-Type such
as text/xml using sa_set_http_header procedure.

URL clause Determines whether URL paths are accepted and, if so, how they are processed.
Specifying URL PATH has the same effect as URL.

○ OFF Indicates that the service name in a URL request must not be followed by a path. OFF is the
default setting. For example, the following form is disallowed due to the path elements /aaa/bbb/
ccc.
http://host-name/service-name/aaa/bbb/ccc

Suppose that CREATE SERVICE echo URL PATH OFF was specified when creating the web
service. A URL similar to http://localhost/echo?id=1 produces the following values:
HTTP_VARIABLE('id') == 1,
HTTP_HEADER('@HTTPQUERYSTRING') == id=1

○ ON Indicates that the service name in a URL request can be followed by a path. The path value is
returned by querying a dedicated HTTP variable named URL. A service can be defined to explicitly
provide the URL parameter or it may be retrieved using the HTTP_VARIABLE function. For
example, the following form is allowed:
http://host-name/service-name/aaa/bbb/ccc

606 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Suppose that CREATE SERVICE echo URL PATH ON was specified when creating the web
service. A URL similar to http://localhost/echo/one/two?id=1 produces the following
values:
HTTP_VARIABLE('id') == 1,
HTTP_VARIABLE('URL') == one/two,
HTTP_HEADER('@HTTPQUERYSTRING') == id=1

○ ELEMENTS Indicates that the service name in a URL request may be followed by a path. The path
is obtained in segments by specifying a single parameter keyword URL1, URL2, and so on. Each
parameter may be retrieved using the HTTP_VARIABLE or NEXT_HTTP_VARIABLE functions.
These iterator functions can be used in applications where a variable number of path elements can be
provided. For example, the following form is allowed:
http://host-name/service-name/aaa/bbb/ccc

Suppose that CREATE SERVICE echo URL PATH ELEMENTS was specified when creating the
web service. A URL similar to http://localhost/echo/one/two?id=1 produces the
following values:
HTTP_VARIABLE('id') == 1,
HTTP_VARIABLE('URL1') == one,
HTTP_VARIABLE('URL2') == two,
HTTP_HEADER('@HTTPQUERYSTRING') == id=1

Up to 10 elements can be obtained. A NULL value is returned if the corresponding element is not
supplied. In the above example, HTTP_VARIABLE('URL3') returns NULL because no
corresponding element was supplied.

For more information about URLs, see “Browsing an HTTP web server” [SQL Anywhere Server -
Programming] and “Accessing client-supplied HTTP variables and headers” [SQL Anywhere Server -
Programming].

AUTHORIZATION clause Determines whether users must specify a user name and password through
basic HTTP authorization when connecting to the service. The default value is ON. If authorization is
OFF, the AS clause is required for all services and a user must be specified with the USER clause. All
requests are run using that user's account and permissions. If AUTHORIZATION is ON, all users must
provide a user name and password. Optionally, you can limit the users that are permitted to use the service
by providing a user or group name with the USER clause. If the user name is NULL, all known users can
access the service. The AUTHORIZATION clause allows your web services to use database authorization
and permissions to control access to the data in your database.

When the authorization value is ON, an HTTP client connecting to a web service uses basic
authentication (RFC 2617) that obfuscates the user and password information using base-64 encoding. It
is recommended that you use the HTTPS protocol for increased security.

ENABLE and DISABLE clauses Determines whether the service is available for use. By default,
when a service is created, it is enabled. When creating or altering a service, you may include an ENABLE
or DISABLE clause. Disabling a service effectively takes the service off line. Later, it can be enabled
using ALTER SERVICE with the ENABLE clause. An HTTP request made to a disabled service
typically returns a 404 Not Found HTTP status.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 607


SQL statements

METHODS clause Specifies the HTTP methods that are supported by the service. Valid values are
DEFAULT, POST, GET, HEAD, PUT, DELETE, and NONE. An asterisk (*) may be used as a short
form to represent the POST, GET, and HEAD methods which are default request types for the RAW,
HTML, and XML service types. Not all HTTP methods are valid for all the service types. The following
table summarizes the valid HTTP methods that can be applied to each service type:

Method value Applies to service Description

DEFAULT all Use DEFAULT to reset the set of default


HTTP methods for the given service type. It
cannot be included in a list with other method
values.

POST RAW, HTML, JSON, Enabled by default.


XML

GET RAW, HTML, JSON, Enabled by default.


XML

HEAD RAW, HTML, JSON, Enabled by default.


XML

PUT RAW, HTML, JSON, Not enabled by default.


XML

DELETE RAW, HTML, JSON, Not enabled by default.


XML

NONE all Use NONE to disable access to a service.

* RAW, HTML, JSON, Same as specifying 'POST,GET,HEAD'.


XML

For example, you can use either of the following clauses to specify that a service supports all HTTP
method types:
METHODS '*,PUT,DELETE'
METHODS 'POST,GET,HEAD,PUT,DELETE'

To reset the list of request types for any service type to its default, you can use the following clause:
METHODS 'DEFAULT'

SECURE clause Specifies whether the service should be accessible on a secure or non-secure listener.
ON indicates that only HTTPS connections are accepted, and that connections received on the HTTP port
are automatically redirected to the HTTPS port. OFF indicates that both HTTP and HTTPS connections
are accepted, provided that the necessary ports are specified when starting the web server. The default
value is OFF.

USER clause Specifies a database user, or group of users, with permissions to execute the web service
request. A USER clause must be specified when the service is configured with AUTHORIZATION OFF

608 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

and should be specified with AUTHORIZATION ON. (the default) An HTTP request made to a service
requiring authorization results in a 401 Authorization Required HTTP response status. Based
on this response, the web browser prompts for a user ID and password.

Caution
It is strongly recommended that you specify a USER clause when authorization is enabled (default).
Otherwise, authorization is granted to all users.

The USER clause controls which database user accounts can be used to process service requests. Database
access permissions are restricted to the privileges assigned to the user of the service.

statement Specifies a command, such as a stored procedure call, to invoke when the service is
accessed.

An HTTP request to a non-DISH service with no statement specifies the SQL expression to execute
within its URL. Although authorization is required, this capability should not be used in production
systems because it makes the server vulnerable to SQL injections. When a statement is defined within the
service, the specified SQL statement is the only statement that can be executed through the service.

In a typical web service application, you use statement to call a function or procedure. You can pass host
variables as parameters to access client-supplied HTTP variables.

The following statement demonstrates a procedure call that passes two host variables to a procedure
named AuthenticateUser. This call presumes that a web client supplies the user_name and
user_password variables:
CALL AuthenticateUser ( :user_name, :user_password );

For more information about passing host variables to a function or procedure, see “Accessing client-
supplied HTTP variables and headers” [SQL Anywhere Server - Programming].

Remarks
Service definitions are stored within the ISYSWEBSERVICE table and can be examined from the
SYSWEBSERVICE view.

Permissions
DBA authority.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 609


SQL statements

See also
● “ALTER SERVICE statement [HTTP web service]” on page 431
● “DROP SERVICE statement” on page 704
● “ISYSWEBSERVICE system table” on page 980
● “SQL Anywhere as an HTTP web server” [SQL Anywhere Server - Programming]
● “Creating and customizing a root web service” [SQL Anywhere Server - Programming]
● “sa_set_http_header system procedure” on page 1134
● “Developing web service applications in an HTTP web server” [SQL Anywhere Server -
Programming]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL CREATE SERVICE is supported by Adaptive Server Enterprise, for XML and
RAW types only.

Examples
The following example demonstrates how to create a JSON service.

Start a database server with the -xs (http or https) option and then execute the following SQL statements
to set up the service:
CREATE PROCEDURE ListEmployees()
RESULT (
EmployeeID integer,
Surname person_name_t,
GivenName person_name_t,
StartDate date,
TerminationDate date )
BEGIN
SELECT EmployeeID, Surname, GivenName, StartDate, TerminationDate
FROM Employees
END;

CREATE SERVICE "jsonEmployeeList"


TYPE 'JSON'
AUTHORIZATION OFF
SECURE OFF
USER DBA
AS CALL ListEmployees();

The JSON service provides data for easy consumption by an AJAX call back.

Execute the following SQL statement to create an HTML service that provides the service in a readable
form:
CREATE SERVICE "EmployeeList"
TYPE 'HTML'
AUTHORIZATION OFF
SECURE OFF
USER DBA
AS CALL ListEmployees();

Use a web browser to access the service using an URL similar to http://localhost/
EmployeeList.

610 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE SERVICE statement [SOAP web service]


Creates a new SOAP over HTTP or DISH service.

Syntax 1: SOAP over HTTP services


CREATE SERVICE service-name
TYPE 'SOAP'
[ DATATYPE { ON | OFF | IN | OUT } ]
[ FORMAT { 'DNET' | 'CONCRETE' [ EXPLICIT { ON | OFF } ] | 'XML' | NULL } ]
[ common-attributes ]
AS statement

common-attributes :
[ AUTHORIZATION { ON | OFF } ]
[ ENABLE | DISABLE ]
[ METHODS 'method,...' ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]

method :
DEFAULT
| POST
| HEAD
| NONE

Syntax 2: DISH services


CREATE SERVICE service-name
TYPE 'DISH'
[ GROUP { group-name | NULL } ]
[ FORMAT { 'DNET' | 'CONCRETE' [ EXPLICIT { ON | OFF } ] | 'XML' | NULL } ]
[ common-attributes ]

common-attributes:
[ AUTHORIZATION { ON | OFF } ]
[ ENABLE | DISABLE ]
[ METHODS 'method,...' ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]

method :
DEFAULT
| POST
| GET
| HEAD
| NONE
|*

Parameters
service-name Web service names can be any sequence of alphanumeric characters or slash (/), hyphen
(-), underscore (_), period (.), exclamation mark (!), tilde (~), asterisk (*), apostrophe ('), left parenthesis
((), or right parenthesis ()), except that the service name must not begin or end with a slash (/) or contain
two or more consecutive slashes (for example, //).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 611


SQL statements

Unlike other services, you cannot use a slash (/) anywhere in a DISH service name.

You can name your service root, but this name has a special function.

TYPE clause Identifies the type of the service where each service defines a specific response format.
The type must be one of the listed service types. There is no default value.

○ 'SOAP' The result set is returned as an XML payload known as a SOAP envelope. The format of
the data may be further refined using by the FORMAT clause. A request to a SOAP service must be a
valid SOAP request, not just a general HTTP request. For more information about the SOAP
standards, see http://www.w3.org/TR/2000/NOTE-SOAP-20000508/.

○ 'DISH' A DISH service (Determine SOAP Handler) is a SOAP endpoint that references any SOAP
service within its GROUP context. It also exposes the interfaces to its SOAP services by generating a
WSDL (Web Services Description Language) for consumption by SOAP client toolkits.

GROUP clause A DISH service without a GROUP clause exposes all SOAP services defined within
the database. By convention, the SOAP service name can be composed of a GROUP and a NAME
element. The name is delimited from the group by the last slash character. For example, a SOAP service
name defined as 'aaa/bbb/ccc' is 'ccc', and the group is 'aaa/bbb'. Delimiting a DISH service using this
convention is invalid. Instead, a GROUP clause is applied to specify the group of SOAP services for
which it is to be the SOAP endpoint.

Note
Slashes are converted to underscores within the WSDL to produce valid XML. Use caution when using a
DISH service that does not specify a GROUP clause such that it exposes all SOAP services that may
contain slashes. Use caution when using groups in conjunction with SOAP service names that contain
underscores to avoid ambiguity.

DATATYPE clause Applies to SOAP services only. When DATATYPE OFF is specified, SOAP
input parameters and response data are defined as XMLSchema string types. In most cases, true data types
are preferred because it negates the need for the SOAP client to cast the data prior to computation.
Parameter data types are exposed in the schema section of the WSDL generated by the DISH service.
Output data types are represented as XML schema type attributes for each column of data.

The following values are permitted for the DATATYPE clause:

○ ON Generates data typing of input parameters and result set responses.

○ OFF All input parameters and response data are typed as XMLSchema string (default).

○ IN Generates true data types for input parameters only. Response data types are XMLSchema
string.

○ OUT Generates true data types for responses only. Input parameters are typed as XMLSchema
string.

For more information about SOAP services, see “Tutorial: Using SQL Anywhere to access a SOAP/DISH
service” [SQL Anywhere Server - Programming].

612 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

For more information about mapping XMLSchema types to SQL data types, see “SOAP data types” [SQL
Anywhere Server - Programming].

FORMAT clause This clause specifies the output format when sending responses to SOAP client
applications.

The SOAP service format is dictated by the associated DISH service format specification when it is not
specified by the SOAP service. The default format is DNET.

SOAP requests should be directed to the DISH service (the SQL Anywhere SOAP endpoint) to leverage
common formatting rules for a group of SOAP services (SOAP operations). A SOAP service FORMAT
specification overrides that of a DISH service. The format specification of the DISH service is used when
a SOAP service does not define a FORMAT clause. If no FORMAT is provided by either service then the
default is 'DNET'.

The following formats are supported:

○ 'DNET' The output is in a System.Data.DataSet compatible format for consumption by .NET client
applications. (default)

○ 'CONCRETE' This output format is used to support client SOAP toolkits that are capable of
generating interfaces representing arrays of row and column objects but are not able to consume the
DNET format. Java and .NET clients can easily consume this output format.

The specific output format is exposed within the WSDL of a DISH service. For CONCRETE OFF or
as a last resort, a CONCRETE format for one or more SOAP services is represented as a
SimpleDataset. Examining the WSDL, a SimpleDataset is composed of an array of rows, which is
composed of an array of any number of columns. This is not an ideal representation because the
specific column names and data types are not specified. It is recommended that SOAP services define
a call to a stored procedure that, in turn, defines a RESULT clause. A DISH service exposing SOAP
services defined in this way can fully describe the result set when generating the WSDL.

By default, EXPLICIT ON is assumed and the WSDL contains a specific Dataset entry for each
SOAP service if the result set for a SOAP service can be described. Each entry name is prefixed by
the SOAP service name and an underscore. For example, a SOAP service named test produces a
test_Dataset object specification containing the XMLSchema definitions for each of its column
elements.

When EXPLICIT ON is specified (default), the WSDL describes an explicit DataSet element when
the following criteria are met:

● The CREATE SERVICE statement calls a stored procedure

● A RESULT clause describing the columns and data types is specified in the stored procedure

When EXPLICIT OFF is specified, the WSDL describes the SimpleDataset element. This
description does not provide the number of columns, column names, or data types.

○ 'XML' The output is generated in an XMLSchema string format. The response is an XML document
that requires further processing by the SOAP client to extract column data. This format is suitable for

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 613


SQL statements

SOAP clients that cannot generate intermediate interface objects that represent arrays of rows and
columns.

○ NULL A NULL type causes the SOAP or DISH service to use the default behavior. The format type
of an existing service is overwritten when using the NULL type in an ALTER SERVICE statement.

AUTHORIZATION clause Determines whether users must specify a user name and password through
basic HTTP authorization when connecting to the service. The default value is ON. If authorization is
OFF, the AS clause is required for SOAP services, and a user must be specified with the USER clause.
All requests are run using that user's account and permissions. If AUTHORIZATION is ON, all users
must provide a user name and password. Optionally, you can limit the users that are permitted to use the
service by providing a user or group name with the USER clause. If the user name is NULL, all known
users can access the service. The AUTHORIZATION clause allows your web services to use database
authorization and permissions to control access to the data in your database.

When the authorization value is ON, an HTTP client connecting to a web service uses basic
authentication (RFC 2617) which obfuscates the user and password information using base-64 encoding.
It is recommended that you use the HTTPS protocol for increased security.

ENABLE and DISABLE clauses Determines whether the service is available for use. By default,
when a service is created, it is enabled. When creating or altering a service, you may include an ENABLE
or DISABLE clause. Disabling a service effectively takes the service off line. Later, it can be enabled
using ALTER SERVICE with the ENABLE clause. An HTTP request made to a disabled service
typically returns a 404 Not Found HTTP status.

METHODS clause Specifies the HTTP methods that are supported by the service. Valid values are
DEFAULT, POST, GET, HEAD, and NONE. An asterisk (*) may be used as a short form to represent the
POST, GET, and HEAD methods. The default method types for SOAP services are POST and HEAD.
The default method types for DISH services are GET, POST, and HEAD. Not all HTTP methods are
valid for all the service types. The following table summarizes the valid HTTP methods that can be
applied to each service type:

Method value Applies to service Description

DEFAULT both Use DEFAULT to reset the set of default


HTTP methods for the given service type.
It cannot be included in a list with other
method values.

POST both Enabled by default for SOAP.

GET DISH only Enabled by default for DISH.

HEAD both Enabled by default for SOAP and DISH.

614 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Method value Applies to service Description

NONE both Use NONE to disable access to a service.


When applied to a SOAP service, the
service cannot be directly accessed by a
SOAP request. This enforce exclusive ac-
cess to a SOAP operation through a DISH
service SOAP endpoint.

It is recommended that you specify


METHOD NONE for each SOAP service.

* DISH only Same as specifying 'POST,GET,HEAD'.

For example, you can use the following clause to specify that a service supports all SOAP over HTTP
method types:

METHODS 'POST,HEAD'

To reset the list of request types for any service type to its default, you can use the following clause:

METHODS 'DEFAULT'

SECURE clause Specifies whether the service should be accessible on a secure or non-secure listener.
ON indicates that only HTTPS connections are accepted, and that connections received on the HTTP port
are automatically redirected to the HTTPS port. OFF indicates that both HTTP and HTTPS connections
are accepted, provided that the necessary ports are specified when starting the web server. The default
value is OFF.

USER clause Specifies a database user, or group of users, with permissions to execute the web service
request. A USER clause must be specified when the service is configured with AUTHORIZATION OFF
and should be specified with AUTHORIZATION ON (the default). An HTTP request made to a service
requiring authorization results in a 401 Authorization Required HTTP response status. Based
on this response, the web browser prompts for a user ID and password.

Caution
It is strongly recommended that you specify a USER clause when authorization is enabled (the default).
Otherwise, authorization is granted to all users.

The USER clause controls which database user accounts can be used to process service requests. Database
access permissions are restricted to the privileges assigned to the user of the service.

statement Specifies a command, such as a stored procedure call, to invoke when the service is
accessed.

A DISH service is the only service that must either define a null statement, or not define a statement. A
SOAP service must define a statement. Any other SERVICE can have a NULL statement, but only if it is
configured with AUTHORIZATION ON.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 615


SQL statements

An HTTP request to a non-DISH service with no statement specifies the SQL expression to execute
within its URL. Although authorization is required, this capability should not be used in production
systems because it makes the server vulnerable to SQL injections. When a statement is defined within the
service, the specified SQL statement is the only statement that can be executed through the service.

In a typical web service application, you use statement to call a function or procedure. You can pass host
variables as parameters to access client-supplied HTTP variables.

The following statement demonstrates a procedure call that passes two host variables to a procedure
named AuthenticateUser. This call presumes that a web client supplies the user_name and
user_password variables:
CALL AuthenticateUser ( :user_name, :user_password );

For more information about passing host variables to a function or procedure, see “Accessing client-
supplied HTTP variables and headers” [SQL Anywhere Server - Programming].

Remarks
Service definitions are stored within the ISYSWEBSERVICE table and can be examined from the
SYSWEBSERVICE view.

Permissions
DBA authority.

Side effects
None.

See also
● “ALTER SERVICE statement [SOAP web service]” on page 436
● “DROP SERVICE statement” on page 704
● “ISYSWEBSERVICE system table” on page 980
● “SQL Anywhere as an HTTP web server” [SQL Anywhere Server - Programming]
● “Creating and customizing a root web service” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL CREATE SERVICE is supported by Adaptive Server Enterprise for SOAP types
only.

CREATE SPATIAL REFERENCE SYSTEM statement


Creates or replaces a spatial reference system.

Syntax
{ CREATE [ OR REPLACE ] SPATIAL REFERENCE SYSTEM
|CREATE SPATIAL REFERENCE SYSTEM IF NOT EXISTS }

616 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

srs-name
[srs-attribute [ srs-attribute ... ]

srs-name : string

srs-attribute :
IDENTIFIED BY srs-id
| DEFINITION { definition-string | NULL }
| ORGANIZATION { organization-name IDENTIFIED BY organization-srs-id | NULL }
| TRANSFORM DEFINITION { transform-definition-string | NULL }
| LINEAR UNIT OF MEASURE linear-unit-name
| ANGULAR UNIT OF MEASURE { angular-unit-name | NULL }
| TYPE { ROUND EARTH | PLANAR }
| COORDINATE coordinate-name { UNBOUNDED | BETWEEN low-number AND high-number }
| ELLIPSOID SEMI MAJOR AXIS semi-major-axis-length { SEMI MINOR AXIS semi-minor-axis-length |
INVERSE FLATTENING inverse-flattening-ratio }
| SNAP TO GRID { grid-size | DEFAULT }
| TOLERANCE { tolerance-distance | DEFAULT }
| POLYGON FORMAT polygon-format
| STORAGE FORMAT storage-format

srs-id : integer

semi-major-axis-length : number

semi-minor-axis-length : number

inverse-flattening-ratio : number

grid-size : DOUBLE : usually between 0 and 1

tolerance-distance : number

axis-order : { 'x/y/z/m' | 'long/lat/z/m' | 'lat/long/z/m' }

polygon-format : { 'CounterClockWise' | 'Clockwise' | 'EvenOdd' }

storage-format : { 'Internal' | 'Original' | 'Mixed' }

Parameters
OR REPLACE clause Specifying OR REPLACE creates the spatial reference system if it does not
already exist in the database, and replaces it if it does exist. An error is returned if you attempt to replace a
spatial reference system while it is in use. An error is also returned if you attempt to replace a spatial
reference system that already exists in the database without specifying the OR REPLACE clause.

CREATE SPATIAL REFERENCE IF NOT EXISTS Specifying CREATE SPATIAL REFERENCE


IF NOT EXISTS checks to see if a spatial reference system by that name already exists. If it does not
exist, the database server creates the spatial reference system. If it does exist, no further action is
performed and no error is returned.

IDENTIFIED BY clause Use this clause to specify the SRID (srs-id) for the spatial reference system. If
the spatial reference system is defined by an organization with an organization-srs-id, then srs-id should
be set to that value.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 617


SQL statements

If the IDENTIFIED BY clause is not specified, then the SRID defaults to the organization-srs-id defined
by either the ORGANIZATION clause or the DEFINITION clause. If neither clause defines an
organization-srs-id that could be used as a default SRID, an error is returned.

When the spatial reference system is based on a well known coordinate system, but has a different
geodesic interpretation, set the srs-id value to be 1000000000 (one billion) plus the well known value. For
example, the SRID for a planar interpretation of the geodetic spatial reference system WGS 84 (ID 4326)
would be 1000004326.

With the exception of SRID 0, spatial reference systems provided by SQL Anywhere that are not based on
well known systems are given a SRID of 2000000000 (two billion) and above. The range of SRID values
from 2000000000 to 2147483647 is reserved by SQL Anywhere and you should not create SRIDs in this
range.

To reduce the possibility of choosing a SRID that is reserved by a defining authority such as OGC or by
other vendors, you should not choose a SRID in the range 0 - 32767 (reserved by EPSG), or in the range 2
147 483 547 - 2147 483 647.

Also, since the SRID is stored as a signed 32-bit integer, the number cannot exceed 231-1 or 2147483647.

DEFINITION clause Use this clause to set, or override, default coordinate system settings. If any
attribute is set in a clause other than the DEFINITION clause, it takes the value specified in the other
clause regardless of what is specified in the DEFINITION clause.

definition-string is a string in the Spatial Reference System Well Known Text syntax as defined by
SQL/MM and OGC. For example, the following query returns the definition for WGS 84.
SELECT ST_SpatialRefSys::ST_FormatWKT( definition )
FROM ST_SPATIAL_REFERENCE_SYSTEMS
WHERE srs_id=4326;

In Interactive SQL, if you double-click the value returned, an easier to read version of the value appears.

When the DEFINITION clause is specified, definition-string is parsed and used to choose default values
for attributes. For example, definition-string may contain an AUTHORITY element that defines the
organization-name and organization-srs-id.

Parameter values in definition-string are overridden by values explicitly set using the SQL statement
clauses. For example, if the ORGANIZATION clause is specified, it overrides the value for
ORGANIZATION in definition-string.

ORGANIZATION clause Use this clause to specify information about the organization that created the
spatial reference system that the new spatial reference system is based on. organization-name is the name
of the organization that created it; organization-srs-id is the numeric identifier the organization uses to
identify the spatial reference system.

TRANSFORM DEFINITION clause Use this clause to specify a description of the transform to use for
the spatial reference system. Currently, only the PROJ.4 transform is supported. For example, the
transform-definition-string for WGS 84 is '+proj=longlat +ellps=WGS84 +datum=WGS84
+no_defs'.

618 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

If you specify an unsupported transform definition, an error is returned.

The transform definition is used by the ST_Transform method when transforming data between spatial
reference systems. Some transforms may still be possible even if there is no transform-definition-string
defined.

LINEAR UNIT OF MEASURE clause Use this clause to specify the linear unit of measure for the
spatial reference system. The value you specify must match a linear unit of measure that is defined in the
ST_UNITS_OF_MEASURE system view.

If this clause is not specified, and is not defined in the DEFINITION clause, the default is METRE.

To add predefined units of measure to the database, use the sa_install_feature system procedure.

To add custom units of measure to the database, use the CREATE SPATIAL UNIT OF MEASURE
statement.

Note
While both METRE and METER are accepted spellings, METRE is preferred as it conforms to the
SQL/MM standard.

ANGULAR UNIT OF MEASURE clause Use this clause to specify the angular unit of measure for the
spatial reference system. The value you specify must match an angular unit of measure defined in the
ST_UNITS_OF_MEASURE system table.

If this clause is not specified, and is not defined in the DEFINITION clause, the default is DEGREE for
geographic spatial reference systems and NULL for non-geographic spatial reference systems.

The angular unit of measure must be non-NULL for geographic spatial reference systems and it must be
NULL for non-geographic spatial reference systems.

To add predefined units of measure to the database, use the sa_install_feature system procedure.

To add custom units of measure to the database, use the CREATE SPATIAL UNIT OF MEASURE
statement.

TYPE clause Use the TYPE clause to control how the SRS interprets lines between points. For
geographic spatial reference systems, the TYPE clause can specify either ROUND EARTH (the default)
or PLANAR. The ROUND EARTH model interprets lines between points as great elliptic arcs. Given
two points on the surface of the Earth, a plane is selected that intersects the two points and the center of
the Earth. This plane intersects the Earth, and the line between the two points is the shortest distance
along this intersection.

For two points that lie directly opposite each other, there is not a single unique plane that intersects the
two points and the center of the Earth. Line segments connecting these anti-podal points are not valid and
give an error in the ROUND EARTH model.

The ROUND EARTH model treats the Earth as a spheroid and selects lines that follow the curvature of
the Earth. In some cases, it may be necessary to use a planar model where a line between two points is
interpreted as a straight line in the equirectangular projection where x=long, y=lat.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 619


SQL statements

In the following example, the blue line shows the line interpretation used in the ROUND EARTH model
and the red line shows the corresponding PLANAR model.

The PLANAR model may be used to match the interpretation used by other products. The PLANAR
model may also be useful because there are some limitations for methods that are not supported in the
ROUND EARTH model (such as ST_Area, ST_ConvexHull) and some are partially supported
(ST_Distance only supported between point geometries). Geometries based on circularstrings are not
supported in ROUND EARTH spatial reference systems.

For non-geographic SRSs, the type must be PLANAR (and that is the default if the TYPE clause is not
specified and either the DEFINITION clause is not specified or it uses a non-geographic definition).

COORDINATE clause Use this clause to specify the bounds on the spatial reference system's
dimensions. coordinate-name is the name of the coordinate system used by the spatial reference system.
For non-geographic coordinate systems, coordinate-name can be x, y, or m. For geographic coordinate
systems, coordinate-name can be LATITUDE, LONGITUDE, z, or m.

Specify UNBOUNDED to place no bounds on the dimensions. Use the BETWEEN clause to set low and
high bounds.

The X and Y coordinates must have associated bounds. For geographic spatial reference systems, the
longitude coordinate is bounded between -180 and 180 degrees and the latitude coordinate is bounded
between -90 and 90 degrees by default the unless COORDINATE clause overrides these settings. For
non-geographic spatial reference systems, the CREATE statement must specify bounds for both X and Y
coordinates.

LATITUDE and LONGITUDE are used for geographic coordinate systems. The bounds for LATITUDE
and LONGITUDE default to the entire Earth, if not specified.

620 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

ELLIPSOID clause Use the ellipsoid clause to specify the values to use for representing the Earth as
an ellipsoid for spatial reference systems of type ROUND EARTH. If the DEFINITION clause is present,
it can specify ellipsoid definition. If the ELLIPSOID clause is specified, it overrides this default ellipsoid.

The Earth is not a perfect sphere because the rotation of the Earth causes a flattening so that the distance
from the center of the Earth to the North or South pole is less than the distance from the center to the
equator. For this reason, the Earth is modeled as an ellipsoid with different values for the semi-major axis
(distance from center to equator) and semi-minor axis (distance from center to the pole). It is most
common to define an ellipsoid using the semi-major axis and the inverse flattening, but it can instead be
specified using the semi-minor axis (for example, this approach must be used when a perfect sphere is
used to approximate the Earth). The semi-major and semi-minor axes are defined in the linear units of the
spatial reference system, and the inverse flattening (1/f) is a ratio:
1/f = (semi-major-axis) / (semi-major-axis - semi-minor-axis)

SQL Anywhere uses the ellipsoid definition when computing distance in geographic spatial reference
systems.

The ellipsoid must be defined for geographic spatial reference systems (either in the DEFINITION clause
or the ELLIPSOID clause), and it must not be specified for non-geographic spatial reference systems.

SNAP TO GRID clause For flat-Earth (planar) spatial reference systems, use the SNAP TO GRID
clause to define the size of the grid SQL Anywhere uses when performing calculations. By default, SQL
Anywhere selects a grid size so that 12 significant digits can be stored at all points in the space bounds for
X and Y. For example, if a spatial reference system bounds X between -180 and 180 and Y between -90
and 90, then a grid size of 0.000000001 (1E-9) is selected.

grid-size must be large enough so that points snapped to the grid can be represented with equal precision
at all points in the bounded space. If grid-size is too small, the server reports an error.

When set to 0, no snapping to grid is performed.

For round-Earth spatial reference systems, SNAP TO GRID must be set to 0.

Specify SNAP TO GRID DEFAULT to set the grid size to the default that the database server would use.

TOLERANCE clause For flat-Earth (planar) spatial reference systems, use the TOLERANCE clause
to specify the precision to use when comparing points. If the distance between two points is less than
tolerance-distance, the two points are considered equal. Setting tolerance-distance allows you to control
the tolerance for imprecision in the input data or limited internal precision. By default, tolerance-distance
is set to be equal to grid-size.

When set to 0, two points must be exactly equal to be considered equal.

For round-Earth spatial reference systems, TOLERANCE must be set to 0.

POLYGON FORMAT clause Internally, SQL Anywhere interprets polygons by looking at the
orientation of the constituent rings. As one travels a ring in the order of the defined points, the inside of
the polygon is on the left side of the ring. The same rules are applied in PLANAR and ROUND EARTH
spatial reference systems.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 621


SQL statements

The interpretation used by SQL Anywhere is a common but not universal interpretation. Some products
use the exact opposite orientation, and some products do not rely on ring orientation to interpret polygons.
The POLYGON FORMAT clause can be used to select a polygon interpretation that matches the input
data, as needed. The following values are supported:

○ 'CounterClockwise' The input follows SQL Anywhere's internal interpretation: the inside of the
polygon is on the left side while following ring orientation.

○ 'Clockwise' The input follows the opposite of SQL Anywhere's approach: the inside of the
polygon is on the right side while following ring orientation.

○ 'EvenOdd' EvenOdd is the default format. With EvenOdd, the orientation of rings is ignored and
the inside of the polygon is instead determined by looking at the nesting of the rings, with the exterior
ring being the largest ring and interior rings being smaller rings inside this ring. A ray is traced from a
point within the rings and radiating outward crossing all rings. If the number the ring being crossed is
an even number, it is an outer ring. If it is odd, it is an inner ring.

STORAGE FORMAT clause When you insert spatial data into the database from an external format
(such as WKT or WKB), the database server normalizes the data to improve the performance and
semantics of spatial operations. The normalized representation may differ from the original representation
(for example, in the orientation of polygon rings or the precision stored in individual coordinates). While
spatial equality is maintained after the normalization, some original input characteristics may not be
reproducible, such as precision and ring orientation. In some cases you may want to store the original
representation, either exclusively, or in addition to the normalized representation.

To control what is stored, specify the STORAGE FORMAT clause followed by one of the following
values:

○ 'Internal' SQL Anywhere stores only the normalized representation. Specify this value when the
original input characteristics do not need to be reproduced. This is the default for planar spatial
reference systems (TYPE PLANAR).

Note
If you are using MobiLink to synchronize your spatial data, you should specify Mixed. MobiLink
tests for equality during synchronization, which requires the data in its original format.

○ 'Original' SQL Anywhere stores only the original representation. The original input characteristics
can be reproduced, but all operations on the stored values must repeat normalization steps, possibly
slowing down operations on the data.

○ 'Mixed' SQL Anywhere stores the internal version and, if it is different from the original version, it
stores the original version as well. By storing both versions, the original representation characteristics
can be reproduced and operations on stored values do not need to repeat normalization steps.
However, storage requirements may increase significantly because potentially two representations are
being stored for each geometry.

Mixed is the default format for round-Earth spatial reference systems (TYPE ROUND EARTH).

622 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
For a geographic spatial reference system, you can specify both a LINEAR and an ANGULAR unit of
measure; otherwise for non-geographic, you specify only a LINEAR unit of measure. The LINEAR unit
of measure is used for computing distance between points and areas. The ANGULAR unit of measure
tells how the angular latitude/longitude are interpreted and is NULL for projected coordinate systems,
non-NULL for geographic coordinate systems.

All derived geometries returned by operations are normalized.

When working with data that is being synchronized with a non-SQL Anywhere database, STORAGE
FORMAT should be set to either 'Original' or 'Mixed' so that the original characteristics of the data can be
preserved.

Permissions
Must have DBA authority or be a member of the SYS_SPATIAL_ADMIN_ROLE group.

Side effects
None

See also
● “sa_install_feature system procedure” on page 1067
● “CREATE SPATIAL UNIT OF MEASURE statement” on page 624
● “ST_UNITS_OF_MEASURE consolidated view” on page 1264
● “ST_SPATIAL_REFERENCE_SYSTEMS consolidated view” on page 1261
● “ALTER SPATIAL REFERENCE SYSTEM statement” on page 442
● “Spatial reference systems (SRS) and Spatial reference identifiers (SRID)” [SQL Anywhere Server -
Spatial Data Support]
● “Using spatial data” [SQL Anywhere Server - Spatial Data Support]
● “sa_install_feature system procedure” on page 1067

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example creates a spatial reference system named mySpatialRS:
CREATE SPATIAL REFERENCE SYSTEM "mySpatialRS"
IDENTIFIED BY 1000026980
LINEAR UNIT OF MEASURE "metre"
TYPE PLANAR
COORDINATE X BETWEEN 171266.736269555 AND 831044.757769222
COORDINATE Y BETWEEN 524881.608973277 AND 691571.125115319
DEFINITION 'PROJCS["NAD83 / Kentucky South",
GEOGCS["NAD83",
DATUM["North_American_Datum_1983",
SPHEROID["GRS 1980",
6378137,298.257222101,AUTHORITY["EPSG","7019"]],
AUTHORITY["EPSG","6269"]],
PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],
UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],
AUTHORITY["EPSG","4269"]],

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 623


SQL statements

UNIT["metre",1,AUTHORITY["EPSG","9001"]],
PROJECTION["Lambert_Conformal_Conic_2SP"],
PARAMETER["standard_parallel_1",37.93333333333333],
PARAMETER["standard_parallel_2",36.73333333333333],
PARAMETER["latitude_of_origin",36.33333333333334],
PARAMETER["central_meridian",-85.75],
PARAMETER["false_easting",500000],
PARAMETER["false_northing",500000],
AUTHORITY["EPSG","26980"],
AXIS["X",EAST],
AXIS["Y",NORTH]]'
TRANSFORM DEFINITION '+proj=lcc +lat_1=37.93333333333333
+lat_2=36.73333333333333
+lat_0=36.33333333333334
+lon_0=-85.75
+x_0=500000
+y_0=500000
+ellps=GRS80
+datum=NAD83
+units=m
+no_defs;

CREATE SPATIAL UNIT OF MEASURE statement


Creates or replaces a spatial unit of measurement.

Syntax
CREATE [ OR REPLACE ] SPATIAL UNIT OF MEASURE identifier
TYPE { LINEAR | ANGULAR }
[ CONVERT USING number ]

Parameters
OR REPLACE clause Including the OR REPLACE creates a new spatial unit of measure, or replaces
an existing spatial unit of measure with the same name. This clause preserves existing permissions. An
error is returned if you attempt to replace a spatial unit that is already in use.

TYPE clause Defines whether the unit of measure is used for angles (ANGULAR) or distances
(LINEAR).

CONVERT USING The conversion factor for the spatial unit relative to the base unit. For linear units,
the base unit is METRE. For angular units, the base unit is RADIAN.

Remarks
The CONVERT USING clause is used to define how to convert a measurement in the defined unit of
measure to the base unit of measure (radians or meters). The measurement is multiplied by the supplied
conversion factor to get a value in the base unit of measure. For example, a measurement of 512
millimeters would be multiplied by a conversion factor of 0.001 to get a measurement of 0.512 metres.

Spatial reference systems always include a linear unit of measure to be used when calculating distances
(ST_Distance or ST_Length), or area. For example, if the linear unit of measure for a spatial reference
system is miles, then the area unit used is square miles. In some cases, spatial methods accept an optional
parameter that specifies the linear unit of measure to use. For example, if the linear unit of measure for a

624 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

spatial reference system is in miles, you could retrieve the distance between two geometries in meters by
using the optional parameter 'metre':
SELECT geom1.ST_Distance( geom2, 'metre' );

For projected coordinate systems, the X and Y coordinates are specified in the linear unit of the spatial
reference system. For geographic coordinate systems, the latitude and longitude are specified in the
angular units of measure associated with the spatial reference system. In many cases, this angular unit of
measure is degrees but any valid angular unit of measure can be used.

You can use the sa_install_feature system procedure to add predefined units of measure to your database.

Permissions
Must have DBA authority or be a member of the SYS_SPATIAL_ADMIN_ROLE.

Side effects
None

See also
● “sa_install_feature system procedure” on page 1067
● “DROP SPATIAL UNIT OF MEASURE statement” on page 705
● “Using spatial data” [SQL Anywhere Server - Spatial Data Support]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example creates a spatial unit of measure named Test.
CREATE SPATIAL UNIT OF MEASURE Test
TYPE LINEAR
CONVERT USING 15;

CREATE STATISTICS statement


Recreates the column statistics used by the optimizer, and stores them in the ISYSCOLSTAT system
table.

Syntax
CREATE STATISTICS object-name [ ( column-list ) ]

object-name :
table-name | materialized-view-name | temp-table-name

Remarks
The CREATE STATISTICS statement recreates the column statistics that SQL Anywhere uses to
optimize database queries, and can be performed on base tables, materialized views, local temporary

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 625


SQL statements

tables, and global temporary tables. You cannot create statistics on proxy tables. Column statistics include
histograms, which reflect the distribution of data in the database for the specified columns. By default,
column statistics are automatically created for tables with five or more rows.

In rare circumstances, when your database queries are very variable, and when data distribution is not
uniform or the data is changing frequently, you can improve performance by executing the CREATE
STATISTICS statement on a table or column.

When executing, the CREATE STATISTICS statement updates existing column statistics regardless of
the size of the table, unless the table is empty, in which case nothing is done. If column statistics exist for
an empty table, they remain unchanged by the CREATE STATISTICS statement. To remove column
statistics for an empty table, execute the DROP STATISTICS statement.

The process of executing CREATE STATISTICS performs a complete scan of the table. For this reason,
careful consideration should be made before executing a CREATE STATISTICS statement.

If you drop statistics, it is recommended that you recreate them using the CREATE STATISTICS
statement. Without statistics, the optimizer can generate inefficient data access plans, causing poor
database performance.

Permissions
DBA authority.

Side effects
Execution plans may change.

See also
● “Optimizer estimates and statistics” [SQL Anywhere Server - SQL Usage]
● “DROP STATISTICS statement” on page 706
● “LOAD TABLE statement” on page 792
● “ISYSCOLSTAT system table” on page 967
● “Histogram utility (dbhist)” [SQL Anywhere Server - Database Administration]
● “sa_get_histogram system procedure” on page 1051

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement updates the column statistics for the ProductID column of the SalesOrderItems
table:
CREATE STATISTICS SalesOrderItems ( ProductID );

CREATE SUBSCRIPTION statement [SQL Remote]


Creates a subscription for a user to a publication.

626 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
CREATE SUBSCRIPTION
TO publication-name [ ( subscription-value ) ]
FOR subscriber-id

publication-name : identifier

subscription-value : string

subscriber-id : string

Parameters
publication-name The name of the publication to which the user is being subscribed. This can include
the owner of the publication.

subscription-value A string that is compared to the subscription expression of the publication. The
subscriber receives all rows for which the subscription expression matches the subscription value.

subscriber-id The user ID of the subscriber to the publication. At the consolidated database, when you
create a subscription to a remote user, the remote user must have been granted REMOTE permission. At
the remote database, when you create a subscription to the consolidated user, that user must have been
granted CONSOLIDATED permission.

Remarks
In SQL Remote, publications and subscriptions are two-way relationships. If you create a subscription for
a remote user to a publication on a consolidated database, you should also create a subscription for the
consolidated user to a publication on the remote database. By default, the Extraction utility (dbxtract) and
the Extract Database Wizard grant the appropriate PUBLISH and CONSOLIDATE permissions to
users in the remote databases.

If subscription-value is supplied, it is matched against each SUBSCRIBE BY expression in the


publication. The subscriber receives all rows for which the value of the expression is equal to the supplied
string.

Permissions
DBA authority

Side effects
Automatic commit.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 627


SQL statements

See also
● “DROP SUBSCRIPTION statement [SQL Remote]” on page 707
● “GRANT REMOTE statement [SQL Remote]” on page 758
● “GRANT CONSOLIDATE statement [SQL Remote]” on page 754
● “SYNCHRONIZE SUBSCRIPTION statement [SQL Remote]” on page 930
● “START SUBSCRIPTION statement [SQL Remote]” on page 914
● “GRANT PUBLISH statement [SQL Remote]” on page 756
● “ISYSSUBSCRIPTION system table” on page 976
● “Subscriptions” [SQL Remote]
● “Replicate the primary key pool” [SQL Remote]
● “Publish only some rows in a table” [SQL Remote]
● “Publishing only some rows using the SUBSCRIBE BY clause” [SQL Remote]
● “Publishing only some rows using a WHERE clause” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement creates a subscription for the user p_chin to the publication pub_sales. The
subscriber receives all rows for which the subscription expression has a value of Eastern.
CREATE SUBSCRIPTION
TO pub_sales ( 'Eastern' )
FOR p_chin;

CREATE SYNCHRONIZATION PROFILE statement


[MobiLink]
Creates a SQL Anywhere synchronization profile.

Syntax
CREATE [ OR REPLACE ] SYNCHRONIZATION PROFILE name string

Parameters
OR REPLACE clause Specifying CREATE OR REPLACE SYNCHRONIZATION PROFILE
replaces the definition of the named synchronization profile if it already exists.

name Specifies the name of the synchronization profile to create. Each profile must have a unique
name.

string Specify a valid option string as described below. Option strings are specified as semicolon
delimited lists of elements of the form option-name=option-value. For example
subscription=s1;verbosity=high.

628 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
Synchronization profiles are named collections of synchronization options that can be used to control
synchronization. For a list of the synchronization profile options supported by dbmlsync, see “MobiLink
synchronization profiles” [MobiLink - Client Administration].

For options that take a Boolean value, setting the value to TRUE is equivalent to specifying the
corresponding option on the command line.

The following values can be used to specify TRUE: TRUE, ON, 1, YES.

The following values can be used to specify FALSE: FALSE, OFF, 0, NO.

When setting extended options, use the following syntax:


CREATE SYNCHRONIZATION PROFILE myprofile
's=mysub;e={ctp=tcpip;adr=''host=localhost;port=2439''}'

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “ALTER SYNCHRONIZATION PROFILE statement [MobiLink]” on page 446
● “DROP SYNCHRONIZATION PROFILE statement [MobiLink]” on page 709
● “SYNCHRONIZE statement [MobiLink]” on page 925

Standards and compatibility


● SQL/2008 Vendor extension.

CREATE SYNCHRONIZATION SUBSCRIPTION statement


[MobiLink]
Creates a subscription in a SQL Anywhere remote database between a MobiLink user and a publication.

Syntax
CREATE SYNCHRONIZATION SUBSCRIPTION[ subscription-name ]
TO publication-name
[ FOR ml-username, ... ]
[ TYPE network-protocol ]
[ ADDRESS protocol-options ]
[ OPTION option=value, ... ]
[ SCRIPT VERSION script-version ]

subscription-name : identifier

ml-username : identifier

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 629


SQL statements

network-protocol : http | https | tls | tcpip

protocol-options : string

value : string | integer

script-version : string

Parameters
subscription-name A unique name that you can use to identify this subscription. It is strongly
recommended that you name all your subscriptions.

TO clause This clause specifies the name of a publication.

FOR clause This clause specifies one or more MobiLink user names. If you specify more than one
user name, a separate subscription is created for each user. If you specify a subscription name, only one
MobiLink user name can be specified.

ml-username is a user who is authorized to synchronize with the MobiLink server.

Omit the FOR clause to set the protocol type, protocol options, and extended options for a publication. If
the FOR clause is omitted, you cannot specify a subscription name or use the SCRIPT VERSION clause.

TYPE clause This clause specifies the network protocol to use for synchronization. The default
protocol is tcpip.

ADDRESS clause This clause specifies network protocol options such as the location of the
MobiLink server. Multiple options must be separated with semicolons.

OPTION clause This clause allows you to set extended options for the subscription. If no FOR clause
is provided, the extended options act as default settings for the publication.

SCRIPT VERSION clause This clause specifies the script version to use during synchronization.
Typically, you must specify a new script version for each schema change you implement.

You cannot use the SCRIPT VERSION clause if the FOR clause is omitted.

Remarks
If no subscription-name is specified, a unique name is generated. The generated subscription name is the
same as the publication name, provided it is unique. Otherwise, a unique name is formed by adding a
number to the end of the publication name, for example, pub001, pub002, and so on.

The network-protocol, protocol-options, and option values can be set in several places.

This statement causes options and other information to be stored in the SQL Anywhere ISYSSYNC
system table. Anyone with DBA authority for the database can view the information, which could include
passwords and encryption certificates. To avoid this potential security issue, you can specify the
information on the dbmlsync command line.

Permissions
DBA authority and exclusive access to all tables referenced in the publication.

630 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
Automatic commit.

See also
● “ALTER SYNCHRONIZATION SUBSCRIPTION statement [MobiLink]” on page 447
● “DROP SYNCHRONIZATION SUBSCRIPTION statement [MobiLink]” on page 709
● SQL Anywhere MobiLink clients: “Synchronization subscription creation” [MobiLink - Client
Administration]
● UltraLite MobiLink clients: “UltraLite client synchronization design” [UltraLite - Database
Management and Reference]
● “MobiLink users” [MobiLink - Client Administration]
● “MobiLink client network protocol options” [MobiLink - Client Administration]
● “MobiLink SQL Anywhere client extended options” [MobiLink - Client Administration]
● “CommunicationType (ctp) extended option” [MobiLink - Client Administration]
● “ISYSSYNC system table” on page 976
● “Priority order” [MobiLink - Client Administration]
● “Script versions” [MobiLink - Server Administration]
● “dbmlsync syntax” [MobiLink - Client Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example creates a subscription named sales between the MobiLink user ml_user1 and the
publication called sales_publication. When the subscription is synchronized, the script version sales_v1 is
used and tables are locked in exclusive mode:
CREATE SYNCHRONIZATION SUBSCRIPTION sales
TO sales_publication
FOR ml_user1
OPTION locktables='exclusive'
SCRIPT VERSION 'sales_v1'

The following example omits the FOR clause and stores settings for the publication called
sales_publication:
CREATE SYNCHRONIZATION SUBSCRIPTION
TO sales_publication
ADDRESS 'host=test.internal;port=2439;
security=ecc_tls'
OPTION locktables='exclusive';

CREATE SYNCHRONIZATION USER statement [MobiLink]


Creates a MobiLink user in a SQL Anywhere remote database.

Syntax
CREATE SYNCHRONIZATION USER ml-username
[ TYPE network-protocol ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 631


SQL statements

[ ADDRESS protocol-options ]
[ OPTION option=value, ... ]

ml-username : identifier

network-protocol :
tcpip
| http
| https
| tls

protocol-options : string

value : string | integer

Parameters
ml_username A name identifying a MobiLink user.

TYPE clause This clause specifies the network protocol to use for synchronization. The default
protocol is tcpip.

ADDRESS clause This clause specifies protocol-options in the form keyword=value, separated by
semicolons. Which settings you supply depends on the communication protocol you are using (TCP/IP,
TLS, HTTP, or HTTPS).

OPTION clause The OPTION clause allows you to set extended options using option=value in a
comma-separated list.

The values for each option cannot contain equal signs or semicolons. The database server accepts any
option that you enter without checking for its validity. Therefore, if you misspell an option or enter an
invalid value, no error message appears until you run the dbmlsync command to perform synchronization.

Options set for a synchronization user can be overridden in individual subscriptions or on the dbmlsync
command line.

The network-protocol, protocol-options, and options can be set in several places.

This statement causes options and other information to be stored in the SQL Anywhere ISYSSYNC
system table. Anyone with DBA authority for the database can view the information, which could include
passwords and encryption certificates. To avoid this potential security issue, you can specify the
information on the dbmlsync command line.

Permissions
DBA authority.

Side effects
Automatic commit.

632 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “ALTER SYNCHRONIZATION USER statement [MobiLink]” on page 449
● “DROP SYNCHRONIZATION USER statement [MobiLink]” on page 710
● “CommunicationType (ctp) extended option” [MobiLink - Client Administration]
● “MobiLink client/server communications encryption” [SQL Anywhere Server - Database
Administration]
● “ISYSSYNC system table” on page 976
● “dbmlsync syntax” [MobiLink - Client Administration]
● “MobiLink users” [MobiLink - Client Administration]
● “MobiLink client network protocol options” [MobiLink - Client Administration]
● “MobiLink SQL Anywhere client extended options” [MobiLink - Client Administration]
● “Priority order” [MobiLink - Client Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example creates a MobiLink user named SSinger, who synchronizes over TCP/IP with a
server computer named mlserver.mycompany.com using the password Sam. The use of a password in the
user definition is not secure.

CREATE SYNCHRONIZATION USER SSinger


TYPE http
ADDRESS 'host=mlserver.mycompany.com'
OPTION MobiLinkPwd='Sam';

CREATE TABLE statement


Creates a new table in the database and, optionally, to create a table on a remote server.

Syntax
CREATE [ GLOBAL TEMPORARY ] TABLE [ IF NOT EXISTS ] [ owner.]table-name
( { column-definition | table-constraint | pctfree }, ... )
[ { IN | ON } dbspace-name ]
[ ENCRYPTED ]
[ ON COMMIT { DELETE | PRESERVE } ROWS
| NOT TRANSACTIONAL ]
[ AT location-string ]
[ SHARE BY ALL ]

column-definition :
column-name data-type
[ COMPRESSED ]
[ INLINE { inline-length | USE DEFAULT } ]
[ PREFIX { prefix-length | USE DEFAULT } ]
[ [ NO ] INDEX ]
[ [ NOT ] NULL ]
[ DEFAULT default-value | IDENTITY ]
[ column-constraint ... ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 633


SQL statements

default-value :
special-value
| string
| global-variable
| [ - ] number
| ( constant-expression )
| ( sequence-expression )
| built-in-function( constant-expression )
| AUTOINCREMENT
| GLOBAL AUTOINCREMENT [ ( partition-size ) ]

special-value :
CURRENT DATABASE
| CURRENT DATE
| CURRENT TIME
| [ CURRENT ] TIMESTAMP
| CURRENT PUBLISHER
| CURRENT REMOTE USER
| [ CURRENT ] USER
| [ CURRENT ] UTC TIMESTAMP
| LAST USER
| NULL

column-constraint :
[ CONSTRAINT constraint-name ] {
UNIQUE [ CLUSTERED ]
| PRIMARY KEY [ CLUSTERED ] [ ASC | DESC ]
| REFERENCES table-name [ ( column-name ) ]
[ MATCH [ UNIQUE ] { SIMPLE | FULL } ]
[ action-list ] [ CLUSTERED ]
| CHECK ( condition )
}
| COMPUTE ( expression )

table-constraint :
[ CONSTRAINT constraint-name ] {
UNIQUE [ CLUSTERED ] ( column-name [ ASC | DESC ], ... )
| PRIMARY KEY [ CLUSTERED ] ( column-name [ ASC | DESC ], ... )
| CHECK ( condition )
| foreign-key-constraint
}

foreign-key-constraint :
[ NOT NULL ] FOREIGN KEY [ role-name ]
[ ( column-name [ ASC | DESC ], ... ) ]
REFERENCES table-name
[ ( column-name, ... ) ]
[ MATCH [ UNIQUE] { SIMPLE | FULL } ]
[ action-list ] [ CHECK ON COMMIT ] [ CLUSTERED ] [ FOR OLAP WORKLOAD ]

action-list :
[ ON UPDATE action ]
[ ON DELETE action ]

action :
CASCADE
| SET NULL

634 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

| SET DEFAULT
| RESTRICT

location-string :
remote-server-name.[db-name].[owner].object-name
| remote-server-name;[db-name];[owner];object-name

pctfree : PCTFREE percent-free-space

percent-free-space : integer

Parameters
IN clause Use this clause to specify the dbspace in which the base table is located. If this clause is not
specified, then the base table is created in the dbspace specified by the default_dbspace option.

Temporary tables can only be created in the temporary dbspace. If you are creating a GLOBAL
TEMPORARY table, and specify IN, the table is created in the temporary dbspace. If you specify a user-
defined dbspace, an error is returned.

ENCRYPTED clause The encrypted clause specifies that the table should be encrypted. You must
enable table encryption when you create a database if you want to encrypt tables. The table is encrypted
using the encryption key and algorithm specified at database creation time.

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. If the SHARE BY ALL clause is specified, either ON
COMMIT PRESERVE ROWS or NOT TRANSACTIONAL must be specified.

NOT TRANSACTIONAL clause The NOT TRANSACTIONAL clause is allowed when creating a
global temporary table. A table created using NOT TRANSACTIONAL is not affected by either
COMMIT or ROLLBACK. If the SHARE BY ALL clause is specified, either ON COMMIT PRESERVE
ROWS or NOT TRANSACTIONAL must be specified.

AT clause Create a remote table on a different server specified by location-string, and 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 syntax allows
file names and extensions to be used in the database and owner fields.

For example, the following statement maps the table a1 to the Microsoft Access file mydbfile.mdb:
CREATE TABLE a1
AT 'access;d:\mydbfile.mdb;;a1';

Windows Mobile does not support the AT clause.

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 database server
supports primary keys.

SHARE BY ALL clause Use this clause only when creating global temporary tables to allow the table
to be shared by all connections to the database. If the SHARE BY ALL clause is specified, either ON
COMMIT PRESERVE ROWS or NOT TRANSACTIONAL must be specified.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 635


SQL statements

IF NOT EXISTS clause No changes are made if the named table already exists, and an error is not
returned.

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.

○ data-type The type of data stored in the column.

○ COMPRESSED clause Compress the column. For example, the following statement creates a
table, t, with two columns: filename and contents. The contents column is LONG BINARY and is
compressed:
CREATE TABLE t (
filename VARCHAR(255),
contents LONG BINARY COMPRESSED
);

INLINE and PREFIX clauses The INLINE clause specifies the maximum BLOB size, in bytes, to
store within the row. BLOBs smaller than or equal to the value specified by the INLINE clause are stored
within the row. BLOBs that exceed the value specified by the INLINE clause are stored outside the row in
table extension pages. Also, a copy of some bytes from the beginning of the BLOB may be kept in the
row when a BLOB is larger than the INLINE value. Use the PREFIX clause to specify how many bytes
are kept in the row. The PREFIX clause can improve the performance of requests that need the prefix
bytes of a BLOB to determine if a row is accepted or rejected.

The prefix data for a compressed column is stored uncompressed, so if all the data required to satisfy a
request is stored in the prefix, no decompression is necessary.

If neither INLINE nor PREFIX is specified, or if USE DEFAULT is specified, default values are applied
as follows:

○ For character data type columns, such as CHAR, NCHAR, and LONG VARCHAR, the default value
of INLINE is 256, and the default value of PREFIX is 8.

○ For binary data type columns, such as BINARY, LONG BINARY, VARBINARY, BIT, VARBIT,
LONG VARBIT, BIT VARYING, and UUID, the default value of INLINE is 256, and the default
value of PREFIX is 0.

Note
It is strongly recommended that you use the default values unless there are specific circumstances that
require a different setting. The default values have been chosen to balance performance and disk space
requirements. For example, if you set INLINE to a large value, and all the BLOBs are stored inline,
row processing performance may degrade. If you set PREFIX too high, you increase the amount of disk
space required to store BLOBs since the prefix data is a duplicate of a portion of the BLOB.

If only one of the values is specified, the other value is automatically set to the largest amount that does
not conflict with the specified value. Neither the INLINE nor PREFIX value can exceed the database
page size. Also, there is a small amount of overhead reserved in a table page that cannot be used to

636 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

store row data. Therefore, specifying an INLINE value approximate to the database page size can result
in a slightly smaller number of bytes being stored inline.

INDEX and NO INDEX clauses When storing BLOBs (character or binary types only), specify
INDEX to create BLOB indexes on inserted values that exceed the internal BLOB size threshold
(approximately eight database pages). This is the default behavior.

BLOB indexes can improve performance when random access searches within the BLOBs are required.
However, for some types of BLOB values, such as images and multimedia files that will never require
random-access, performance can improve if BLOB indexing is turned off. To turn off BLOB indexing for
a column, specify NO INDEX.

Note
A BLOB index is not the same as a table index. A table index is created to index values in one or more
columns.

NULL and NOT NULL clauses If NULL is specified, NULL values are allowed in the column. This
is the default behavior. This setting is controlled by the allow_nulls_by_default database option.

By default, columns declared as BIT are not nullable, but they can be explicitly made nullable.

If NOT NULL is specified, NULL values are not allowed.

If the column is part of a UNIQUE or PRIMARY KEY constraint, the column cannot contain NULL,
even if NULL is specified.

DEFAULT clause 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 value is specified, it is
equivalent to DEFAULT NULL.

Following is a list of possible values for DEFAULT:

○ special-value You use one of several specials values in the DEFAULT clause.

○ [ CURRENT ] 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 of day 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.

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.

You can automatically truncate TIMESTAMP values in SQL Anywhere based on the
default_timestamp_increment option. This is useful for maintaining compatibility with other database
software that records less precise timestamp values.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 637


SQL statements

The global variable @@dbts returns a TIMESTAMP value representing the last value generated for a
column using DEFAULT TIMESTAMP.

○ [ CURRENT ] UTC TIMESTAMP Provides a way of indicating when each row in the table was last
modified. When a column is declared with DEFAULT UTC TIMESTAMP, a default value is
provided for inserts, and the value is updated with the current Coordinated Universal Time (UTC)
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 UTC TIMESTAMP instead of DEFAULT UTC TIMESTAMP.

The behavior of this default is the same as TIMESTAMP and CURRENT TIMESTAMP except that
the date and time of day is in Coordinated Universal Time (UTC).

○ string See “Strings” on page 5.

○ global-variable See “Global variables” on page 75.

○ constant-expression 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.

○ sequence-expression You can set DEFAULT to the current value or next value from a sequence
in the database.

○ AUTOINCREMENT When using AUTOINCREMENT, the column must be one of the integer data
types, or an exact numeric type.

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 that is larger than the current maximum value for the column, that value is inserted and then
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 column
value less than the maximum, subsequent rows without explicit assignment are still automatically
incremented with a value of one greater than the previous maximum.

You can find the most recently inserted value of the column by inspecting the @@identity global
variable.

AUTOINCREMENT values are maintained as signed 64-bit integers, corresponding to the data type
of the max_identity column in the SYSTABCOL system view. When the next value to be generated
exceeds the maximum value that can be stored in the column to which the AUTOINCREMENT is
assigned, NULL is returned. If the column has been declared to not allow NULLs, as is true for
primary key columns, a SQL error is generated.

The next value to use for a column can be reset using the sa_reset_identity procedure.

○ GLOBAL AUTOINCREMENT This default is intended for use when multiple databases are used in
a MobiLink synchronization environment or SQL Remote replication.

638 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

This option is similar to AUTOINCREMENT, except that the domain is partitioned. Each partition
contains the same number of values. You assign each copy of the database a unique global database
identification number. SQL Anywhere supplies default values in a database only from the partition
uniquely identified by that database's number.

The partition size can be specified in parentheses immediately following the AUTOINCREMENT
keyword. The partition size can 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 232 =
4294967296; for columns of all other types, the default partition size is 216 = 65536. Since these
defaults may be inappropriate, especially if your column is not of type INT or BIGINT, it is best to
specify the partition size explicitly.

When using this default, the value of the public option global_database_id in each database must be
set to a unique, non-negative integer. This value uniquely identifies the database and indicates from
which partition default values are to be assigned. The range of allowed values is np + 1 to p(n + 1),
where n is the value of the public option global_database_id and p is the partition size. For example, if
you define the partition size to be 1000 and set global_database_id to 3, then the range is from 3001 to
4000.

If the previous value is less than p(n + 1), the next default value is one greater than the previous
largest value in the column. If the column contains no values, the first default value is np + 1. Default
column values are not affected by values in the column outside the current partition; that is, by
numbers less than np + 1 or greater than p(n + 1). Such values may be present if they have been
replicated from another database via MobiLink or SQL Remote.

You can find the most recently inserted value of the column by inspecting the @@identity global
variable.

GLOBAL AUTOINCREMENT values are maintained as signed 64-bit integers, corresponding to the
data type of the max_identity column in the SYSTABCOL system view. When the supply of values
within the partition has been exhausted, NULL is returned. If the column has been declared to not
allow NULLs, as is true for primary key columns, a SQL error is generated. 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. To detect that the supply of unused values is low and handle this condition, create an
event of type GlobalAutoincrement.

Because the public option global_database_id cannot be set to a negative value, the values chosen are
always positive. The maximum identification number is restricted only by the column data type and
the partition size.

If the public option global_database_id is set to the default value of 2147483647, a NULL value is
inserted into the column. If NULL values are not permitted, attempting to insert the row causes an
error.

The next value to use for a column can be reset using the sa_reset_identity procedure.

○ LAST USER LAST USER is the user ID of the user who last modified the row.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 639


SQL statements

LAST USER can be used as a default value in columns with character data types.

On INSERT, this default has the same effect as CURRENT USER.

On UPDATE, if a column with a default of LAST USER is not explicitly modified, it is changed to
the name of the current user.

When used in conjunction with DEFAULT TIMESTAMP or DEFAULT UTC TIMESTAMP, a


default of LAST USER can be used to record (in separate columns) both the user and the date and
time a row was last changed.

IDENTITY clause IDENTITY is a Transact-SQL-compatible alternative to using DEFAULT


AUTOINCREMENT. In SQL Anywhere, a column defined with IDENTITY is implemented as
DEFAULT AUTOINCREMENT.

column-constraint and table-constraint clauses 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. There are two classes of constraints that can be created: check constraint, and
referential integrity (RI) constraints. Check constraints are used to specify conditions that must be
satisfied by values of columns being put into the database. RI constraints establish a relationship between
data in different tables that must be maintained in addition to specifying uniqueness requirements for data.

There are three types of RI constraints: primary key, foreign key, and unique constraint. When you create
an RI constraint (primary key, foreign key or unique constraint), the database server enforces the
constraint by implicitly creating an index on the columns that make up the key of the constraint. The
index is created on the key for the constraint as specified. A key consists of an ordered list of columns and
a sequencing of values (ASC/DESC) for each column.

Constraints can be specified on columns or tables. A column constraint refers to one column in a table,
while a table constraint can refer to one or more columns in a table.

○ PRIMARY KEY clause A primary key uniquely defines each row in the table. Primary keys
comprise one or more columns. A table cannot have more than one primary key. In a column-
constraint clause, specifying PRIMARY KEY indicates that the column is the primary key for the
table. In a table-constraint, you use the PRIMARY KEY clause to specify one or more columns that,
when combined in the specified order, make up the primary key for the table.

The ordering of columns in a primary key need not match the respective ordinal numbers of the
columns. That is, the columns in a primary key need not have the same physical order in the row.
Additionally, you cannot specify duplicate column names.

When you create a primary key, an index for the key is automatically created. You can specify the
sequencing of values in the index by specifying ASC (ascending) or DESC (descending) for each
column. You can also specify whether to cluster the index, using the CLUSTERED keyword.

Columns included in primary keys cannot allow NULL. Each row in the table has a unique primary
key value.

640 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

It is recommended that you do not use approximate data types such as FLOAT and DOUBLE for
primary keys. Approximate numeric data types are subject to rounding errors after arithmetic
operations.

Spatial columns cannot be included in a primary key.

○ FOREIGN KEY clause A foreign key restricts the values for a set of columns to match the values
in a primary key or 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 Customers table.

The foreign key column order does not need to reflect the order of columns in the table.

Duplicate column names are not allowed in the foreign key specification.

The default action is RESTRICT if no action is specified for an UPDATE or DELETE operation.

When you create a foreign key, an index for the key is automatically created. You can specify the
sequencing of values in the index by specifying ASC (ascending) or DESC (descending) for each
column. You can also specify whether to cluster the index, using the CLUSTERED keyword.

A global temporary table cannot have a foreign key that references a base table and a base table
cannot have a foreign key that references a global temporary table.

● NOT NULL clause Disallow NULLs 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 clause The role name is the name of the foreign key. The main function of the role
name is to distinguish between two foreign keys to the same table. If no role name is specified, the
role name is assigned as follows:

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.

● REFERENCES clause A foreign key constraint can be implemented using a REFERENCES


column constraint (single column only) or a FOREIGN KEY table constraint, in which case the
constraint can specify one or more columns. 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 column references the single primary key column of the
primary table.

● MATCH clause The MATCH clause determines what is considered a match when using a
multi-column foreign key by allowing you to regulate what constitutes an orphaned row versus
what constitutes a violation of referential integrity. The MATCH clause also allows you to specify
uniqueness for the key, thereby eliminating the need to declare uniqueness separately.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 641


SQL statements

The following is a list of MATCH types you can specify. See the Examples section at the end of
this topic for a description of how the MATCH type affects matching behavior.

○ MATCH [ UNIQUE ] SIMPLE A match occurs for a row in the foreign key table if all the
column values match the corresponding column values present in a row of the primary key
table. A row is orphaned in the foreign key table if at least one column value in the foreign key
is NULL.

MATCH SIMPLE is the default behavior.

If the UNIQUE keyword is specified, the referencing table can have only one match for non-
NULL key values.

○ MATCH [ UNIQUE ] FULL A match occurs for a row in the foreign key table if none of the
values are NULL and the values match the corresponding column values in a row of the
primary key table. A row is orphaned if all column values in the foreign key are NULL.

If the UNIQUE keyword is specified, the referencing table can have only one match for non-
NULL key values.

○ UNIQUE clause In a column-constraint clause, a UNIQUE constraint specifies that the values in
the column must be unique. In a table-constraint clause, the UNIQUE constraint 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 can have more than one UNIQUE constraint.

A UNIQUE constraint is not the same as a unique index. Columns of a unique index are allowed to be
NULL, while columns in a UNIQUE constraint are not. Also, a foreign key can reference either a
primary key or a UNIQUE constraint, but cannot reference a unique index since a unique index can
include multiple instances of NULL.

Columns in a UNIQUE constraint can be specified in any order. Additionally, you can specify the
sequencing of values in the corresponding index that is automatically created, by specifying ASC
(ascending) or DESC (descending) for each column. You cannot specify duplicate column names,
however.

It is recommended that you do not use approximate data types such as FLOAT and DOUBLE for
columns with unique constraints. Approximate numeric data types are subject to rounding errors after
arithmetic operations.

You can also specify whether to cluster the constraint, using the CLUSTERED keyword.

○ CHECK clause This constraint 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.

If you need to create a CHECK constraint that involves a relationship between two or more columns
in the table (for example, column A must be less than column B), define a table constraint instead.

No row in a table is allowed to violate a CHECK constraint. If an INSERT or UPDATE statement


would cause a row to violate the constraint, the operation is not permitted and the effects of the
statement are undone. The change is rejected only if a CHECK constraint condition evaluates to

642 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

FALSE, and the change is allowed if a CHECK constraint condition evaluates to TRUE or
UNKNOWN.

○ COMPUTE clause The COMPUTE clause is only for use in a column-constraint clause.

When a column is created using a COMPUTE clause, 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 whenever the row is modified. The COMPUTE expression should not
return a non-deterministic value. For example, it should not include a special value such as
CURRENT TIMESTAMP, or a non-deterministic function. If a COMPUTE expression returns a non-
deterministic value, then it cannot be used to match an expression in a query.

The COMPUTE clause is ignored for remote tables.

Any UPDATE statement that attempts to change the value of a computed column fires any triggers
associated with the column.

CHECK ON COMMIT clause The CHECK ON COMMIT option 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 option delays foreign key checking, but does not
delay other actions such as CASCADE, SET NULL, SET DEFAULT, or check constraints.

FOR OLAP WORKLOAD clause When you specify FOR OLAP WORKLOAD in the
REFERENCES clause of a foreign key definition, the database server performs certain optimizations and
gathers statistics on the key to help improve performance for OLAP workloads, particularly when the
optimization_workload option is set to OLAP.

PCTFREE clause Specifies the percentage of free space you want to reserve for each table page. The
free space is used if rows increase in size when the data is updated. If there is no free space in a table
page, every increase in the size of a row on that page requires the row to be split across multiple table
pages, causing row fragmentation and possible performance degradation.

The value percent-free-space is an integer between 0 and 100. The former value specifies that no free
space is to be left on each page—each page is to be fully packed. A high value causes each row to be
inserted into a page by itself. If PCTFREE is not set, or is later dropped, the default PCTFREE value is
applied according to the database page size (200 bytes for a 4 KB (and up) page size). The value for
PCTFREE is stored in the ISYSTAB system table.

Remarks
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.

Tables created by preceding the table name in a CREATE TABLE statement with a pound sign (#) are
declared temporary tables, which are available only in the current connection. Temporary tables created
with the pound sign (#) are identical to those created with the ON COMMIT PRESERVE ROWS clause.

Two local temporary tables within the same scope cannot have the same name. If you create a temporary
table with the same name as a base table, the base table only becomes visible within the connection once

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 643


SQL statements

the scope of the local temporary table ends. A connection cannot create a base table with the same name
as an existing temporary table.

Columns in SQL Anywhere allow NULLs by default. This setting can be controlled using the
allow_nulls_by_default database option.

Permissions
DBA or RESOURCE authority

Side effects
Automatic commit (even when creating global temporary tables).

See also
● “OLAP support” [SQL Anywhere Server - SQL Usage]
● “allow_nulls_by_default option” [SQL Anywhere Server - Database Administration]
● “Events” [SQL Anywhere Server - Database Administration]
● “sa_reset_identity system procedure” on page 1112
● “Choosing between sequences and AUTOINCREMENT values” [SQL Anywhere Server - SQL
Usage]
● “Reloading tables with AUTOINCREMENT columns” [SQL Anywhere 12 - Changes and Upgrading]
● “CREATE LOCAL TEMPORARY TABLE statement” on page 556
● “@@identity global variable” on page 78
● “The special IDENTITY column” [SQL Anywhere Server - SQL Usage]
● “Enabling table encryption in the database” [SQL Anywhere Server - Database Administration]
● “ALTER TABLE statement” on page 451
● “CREATE DBSPACE statement” on page 515
● “CREATE EXISTING TABLE statement” on page 532
● “DECLARE LOCAL TEMPORARY TABLE statement” on page 672
● “DROP TABLE statement” on page 711
● “optimization_workload option” [SQL Anywhere Server - Database Administration]
● “Special values” on page 58
● “SQL data types” on page 81
● “Creating a table” [SQL Anywhere Server - SQL Usage]
● “allow_nulls_by_default option” [SQL Anywhere Server - Database Administration]
● “Temporary tables” [SQL Anywhere Server - SQL Usage]
● “Computed columns” [SQL Anywhere Server - SQL Usage]
● “CREATE DBSPACE statement”
● “Additional dbspaces considerations” [SQL Anywhere Server - Database Administration]
● “Use of a sequence to generate unique values” [SQL Anywhere Server - SQL Usage]
● “default_dbspace option” [SQL Anywhere Server - Database Administration]
● “DECLARE LOCAL TEMPORARY TABLE statement” on page 672

Standards and compatibility

● SQL/2008 CREATE TABLE is a core feature of the SQL/2008 standard, though some of its
components supported in SQL Anywhere are optional SQL language features. A subset of these
features include:

644 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ Temporary table support is SQL language feature F531.

○ Support for IDENTITY columns is SQL feature T174, though SQL Anywhere uses slightly
different syntax from that in the standard.

○ Foreign key constraint support includes SQL language features T191 "Referential action:
RESTRICT", F741 "Referential MATCH types", F191 "Referential delete actions", and F701
"Referential update actions". Note that SQL Anywhere does not support MATCH PARTIAL.
SQL Anywhere does not support SQL language feature T591 ("UNIQUE constraints of possibly
null columns"). In SQL Anywhere, all columns that are part of a PRIMARY KEY or UNIQUE
constraint must be declared NOT NULL.

The following components of CREATE TABLE are vendor extensions:

○ The { IN | ON } dbspace-name clause.

○ The ENCRYPTED, NOT TRANSACTIONAL, and SHARE BY ALL clauses.

○ The COMPRESSED, INLINE, PREFIX, and NO INDEX clauses of a column definition.

○ Various implementation-defined DEFAULT values, including AUTOINCREMENT, GLOBAL


AUTOINCREMENT, CURRENT DATABASE, CURRENT REMOTE USER, CURRENT UTC
TIMESTAMP, and most special values. A DEFAULT clause that references a SEQUENCE
generator is also a vendor extension.

○ The specification of MATCH UNIQUE.

○ Sortedness specification (ASC or DESC) on a PRIMARY KEY or FOREIGN KEY clause.

○ The ability to specify FOREIGN KEY columns in an order different from that specified in the
referenced table's PRIMARY KEY clause.

Examples
The following example creates 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
);

The following example creates a table for a library database to hold information about borrowed books.
The default value for date_borrowed indicates that the book is borrowed on the day the entry is made. The
date_returned column is NULL until the book is returned.
CREATE TABLE borrowed_book (
date_borrowed DATE NOT NULL DEFAULT CURRENT DATE,
date_returned DATE,

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 645


SQL statements

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 )
);

The following example creates 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
);

The following example creates a table named t1 at a fictitious 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';

The following example creates two tables named Table1 and Table2, adds foreign keys to Table2, and
inserts values into Table1. The final statement attempts to insert values into Table2. An error is returned
because the values that you attempt to insert are not a simple match with Table1.
CREATE TABLE Table1 ( P1 INT, P2 INT, P3 INT, P4 INT, P5 INT, P6 INT,
PRIMARY KEY ( P1, P2 ) );
CREATE TABLE Table2 ( F1 INT, F2 INT, F3 INT, PRIMARY KEY ( F1, F2 ) );
ALTER TABLE Table2
ADD FOREIGN KEY fk2( F1,F2 )
REFERENCES Table1( P1, P2 )
MATCH SIMPLE;
INSERT INTO Table1 (P1, P2, P3, P4, P5, P6) VALUES ( 1,2,3,4,5,6 );
INSERT INTO Table2 (F1,F2) VALUES ( 3,4 );

The following statements show how MATCH SIMPLE and MATCH SIMPLE UNIQUE differ in how
multi-column foreign keys are handled when some, but not all, of the columns in the key are NULL:
CREATE TABLE pt( pk INT PRIMARY KEY, str VARCHAR(10));
INSERT INTO pt VALUES(1,'one'), (2,'two');
COMMIT;

CREATE TABLE ft1( fpk INT PRIMARY KEY, FOREIGN KEY (ref) REFERENCES pt MATCH
SIMPLE);
INSERT INTO ft1 VALUES(100,1), (200,1); //This statement will insert 2 rows.

CREATE TABLE ft2( fpk INT PRIMARY KEY, FOREIGN KEY (ref) REFERENCES pt MATCH
UNIQUE SIMPLE);

646 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

INSERT INTO ft2 VALUES(100,1), (200,1); //This statement will fail because
the values for the second column are not unique.

The following statements show how MATCH SIMPLE and MATCH UNIQUE SIMPLE differ:
CREATE TABLE pt2(
pk1 INT NOT NULL,
pk2 INT NOT NULL,
str VARCHAR(10),
PRIMARY KEY (pk1,pk2));

INSERT INTO pt2 VALUES(1,10,'one-ten'), (2,20,'two-twenty');


COMMIT;

CREATE TABLE ft3(


fpk INT PRIMARY KEY,
ref1 INT,
ref2 INT );

ALTER TABLE ft3 ADD FOREIGN KEY (ref1,ref2)


REFERENCES pt2 (pk1,pk2) MATCH SIMPLE;

CREATE TABLE ft4(


fpk INT PRIMARY KEY,
ref1 INT,
ref2 INT );

ALTER TABLE ft4 add FOREIGN KEY (ref1,ref2)


REFERENCES pt2 (pk1,pk2) MATCH FULL;

INSERT INTO ft3 VALUES(100,1,10);


// MATCH SIMPLE test succeeds; all column values match the corresponding
values in pt2.

INSERT INTO ft3 VALUES(200,null,null);


// MATCH SIMPLE test succeeds; at least one column in the key is null.

INSERT INTO ft3 VALUES(300,2,null);


// MATCH SIMPLE test succeeds; at least one column in the key is null.

INSERT INTO ft4 VALUES(100,1,10);


// MATCH FULL test succeeds; all column values match the corresponding
values in pt2.

INSERT INTO ft4 VALUES(200,null,null);


// MATCH FULL test succeeds; all column values in the key are null.

INSERT INTO ft4 VALUES(300,2,null);


// MATCH FULL test fails; both columns in the key must be null or match the
corresponding values in pt2.

CREATE TEXT CONFIGURATION statement


Creates a text configuration object for use with building and updating text indexes.

Syntax
CREATE TEXT CONFIGURATION [ owner.]new-config-name
FROM [ owner.]existing-config-name

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 647


SQL statements

Parameters
FROM clause Specify the name of a text configuration object to use as the template for creating the
new one. The names of the default text configuration objects are default_char and default_nchar.

When you create a text configuration object, the database options that affect how date and time values are
converted to strings are copied from the default_char and default_nchar text configuration object
templates.

Remarks
You create a text configuration object using another text configuration object as a template and then alter
the options as needed using the ALTER TEXT CONFIGURATION statement.

To view the list of all text configuration objects in the database, and their settings, query the
SYSTEXTCONFIG system view.

Permissions
Must have DBA or RESOURCE authority.

All text configuration objects have PUBLIC access. Any user with permission to create a text index can
use any text configuration object.

Side effects
Automatic commit

See also
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Default text configuration objects” [SQL Anywhere Server - SQL Usage]
● “Database options that impact text configuration objects” [SQL Anywhere Server - SQL Usage]
● “What to specify when creating or altering text configuration objects” [SQL Anywhere Server - SQL
Usage]
● “SYSTEXTCONFIG system view” on page 1248
● “Tutorial: Performing a full text search on a GENERIC text index” [SQL Anywhere Server - SQL
Usage]
● “Tutorial: Performing a fuzzy full text search” [SQL Anywhere Server - SQL Usage]
● “ALTER TEXT CONFIGURATION statement” on page 465
● “DROP TEXT CONFIGURATION statement” on page 712
● “sa_refresh_text_indexes system procedure” on page 1109

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following CREATE TEXT CONFIGURATION statement creates a text configuration object,
max_term_sixteen, using the default_char text configuration object. The subsequent ALTER TEXT
CONFIGURATION statement changes the maximum term length for max_term_sixteen to 16.

648 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE TEXT CONFIGURATION max_term_sixteen FROM default_char;


ALTER TEXT CONFIGURATION max_term_sixteen
MAXIMUM TERM LENGTH 16;

CREATE TEXT INDEX statement


Creates a text index.

Syntax
CREATE TEXT INDEX [ IF NOT EXISTS ] text-index-name
ON [ owner.]table-name( column-name, ... )
[ IN dbspace-name ]
[ CONFIGURATION [ owner.]text-configuration-name ]
[ { IMMEDIATE REFRESH
| MANUAL REFRESH
| AUTO REFRESH [ EVERY integer { MINUTES | HOURS } ] ]
}

Parameters
IF NOT EXISTS clause When the IF NOT EXISTS clause is specified and the named text index
already exists, no changes are made and an error is not returned.

ON clause Use this clause to specify the table and columns on which to build the text index.

IN clause Use this clause to specify the dbspace in which the text index is located. If this clause is not
specified, then the text index is created in the same dbspace as the table it references.

CONFIGURATION clause Use this clause to specify the text configuration object to use when
creating the text index. If this clause is not specified, the default_nchar text configuration object is used if
any of the columns in the index are NCHAR; otherwise, the default_char text configuration object is used.

REFRESH clause Use this clause to specify the refresh type for the text index. If you do not specify a
REFRESH clause, IMMEDIATE REFRESH is used as the default. Following are the list of refresh types
you can specify:

○ IMMEDIATE REFRESH Specify IMMEDIATE REFRESH to refresh the text index each time
changes in the underlying table impact data in the text index.

○ AUTO REFRESH Use this clause to refresh the materialized view automatically using an internal
server event. Use the EVERY subclause to specify the refresh interval in minutes or hours. If you
specify AUTO REFRESH without supplying interval information, the database server refreshes the
text index every 60 minutes. A text index may be refreshed earlier than specified by the AUTO
REFRESH clause if the pending_size value, as returned by the sa_text_index_stats system procedure,
exceeds 20% of the text index size at the last refresh or if the deleted_length exceeds 50% of the text
index size. An internal event executes once per minute to check this condition for all AUTO
REFRESH text indexes.

○ MANUAL REFRESH Use this clause to specify that the text index is refreshed manually.

For more information about refresh types, see “Text index refresh types” [SQL Anywhere Server - SQL
Usage].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 649


SQL statements

Remarks
You cannot create a text index on views, materialized views, or temporary tables.

An IMMEDIATE REFRESH text index is populated at creation time and an exclusive lock is held on the
table during this initial refresh. IMMEDIATE REFRESH text indexes provide full support for queries that
use snapshot isolation.

MANUAL and AUTO REFRESH text indexes must be initialized (refreshed) after creation.

Refreshes for AUTO REFRESH text indexes scan the table using isolation level 0.

Once a text index is created, you cannot change it to, or from, being defined as IMMEDIATE REFRESH.
If either of these changes is required, you must drop and recreate the text index.

You can choose to manually refresh an AUTO REFRESH text index using the REFRESH TEXT INDEX
statement.

To view text indexes and the text configuration objects they refer to, see “Viewing information about a
text index in the database (Sybase Central)” [SQL Anywhere Server - SQL Usage].

Permissions
Must be the owner of the underlying table, or have DBA authority, or have REFERENCES permission.

This statement cannot be executed when there are cursors opened with the WITH HOLD clause that use
either statement or transaction snapshots.

Side effects
Automatic commit

See also
● “Tutorial: Performing a full text search on a GENERIC text index” [SQL Anywhere Server - SQL
Usage]
● “isolation_level option” [SQL Anywhere Server - Database Administration]
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]
● “REFRESH TEXT INDEX statement” on page 846
● “Tutorial: Performing a fuzzy full text search” [SQL Anywhere Server - SQL Usage]
● “Text index concepts and reference” [SQL Anywhere Server - SQL Usage]
● “SYSTEXTCONFIG system view” on page 1248
● “ALTER TEXT INDEX statement” on page 468
● “DROP TEXT INDEX statement” on page 713
● “REFRESH TEXT INDEX statement” on page 846
● “TRUNCATE TEXT INDEX statement” on page 935
● “sa_char_terms system procedure” on page 1009
● “sa_nchar_terms system procedure” on page 1094
● “sa_refresh_text_indexes system procedure” on page 1109
● “sa_text_index_stats system procedure” on page 1149

650 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example creates a text index, myTxtIdx, on the Description column of the
MarketingInformation table in the sample database. The MarketingTextConfig text configuration object is
used, and the refresh interval is set to every 24 hours.

CREATE TEXT INDEX myTxtIdx ON MarketingInformation ( Description )


CONFIGURATION default_char
AUTO REFRESH EVERY 24 HOURS;

CREATE TRIGGER statement


Creates a trigger on a table.

Syntax
CREATE [ OR REPLACE ] TRIGGER trigger-name trigger-type
{ trigger-event-list | UPDATE OF column-list }
[ 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 ) ]
trigger-body

column-list : column-name[, ...]

trigger-type :
BEFORE
| AFTER
| INSTEAD OF
| RESOLVE

trigger-event-list : trigger-event[, ... ]

trigger-event :
DELETE
| INSERT
| UPDATE

trigger-body : a BEGIN statement. See “BEGIN statement” on page 484.

Parameters
OR REPLACE clause Specifying OR REPLACE creates a new trigger, or replaces an existing trigger
with the same name.

trigger-event Triggers can be fired by the following events. You can define either multiple triggers for
DELETE, INSERT, or UPDATE events, or one trigger for an UPDATE OF column-list event:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 651


SQL statements

○ DELETE clause Invoked whenever a row of the associated table is deleted.

○ INSERT clause Invoked whenever a new row is inserted into the table associated with the trigger.

○ UPDATE clause Invoked whenever a row of the associated table is updated.

○ UPDATE OF column-list clause Invoked whenever a row of the associated table is updated and a
column in the column-list is modified. This type of trigger event cannot be used in a trigger-event-list;
it must be the only trigger event defined for the trigger. This clause cannot be used in an INSTEAD
OF trigger.

You can write separate triggers for each event that you need to handle or, if you have some shared
actions and some actions that depend on the event, you can create a trigger for all events and use an IF
statement to distinguish the action taking place.

trigger-type Row-level triggers can be defined to execute BEFORE, AFTER, or INSTEAD OF an


insert, update, or delete operation. Statement-level triggers can be defined to execute INSTEAD OF or
AFTER the statement.

BEFORE UPDATE triggers fire any time an UPDATE occurs on a row, whether the new value differs
from the old value. That is, if a column-list is specified for a BEFORE UPDATE trigger, the trigger fires
if any of the columns in column-list appear in the SET clause of the UPDATE statement. If a column-list
is specified for an AFTER UPDATE trigger, the trigger is fired only if the value of any of the columns in
column-list is changed by the UPDATE statement.

INSTEAD OF triggers are the only form of trigger that you can define on a regular view. INSTEAD OF
triggers replace the triggering action with another action. When an INSTEAD OF trigger fires, the
triggering action is skipped and the specified action is performed. INSTEAD OF triggers can be defined
at a row-level or a statement-level. A statement-level INSTEAD OF trigger replaces the entire statement,
including all row-level operations. If a statement-level INSTEAD OF trigger fires, no row-level triggers
fire as a result of that statement. However, the body of the statement-level trigger could perform other
operations that, in turn, cause other row-level triggers to fire.

If you are defining an INSTEAD OF trigger, you cannot use the UPDATE OF column-list clause, the
ORDER clause, or the WHEN clause.

The RESOLVE trigger type is for use with SQL Remote: it fires before row-level UPDATE or UPDATE
OF column-list only.

ORDER clause When defining additional triggers of the same type (insert, update, or delete) to fire at
the same time (before, after, or resolve), you must specify an ORDER clause to tell the database server
the order in which to fire the triggers. Order numbers must be unique among same-type triggers
configured to fire at the same time. If you specify an order number that is not unique, an error is returned.
Order numbers do not need to be in consecutive order (for example, you could specify 1, 12, 30). The
database server fires the triggers starting with the lowest number.

If you omit the ORDER clause, or specify 0, the database server assigns the order of 1. However, if
another same-type trigger is already set to 1, an error is returned.

When adding additional triggers, you may need to modify the existing same-type triggers for the event,
depending on whether the actions of the triggers interact. If they do not interact, the new trigger must have

652 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

an ORDER value higher than the existing triggers. If they do interact, you need to consider what the other
triggers do, and you may need to change the order in which they fire.

The ORDER clause is not supported for INSTEAD OF triggers since there can only be one INSTEAD OF
trigger of each type (insert, update, or delete) defined on a table or view.

REFERENCING clause The REFERENCING OLD and REFERENCING NEW clauses allow you to
refer to the inserted, deleted, or updated rows. With this clause an UPDATE is treated as a delete followed
by an insert.

An INSERT takes the REFERENCING NEW clause, which represents the inserted row. There is no
REFERENCING OLD clause.

A DELETE takes the REFERENCING OLD clause, which represents the deleted row. There is no
REFERENCING NEW clause.

An UPDATE takes the REFERENCING OLD clause, which represents the row before the update, and it
takes the REFERENCING NEW clause, which represents the row after the update.

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 before 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 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.

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 specify the FOR EACH
STATEMENT clause if you are declaring a statement-level trigger.

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. This clause cannot be used in an INSTEAD OF
trigger.

trigger-body The trigger body contains the actions to take when the triggering action occurs, and
consists of a BEGIN statement.

You can include trigger operation conditions in the BEGIN statement. Trigger operation conditions
perform actions depending on the trigger event that caused the trigger to fire. For example, if the trigger is
defined to fire for both updates and deletes, you can specify different actions for the two conditions.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 653


SQL statements

Remarks
The CREATE TRIGGER statement creates a trigger associated with a table in the database, and stores the
trigger in the database.

You cannot define a trigger on a materialized view. If you do, a


SQLE_INVALID_TRIGGER_MATVIEW error is returned.

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.

Permissions
Must have RESOURCE authority and have ALTER permissions on the table, or must be the owner of the
table or have DBA authority. CREATE TRIGGER puts a table lock on the table, and requires exclusive
use of the table.

Side effects
Automatic commit.

See also
● “BEGIN statement” on page 484
● “CREATE PROCEDURE statement” on page 585
● “CREATE PROCEDURE statement [Web service]” on page 575
● “CREATE TRIGGER statement [T-SQL]” on page 657
● “DROP TRIGGER statement” on page 714
● “ROLLBACK TRIGGER statement” on page 868
● “UPDATE statement” on page 948
● “ALTER TRIGGER statement” on page 469
● “RAISERROR statement” on page 838
● “CONFLICT function [Miscellaneous]” on page 167
● “INSTEAD OF triggers” [SQL Anywhere Server - SQL Usage]
● “SQL statements for implementing integrity constraints” [SQL Anywhere Server - SQL Usage]
● “Creating triggers” [SQL Anywhere Server - SQL Usage]
● “Triggers” [SQL Anywhere Server - SQL Usage]
● “Trigger execution” [SQL Anywhere Server - SQL Usage]
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]
● “Trigger operation conditions” on page 54
● “Custom conflict resolution using triggers” [SQL Remote]

Standards and compatibility


● SQL/2008 CREATE TRIGGER is part of optional SQL language feature T211 "Basic trigger
capability" of the SQL/2008 standard. Row triggers are optional SQL language feature T212, while
INSTEAD OF triggers are optional SQL language feature T213.

Some features of SQL Anywhere triggers are vendor extensions. These include:

654 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ The optional OR REPLACE syntax. If an existing trigger is replaced, authorization of the creation
of the new trigger instance is bypassed.

○ The ORDER clause. In SQL/2008, triggers are fired in the order they were created.

○ RESOLVE triggers are a vendor extension.

● Transact-SQL ROW and RESOLVE triggers are not supported by Adaptive Server Enterprise.
The SQL Anywhere Transact-SQL dialect does not support Transact-SQL INSTEAD OF triggers,
though these are supported by Adaptive Server Enterprise. Transact-SQL triggers are defined using
different syntax.

Example
This example creates a statement-level trigger. You must first create a table:
CREATE TABLE t0
( id integer NOT NULL,
times timestamp NULL DEFAULT current timestamp,
remarks text NULL,
PRIMARY KEY ( id )
);

Next, create a statement-level trigger for this table:


CREATE TRIGGER myTrig AFTER INSERT ORDER 4 ON t0
REFERENCING NEW AS new_name
FOR EACH STATEMENT
BEGIN
DECLARE @id1 INTEGER;
DECLARE @times1 TIMESTAMP;
DECLARE @remarks1 LONG VARCHAR;
DECLARE @err_notfound EXCEPTION FOR SQLSTATE VALUE '02000';
//declare a cursor for table new_name
DECLARE new1 CURSOR FOR
SELECT id, times, remarks FROM new_name;
OPEN new1;
//Open the cursor, and get the value
LoopGetRow:
LOOP
FETCH NEXT new1 INTO @id1, @times1,@remarks1;
IF SQLSTATE = @err_notfound THEN
LEAVE LoopGetRow
END IF;
//print the value or for other use
PRINT (@remarks1);
END LOOP LoopGetRow;
CLOSE new1
END;

The following example replaces the myTrig trigger created in the previous example.
CREATE OR REPLACE TRIGGER myTrig AFTER INSERT ORDER 4 ON t0
REFERENCING NEW AS new_name
FOR EACH STATEMENT
BEGIN
FOR L1 AS new1 CURSOR FOR
SELECT id, times, remarks FROM new_name
DO
//print the value or for other use

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 655


SQL statements

PRINT (@remarks1);
END FOR;
END;

The next example shows how you can use REFERENCING NEW in a BEFORE UPDATE trigger. This
example ensures that postal codes in the new Employees table are in uppercase:
CREATE TRIGGER emp_upper_postal_code
BEFORE UPDATE OF PostalCode
ON Employees
REFERENCING NEW AS new_emp
FOR EACH ROW
WHEN ( ISNUMERIC( new_emp.PostalCode ) = 0 )
BEGIN
-- Ensure postal code is uppercase (employee might be
-- in Canada where postal codes contain letters)
SET new_emp.PostalCode = UPPER(new_emp.PostalCode)
END;

UPDATE Employees SET state='ON', PostalCode='n2x 4y7' WHERE EmployeeID=191;


SELECT PostalCode FROM Employees WHERE EmployeeID = 191;

The next example shows how you can use REFERENCING OLD in a BEFORE DELETE trigger. This
example prevents deleting an employee from the Employees table who has not been terminated.
CREATE TRIGGER TR_check_delete_employee
BEFORE DELETE
ON Employees
REFERENCING OLD AS current_employees
FOR EACH ROW /* WHEN( search_condition ) */
BEGIN
IF current_employees.TerminationDate IS NULL THEN
RAISERROR 30001 'You cannot delete an employee who has not been fired';
END IF;
END;

The next example shows how you can use REFERENCING NEW and REFERENCING OLD in a
BEFORE UPDATE trigger. This example prevents a decrease in an employee's salary.
CREATE TRIGGER TR_check_salary_decrease
BEFORE UPDATE
ON Employees
REFERENCING OLD AS before_update
NEW AS after_update
FOR EACH ROW
BEGIN
IF after_update.salary < before_update.salary THEN
RAISERROR 30002 'You cannot decrease a salary';
END IF;
END;

The next example shows how you can use REFERENCING NEW and REFERENCING OLD in a
BEFORE UPDATE trigger. This example also disallows decreasing an employee's salary, but this trigger
is more efficient because it fires only when the salary column is updated.
CREATE TRIGGER TR_check_salary_decrease_column
BEFORE UPDATE OF Salary
ON Employees
REFERENCING OLD AS before_update
NEW AS after_update
FOR EACH ROW /* WHEN( search_condition ) */

656 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

BEGIN
IF after_update.salary < before_update.salary THEN
RAISERROR 30002 'You cannot decrease a salary';
End IF;
END;

The next example shows how you can use REFERENCING NEW and in a BEFORE INSERT and
UPDATE trigger. The following example creates a trigger that will fire before a row in the
SalesOrderItems table is inserted or updated.
CREATE TRIGGER TR_update_date
BEFORE INSERT, UPDATE
ON SalesOrderItems
REFERENCING NEW AS new_row
FOR EACH ROW
BEGIN
SET new_row.ShipDate = CURRENT TIMESTAMP;
END;

CREATE TRIGGER statement [T-SQL]


Creates 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

Remarks
CREATE TRIGGER acquires an exclusive table lock on the table.

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 referenced using the REFERENCING
clause.

Trigger names must be unique in the database.

Transact-SQL triggers are executed AFTER the triggering statement has executed.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 657


SQL statements

Since the ORDER clause is not supported when creating Transact-SQL triggers, the value of trigger_order
is set to 1. The SYSTRIGGER system table has a unique index on: table_id, event, trigger_time, and
trigger_order. For a particular event (insert, update, delete), statement-level triggers are always AFTER
and trigger_order cannot be set, so there can be only one of each type per table, assuming any other
triggers do not set an order other than 1.

Permissions
DBA authority, or RESOURCE authority and ALTER permissions on the table.

Side effects
Automatic commit.

See also
● “CREATE TRIGGER statement” on page 651
● “Transact-SQL triggers” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL ROW triggers are not supported by Adaptive Server Enterprise. The SQL
Anywhere Transact-SQL dialect does not support Transact-SQL INSTEAD OF triggers, though these
are supported by Adaptive Server Enterprise.

CREATE USER statement


Creates a database user or group.

Syntax
CREATE USER user-name [ IDENTIFIED BY password ]
[ LOGIN POLICY policy-name ]
[ FORCE PASSWORD CHANGE { ON | OFF } ]

Parameters
user-name The name of the user you are creating.

IDENTIFIED BY clause The password of the user. A user without a password cannot connect to the
database.

policy-name The name of the login policy to assign the user. If no login policy is specified, the
DEFAULT login policy is applied.

FORCE PASSWORD CHANGE clause Controls whether the user must specify a new password
when they log in. This setting overrides the password_expiry_on_next_login option setting in the user's
policy.

658 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
You do not have to specify a password for the user. A user without a 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. A user ID must be a valid identifier.

● User IDs cannot:

○ begin with white space, single quotes, or double quotes


○ end with white space
○ contain semicolons

● Passwords are case-sensitive and they cannot:

○ begin with white space, single quotes, or double quotes


○ end with white space
○ contain semicolons
○ be longer than 255 bytes in length

Permissions
DBA authority

Side effects
None.

See also
● “CREATE LOGIN POLICY statement” on page 558
● “ALTER LOGIN POLICY statement” on page 415
● “ALTER USER statement” on page 470
● “COMMENT statement” on page 499
● “DROP LOGIN POLICY statement” on page 696
● “DROP USER statement” on page 715
● “Login policies” [SQL Anywhere Server - Database Administration]
● “Creating a user and assigning a login policy” [SQL Anywhere Server - Database Administration]
● “GRANT statement” on page 760
● “min_password_length option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example creates a user named SQLTester with the password welcome. The SQLTester user
is assigned to the Test1 login policy and the password expires on the next login.
CREATE USER SQLTester IDENTIFIED BY welcome
LOGIN POLICY Test1
FORCE PASSWORD CHANGE ON;

The following example creates a group named MyGroup

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 659


SQL statements

CREATE USER MyGroup;


GRANT GROUP TO MyGroup;

CREATE VARIABLE statement


Creates a SQL variable.

Syntax
CREATE [ OR REPLACE ] VARIABLE identifier data-type [ { = | DEFAULT } initial-value ]

initial-value :
special-value
| string
| [ - ] number
| ( constant-expression )
| built-in-function ( constant-expression )
| NULL

special-value :
CURRENT {
DATABASE
| DATE
| PUBLISHER
| TIME
| TIMESTAMP
| USER
| UTC TIMESTAMP }
| USER

Parameters
● OR REPLACE clause Specifying the OR REPLACE clause drops the named variable if it already
exists and replaces its definition. You can use the OR REPLACE clause as an alternative to the
VAREXISTS function in SQL scripts.

● DEFAULT clause If you specify initial-value, the data type must match the type defined by data-
type.

Remarks
The CREATE VARIABLE statement creates a new variable of the specified data type. If you specify
initial-value, the variable is set to that value. If you do not specify an initial-value, the variable contains
the NULL value until a different value is assigned by the SET statement.

A variable can be used in a SQL expression anywhere a column name is allowed. Name resolution is
performed as follows:

1. Match any aliases specified in the query's SELECT list.

2. Match column names for any referenced tables.

3. Assume the name is a variable.

660 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Variables belong to the current connection, and persist until 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.

Permissions
None.

Side effects
None.

See also
● “Compound statements” [SQL Anywhere Server - SQL Usage]
● “BEGIN statement” on page 484
● “SQL data types” on page 81
● “DROP VARIABLE statement” on page 716
● “SET statement” on page 899
● “VAREXISTS function [Miscellaneous]” on page 379
● “Special values” on page 58

Standards and compatibility


● SQL/2008 Vendor extension.

Example
This example creates a variable named first_name, of data type VARCHAR(50).
CREATE VARIABLE first_name VARCHAR(50);

This example creates a variable named 'birthday', of data type DATE.


CREATE VARIABLE birthday DATE;

This example creates a variable named v1 as an INT with the initial setting of 5.
CREATE VARIABLE v1 INT = 5;

This example creates a variable named v1 and sets its value to 10, regardless of whether or not the v1
variable already exists.
CREATE OR REPLACE VARIABLE v1 INT = 10;

CREATE VIEW statement


Creates a view on the database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 661


SQL statements

Syntax
CREATE [ OR REPLACE ] VIEW
[ owner.]view-name [ ( column-name, ... ) ]
AS query-expression
[ WITH CHECK OPTION ]

Parameters
OR REPLACE clause Specifying OR REPLACE (CREATE OR REPLACE VIEW) creates a new
view or replaces an existing view with the same name. Existing permissions are preserved when you use
the OR REPLACE clause, but INSTEAD OF triggers on the view are dropped.

If you execute a CREATE OR REPLACE VIEW statement on a view that has one or more INSTEAD OF
triggers, an error is returned. You must drop the trigger before the view can be dropped or altered.

AS clause The SELECT statement on which the view is based. The SELECT statement must not refer
to local temporary tables. Also, query-expression can have a GROUP BY, HAVING, WINDOW, or
ORDER BY clause, and can contain UNION, EXCEPT, INTERSECT, or a common table expression.

The semantics of queries dictates that the order of the rows returned is undefined unless the query
combines an ORDER BY clause with a TOP or FIRST clause in the SELECT statement. If an ORDER
BY clause is specified along with either a TOP or FIRST clause, then the query returns the top n rows, or
the first row, respectively.

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 view as defined by its query-expression.

Remarks
Views do not physically exist in the database as tables. They are derived each time they are used. A view
is derived as the result of a SELECT statement specified in a CREATE VIEW statement. Table names
that are used in a view should specify the user ID of the table owner to distinguish tables with the same
name. To create a view owned by another user you must have DBA authority and you must specify the
owner.

A view name can be used in place of a table name in SELECT, DELETE, UPDATE, and INSERT
statements.

SELECT * can only be used in the main query of the CREATE VIEW statement. Derived tables and
subqueries must use full expressions in the SELECT list, rather than the * operator. For example,
CREATE VIEW V AS SELECT * FROM T, (SELECT * FROM R) AS DT is incorrect, as the
derived table DT is specified using SELECT * rather than using a SELECT list with specified
expressions. Similarly, an implicit SELECT * used in a derived table is not allowed. For example,
CREATE VIEW V AS SELECT * FROM T, LATERAL(proc(T.A.)) AS DT has an implicit
SELECT *, as LATERAL(proc(T.A.)) is a short form for LATERAL(SELECT * FROM
proc(T.A.)) and is therefore not allowed in the view definition.

Views can be updated unless the query-expression defining the view contains a GROUP BY clause, a
WINDOW clause, an aggregate function, or involves a set operator (UNION, INTERSECT, EXCEPT).
An update to the view causes the underlying table(s) to be updated.

662 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The view's columns are given the names specified in the column-name list. If the column name list is not
specified, view columns are given names from the SELECT list items. All items in the SELECT list must
have unique names. To use names from the SELECT list items, each item must be a simple column name
or have a specified alias.

SQL Anywhere does permit unnamed expressions in the SELECT list of the query-expression referenced
in the CREATE VIEW statement. Unnamed expressions in the SELECT list of the query-expression are
assigned the name expression, concatenated with an integer value if more than one such expression
exists. For example, the following statement would define view V with three columns (expression,
expression1, and expression2), and these names would appear in the SYSCOLUMN system view for the
created view V.
CREATE VIEW V AS
SELECT DATEADD( DAY, 1, NOW() ), DATEADD( DAY, 2, NOW() ), DATEADD( DAY,
2, NOW() )
FROM SYS.DUMMY;

Relying on these generated names is not recommended since other views with unnamed SELECT list
expressions have the identical assigned names.

Typically, a view references tables and views (and their respective attributes) that are defined in the
catalog. However, a view can also reference SQL variables. In this case, when a query that references the
view is executed, the value of the SQL variable is used. Views that reference SQL variables are called
parameterized views since the variables act as parameters to the execution of the view.

Parameterized views offer an alternative to embedding the body of an equivalent SELECT block in a
query as a derived table in the query's FROM clause. Parameterized views can be useful for queries that
are embedded in stored procedures where the SQL variables referenced in the view are input parameters
for the procedure.

It is not necessary for the SQL variable to exist when the CREATE VIEW statement is executed.
However, if the SQL variable is not defined when a query that refers to the view is executed, an error is
returned indicating that the column (variable) could not be found.

Permissions
Must have RESOURCE authority and SELECT permission on the tables in the view definition.

Side effects
Automatic commit.

See also
● “CREATE TABLE statement” on page 633
● “CREATE MATERIALIZED VIEW statement” on page 560
● “ALTER MATERIALIZED VIEW statement” on page 417
● “INSTEAD OF triggers” [SQL Anywhere Server - SQL Usage]
● “SELECT statement” on page 871
● “Views” [SQL Anywhere Server - SQL Usage]
● “Creating a regular view (Sybase Central)” [SQL Anywhere Server - SQL Usage]
● “ALTER VIEW statement” on page 472

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 663


SQL statements

Standards and compatibility


● SQL/2008 CREATE VIEW is a core feature of the SQL/2008 standard, but some features of a
view's embedded SELECT statement are optional language features. The ability to specify an ORDER
BY clause with the top-level SELECT statement in the view definition is optional SQL/2008 language
feature F852. The ability to restrict the result set of a view using SELECT TOP or LIMIT is optional
SQL/2008 language feature F859 (though the SQL/2008 standard uses the FETCH clause for this
purpose). Specifying WITH CHECK OPTION on a view that is not simply updatable—for example,
the view's SELECT statement contains a derived table involving aggregation or DISTINCT, or a set
operator (INTERSECT, EXCEPT or UNION)—is optional SQL/2008 language feature T111.

Some features of CREATE VIEW are vendor extensions. Parameterized views are a vendor extension,
as is the optional OR REPLACE syntax and the automatic generation of names for unnamed SELECT
list expressions.

Example
The following example creates a view showing information for male employees only. This view has the
same column names as the base table:
CREATE VIEW MaleEmployees
AS SELECT *
FROM Employees
WHERE Sex = 'M';

The following example creates a view showing employees and the departments they belong to:
CREATE VIEW EmployeesAndDepartments
AS SELECT Surname, GivenName, DepartmentName
FROM Employees JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;

The following example replaces the EmployeesAndDepartments view created in the previous example.
After replacing the view, the view shows the city, state, and country location for each employee:
CREATE OR REPLACE VIEW EmployeesAndDepartments
AS SELECT Surname, GivenName, City, State, Country
FROM Employees JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;

The following example creates a parameterized view based on the variables var1 and var2, which are
neither attributes of the Employees nor Departments tables:
CREATE VIEW EmployeesByState
AS SELECT Surname, GivenName, DepartmentName
FROM Employees JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID
WHERE Employees.State = var1 and Employees.Status = var2;

Variables can appear in the view's SELECT statement in any context where a variable is a permitted
expression. For example, the following parameterized view utilizes the parameter var1 as the pattern for a
LIKE predicate:
CREATE VIEW ProductsByDescription
AS SELECT *
FROM Products
WHERE Products.Description LIKE var1;

664 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

To use this view, the variable var1 must be defined before the query referencing the view is executed. For
example, the following BEGIN statement could be placed in a procedure, function, or a batch statement:
BEGIN
DECLARE var1 CHAR(20);
SET var1 = '%cap%';
SELECT * FROM ProductsByDescription
END

DEALLOCATE DESCRIPTOR statement [ESQL]


Frees memory associated with a SQL descriptor area.

Syntax
DEALLOCATE DESCRIPTOR descriptor-name

descriptor-name : identifier

Remarks
Frees all memory associated with a descriptor area, including the data items, indicator variables, and the
structure itself.

Permissions
None.

Side effects
None.

See also
● “ALLOCATE DESCRIPTOR statement [ESQL]” on page 398
● “The SQL descriptor area (SQLDA)” [SQL Anywhere Server - Programming]
● “SET DESCRIPTOR statement [ESQL]” on page 882

Standards and compatibility


● SQL/2008 DEALLOCATE DESCRIPTOR is part of optional SQL/2008 language feature B031,
"Basic dynamic SQL".

Example
For an example, see “ALLOCATE DESCRIPTOR statement [ESQL]” on page 398.

DEALLOCATE statement
This statement has no effect in SQL Anywhere, and is ignored. It is provided for compatibility with
Adaptive Server Enterprise and Microsoft SQL Server. Refer to your Adaptive Server Enterprise or
Microsoft SQL Server documentation for more information about this statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 665


SQL statements

Standards and compatibility


● SQL/2008 Vendor extension.

Declaration section [ESQL]


Declares 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;

Remarks
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 are used as host variables. Not all C declarations are valid inside a
declaration section.

Permissions
None.

See also
● “Host variables in embedded SQL” [SQL Anywhere Server - Programming]
● “BEGIN statement” on page 484

Standards and compatibility


● SQL/2008 Core feature.

Example
EXEC SQL BEGIN DECLARE SECTION;
char *surname, initials[5];
int dept;
EXEC SQL END DECLARE SECTION;

DECLARE CURSOR statement [ESQL] [SP]


Declares a cursor.

Syntax 1 [ESQL]
DECLARE cursor-name
[ UNIQUE ]
[ NO SCROLL
| DYNAMIC SCROLL
| SCROLL

666 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

| INSENSITIVE
| SENSITIVE
]
CURSOR FOR
{ select-statement
| statement-name
| call-statement }

Syntax 2 [SP]
DECLARE cursor-name
[ NO SCROLL
| DYNAMIC SCROLL
| SCROLL
| INSENSITIVE
| SENSITIVE
]
CURSOR
{ FOR select-statement
| FOR call-statement
| USING variable-name }

cursor-name : identifier

statement-name : identifier | hostvar

variable-name : identifier

Parameters
UNIQUE clause When a cursor is declared UNIQUE, the query is forced to return all the columns
required to uniquely identify each row. Often this means ensuring that all columns in the primary key or a
uniqueness table constraint are returned. Any columns that are required but were not specified in the
query are added to the result set.

A DESCRIBE done on a UNIQUE cursor sets the following additional options 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.

NO SCROLL clause A cursor declared NO SCROLL is restricted to moving forward through the
result set using FETCH NEXT and FETCH RELATIVE 0 seek operations.

As rows cannot be returned to once the cursor leaves the row, there are no sensitivity restrictions on the
cursor. When a NO SCROLL cursor is requested, SQL Anywhere supplies the most efficient kind of
cursor, which is an asensitive cursor.

DYNAMIC SCROLL clause DYNAMIC SCROLL is the default cursor type. DYNAMIC SCROLL
cursors can use all formats of the FETCH statement.

When a DYNAMIC SCROLL cursor is requested, SQL Anywhere supplies an asensitive cursor. When
using cursors there is always a trade-off between efficiency and consistency. Asensitive cursors provide
efficient performance at the expense of consistency.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 667


SQL statements

SCROLL clause A cursor declared SCROLL can use all formats of the FETCH statement. When a
SCROLL cursor is requested, SQL Anywhere supplies a value-sensitive cursor. With a value-sensitive
cursor, a subsequent FETCH of a previously FETCHed result row may return a warning or an error if the
underlying row has been modified or deleted.

SQL Anywhere must execute value-sensitive cursors in such a way that result set membership is
guaranteed. DYNAMIC SCROLL cursors are more efficient and should be used unless the consistent
behavior of SCROLL cursors is required.

INSENSITIVE clause 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 from concurrently-
executing transactions, or any other update operations from within the same transaction. INSENSITIVE
cursors are not updatable.

SENSITIVE clause A cursor declared SENSITIVE is sensitive to changes to membership or values of


the result set.

FOR statement-name clause Statements are named using the PREPARE statement. Cursors can be
declared only for a prepared SELECT or CALL. The cursor updatability specified in the PREPARE
statement is used for the cursor, unless the SQL preprocessor -m HISTORICAL option is specified.

USING variable-name clause 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:


CREATE FUNCTION GetRowCount( 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;
CLOSE crsr;
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.SYSTAB ' ||


'WHERE table_id=' || string(id_value);
BEGIN

668 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

DECLARE crsr CURSOR USING qry;


OPEN crsr;
FETCH crsr INTO tabname;
CLOSE crsr;
END
END;

Remarks
Cursors are the primary means for manipulating the results of queries. The DECLARE CURSOR
statement declares a cursor with the specified name for a SELECT statement or a CALL statement. In a
Watcom SQL procedure, trigger, or batch, a DECLARE CURSOR statement must appear with other
declarations, immediately following the BEGIN keyword. Cursor names must be unique.

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).

The type of cursor specified in a DECLARE CURSOR statement can dictate the execution plan selected
by the query optimizer for that statement. For example, an INSENSITIVE cursor over a SELECT
statement requires the complete materialization of the result set of the SELECT statement when the cursor
is opened. Moreover, the type of cursor must match the characteristics of the underlying statement. If
there is a mismatch between the cursor type and the statement, then the cursor type may be changed
automatically. For example, an INSENSITIVE cursor declaration conflicts with an updatable SELECT
statement that specifies FOR UPDATE, since by definition INSENSITIVE cursors are read only. In this
case, the cursor type is changed automatically from INSENSITIVE to an updatable, value-sensitive cursor
when the cursor is opened.

If the updatability of a SELECT statement embedded in a cursor declaration is unspecified, it is


determined by the setting of the ansi_update_constraints option.

Permissions
None.

Side effects
If the cursor type must be changed to satisfy the requirements of the underlying statement, a warning is
returned when the cursor is opened.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 669


SQL statements

See also
● “PREPARE statement [ESQL]” on page 833
● “OPEN statement [ESQL] [SP]” on page 821
● “EXPLAIN statement [ESQL]” on page 727
● “SELECT statement” on page 871
● “CALL statement” on page 491
● “FOR statement” on page 733
● “FOR UPDATE or FOR READ ONLY clause, SELECT statement” on page 876
● “WITH table-hint clause, FROM clause” on page 744
● “The SQL preprocessor” [SQL Anywhere Server - Programming]
● “Sensitive cursors” [SQL Anywhere Server - Programming]
● “Insensitive cursors” [SQL Anywhere Server - Programming]
● “Value-sensitive cursors” [SQL Anywhere Server - Programming]
● “Asensitive cursors” [SQL Anywhere Server - Programming]
● “ansi_update_constraints option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 DECLARE CURSOR is a core feature of the SQL/2008 standard. The ability to specify
FOR UPDATE with SCROLL or NO SCROLL is optional SQL language feature F831, "Full cursor
update". Using DECLARE CURSOR in an embedded SQL program constitutes optional SQL
language feature B031. Some cursor types are also optional SQL features. These include:

○ INSENSITIVE cursors are optional SQL language feature F791 of the SQL/2008 standard.

○ SENSITIVE cursors are optional SQL language feature F231 of the SQL/2008 standard.

○ Scrollable cursors are optional SQL language feature F431 of the SQL/2008 standard.

SQL Anywhere supports a number of vendor extensions to DECLARE CURSOR, including:

○ SQL Anywhere supports several extensions to the FOR UPDATE clause, which SQL/2008 defines
as a clause of the DECLARE CURSOR statement.

○ WITH HOLD is specified as a clause of the OPEN statement, rather than as a clause of the
DECLARE CURSOR statement as defined in SQL/2008.

○ The SQL/2008 standard separates the notions of cursor sensitivity and scrollability, while for
historical reasons SQL Anywhere combines the two. In SQL Anywhere, all cursors are forward-
and-backward scrollable except for those declared as NO SCROLL.

○ DYNAMIC SCROLL and UNIQUE are vendor extensions. DYNAMIC SCROLL has similar
behavior to cursors declared as ASENSITIVE in the SQL/2008 standard.

○ The ability to declare a cursor over a CALL statement, or with a USING clause, is a vendor
extension.

● Transact-SQL DECLARE CURSOR is supported by Adaptive Server Enterprise, but there are
several behavioral differences. Adaptive Server Enterprise differentiates, as in SQL/2008, between
scrollability and sensitivity; in Adaptive Server Enterprise, cursor sensitivity options are SEMI-

670 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

SENSITIVE, INSENSITIVE, or default (akin to ASENSITIVE). In Adaptive Server Enterprise, NO


SCROLL cursors are the default, and all scrollable cursors are read-only. Several features of the
DECLARE CURSOR statement are not supported by Adaptive Server Enterprise. These include:

○ Adaptive Server Enterprise does not support the SQL Anywhere cursor concurrency clause.
To acquire a lock on a fetched row, you must use the HOLDLOCK table hint.

○ Adaptive Server Enterprise does not support DYNAMIC SCROLL or UNIQUE cursors.
DYNAMIC SCROLL is similar to Adaptive Server Enterprise default cursor behavior.

○ The ability to declare a cursor over a CALL statement, or with a USING clause, is not supported by
Adaptive Server Enterprise.

In Adaptive Server Enterprise, Transact-SQL procedures and functions can contain multiple
DECLARE CURSOR statements that use the same cursor name. In Adaptive Server Enterprise, the
DEALLOCATE CURSOR statement is used to eliminate a cursor from the current scope, so that a
subsequent OPEN statement can reference the correct, previously-declared cursor. This feature is not
supported in SQL Anywhere. In SQL Anywhere, all cursors in a given scope must have unique
names. If a Transact-SQL dialect procedure contains multiple cursor declarations with the same name,
the procedure parses without error. However, at execution time, if a second DECLARE CURSOR
statement with the same cursor name is executed, an error occurs.

You should be aware that the TDS wire protocol for Open Client and jConnect connections does not
implement true scrollable result sets. When scrolling backward through a cursor, the FETCH request
may be satisfied immediately if the desired row is within a window of prefetched rows that have
already been retrieved by the TDS client. If the desired row is beyond this window, however, the
cursor's SELECT statement may be re-executed.

Example
The following example illustrates how to declare a scroll cursor in embedded SQL:
EXEC SQL DECLARE cur_employee SCROLL CURSOR
FOR SELECT * FROM Employees;

The following example illustrates how to declare a cursor for a prepared statement in embedded SQL:
EXEC SQL PREPARE employee_statement
FROM 'SELECT Surname FROM Employees'FOR READ ONLY;
EXEC SQL DECLARE cur_employee CURSOR
FOR employee_statement;

The following example illustrates the use of cursors in a stored procedure:


BEGIN
DECLARE cur_employee CURSOR FOR
SELECT Surname
FROM Employees;
DECLARE name CHAR(40);
OPEN cur_employee;
lp: LOOP
FETCH NEXT cur_employee INTO name;
IF SQLCODE <> 0 THEN LEAVE lp END IF;
...

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 671


SQL statements

END LOOP;
CLOSE cur_employee;
END

DECLARE LOCAL TEMPORARY TABLE statement


Declares a local temporary table.

Syntax
DECLARE LOCAL TEMPORARY TABLE table-name
( { column-definition [ column-constraint ... ] | table-constraint | pctfree }, ... )
[ ON COMMIT { DELETE | PRESERVE } ROWS
| NOT TRANSACTIONAL ]

pctfree : PCTFREE percent-free-space

percent-free-space : integer

Parameters
ON COMMIT clause By default, the rows of a temporary table are deleted on a COMMIT. You can
use the ON COMMIT clause to preserve rows on a COMMIT.

NOT TRANSACTIONAL clause A table created using this clause is not affected by either COMMIT
or ROLLBACK. The NOT TRANSACTIONAL clause provides performance improvements in some
circumstances because operations on non-transactional temporary tables do not cause entries to be made
in the rollback log. For example, NOT TRANSACTIONAL can be useful if procedures that use the
temporary table are called repeatedly with no intervening COMMITs or ROLLBACKs.

Remarks
You cannot use the REFERENCES column-constraint or the FOREIGN KEY table-constraint on a local
temporary table.

The DECLARE LOCAL TEMPORARY TABLE statement declares a temporary table.

Tables created using DECLARE LOCAL TEMPORARY TABLE do not appear in the SYSTABLE view
of the system catalog.

The rows of a declared temporary table are deleted when the table is explicitly dropped or when the table
goes out of scope. You can also explicitly delete rows using TRUNCATE or DELETE.

Declared local temporary tables within compound statements exist within the compound statement.
Otherwise, the declared local temporary table exists until the end of the connection.

Two local temporary tables within the same scope cannot have the same name. If you create temporary
table with the same name as a base table, the base table only becomes visible within the connection once
the scope of the local temporary table ends. A connection cannot create a base table with the same name
as an existing temporary table.

672 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

If you want a procedure to create a local temporary table that persists after the procedure completes, use
the CREATE LOCAL TEMPORARY TABLE statement instead.

Permissions
None.

Side effects
None.

See also
● “CREATE TABLE statement” on page 633
● “CREATE LOCAL TEMPORARY TABLE statement” on page 556
● “Compound statements” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 DECLARE LOCAL TEMPORARY TABLE is part of optional language feature F531
of the SQL/2008 standard. The PCTFREE and NOT TRANSACTIONAL clauses are vendor
extensions. The column and constraint definitions defined by the statement may also include vendor
extension syntax. In SQL/2008, the standard stipulates that tables created via the DECLARE LOCAL
TEMPORARY TABLE statement appear in the system catalog; this is not the case with SQL
Anywhere.

● Transact-SQL DECLARE LOCAL TEMPORARY TABLE is not supported by Adaptive Server


Enterprise. In Sybase Adaptive Server Enterprise, one creates a temporary table using the CREATE
TABLE statement with a table name that begins with the special character #.

Example
The following example illustrates how to declare a temporary table in a stored procedure:
BEGIN
DECLARE LOCAL TEMPORARY TABLE TempTab ( number INT );
...
END

DECLARE statement
Declares a SQL variable or an exception within a compound statement (BEGIN...END).

Syntax 1: Declaring a variable

DECLARE variable-name [, ... ] data-type


[ { = | DEFAULT } initial-value ]

initial-value :
special-value
| string
| [ - ] number
| ( constant-expression )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 673


SQL statements

| built-in-function ( constant-expression )
| NULL

special-value :
CURRENT {
DATABASE
| DATE
| PUBLISHER
| TIME
| TIMESTAMP
| USER
| UTC TIMESTAMP }
| USER

Syntax 2: Declaring an exception


DECLARE exception-name EXCEPTION
FOR SQLSTATE [ VALUE ] string

Remarks
DECLARE variable-name: Variables used in the body of a procedure, trigger, or batch can be declared
using the DECLARE statement using Syntax 1. The variable persists for the duration of the compound
statement in which it is declared. If you specify initial-value, the variable is set to that value. If you do not
specify an initial-value, the variable contains the NULL value until a different value is assigned by the
SET statement.

The body of a Watcom SQL procedure or trigger is a compound statement, and variables must be declared
with other declarations, such as a cursor declaration (DECLARE CURSOR), immediately following the
BEGIN keyword. In a Transact-SQL procedure or trigger, there is no such restriction.

If you specify initial-value, the data type must match the type defined by data-type.

DECLARE exception-name EXCEPTION: Use this syntax to declare variables for SQL language
exceptions within a compound statement (BEGIN...END). The variables can be used, for example, for
comparison with the SQLSTATEs obtained during execution, with the SIGNAL statement, or as part of
the exception case within the exception handler.

See also
● “SQL data types” on page 81
● “DECLARE statement” on page 673
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “BEGIN statement” on page 484
● “SQLSTATE special value” on page 67
● “Special values” on page 58
● “Exception handlers” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Syntax 1 (declaring variables) - Persistent Stored Module feature. Syntax 2 (declaring
exceptions) - The form of exception declaration supported by SQL Anywhere, namely the DECLARE
EXCEPTION statement, is a vendor extension; in SQL/2008, exceptions are specified using a handler

674 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

declaration using the keywords DECLARE HANDLER. The DECLARE...EXCEPTION syntax is not
allowed in T-SQL procedures.

● Transact-SQL Syntax 2 (declaring exceptions) cannot be used in Transact-SQL compound


statements and procedures.

Example
The following batch illustrates the use of the DECLARE statement and prints a message in the database
server messages window:
BEGIN
DECLARE varname CHAR(61);
SET varname = 'Test name';
MESSAGE varname;
END

This example declares the following variables:

● v1 as an INT with the initial setting of 5.


● v2 and v3 as CHAR(10), both with an initial value of abc.
BEGIN
DECLARE v1 INT = 5;
DECLARE v2, v3 CHAR(10) = 'abc';
// ...
END

The following procedure declares an exception for use with the SQLSTATE comparison:
CREATE PROCEDURE HighSales (IN cutoff INT, OUT HighValues INT)
BEGIN
DECLARE err_notfound EXCEPTION FOR
SQLSTATE '02000';
DECLARE curThisCust CURSOR FOR
SELECT CAST( sum( SalesOrderItems.Quantity *
Products.UnitPrice ) AS INTEGER) VALUE
FROM Customers
LEFT OUTER JOIN SalesOrders
LEFT OUTER JOIN SalesOrderItems
LEFT OUTER JOIN Products
GROUP BY CompanyName;
DECLARE ThisValue INT;
SET HighValues = 0;
OPEN curThisCust;
CustomerLoop:
LOOP
FETCH NEXT curThisCust
INTO ThisValue;
IF SQLSTATE = err_notfound THEN
LEAVE CustomerLoop;
END IF;
IF ThisValue > cutoff THEN
SET HighValues = HighValues + ThisValue;
END IF;
END LOOP CustomerLoop;
CLOSE curThisCust;
END;

The following compound statement declares an exception for use with SIGNAL and an exception handler:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 675


SQL statements

BEGIN
DECLARE err_div_by_0 EXCEPTION FOR
SQLSTATE '22012';
DECLARE curQuantity CURSOR FOR
SELECT Quantity
FROM SalesOrderItems
WHERE ProductID = 300;
DECLARE Quantities INT;
DECLARE altogether INT;
SET Quantities = 0;
SET altogether = 0;
OPEN curQuantity;
LOOP
FETCH NEXT curQuantity
INTO Quantities;
IF SQLSTATE = '02000' THEN
SIGNAL err_div_by_0;
END IF;
SET altogether = altogether + Quantities;
END LOOP;
EXCEPTION
WHEN err_div_by_0 THEN
CLOSE curQuantity;
SELECT altogether;
return;
WHEN OTHERS THEN
RESIGNAL;
END;

DELETE statement (positioned) [ESQL] [SP]


Deletes the data at the current location of a cursor.

Syntax
DELETE [ [FROM ]table ] WHERE CURRENT OF cursor-name

cursor-name : identifier | hostvar

table : [ owner.]table-or-view [ [ AS ] correlation-name ]

owner : identifier

table-or-view : identifier

correlation-name : identifier

Remarks
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.

676 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

● 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, table must unambiguously identify an updatable table in the cursor. If
acorrelation-name is specified, the server attempts to match that correlation name with a correlation
name specified in the underlying cursor. If a correlation name is not specified in the DELETE
statement, and a table owner is not specified, then the server attempts to match table-or-view with an
updatable table in the underlying cursor. table-or-view is first matched against any correlation names.

○ If a correlation name exists in the underlying cursor, table-or-view may be matched with the
corresponding correlation name.

○ If a correlation name does not exist, table-or-view must unambiguously match a table name in the
cursor.

● If a FROM clause is included, and a table owner is specified, table must unambiguously match an
updatable table in the underlying cursor.

● The positioned DELETE statement can be used on a cursor open on a view as long as the view is
updatable.

Permissions
Must have DELETE permission on tables used in the cursor.

Side effects
None.

See also
● “UPDATE statement” on page 948
● “UPDATE (positioned) statement [ESQL] [SP]” on page 943
● “INSERT statement” on page 780
● “PUT statement [ESQL]” on page 837

Standards and compatibility


● SQL/2008 The DELETE statement (positioned) is a core feature of the SQL/2008 standard. The
ability to use a positioned DELETE statement from within an embedded SQL program is part of
optional SQL language feature B031, "Basic dynamic SQL".

The FROM keyword is mandatory in SQL/2008, but optional in SQL Anywhere. The range of cursors
that can be updated may contain vendor extensions if the ansi_update_constraints option is set to Off.

Example
The following statement removes the current row in the cursor cur_employee from the database.

DELETE
WHERE CURRENT OF cur_employee;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 677


SQL statements

DELETE statement
Deletes rows from the database.

Syntax 1
DELETE [ row-limitation ]
[ FROM ] [ owner.]table-or-view [ [ AS ] correlation-name ]
[ WHERE search-condition ]
[ ORDER BY { expression | integer } [ ASC | DESC ], ... ]
[ OPTION( query-hint, ... ) ]

Syntax 2 - Transact-SQL
DELETE [ row-limitation ]
[ FROM ] [ owner.]table-or-view [ [ AS ] correlation-name ]
[ FROM table-expression ]
[ WHERE search-condition ]
[ ORDER BY { expression | integer } [ ASC | DESC ], ... ]
[ OPTION( query-hint, ... ) ]

table-or-view : identifier

row-limitation :
FIRST
| TOP { ALL | limit-expression } [ START AT startat-expression ]

limit-expression : simple-expression
startat-expression : simple-expression

simple-expression :
integer
| variable
| ( simple-expression )
| ( simple-expression { + | - | * } simple-expression )

query-hint :
MATERIALIZED VIEW OPTIMIZATION option-value
| FORCE OPTIMIZATION
| FORCE NO OPTIMIZATION
| option-name = option-value

table-expression : A full table expression that can include joins. See “FROM
clause” on page 738.

option-name : identifier

option-value :
hostvar (indicator allowed)
| string
| identifier
| number

678 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Parameters
row-limitation clause The row limitation clause allows you to restrict the rows being deleted to only a
subset of the rows that satisfy the WHERE clause. The TOP and START AT arguments can be simple
arithmetic expressions over host variables, integer constants, or integer variables. The TOP argument
must evaluate to a value greater than or equal to 0. The START AT argument must evaluate to a value
greater than 0. When specifying these clauses, an ORDER BY clause is required to order the rows in a
meaningful manner.

FROM clause The FROM clause indicates the table from which rows will be deleted. In Syntax 2, the
second FROM clause in the DELETE statement determines the rows to be deleted from the specified table
based on joins with other tables. table-expression can contain arbitrarily complex table expressions,
including derived tables and KEY and NATURAL joins.

The following examples illustrate how correlation names are matched when Syntax 2 is used. With this
statement:
DELETE
FROM table_1
FROM table_1 AS alias_1, table_2 AS alias_2
WHERE ...

table table_1 doesn't have a correlation name in the first FROM clause but does 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. This is allowed as 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.

However, in the following example, there are two instances of table_1 in the second FROM clause. The
statement fails with a syntax error because it is not clear which instance of the table_1 from the second
FROM clause matches the first instance of table_1 in the first FROM clause.
DELETE
FROM table_1
FROM table_1 AS alias_1, table_1 AS alias_2
WHERE ...

WHERE clause The DELETE statement deletes all the rows that satisfy the conditions in the WHERE
clause. If no WHERE clause is specified, all rows from the named table are deleted. If a second FROM
clause is present, the WHERE clause qualifies the rows of the second FROM clause's table-expression.

ORDER BY clause Specifies the sort order for the rows to be deleted. 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 cannot use ordinal column numbers in the ORDER BY clause.

Each item in the ORDER BY list can be labeled as ASC for ascending order (the default) or DESC for
descending order.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 679


SQL statements

OPTION clause Use this clause to specify hints for executing the statement. The following hints are
supported:

○ MATERIALIZED VIEW OPTIMIZATION option-value


○ FORCE OPTIMIZATION
○ FORCE NO OPTIMIZATION
○ option-name = option-value. Note that a OPTION( isolation_level = ... ) specification
in the query text overrides all other means of specifying isolation level for a query.

Remarks
Deleting a significant amount of data using the DELETE statement causes an update to column statistics.

If you want to delete all of the rows of a table, consider using the more efficient TRUNCATE TABLE
statement.

DELETE operations can be performed on views if the query specification defining the view is updatable.
A view is updatable provided the SELECT statement defining the view has only one table in the FROM
clause and does not contain a DISTINCT clause, a GROUP BY clause, a WINDOW clause, an aggregate
function, or involve a set operator such as UNION or INTERSECT.

Permissions
Must have DELETE permission on the table.

Side effects
None.

See also
● “TRUNCATE statement” on page 933
● “Row limitation clauses in SELECT, UPDATE, and DELETE query blocks” [SQL Anywhere Server -
SQL Usage]
● “INSERT statement” on page 780
● “INPUT statement [Interactive SQL]” on page 773
● “FROM clause” on page 738
● “OPTION clause, SELECT statement” on page 877
● “Regular views” [SQL Anywhere Server - SQL Usage]
● “Locks during deletes” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Syntax 1 is a core feature of the SQL/2008 standard, whereas Syntax 2 is a Transact-
SQL vendor extension. The following features of Syntax 1 are vendor extensions:

○ The optional FROM keyword.

○ The row-limitation clause and the ORDER BY clause.

○ The OPTION clause.

680 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Example
Remove all data before 2000 from the FinancialData table.
DELETE
FROM FinancialData
WHERE Year < 2000;

Remove the first 10 orders from SalesOrderItems table where ship date is older than 2001-01-01 and their
region is Central.
DELETE TOP 10
FROM SalesOrderItems
FROM SalesOrders
WHERE SalesOrderItems.ID = SalesOrders.ID
and ShipDate < '2001-01-01' and Region ='Central'
ORDER BY ShipDate ASC;

Remove department 600 from the database, executing the statement at isolation level 3.
DELETE FROM Departments
WHERE DepartmentID = 600
OPTION( isolation_level = 3 );

DESCRIBE statement [ESQL]


Gets 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 | hostvar

cursor-name : declared cursor

sqlda-name : identifier

Parameters
USER TYPES clause A DESCRIBE statement with the USER TYPES clause returns information
about domains of a column. Typically, such a DESCRIBE is done when a previous DESCRIBE returns an
indicator of DT_HAS_USERTYPE_INFO.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 681


SQL statements

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 clause DESCRIBE ALL allows you to describe INPUT and OUTPUT with one request to the
database server. This has a performance benefit. The OUTPUT information is filled in the SQLDA first,
followed by the INPUT 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.

BIND VARIABLES FOR clause Equivalent to the INPUT clause.

SELECT LIST FOR clause Equivalent to the OUTPUT clause.

INPUT clause 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 sqlda 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.

OUTPUT clause 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 is derived
from the SELECT list item: if the item is a simple column name, it is used; otherwise, a substring of the
expression is 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.

682 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

LONG NAMES clause 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 clause This clause is used to describe procedures that can 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 re-describing is required.

Remarks
The DESCRIBE statement sets up the named SQLDA to describe either the OUTPUT (equivalently
SELECT LIST FOR) or the INPUT (equivalently BIND VARIABLES FOR) 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.

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.

In embedded SQL, NCHAR, NVARCHAR and LONG NVARCHAR are described as DT_FIXCHAR,
DT_VARCHAR, and DT_LONGVARCHAR, respectively, by default. If the db_change_nchar_charset
function has been called, these data types are described as DT_NFIXCHAR, DT_NVARCHAR and
DT_LONGNVARCHAR, respectively.

Permissions
None.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 683


SQL statements

See also
● “ALLOCATE DESCRIPTOR statement [ESQL]” on page 398
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “OPEN statement [ESQL] [SP]” on page 821
● “PREPARE statement [ESQL]” on page 833
● “db_change_nchar_charset function” [SQL Anywhere Server - Programming]
● “The SQL descriptor area (SQLDA)” [SQL Anywhere Server - Programming]
● “LONG NVARCHAR data type” on page 83
● “NCHAR data type” on page 84
● “NVARCHAR data type” on page 85

Standards and compatibility


● SQL/2008 The DESCRIBE OUTPUT statement is optional SQL language feature B031, "Basic
dynamic SQL", of the SQL/2008 standard. The DESCRIBE INPUT statement is optional SQL
language feature B032, "Extended dynamic SQL". Many of the other clauses of the DESCRIBE
statement are vendor extensions. These include:

○ The USER TYPES, ALL, BIND VARIABLES FOR, LONG NAMES, and WITH VARIABLE
RESULT clauses.

○ DESCRIBE uses the INTO clause to identify the sqlda; in the SQL/2008 standard, the USING
keyword is used instead.

○ In the SQL/2008 standard, the CURSOR clause ends with the keyword STRUCTURE.
STRUCTURE is not supported by SQL Anywhere.

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;
}

DESCRIBE statement [Interactive SQL]


Returns information about a given database object.

Syntax 1 - Describing database objects


DESCRIBE [ [ INDEX FOR ] TABLE | PROCEDURE ] [ owner.]object-name

684 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

object-name :
table
| view
| materialized view
| procedure
| function

Syntax 2 - Describing the current connection


DESCRIBE CONNECTION

Parameters
INDEX FOR clause Indicates that you want to see the indexes for the specified object-name.

TABLE clause Indicates that object-name to be described is a table or a view.

PROCEDURE clause Indicates that object-name is a procedure or a function.

Remarks
Use DESCRIBE TABLE to list all the columns in the specified table or view. The DESCRIBE TABLE
statement returns one row per table column, containing:

● Column The name of the column.

● Type The type of data in the column.

● Nullable Whether nulls are allowed (1=yes, 0=no).

● Primary Key Whether the column is in the primary key (1=yes, 0=no).

Use DESCRIBE INDEX FOR TABLE to list all the indexes for the specified table. The DESCRIBE
TABLE statement returns one row per index, containing:

● Index Name The name of the index.

● Columns The columns in the index.

● Unique Whether the index is unique (1=yes, 0=no).

● Type The type of index. Possible values are: Clustered, Statistic, Hashed, and Other.

Use DESCRIBE PROCEDURE to list all the parameters used by the specified procedure or function. The
DESCRIBE PROCEDURE statement returns one row for each parameter, containing:

● Parameter The name of the parameter.

● Type The data type of the parameter.

● In/Out Information about what is passed to, or returned from, the parameter. Possible values are:

○ In The parameter is passed to the procedure, but is not modified.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 685


SQL statements

○ Out The procedure ignores the parameter's initial value and sets its value when the procedure
returns.

○ In/Out The parameter is passed to the procedure and the procedure sets the parameter's value
when the procedure returns.

○ Result The parameter returns a result set.

○ Return The parameter returns a declared return value.

If you do not specify either TABLE or PROCEDURE (for example, DESCRIBE object-name),
Interactive SQL assumes the object is a table. However, if no such table exists, Interactive SQL attempts
to describe the object as either a procedure or a function.

Use Syntax 2 to list information about the database or database server that Interactive SQL is connected
to. The following properties are returned:

● Database Product The name and version number of the database product Interactive SQL is
connected to (for example, SQL Anywhere 12.0.1.3600).

● Host Name The network name of the computer the database server is running on.

● Host TCP/IP Address The IP address of the computer the database server is running on.

● Host Operating System The name and version number of the operating system used by the
computer the database server is running on.

● Server Name The name of the database server.

● Server TCP/IP Port The port number used by the database server for the current connection.

● Database Name The name of the database that Interactive SQL is connected to.

● Database Character Set The character set used for CHAR columns in the database.

● Connection String The connection string that was used to connect to the database or database
server. Three asterisks replace passwords.

Properties that do not apply to the current connection are omitted. For example, if you connect to a
database server using shared memory, then the TCP/IP port is omitted.

Permissions
None

Side effects
None

See also
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

686 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
Describe the columns in the Departments table:
DESCRIBE TABLE Departments;

Here is an example of the result set for this statement:

Column Type Nullable Primary key

DepartmentID integer 0 1

DepartmentName char(40) 0 0

DepartmentHeadID integer 1 0

List the indexes for the Customers table:


DESCRIBE INDEX FOR TABLE Customers;

Here is an example of the results for this statement:

Index Name Columns Unique Type

IX_customer_name Surname,GivenName 0 Clustered

DETACH TRACING statement


Ends a diagnostic tracing session.

Syntax
DETACH TRACING { WITH | WITHOUT } SAVE

Parameters
WITH SAVE clause Specify WITH SAVE to save data any unsaved diagnostic data in the diagnostic
tables.

WITHOUT SAVE clause Specify WITHOUT SAVE if you do not want to save any unsaved tracing
data.

Remarks
Execute this statement from the database being profiled to stop sending diagnostic information to the
diagnostic tables. If you specify the WITHOUT SAVE clause, you can still save the data later—assuming
the tracing database is still running and another tracing session has not been started—by using the
sa_save_trace_data system procedure.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 687


SQL statements

To see the current tracing levels set for a database, look in the sa_diagnostic_tracing_level table.

Note
Tracing information is not unloaded as part of a database unload or reload operation. If you want to
transfer tracing information from one database to another, you must do so manually by copying the
contents of the sa_diagnostic_* tables; however, this is not recommended.

Permissions
Must have DBA or PROFILE authority.

Side effects
None.

See also
● “ATTACH TRACING statement” on page 475
● “REFRESH TRACING LEVEL statement” on page 848
● “Diagnostic tracing” [SQL Anywhere Server - SQL Usage]
● “sa_diagnostic_tracing_level table” on page 991
● “sa_save_trace_data system procedure” on page 1116

Standards and compatibility


● SQL/2008 Vendor extension.

DISCONNECT statement [ESQL] [Interactive SQL]


Drops the current connection to a database.

Syntax
DISCONNECT [ connection-name | CURRENT | ALL ]

connection-name :
identifier
| string
| hostvar

Remarks
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 the application's connections to all database environments. CURRENT is
the default, and will drop the current connection.

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 performs an implicit
ROLLBACK. By default, the commit_on_exit option is set to On.

This statement is not supported in procedures, triggers, events, or batches.

688 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Permissions
None.

Side effects
None.

See also
● “DROP CONNECTION statement” on page 689
● “CONNECT statement [ESQL] [Interactive SQL]” on page 504
● “SET CONNECTION statement [Interactive SQL] [ESQL]” on page 881
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 DISCONNECT comprises optional SQL language feature F771 of the SQL/2008
standard. The ability to specify DISCONNECT without a parameter is a vendor extension. The
commit_on_exit option is a vendor extension.

Example
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;

DROP CONNECTION statement


Drops a user's connection to the database.

Syntax
DROP CONNECTION connection-id

Remarks
The DROP CONNECTION statement disconnects a user from the database by dropping the connection to
the database.

The connection-id parameter is an integer constant. You can obtain the connection-id using the
sa_conn_info system procedure.

This statement is not supported in procedures, triggers, events, or batches.

Permissions
DBA authority

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 689


SQL statements

Side effects
None.

See also
● “CONNECT statement [ESQL] [Interactive SQL]” on page 504
● “sa_conn_info system procedure” on page 1020
● “Exception handlers” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following procedure drops a connection identified by its connection number. Note that when
executing the DROP CONNECTION statement from within a procedure, you should do so using the
EXECUTE IMMEDIATE statement, as shown in this example:
CREATE PROCEDURE drop_connection_by_id( IN conn_number INTEGER )
BEGIN
EXECUTE IMMEDIATE 'DROP CONNECTION ' || conn_number;
END;

The following statement drops the connection with ID number 4.


DROP CONNECTION 4;

DROP DATABASE statement


Deletes all database files associated with a database.

Syntax
DROP DATABASE database-name [ KEY key ]

Remarks
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.

DROP DATABASE cannot be used in stored procedures, triggers, events, or batches.

Permissions
Required permissions are set using the database server -gu option. The default setting is to require DBA
authority.

The database must not be in use to be dropped.

You must specify a key if you want to drop a strongly encrypted database

Not supported on Windows Mobile.

690 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

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 508
● “DatabaseKey (DBKEY) connection parameter” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Drop the database temp.db, in the C:\temp directory:
DROP DATABASE 'c:\temp\temp.db';

DROP DATATYPE statement


Removes a datatype from the database.

Syntax
DROP DATATYPE datatype-name

Remarks
It is recommended that you use DROP DOMAIN rather than DROP DATATYPE, as DROP DOMAIN is
the syntax used in the SQL/2008 standard. You cannot drop system-defined data types (such as MONEY
or UNIQUEIDENTIFIERSTR) from a database.

Permissions
Any user who owns the object, or has DBA authority, can execute the DROP DATATYPE statement.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL.

See also
● “DROP DOMAIN statement” on page 692
● “CREATE DOMAIN statement” on page 519
● “ALTER DOMAIN statement” on page 407

Standards and compatibility


● SQL/2008 Domain support is optional SQL language feature F251 in the SQL/2008 standard. The
DROP DATATYPE statement is a vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 691


SQL statements

Example
Drop MyDatatype from the database. If the data type does not exist, an error is returned.
DROP DATATYPE MyDatatype;

DROP DBSPACE statement


Removes a dbspace from the database.

Syntax
DROP DBSPACE dbspace-name

Remarks
You must drop all tables in the dbspace before dropping the dbspace. You cannot use the DROP
DBSPACE statement to drop the predefined dbspaces SYSTEM, TEMPORARY, TEMP, TRANSLOG,
or TRANSLOGMIRROR.

DROP DBSPACE is prevented whenever the statement affects an object that is currently being used by
another connection.

Permissions
You must own the object, or have DBA authority, and be the only connection to the database.

Side effects
Automatic commit, and causes an implicit checkpoint. Clears the Results tab in the Results pane in
Interactive SQL.

See also
● “CREATE DBSPACE statement” on page 515
● “ALTER DBSPACE statement” on page 405
● “Deleting a dbspace” [SQL Anywhere Server - Database Administration]
● “Predefined dbspaces” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Drop MyDBSpace from the database. If the dbspace does not exist, an error is returned.
DROP DBSPACE MyDBSpace;

DROP DOMAIN statement


Removes a domain from the database.

692 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
DROP DOMAIN domain-name

Remarks
DROP DOMAIN is prevented if the data type is used in a table column, or in a procedure or function
argument. You must change data types on all columns defined using the domain 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 SQL/2008 standard. You cannot drop system-defined data types (such as MONEY or
UNIQUEIDENTIFIERSTR) from a database.

Permissions
Any user who owns the object, or has DBA authority, can execute the DROP DOMAIN statement.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL.

See also
● “CREATE DOMAIN statement” on page 519
● “ALTER DOMAIN statement” on page 407

Standards and compatibility


● SQL/2008 Domain support is optional SQL language feature F251 in the SQL/2008 standard.

Example
Drop the domain MyDomain from the database. If the domain does not exist, an error is returned.

DROP DOMAIN MyDomain;

DROP EVENT statement


Drops an event from the database.

Syntax
DROP EVENT [ IF EXISTS ] [ owner.]event-name

Remarks
Use the IF EXISTS clause if you do not want an error returned when the DROP EVENT statement
attempts to remove an event that does not exist.

Permissions
Any user who owns the object, or has DBA authority, can execute the DROP EVENT statement.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 693


SQL statements

See also
● “CREATE EVENT statement” on page 526
● “ALTER EVENT statement” on page 408
● “TRIGGER EVENT statement” on page 932

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Drop MyEvent from the database. If the event does not exist, an error is returned.
DROP EVENT MyEvent;

DROP EXTERNLOGIN statement


Drops an external login from the SQL Anywhere catalogs.

Syntax
DROP EXTERNLOGIN login-name TO remote-server

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.

Remarks
DROP EXTERNLOGIN deletes an external login from the SQL Anywhere catalogs.

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “CREATE EXTERNLOGIN statement” on page 534

Standards and compatibility


● SQL/2008 Vendor extension.

Example
DROP EXTERNLOGIN DBA TO sybase1;

694 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

DROP FUNCTION statement


Removes a function from the database.

Syntax
DROP FUNCTION [ IF EXISTS ] [ owner.]function-name

Remarks
Use the IF EXISTS clause if you do not want an error returned when the DROP FUNCTION statement
attempts to remove a function that does not exist.

DROP FUNCTION is prevented when the statement affects an object that is currently being used by
another connection.

Permissions
Any user who owns the object, or has DBA authority, can execute the DROP FUNCTION statement.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL.

See also
● “CREATE FUNCTION statement” on page 548
● “CREATE FUNCTION statement [External call]” on page 535
● “CREATE FUNCTION statement [Web service]” on page 541
● “ALTER FUNCTION statement” on page 412

Standards and compatibility


● SQL/2008 Core feature. The IF EXISTS clause is a vendor extension.

Example
Drop MyFunction from the database. If the function does not exist, an error is returned.
DROP FUNCTION MyFunction;

DROP INDEX statement


Removes an index from the database.

Syntax
DROP INDEX [ IF EXISTS ] { [ [ owner.]table-name.]index-name | [ [ owner.]materialized-view-
name. ]index-name }

Remarks
Use the IF EXISTS clause if you do not want an error returned when the DROP INDEX statement
attempts to remove an index that does not exist.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 695


SQL statements

When you specify the IF EXISTS clause and the named table cannot be located, an error is returned.

DROP INDEX is prevented when the statement affects an object that is currently being used by another
connection.

Permissions
A user with REFERENCES permissions on the table can execute DROP INDEX.

The DROP INDEX statement cannot be executed when there are cursors opened with the WITH HOLD
clause that use either statement or transaction snapshots.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL. The DROP INDEX
statement closes all cursors for the current connection.

If you use the DROP INDEX statement to drop an index on a local temporary table an error is returned
indicating that the index could not be found. Use the DROP TABLE statement to drop a local temporary
table. Indexes on local temporary tables are dropped automatically when the local temporary table goes
out of scope.

See also
● “CREATE INDEX statement” on page 553
● “ALTER INDEX statement” on page 413
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Drop MyIndex from the database. If the index does not exist, an error is returned.
DROP INDEX MyIndex;

DROP LOGIN POLICY statement


Drops a login policy.

Syntax
DROP LOGIN POLICY policy-name

Parameters
policy-name The name of the login policy.

Remarks
The statement fails if you drop a policy that is assigned to a user. You cannot drop the root login policy.
Use the ALTER USER statement to change a user's policy assignment.

696 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Permissions
DBA authority.

Side effects
None.

See also
● “ALTER LOGIN POLICY statement” on page 415
● “ALTER USER statement” on page 470
● “COMMENT statement” on page 499
● “CREATE LOGIN POLICY statement” on page 558
● “CREATE USER statement” on page 658
● “DROP USER statement” on page 715
● “Login policies” [SQL Anywhere Server - Database Administration]
● “Dropping a login policy” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example creates a login policy, Test11, and then deletes it.

CREATE LOGIN POLICY Test11;


DROP LOGIN POLICY Test11;

DROP MATERIALIZED VIEW statement


Removes a materialized view from the database.

Syntax
DROP MATERIALIZED VIEW [ IF EXISTS ] [ owner.]materialized-view-name

Remarks
All data in the table is automatically deleted as part of the dropping process. All indexes and keys for the
materialized view are dropped as well.

Use the IF EXISTS clause if you do not want an error returned when the DROP MATERIALIZED VIEW
statement attempts to remove a materialized view that does not exist.

You cannot execute a DROP MATERIALIZED VIEW statement on an object that is currently being used
by another connection.

Executing a DROP MATERIALIZED VIEW statement changes the status of all dependent regular views
to INVALID. To determine view dependencies before dropping a materialized view, use the
sa_dependent_views system procedure.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 697


SQL statements

Permissions
Any user who owns the object, or has DBA authority, can execute the DROP MATERIALIZED VIEW
statement.

Side effects
Automatic commit. If the materialized view had been populated, DROP MATERIALIZED VIEW will
trigger an automatic checkpoint. Clears the Results tab in the Results pane in Interactive SQL. Closes all
cursors for the current connection.

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 affect performance if you are regularly dropping and creating views.

See also
● “CREATE MATERIALIZED VIEW statement” on page 560
● “ALTER MATERIALIZED VIEW statement” on page 417
● “REFRESH MATERIALIZED VIEW statement” on page 843
● “Advanced: Status and properties for materialized views” [SQL Anywhere Server - SQL Usage]
● “sa_dependent_views system procedure” on page 1033

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Drop MyMaterializedView from the database. If the materialized view does not exist, an error is returned.
DROP MATERIALIZED VIEW MyMaterializedView;

DROP MESSAGE statement


Removes a message from the database.

Syntax
DROP MESSAGE msgnum

Remarks
None.

Permissions
Any user who owns the object, or has DBA authority, can execute the DROP MESSAGE statement.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL.

698 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “PRINT statement [T-SQL]” on page 836
● “CREATE MESSAGE statement [T-SQL]” on page 563
● “ISYSUSERMESSAGE system table” on page 979

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL DROP MESSAGE supplies the functionality provided by the sp_dropmessage()


system procedure in Adaptive Server Enterprise.

Example
Drop MyMessage from the database. If the message does not exist, an error is returned.
DROP MESSAGE MyMessage;

DROP MIRROR SERVER statement


Note
Read-only scale-out and database mirroring each require a separate license. See “Separately licensed
components” [SQL Anywhere 12 - Introduction].

Drops a mirror server.

Syntax
DROP MIRROR SERVER mirror-server-name

Remarks
Cloud note: This statement is not supported on tenant databases in the cloud.

Removes the specified mirror server from the database.

Permissions
Must have DBA authority.

Side effects
Automatic commit.

See also
● “Database mirroring” [SQL Anywhere Server - Database Administration]
● “CREATE MIRROR SERVER statement” on page 564
● “ALTER MIRROR SERVER statement” on page 420
● “COMMENT statement” on page 499

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 699


SQL statements

Standards and compatibility


● SQL/2008 Vendor extension

Example
The following statement removes the mirror server named scaleout_server_root from the database:
DROP MIRROR SERVER scaleout_server_root;

DROP PROCEDURE statement


Removes a procedure from the database.

Syntax
DROP PROCEDURE [ IF EXISTS ] [ owner.]procedure-name

Remarks
Use the IF EXISTS clause if you do not want an error returned when the DROP PROCEDURE statement
attempts to remove a procedure that does not exist.

You cannot execute a DROP PROCEDURE statement when the statement affects an object that is
currently being used by another connection.

Permissions
Any user who owns the object, or has DBA authority, can execute the DROP PROCEDURE statement.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL.

See also
● “CREATE PROCEDURE statement” on page 585
● “CREATE PROCEDURE statement [External call]” on page 567
● “CREATE PROCEDURE statement [Web service]” on page 575
● “ALTER PROCEDURE statement” on page 423

Standards and compatibility


● SQL/2008 Core feature. The IF EXISTS clause is a vendor extension.

Example
Drop MyProcedure from the database. If the procedure does not exist, an error is returned.
DROP PROCEDURE MyProcedure;

700 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

DROP PUBLICATION statement [MobiLink] [SQL Remote]


Drops a publication.

Syntax
DROP PUBLICATION [ IF EXISTS ] [ owner.]publication-name

owner, publication-name : identifier

Remarks
This statement is applicable only to MobiLink and SQL Remote.

In MobiLink, a publication identifies synchronized data in a SQL Anywhere remote database. In SQL
Remote, publications identify replicated data in both consolidated and remote databases.

Use the IF EXISTS clause if you do not want an error returned when the DROP PUBLICATION
statement attempts to remove a publication that does not exist.

Permissions
Must have DBA authority, or be the owner of the publication. Requires exclusive access to all tables
referred to in the statement.

Side effects
Automatic commit. All subscriptions to the publication are dropped.

See also
● “ALTER PUBLICATION statement [MobiLink] [SQL Remote]” on page 425
● “CREATE PUBLICATION statement [MobiLink] [SQL Remote]” on page 592
● SQL Anywhere MobiLink clients: “Publications” [MobiLink - Client Administration]
● UltraLite MobiLink clients: “DROP PUBLICATION statement [UltraLite]” [UltraLite - Database
Management and Reference]
● SQL Anywhere MobiLink clients: “Dropping publications” [MobiLink - Client Administration]
● SQL Remote: “Dropping a publication” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement drops the pub_contact publication.
DROP PUBLICATION pub_contact;

DROP REMOTE MESSAGE TYPE statement [SQL Remote]


Deletes a message type definition from a database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 701


SQL statements

Syntax
DROP REMOTE MESSAGE TYPE message-system

message-system :
FILE
| FTP
| SMTP

Remarks
The statement removes a message type from a database.

Permissions
DBA authority, and there must be no user granted REMOTE or CONSOLIDATE permissions with this
type.

Side effects
Automatic commit.

See also
● “CREATE REMOTE MESSAGE TYPE statement [SQL Remote]” on page 596
● “SQL Remote message systems” [SQL Remote]
● “Deleting message types” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement drops the FILE message type from a database.
DROP REMOTE MESSAGE TYPE file;

DROP SEQUENCE statement


Drops a sequence.

Syntax
DROP SEQUENCE [ owner.] sequence-name

Remarks
If the named sequence cannot be located, an error message is returned. When you drop a sequence, all
synonyms for the name of the sequence are dropped automatically by the database server.

Permissions
Must have DBA authority or be the owner of the sequence and have RESOURCE authority.

702 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
None

See also
● “Use of a sequence to generate unique values” [SQL Anywhere Server - SQL Usage]
● “ALTER SEQUENCE statement” on page 427
● “CREATE SEQUENCE statement” on page 599

Standards and compatibility


● SQL/2008 Sequences comprise SQL/2008 optional language feature T176.

Example
The following example drops a sequence named Test:
DROP SEQUENCE Test;

DROP SERVER statement


Drops a remote server from the SQL Anywhere catalog.

Syntax
DROP SERVER server-name

Remarks
DROP SERVER deletes a remote server from the SQL Anywhere catalogs. You must drop all the proxy
tables that have been defined for the remote server before this statement will succeed.

Permissions
DBA authority.

Not supported on Windows Mobile.

Side effects
Automatic commit.

See also
● “CREATE SERVER statement” on page 601

Standards and compatibility


● SQL/2008 Vendor extension.

Example
DROP SERVER ase_prod;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 703


SQL statements

DROP SERVICE statement


Drops a web service.

Syntax
DROP SERVICE service-name

Remarks
This statement deletes a web service listed in the ISYSWEBSERVICE system table.

Permissions
DBA authority

Side effects
None.

See also
● “CREATE SERVICE statement [HTTP web service]” on page 605
● “CREATE SERVICE statement [SOAP web service]” on page 611
● “ALTER SERVICE statement [HTTP web service]” on page 431
● “ALTER SERVICE statement [SOAP web service]” on page 436
● “ISYSWEBSERVICE system table” on page 980

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following SQL statement illustrates how to drop a web service named WebServiceTable:
DROP SERVICE WebServiceTable;

DROP SPATIAL REFERENCE SYSTEM statement


Drops a spatial reference system.

Syntax
DROP SPATIAL REFERENCE SYSTEM [ IF EXISTS ] name

Remarks
Use the IF EXISTS clause if you do not want an error returned when the DROP SPATIAL REFERENCE
SYSTEM statement attempts to remove a spatial reference system that does not exist.

Permissions
Must have DBA authority.

704 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
None

See also
● “CREATE SPATIAL REFERENCE SYSTEM statement” on page 616
● “ALTER SPATIAL REFERENCE SYSTEM statement” on page 442
● “Using spatial data” [SQL Anywhere Server - Spatial Data Support]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example drops a spatial reference system named TEST.

DROP SPATIAL REFERENCE SYSTEM Test;

DROP SPATIAL UNIT OF MEASURE statement


Drops a spatial unit of measurement.

Syntax
DROP SPATIAL UNIT OF MEASURE [ IF EXISTS ] identifier

Remarks
Use the IF EXISTS clause if you do not want an error returned when the DROP SPATIAL UNIT OF
MEASURE statement attempts to remove a spatial unit of measure that does not exist.

Permissions
Must have DBA authority or be a member of the SYS_SPATIAL_ADMIN_ROLE.

Side effects
None

See also
● “CREATE SPATIAL UNIT OF MEASURE statement” on page 624
● “Using spatial data” [SQL Anywhere Server - Spatial Data Support]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example drops a spatial unit of measure named TEST.

DROP SPATIAL UNIT OF MEASURE Test;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 705


SQL statements

DROP STATEMENT statement [ESQL]


Frees statement resources.

Syntax
DROP STATEMENT [ owner.]statement-name

statement-name :
identifier
| hostvar

Remarks
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.

Permissions
Must have prepared the statement.

Side effects
None.

See also
● “PREPARE statement [ESQL]” on page 833

Standards and compatibility


● SQL/2008 Vendor extension. In the SQL/2008 standard, this functionality is provided by the
DEALLOCATE PREPARE statement, which is part of the optional SQL language feature B032,
"Extended dynamic SQL".

Example
The following are examples of DROP STATEMENT use:

EXEC SQL DROP STATEMENT S1;


EXEC SQL DROP STATEMENT :stmt;

DROP STATISTICS statement


Erases all column statistics on the specified columns.

Syntax
DROP STATISTICS [ ON ] [owner.]object-name [ ( column-list ) ]

object-name :
table-name

706 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

| materialized-view-name
| temp-table-name

Remarks
The SQL Anywhere optimizer uses column statistics to determine the best strategy for executing each
statement. SQL Anywhere automatically gathers and updates these statistics. Column statistics are stored
permanently in the database in the ISYSCOLSTAT system table. Column statistics gathered while
processing one statement are available when searching for efficient ways to execute subsequent
statements.

Occasionally, the column statistics can 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.

The DROP STATISTICS statement deletes all internal statistical data from the ISYSCOLSTAT system
table for the specified columns. This drastic step leaves the optimizer with no access to essential statistical
information. Without these statistics, the optimizer can generate inefficient data access plans, causing
poor database performance.

The DROP STATISTICS statement requires an exclusive lock on the table against which it is being
performed. This means that execution of the statement cannot proceed until all other connections that
refer to the table have either committed or rolled back the referring transactions, or closed any open
cursors that refer to the table.

This statement should be used only during problem determination or when reloading data into a database
that differs substantially from the original data.

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “CREATE STATISTICS statement” on page 625
● “Optimizer estimates and statistics” [SQL Anywhere Server - SQL Usage]
● “ISYSCOLSTAT system table” on page 967

Standards and compatibility


● SQL/2008 Vendor extension.

DROP SUBSCRIPTION statement [SQL Remote]


Drops a subscription for a user from a publication.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 707


SQL statements

Syntax
DROP SUBSCRIPTION TO publication-name [ ( subscription-value ) ]
FOR subscriber-id, ...

subscription-value : string

subscriber-id : string

Parameters
publication-name The name of the publication to which the user is being subscribed. This can include
the owner of the publication.

subscription-value A string that is compared to the subscription expression of the publication. This
value is required because a user can have more than one subscription to a publication.

subscriber-id The user ID of the subscriber to the publication.

Remarks
Drops a SQL Remote subscription for a user ID to a publication in the current database. The user ID will
no longer receive updates when data in the publication is changed.

In SQL Remote, publications and subscriptions are two-way relationships. If you drop a subscription for a
remote user to a publication on a consolidated database, you should also drop the subscription for the
consolidated database on the remote database to prevent updates on the remote database being sent to the
consolidated database.

Permissions
DBA authority.

Side effects
Automatic commit.

See also
● “CREATE SUBSCRIPTION statement [SQL Remote]” on page 626
● “STOP SUBSCRIPTION statement [SQL Remote]” on page 922
● “ISYSSUBSCRIPTION system table” on page 976

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement drops a subscription for the SamS user ID to the pub_contact publication.
DROP SUBSCRIPTION TO pub_contact
FOR SamS;

708 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

DROP SYNCHRONIZATION PROFILE statement [MobiLink]


Deletes a SQL Anywhere synchronization profile.

Syntax
DROP SYNCHRONIZATION PROFILE [ IF EXISTS ] name

Parameters
name The name of the synchronization profile to delete.

Remarks
Synchronization profiles are named collections of synchronization options that can be used to control
synchronization. Use the IF EXISTS clause if you do not want an error returned when the DROP
SYNCHRONIZATION PROFILE statement attempts to remove a synchronization profile that does not
exist.

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “CREATE SYNCHRONIZATION PROFILE statement [MobiLink]” on page 628
● “ALTER SYNCHRONIZATION PROFILE statement [MobiLink]” on page 446

Standards and compatibility


● SQL/2008 Vendor extension.

DROP SYNCHRONIZATION SUBSCRIPTION statement


[MobiLink]
Drops a synchronization subscription in a remote database.

Syntax
DROP SYNCHRONIZATION SUBSCRIPTION {subscription-name |
TO publication-name
[ FOR ml-username, ... ]}

Parameters
subscription-name Specifies the name of the subscription to drop.

TO clause Specify the name of a publication.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 709


SQL statements

FOR clause Specify one more users.

Omitting this clause drops the default settings for the publication.

Permissions
Must have DBA authority. Requires exclusive access to all tables referred to in the publication.

Side Effects
Automatic commit.

See also
● “ALTER SYNCHRONIZATION SUBSCRIPTION statement [MobiLink]” on page 447
● “CREATE SYNCHRONIZATION SUBSCRIPTION statement [MobiLink]” on page 629
● “ISYSSYNC system table” on page 976
● “Dropping MobiLink subscriptions” [MobiLink - Client Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example drops the subscription named mysub:
DROP SYNCHRONIZATION SUBSCRIPTION mysub;

The following example drops the subscription between the user ml_user1 and the publication called
sales_publication:
DROP SYNCHRONIZATION SUBSCRIPTION
TO sales_publication
FOR "ml_user1";

The following example omits the FOR clause, and so drops the default settings for the publication called
sales_publication:
DROP SYNCHRONIZATION SUBSCRIPTION
TO sales_publication;

DROP SYNCHRONIZATION USER statement [MobiLink]


Drops one or more synchronization users from a SQL Anywhere remote database.

Syntax
DROP SYNCHRONIZATION USER ml-username, ...

ml-username : identifier

Remarks
Drop one or more synchronization users from a MobiLink remote database.

710 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Permissions
DBA authority and exclusive access to all tables referred to publications subscribed by the user.

Side Effects
All subscriptions associated with the user are also deleted.

See also
● “ALTER SYNCHRONIZATION USER statement [MobiLink]” on page 449
● “CREATE SYNCHRONIZATION USER statement [MobiLink]” on page 631
● “ISYSSYNC system table” on page 976

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Remove MobiLink user ml_user1 from the database.
DROP SYNCHRONIZATION USER ml_user1;

DROP TABLE statement


Removes a table from the database.

Syntax
DROP TABLE [ IF EXISTS ] [ owner.]table-name

Remarks
When you remove a table, all data in the table is automatically deleted as part of the dropping process. All
indexes and keys for the table are dropped as well.

Use the IF EXISTS clause if you do not want an error returned when the DROP TABLE statement
attempts to remove a table that does not exist.

You cannot execute a DROP TABLE statement when the statement affects a table that is currently being
used by another connection. Execution of a DROP TABLE statement is also prevented if there is a
materialized view dependent on the table.

When you execute a DROP TABLE statement, the status of all dependent regular views change to
INVALID. To determine view dependencies before dropping a table, use the sa_dependent_views system
procedure.

Permissions
Any user who owns the object, or has DBA authority, can execute the DROP TABLE statement.

Global temporary tables cannot be dropped unless all users that have referenced the temporary table have
disconnected.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 711


SQL statements

Side effects
Automatic commit. DROP TABLE may also cause an automatic checkpoint. Clears the Results tab in the
Results pane in Interactive SQL. Executing a DROP TABLE statement closes all cursors for the current
connection.

You can use the DROP TABLE statement to drop a local temporary table.

See also
● “Dropping a table” [SQL Anywhere Server - SQL Usage]
● “CREATE TABLE statement” on page 633
● “ALTER TABLE statement” on page 451
● “sa_dependent_views system procedure” on page 1033

Standards and compatibility


● SQL/2008 DROP TABLE is a core feature of the SQL/2008 standard. The IF EXISTS clause is a
vendor extension. The ability to drop a declared local temporary table with the DROP TABLE
statement is a vendor extension.

Example
Drop MyTable from the database. If the table does not exist, an error is returned.
DROP TABLE MyTable;

Drop MyTable from the database if it exists. If the table does not exist, an error is not returned.
DROP TABLE IF EXISTS MyTable;

DROP TEXT CONFIGURATION statement


Drops a text configuration object.

Syntax
DROP TEXT CONFIGURATION [ owner.]text-config-name

Remarks
Attempting to drop a text configuration object with dependent text indexes results in an error. You must
drop the dependent text indexes before dropping the text configuration object.

Text configuration objects are stored in the ISYSTEXTCONFIG system table.

Permissions
Must be the owner of the text configuration object or have DBA authority.

Side effects
Automatic commit

712 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “DROP TEXT INDEX statement” on page 713
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Text configuration object concepts and reference” [SQL Anywhere Server - SQL Usage]
● “SYSTEXTCONFIG system view” on page 1248
● “CREATE TEXT CONFIGURATION statement” on page 647
● “ALTER TEXT CONFIGURATION statement” on page 465

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements create and drop the mytextconfig text configuration object:
CREATE TEXT CONFIGURATION mytextconfig FROM default_char;
DROP TEXT CONFIGURATION mytextconfig;

DROP TEXT INDEX statement


Removes a text index from the database.

Syntax
DROP TEXT INDEX text-index-name
ON [ owner.]table-name

Parameters
ON clause Use this clause to specify the table on which the text index was built.

Remarks
You must drop dependent text indexes before you can drop a text configuration object.

Permissions
Must be the owner of the underlying table, or have DBA authority, or have REFERENCES permission.

This statement cannot be executed when there are cursors opened with the WITH HOLD clause that use
either statement or transaction snapshots.

Side effects
Automatic commit

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 713


SQL statements

See also
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Text index concepts and reference” [SQL Anywhere Server - SQL Usage]
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]
● “SYSTEXTCONFIG system view” on page 1248
● “CREATE TEXT INDEX statement” on page 649
● “ALTER TEXT INDEX statement” on page 468
● “DROP TEXT INDEX statement” on page 713
● “REFRESH TEXT INDEX statement” on page 846
● “TRUNCATE TEXT INDEX statement” on page 935

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statements create and drop the TextIdx text index:
CREATE TEXT INDEX TextIdx ON MarketingInformation ( Description )
DROP TEXT INDEX TextIdx ON MarketingInformation;

DROP TRIGGER statement


Removes a trigger from the database.

Syntax
DROP TRIGGER [ IF EXISTS ] [ owner.] [ table-name.]trigger-name

Remarks
Use the IF EXISTS clause if you do not want an error returned when the DROP statement attempts to
remove a database object that does not exist.

Permissions
A user with ALTER permissions on the table can execute DROP TRIGGER.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL.

See also
● “CREATE TRIGGER statement” on page 651
● “ALTER TRIGGER statement” on page 469
● “ROLLBACK TRIGGER statement” on page 868
● “Dropping triggers” [SQL Anywhere Server - SQL Usage]

714 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Standards and compatibility


● SQL/2008 DROP TRIGGER comprises part of optional SQL language feature T211, "Basic trigger
capability", of the SQL/2008 standard. The IF EXISTS clause is a vendor extension.

Example
Drop MyTrigger from the database. If the trigger does not exist, an error is returned.

DROP TRIGGER MyTrigger;

DROP USER statement


Drops a user.

Syntax
DROP USER user-name

Parameters
● user-name The name of the user you are dropping.

Permissions
DBA authority.

Remarks
Dropping a user also deletes all database objects (such as tables or procedures) that they own, as well as
any external logins for the user. The user being removed cannot be connected to the database when the
statement is executed.

Side effects
None.

See also
● “ALTER LOGIN POLICY statement” on page 415
● “ALTER USER statement” on page 470
● “COMMENT statement” on page 499
● “CREATE LOGIN POLICY statement” on page 558
● “CREATE USER statement” on page 658
● “DROP LOGIN POLICY statement” on page 696
● “Login policies” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example drops the user SQLTester from a database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 715


SQL statements

DROP USER SQLTester;

DROP VARIABLE statement


Eliminates a SQL variable.

Syntax
DROP VARIABLE [ IF EXISTS ] identifier

Remarks
The DROP VARIABLE statement eliminates a SQL variable that was previously created using the
CREATE VARIABLE statement. Variables are 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
can free up significant resources (primarily disk space).

Use the IF EXISTS clause if you do not want an error returned when the DROP statement attempts to
remove a database object that does not exist.

Permissions
None.

Side effects
None.

See also
● “CREATE VARIABLE statement” on page 660
● “SET statement” on page 899

Standards and compatibility


● SQL/2008 Vendor extension.

DROP VIEW statement


Removes a view from the database.

Syntax
DROP VIEW [ IF EXISTS ] [ owner.]view-name

Remarks
Use the IF EXISTS clause if you do not want an error returned when the DROP VIEW statement attempts
to remove a view that does not exist.

716 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

When you execute the DROP VIEW statement, the status of all dependent regular views change to
INVALID. To determine view dependencies before dropping a view, use the sa_dependent_views system
procedure.

If you execute a DROP VIEW statement on a view that has one or more INSTEAD OF triggers, an error
is returned. You must drop the trigger before the view can be dropped or altered.

Permissions
Any user who owns the object, or has DBA authority, can execute the DROP VIEW statement.

Side effects
Automatic commit. Clears the Results tab in the Results pane in Interactive SQL. Executing a DROP
VIEW statement closes all cursors for the current connection.

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 affect performance if you are regularly dropping and creating views.

See also
● “CREATE VIEW statement” on page 661
● “ALTER VIEW statement” on page 472
● “sa_dependent_views system procedure” on page 1033

Standards and compatibility


● SQL/2008 DROP VIEW is a core feature of the SQL/2008 standard. The IF EXISTS clause is a
vendor extension.

Example
Drop MyView from the database. If the view does not exist, an error is returned.
DROP VIEW MyView;

EXCEPT statement
Returns the set difference of two query blocks.

Syntax
[ WITH temporary-views ] main-query-block
EXCEPT [ ALL | DISTINCT ] except-query-block
[ ORDER BY [ integer | select-list-expression-name ] [ ASC | DESC ], ... ]
[ FOR XML xml-mode ]
[ OPTION( query-hint, ... ) ]

query-hint :
MATERIALIZED VIEW OPTIMIZATION option-value
| FORCE OPTIMIZATION
| option-name = option-value

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 717


SQL statements

main-query-block : query-block. See “Common elements in SQL syntax” on page 395.

except-query-block : query-block. See “Common elements in SQL syntax” on page 395.

option-name : identifier

option-value :
hostvar (indicator allowed)
| string
| identifier
| number

Parameters
main-query-block A query block, comprising a SELECT statement or a query expression (possibly
nested).

except-query-block A query block, comprising a SELECT statement or a query expression (possibly


nested).

FOR XML clause For information about the FOR XML clause, see “SELECT statement”
on page 871.

OPTION clause Use this clause to specify hints for executing the statement. The following hints are
supported:

○ MATERIALIZED VIEW OPTIMIZATION option-value


○ FORCE OPTIMIZATION
○ option-name = option-value. Note that a OPTION( isolation_level = ... ) specification
in the query text overrides all other means of specifying isolation level for a query.

Remarks
The EXCEPT statement returns all rows in main-query-block except those that also appear in the except-
query-block. Specify EXCEPT or EXCEPT DISTINCT if you do not want duplicates from main-query-
block to appear as duplicates in the result. Otherwise, specify EXCEPT ALL. Note that query blocks can
be nested.

The use of EXCEPT alone is equivalent to EXCEPT DISTINCT.

The main-query-block and the except-query-block must be UNION-compatible; they must each have the
same number of items in their respective SELECT lists, and the types of each expression should be
comparable. If corresponding items in two SELECT lists have different data types, SQL Anywhere
chooses a data type for the corresponding column in the result and automatically convert the columns in
each query-block appropriately.

EXCEPT ALL implements bag difference rather than set difference. For example, if main-query-block
contains 5 (duplicate) rows with specific values, and except-query-block contains 2 duplicate rows with
identical values, then EXCEPT ALL will return 3 rows.

The results of EXCEPT are the same as the results of EXCEPT ALL if main-query-block does not contain
duplicate rows.

718 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The column names displayed are the same column names that are displayed for the first query-block and
these names are used to determine the expression names to be matched with the ORDER BY clause. An
alternative way of customizing result set column names is to use a common table expression (the WITH
clause).

Permissions
Must have SELECT permission for each query-block.

Side effects
None

See also
● “INTERSECT statement” on page 788
● “UNION statement” on page 936
● “SELECT statement” on page 871
● “OPTION clause, SELECT statement” on page 877

Standards and compatibility


● SQL/2008 EXCEPT DISTINCT is a core feature of the SQL/2008 standard; EXCEPT ALL
comprises the optional SQL language feature F304. Explicitly specifying the DISTINCT keyword
with EXCEPT is optional SQL language feature T551 of the SQL/2008 standard. Specifying an
ORDER BY clause with EXCEPT is SQL language feature F850. A query-block that contains an
ORDER BY clause constitutes SQL/2008 feature F851. A query block that contains a row-limit clause
(SELECT TOP or LIMIT) comprises optional SQL language feature F857 or F858, depending on the
context. The FOR XML clause and the OPTION clause are vendor extensions.

● Transact-SQL EXCEPT is not supported by Adaptive Server Enterprise. However, both EXCEPT
ALL and EXCEPT DISTINCT can be used in the Transact-SQL dialect supported by SQL Anywhere.

Example
For examples of EXCEPT usage, see “Set operators and NULL” [SQL Anywhere Server - SQL Usage].

EXECUTE IMMEDIATE statement [SP]


Enables dynamically constructed statements to be executed from within a procedure.

Syntax 1
EXECUTE IMMEDIATE [ execute-option ] string-expression

execute-option :
WITH QUOTES [ ON | OFF ]
| WITH ESCAPES { ON | OFF }
| WITH BATCH { ON | OFF }
| WITH RESULT SET { ON | OFF }

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 719


SQL statements

Syntax 2 - Transact-SQL
EXECUTE ( string-expression )

Parameters
WITH QUOTES clause When you specify WITH QUOTES or WITH QUOTES ON, any double
quotes in the string-expression are assumed to delimit an identifier. When you do not specify WITH
QUOTES, or specify WITH QUOTES OFF, the treatment of double quotes in the string-expression
depends on the current setting of the quoted_identifier option.

WITH QUOTES is useful when an object name that is passed into the stored procedure is used to
construct the statement that is to be executed, but the name might require double quotes and the procedure
might be called when the quoted_identifier option is set to Off.

WITH ESCAPES clause WITH ESCAPES OFF causes any escape sequences (such as \n, \x, or \\) in
the string-expression to be ignored. For example, two consecutive backslashes remain as two backslashes,
rather than being converted to a single backslash. The default setting is equivalent to WITH ESCAPES
ON.

One use of WITH ESCAPES OFF is for easier execution of dynamically constructed statements
referencing file names that contain backslashes.

In some contexts, escape sequences in the string-expression are transformed before the EXECUTE
IMMEDIATE statement is executed. For example, compound statements are parsed before being
executed, and escape sequences are transformed during this parsing, regardless of the WITH ESCAPES
setting. In these contexts, WITH ESCAPES OFF prevents further translations from occurring. For
example:

BEGIN
DECLARE String1 LONG VARCHAR;
DECLARE String2 LONG VARCHAR;
EXECUTE IMMEDIATE
'SET String1 = ''One backslash: \\\\ ''';
EXECUTE IMMEDIATE WITH ESCAPES OFF
'SET String2 = ''Two backslashes: \\\\ ''';
SELECT String1, String2
END

WITH BATCH clause The WITH BATCH clause allows you to control the execution of batches in
EXECUTE IMMEDIATE statements. Setting WITH BATCH OFF provides protection against
inadvertent SQL-injection when the procedure is run.

WITH BATCH ON is the default, except for procedures owned by dbo.

When WITH BATCH OFF is used, the statement specified by string-expression must be a single
statement.

WITH RESULT SET clause The WITH RESULT SET clause allows the server to define correctly the
procedure containing it. Specifying WITH RESULT SET ON or WITH RESULT SET OFF affects both
what happens when the procedure is created, as well as what happens when the procedure is executed.
The default option is WITH RESULT SET OFF.

720 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

You can have an EXECUTE IMMEDIATE statement return a result set by specifying WITH RESULT
SET ON. With this clause, the containing procedure is marked as returning a result set.

Remarks
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. String literals cannot span multiple
lines.

Only global variables can be referenced in a statement executed by EXECUTE IMMEDIATE.

Only Syntax 2 can be used inside Transact-SQL stored procedures and triggers.

Statements executed with EXECUTE IMMEDIATE do not have their plans cached.

Permissions
None.

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.

See also
● “quoted_identifier option” [SQL Anywhere Server - Database Administration]
● “EXECUTE IMMEDIATE used in procedures, triggers, user-defined functions, and batches” [SQL
Anywhere Server - SQL Usage]
● “CREATE PROCEDURE statement” on page 585
● “CREATE PROCEDURE statement [External call]” on page 567
● “CREATE PROCEDURE statement [Web service]” on page 575
● “BEGIN statement” on page 484
● “EXECUTE statement [ESQL]” on page 722
● “EXECUTE statement [T-SQL]” on page 724

Standards and compatibility


● SQL/2008 EXECUTE IMMEDIATE is optional SQL language feature B031, "Basic dynamic
SQL", of the SQL/2008 standard. The execute-option syntax is a vendor extension. The SQL/2008
standard prohibits the use of EXECUTE IMMEDIATE that returns a result set.

● Transact-SQL Syntax 2 is the Transact-SQL dialect's syntax for EXECUTE IMMEDIATE. The
execute-option syntax is not supported by Adaptive Server Enterprise.

Examples
The following procedure creates a table, where the table name is supplied as a parameter to the procedure.
CREATE PROCEDURE CreateTableProc(
IN tablename char(30)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 721


SQL statements

)
BEGIN
EXECUTE IMMEDIATE
'CREATE TABLE ' || tablename ||
' ( column1 INT PRIMARY KEY)'
END;

To call the procedure and create a table called mytable:


CALL CreateTableProc( 'mytable' );

EXECUTE statement [ESQL]


Executes a prepared SQL statement.

Syntax 1
EXECUTE statement
[ USING { hostvar-list | [ SQL ] DESCRIPTOR sqlda-name } ]
[ INTO { into-hostvar-list | [ SQL ] DESCRIPTOR into-sqlda-name } ]
[ ARRAY :row-count ]

row-count : integer | hostvar

statement : identifier | hostvar | string

sqlda-name : identifier

into-sqlda-name : identifier

Syntax 2
EXECUTE IMMEDIATE statement

statement : string | hostvar

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 can improve performance. The integer
value is the number of rows to be inserted. The SQLDA must contain a variable for each entry (number of

722 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

rows * number of columns). The first row is placed in SQLDA variables 0 to (columns per row)-1, and so
on.

Remarks
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.

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 placeholders that supply information for the request (bind variables),
either the sqlda-name must specify a C variable which is a pointer to a SQLDA containing enough
descriptors for all the bind variables occurring in the statement, or the bind variables must be supplied
in the hostvar-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.

Permissions
Permissions are checked on the statement being executed.

Side effects
None.

See also
● “EXECUTE IMMEDIATE statement [SP]” on page 719
● “PREPARE statement [ESQL]” on page 833
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “Cursors in embedded SQL” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 The EXECUTE statement comprises part of optional SQL language feature B031,
"Basic dynamic SQL", of the SQL/2008 standard. The INTO clause is part of optional language
feature B032, "Extended dynamic SQL". The ARRAY clause is a vendor extension.

The EXECUTE IMMEDIATE statement supported with embedded SQL is also part of optional SQL
language feature B031.

Example
Execute a DELETE.

EXEC SQL EXECUTE IMMEDIATE


'DELETE FROM Employees WHERE EmployeeID = 105';

Execute a prepared DELETE statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 723


SQL statements

EXEC SQL PREPARE del_stmt FROM


'DELETE FROM Employees WHERE EmployeeID = :a';
EXEC SQL EXECUTE del_stmt USING :employee_number;

Execute a prepared query.


EXEC SQL PREPARE sel1 FROM
'SELECT Surname FROM Employees WHERE EmployeeID = :a';
EXEC SQL EXECUTE sel1 USING :employee_number INTO :surname;

EXECUTE statement [T-SQL]


Syntax 1 invokes a procedure, as an Adaptive Server Enterprise-compatible alternative to the CALL
statement. Syntax 2 executes a prepared SQL statement in Transact-SQL.

Syntax 1
[ EXECUTE | EXEC ][ @return_status = ] [creator.]procedure_name [ argument, ... ]

argument :
[ @parameter-name = ] expression
| [ @parameter-name = ] @variable [ output ]

Syntax 2
EXECUTE ( string-expression )

Remarks
Syntax 1 is implemented for Transact-SQL compatibility. EXECUTE calls a stored procedure, optionally
supplying procedure parameters and retrieving output values and return status information. In Watcom
SQL, use the CALL or EXECUTE IMMEDIATE statements.

With Syntax 2, you can execute dynamic statements within Transact-SQL stored procedures and triggers.
The EXECUTE 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. Syntax 2 of the EXECUTE statement is implemented
for Transact-SQL compatibility, but can be used in either Transact-SQL or Watcom SQL batches and
procedures.

The Transact-SQL EXECUTE statement does not have a way to signify that a result set is expected. One
way to indicate that a Transact-SQL procedure returns a result set is to include something like the
following:
IF 1 = 0
SELECT 1 AS a

You can also execute statements within Transact-SQL stored procedures and triggers.

Permissions
Must be the owner of the procedure, have EXECUTE permission for the procedure, or have DBA
authority.

724 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
None.

See also
● “CALL statement” on page 491
● “EXECUTE statement [ESQL]” on page 722
● “EXECUTE IMMEDIATE statement [SP]” on page 719

Standards and compatibility


● SQL/2008 Syntax 1 is a vendor extension. Syntax 2 offers functionality equivalent to the
EXECUTE IMMEDIATE statement in the SQL/2008 standard, which is optional SQL language
feature B031, "Basic dynamic SQL". However, the syntax of Syntax 2 differs from that of the SQL/
2008 standard.

Example
The following procedure illustrates Syntax 1.
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 in the client
window. If you are connected from an ODBC or embedded SQL application, the messages are displayed
in the database server messages 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;

The following statement executes the procedure, and stores the return value in a variable for checking
return status.
EXECUTE @status = p1 23;

EXIT statement [Interactive SQL]


Leaves Interactive SQL.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 725


SQL statements

Syntax
{ EXIT | QUIT | BYE } [ return-code ]

return-code : number | connection-variable

Remarks
This statement closes the Interactive SQL window if you are running Interactive SQL as a windowed
program, or terminates Interactive SQL altogether when running in command-prompt (batch) mode. In
both cases, the database connection is also closed. 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 performs an implicit ROLLBACK. By default, the commit_on_exit
option is set to On.

The optional return code can be checked in batch files to determine the success or failure of the statements
in an Interactive SQL script file. The default return code is 0.

Permissions
None.

Side effects
This statement automatically performs a commit if option commit_on_exit is set to On (the default);
otherwise it performs an implicit rollback.

On Windows operating systems the optional return value is available as ERRORLEVEL.

See also
● “SET OPTION statement” on page 886
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example sets the Interactive SQL return value to 1 if there are any rows in table T, or to 0 if
T contains no rows.
CREATE VARIABLE rowCount INT;
CREATE VARIABLE retcode INT;
SELECT COUNT(*) INTO rowCount FROM T;
IF( rowCount > 0 ) THEN
SET retcode = 1;
ELSE
SET retcode = 0;
END IF;
EXIT retcode;

726 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Note
You cannot write the following statement because EXIT is an Interactive SQL statement (not a SQL
statement), and you cannot include any Interactive SQL statement in other SQL block statements.
CREATE VARIABLE rowCount INT;
SELECT COUNT(*) INTO rowCount FROM T;
IF( rowCount > 0 ) THEN
EXIT 1 // <-- not allowed
ELSE
EXIT 0 // <-- not allowed
END IF;

EXPLAIN statement [ESQL]


Retrieves a text specification of the optimization strategy used for a particular cursor.

Syntax
EXPLAIN PLAN FOR CURSOR cursor-name
{ INTO hostvar | USING DESCRIPTOR sqlda-name }

cursor-name : identifier | hostvar

sqlda-name : identifier

Remarks
The EXPLAIN statement retrieves a text representation of the optimization strategy for the named cursor.
The cursor must be previously declared and opened.

The hostvar 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 are accessed by the database
server. After each table is a parenthesized index name. This is the index that is used to access the table. If
no index is used (the table is 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.

After successful execution of the EXPLAIN statement, the sqlerrd 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.

A discussion with quite a few examples of the optimization string can be found in “Performance
monitoring and diagnostic tools” [SQL Anywhere Server - SQL Usage].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 727


SQL statements

Permissions
Must have opened the named cursor.

Side effects
None.

See also
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “PREPARE statement [ESQL]” on page 833
● “FETCH statement [ESQL] [SP]” on page 728
● “CLOSE statement [ESQL] [SP]” on page 498
● “OPEN statement [ESQL] [SP]” on page 821
● “Cursors in embedded SQL” [SQL Anywhere Server - Programming]
● “The SQL Communication Area (SQLCA)” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example illustrates the use of EXPLAIN:
EXEC SQL BEGIN DECLARE SECTION;
char plan[300];
EXEC SQL END DECLARE SECTION;
EXEC SQL DECLARE employee_cursor CURSOR FOR
SELECT EmployeeID, Surname
FROM Employees
WHERE Surname 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:


'Employees <seq>'

FETCH statement [ESQL] [SP]


Positions, or re-positions, a cursor to a specific row, and then copies expression values from that row into
variables accessible from within the stored procedure or application.

Syntax 1 [SP]
FETCH [ cursor-position ] cursor-name
INTO variable-list [ FOR UPDATE ]

Syntax 2 [ESQL]
FETCH [ cursor-position ] cursor-name
[ INTO { hostvar-list } | USING [ SQL ] DESCRIPTOR sqlda-name ]

728 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

[ PURGE ]
[ BLOCK n ]
[ FOR UPDATE ]
[ ARRAY fetch-count ]

cursor-position :
NEXT | PRIOR | FIRST | LAST
| { ABSOLUTE | RELATIVE } row-count

row-count : number | hostvar

cursor-name : identifier | hostvar

hostvar-list : may contain indicator variables

variable-list : stored procedure variables

sqlda-name : identifier

fetch-count : integer | hostvar

Parameters
● INTO clause The INTO clause is optional. If it is not specified, the FETCH statement positions the
cursor only. The hostvar-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 not specified, NEXT is assumed. 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 clause Next is the default positioning, and causes the cursor to be advanced one row before
the row is fetched.

● PRIOR clause Causes the cursor to be backed up one row before fetching.

● RELATIVE clause 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 backward. So, 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 clause The ABSOLUTE positioning parameter is used to go to a particular row. A


zero indicates the position before the first row.

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 clause A short form for ABSOLUTE 1.

● LAST clause A short form for ABSOLUTE -1.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 729


SQL statements

Note
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. Sometimes the inserted row does not
appear until the cursor is closed and opened again.

This occurs if a temporary table had to be created to open the cursor.

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 database server. The client buffers these rows, and subsequent fetches are
retrieved from these buffers without a new request to the database server.

The BLOCK clause is for use in embedded SQL only. It gives the client and server a hint about how
many rows may be fetched by the application. The special value of 0 means the request is sent to the
database server and a single row is returned (no row blocking). The BLOCK clause will reduce the
number of rows included in the next prefetch to the BLOCK value. To increase the number of rows
prefetched, use the PrefetchRows connection parameter.

If you do not specify a BLOCK clause, the value specified on OPEN is used.

FETCH RELATIVE 0 always re-fetches the row.

If prefetch is disabled for the cursor, the BLOCK clause is ignored and rows are fetched one at a time.
If ARRAY is also specified, then the number of rows specified by ARRAY are fetched.

● 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 database 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 an intent lock on the row. The lock is held until the end of the current
transaction.

● 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.

730 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
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
must be executed before the FETCH statement.

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.

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. The cursor is positioned on the last row if the attempted fetch was beyond
the end of the cursor, and on the first row 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 hostvar-list or the sqlda-name
descriptor array.

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
A FETCH statement may cause multiple rows to be retrieved from the server to the client if prefetching is
enabled.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 731


SQL statements

See also
● “SELECT statement” on page 871
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “FOR statement” on page 733
● “PREPARE statement [ESQL]” on page 833
● “OPEN statement [ESQL] [SP]” on page 821
● “RESUME statement” on page 857
● “How locking works” [SQL Anywhere Server - SQL Usage]
● “Fetching data” [SQL Anywhere Server - Programming]
● “Fetching more than one row at a time” [SQL Anywhere Server - Programming]
● “Use work tables in query processing (use All-rows optimization goal)” [SQL Anywhere Server - SQL
Usage]
● “Cursors in embedded SQL” [SQL Anywhere Server - Programming]
● “Cursors in procedures, triggers, user-defined functions, and batches” [SQL Anywhere Server - SQL
Usage]

Standards and compatibility


● SQL/2008 With minor exceptions, Syntax 1 of the FETCH statement is a core feature of the SQL/
2008 standard. Scrolling options other than NEXT constitute optional SQL language feature F431,
"Read-only scrollable cursors". SQL Anywhere does not support the optional FROM clause of the
FETCH statement as documented in the SQL/2008 standard.

Syntax 2 is a vendor extension.

The FOR UPDATE, PURGE, ARRAY, BLOCK, and USING [SQL] DESCRIPTOR clauses are
vendor extensions.

Example
The following is an embedded SQL example:
EXEC SQL DECLARE cur_employee CURSOR FOR
SELECT EmployeeID, Surname FROM Employees;
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 Surname
FROM Employees;
DECLARE name CHAR(40);
OPEN cur_employee;
lp: LOOP
FETCH NEXT cur_employee into name;
IF SQLCODE <> 0 THEN LEAVE lp END IF;
...
END LOOP;
CLOSE cur_employee;
END

732 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

FOR statement
Repeats the execution of a statement list once for each row in a cursor.

Syntax
[ statement-label : ]
FOR for-loop-name AS cursor-name [ cursor-type ] CURSOR
{ FOR statement [ FOR { UPDATE [ cursor-concurrency ] | READ ONLY } ]
| USING variable-name }
DO statement-list
END FOR [ statement-label ]

cursor-type :
NO SCROLL
| DYNAMIC SCROLL
| SCROLL
| INSENSITIVE
| SENSITIVE

cursor-concurrency : BY { VALUES | TIMESTAMP | LOCK }

variable-name : identifier

Parameters
NO SCROLL clause A cursor declared NO SCROLL is restricted to moving forward through the
result set using FETCH NEXT and FETCH RELATIVE 0 seek operations.

As rows cannot be returned to once the cursor leaves the row, there are no sensitivity restrictions on the
cursor. When a NO SCROLL cursor is requested, SQL Anywhere supplies the most efficient kind of
cursor, which is an asensitive cursor.

DYNAMIC SCROLL clause DYNAMIC SCROLL is the default cursor type. DYNAMIC SCROLL
cursors can use all formats of the FETCH statement.

When a DYNAMIC SCROLL cursor is requested, SQL Anywhere supplies an asensitive cursor. When
using cursors there is always a trade-off between efficiency and consistency. Asensitive cursors provide
efficient performance at the expense of consistency.

SCROLL clause A cursor declared SCROLL can use all formats of the FETCH statement. When a
SCROLL cursor is requested, SQL Anywhere supplies a value-sensitive cursor.

SQL Anywhere must execute value-sensitive cursors in such a way that result set membership is
guaranteed. DYNAMIC SCROLL cursors are more efficient and should be used unless the consistent
behavior of SCROLL cursors is required.

INSENSITIVE clause A cursor declared INSENSITIVE has its values and membership fixed over its
lifetime. The result set of the SELECT statement is materialized when the cursor is opened. FETCHING
from an INSENSITIVE cursor does not see the effect of any other INSERT, UPDATE, MERGE, PUT, or
DELETE statement from any connection, including the connection that opened the cursor.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 733


SQL statements

SENSITIVE clause A cursor declared SENSITIVE is sensitive to changes to membership or values of


the result set.

FOR UPDATE clause FOR UPDATE is the default. Cursors default to FOR UPDATE for single-table
queries without an ORDER BY clause, or if the ansi_update_constraints option is set to Off. When the
ansi_update_constraints option is set to Cursors or Strict, then cursors over a query containing an ORDER
BY clause default to READ ONLY. However, you can explicitly mark cursors as updatable using the
FOR UPDATE clause.

FOR READ ONLY clause A cursor declared FOR READ ONLY cannot be used in UPDATE
(positioned), DELETE (positioned), or PUT statements. Because it is expensive to allow updates over
cursors with an ORDER BY clause or a join, cursors over a query containing a join of two or more tables
are READ ONLY and cannot be made updatable unless the ansi_update_constraints database option is
Off. In response to any request for a cursor that specifies FOR UPDATE, SQL Anywhere provides either
a value-sensitive cursor or a sensitive cursor. Insensitive and asensitive cursors are not updatable.

See also
● “Sensitive cursors” [SQL Anywhere Server - Programming]
● “Insensitive cursors” [SQL Anywhere Server - Programming]
● “Value-sensitive cursors” [SQL Anywhere Server - Programming]
● “Asensitive cursors” [SQL Anywhere Server - Programming]

Remarks
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.

Valid cursor types include dynamic scroll (default), scroll, no scroll, sensitive, and insensitive.

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 are the data types of the expressions in the SELECT list. The names
are the SELECT list item aliases, if they exist; otherwise, they are 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 are 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.

The cursor created by a FOR statement is implicitly opened WITH HOLD, so statements executed within
the loop that cause a COMMIT do not cause the cursor to be closed.

Permissions
None.

Side effects
None.

734 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “FETCH statement [ESQL] [SP]” on page 728
● “CONTINUE statement” on page 507
● “LOOP statement” on page 810

Standards and compatibility


● SQL/2008 The FOR statement is part of optional SQL/2008 language feature P002,
"Computational completeness". The USING clause of the FOR statement is a vendor extension. As
with the DECLARE CURSOR statement, the use of cursor-concurrency is a vendor extension, as are
the combinations of cursor sensitivity and cursor scrollability options.

Example
The following fragment illustrates the use of the FOR loop.
FOR names AS curs INSENSITIVE CURSOR FOR
SELECT Surname
FROM Employees
DO
CALL search_for_name( Surname );
END FOR;

This fragment also illustrates the use of the FOR loop.


BEGIN
FOR names AS curs SCROLL CURSOR FOR
SELECT EmployeeID, GivenName FROM Employees where EmployeeID < 130
FOR UPDATE BY VALUES
DO
MESSAGE 'emp: ' || GivenName;
END FOR;
END

The following example shows the FOR loop being using inside of a procedure called myproc, which
returns the top 10 employees from the Employees table, depending on the sort order specified when
calling the procedure (asc for ascending, and desc for descending).
CALL sa_make_object( 'procedure', 'myproc' ) ;
ALTER PROCEDURE myproc (
IN @order_by VARCHAR(20) DEFAULT NULL
)
RESULT ( Surname person_name_t )
BEGIN
DECLARE @sql LONG VARCHAR;
DECLARE @msg LONG VARCHAR;
DECLARE LOCAL TEMPORARY TABLE temp_names( surnames person_name_t );
SET @sql = 'SELECT TOP(10) * FROM Employees AS t ' ;

CASE @order_by
WHEN 'asc' THEN
SET @sql = @sql || 'ORDER BY t.Surname ASC';
SET @msg = 'Sorted ascending by last name: ';
WHEN 'desc' THEN
SET @sql = @sql || 'ORDER BY t.Surname DESC';
SET @msg = 'Sorted ascending by last name: ';
END CASE;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 735


SQL statements

FOR loop_name AS SCROLL CURSOR USING @sql


DO
INSERT INTO temp_names( surnames ) VALUES( Surname );
MESSAGE( @msg || Surname ) ;
END FOR;
SELECT * FROM temp_names;
END ;

Calling the myproc procedure and specifying asc (for example, CALL myproc( 'asc' );) returns
the following results:

Surname

Ahmed

Barker

Barletta

Bertrand

Bigelow

Blaikie

Braun

Breault

Bucceri

Butterfield

FORWARD TO statement
Sends native syntax SQL statements to a remote server.

Syntax 1
FORWARD TO server-name sql-statement

Syntax 2
FORWARD TO [ server-name ]

Parameters
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 ({}) or single quotes.

736 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
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 SQL 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, execute FORWARD TO without a server-name specification.

If you encounter an error from the remote server while in passthrough mode, you must still execute a
FORWARD TO statement to turn passthrough off.

When establishing a connection to server-name on behalf of the user, the database server uses one of the
following:

● A remote login alias set using CREATE EXTERNLOGIN

● If a remote login alias is not set up, the name and password used to communicate with SQL 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.

Note
The FORWARD TO statement is a server directive and cannot be used in stored procedures, triggers,
events, or batches.

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 before the FORWARD TO statement is automatically
committed.

See also
● “PASSTHROUGH statement [SQL Remote]” on page 831

Example
The following example sends a SQL statement to the remote server RemoteASE:
FORWARD TO RemoteASE { SELECT * FROM titles };

The following example shows a passthrough session with the remote server aseprod:
FORWARD TO aseprod
SELECT * FROM titles

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 737


SQL statements

SELECT * FROM authors


FORWARD TO;

Standards and compatibility


● SQL/2008 Vendor extension.

FROM clause
Specifies the database tables or views involved in a DELETE, SELECT, or UPDATE statement. When
used within a SELECT statement, the FROM clause can also be used in a MERGE or INSERT statement.

Syntax
FROM table-expression, ...

table-expression :
table-name
| view-name
| procedure-name
| derived-table
| lateral-derived-table
| join-expression
| ( table-expression, ... )
| openstring-expression
| apply-expression
| contains-expression
| dml-derived-table

table-name :
[ userid.]table-name ]
[ [ AS ] correlation-name ]
[ WITH ( hint [...] ) ]
[ FORCE INDEX ( index-name ) ]

view-name :
[ userid.]view-name [ [ AS ] correlation-name ]
[ WITH ( table-hint ) ]

procedure-name :
[ owner.]procedure-name ( [ parameter, ... ] )
[ WITH ( column-name data-type, ... ) ]
[ [ AS ] correlation-name ]

derived-table :
( select-statement )
[ AS ] correlation-name [ ( column-name, ... ) ]

lateral-derived-table :
LATERAL ( select-statement | table-expression )
[ AS ] correlation-name [ ( column-name, ... ) ]

738 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

join-expression :
table-expression join-operator table-expression
[ ON join-condition ]

join-operator :
[ KEY | NATURAL ] [ join-type ] JOIN
| CROSS JOIN

join-type :
INNER
| LEFT [ OUTER ]
| RIGHT [ OUTER ]
| FULL [ OUTER ]

hint :
table-hint | index-hint

table-hint :
READPAST
| UPDLOCK
| XLOCK
| FASTFIRSTROW
| HOLDLOCK
| NOLOCK
| READCOMMITTED
| READUNCOMMITTED
| REPEATABLEREAD
| SERIALIZABLE

index-hint :
NO INDEX
| INDEX ( [ PRIMARY KEY | FOREIGN KEY ] index-name [, ...] ) [ INDEX ONLY { ON | OFF } ]
| CLUSTERED INDEX [ INDEX ONLY { ON | OFF } ]

openstring-expression :
OPENSTRING ( { FILE | VALUE } string-expression )
WITH ( rowset-schema )
[ OPTION ( scan-option ... ) ]
[ AS ] correlation-name

apply-expression :
table-expression { CROSS | OUTER } APPLY table-expression

contains-expression :
{ table-name | view-name } CONTAINS ( column-name [,...], contains-query ) [ [ AS ] score-correlation-
name ]

rowset-schema :
column-schema-list
| TABLE [owner.]table-name [ ( column-list ) ]

column-schema-list :
{ column-name user-or-base-type | filler( ) } [ , ... ]

column-list :
{ column-name | filler( ) } [ , ... ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 739


SQL statements

scan-option :
BYTE ORDER MARK { ON | OFF }
| COMMENTS INTRODUCED BY comment-prefix
| { COMPRESSED | AUTO | NOT COMPRESSED }
| DELIMITED BY string
| ENCODING encoding
| { ENCRYPTED KEY key-expression | NOT ENCRYPTED }
| ESCAPE CHARACTER character
| ESCAPES { ON | OFF }
| FORMAT { TEXT | BCP }
| HEXADECIMAL { ON | OFF }
| QUOTE string
| QUOTES { ON | OFF }
| ROW DELIMITED BY string
| SKIP integer
| STRIP { ON | OFF | LTRIM | RTRIM | BOTH }

key-expression : string | variable

contains-query : string

dml-derived-table :
( dml-statement ) REFERENCING ( [ table-version-names | NONE ] )

dml-statement :
insert-statement
delete-statement
update-statement
merge-statement

table-version-names :
OLD [ AS ] correlation-name [ FINAL [ AS ] correlation-name ]
| FINAL [ AS ] correlation-name

Parameters

● table-name A base table or temporary table. Tables owned by a different user can be qualified by
specifying the user ID. Tables owned by groups to which the current user belongs are found by default
without specifying the user ID.

● view-name Specifies a view to include in the query. As with tables, views owned by a different
user can be qualified by specifying the user ID. Views owned by groups to which the current user
belongs are found by default without specifying the user ID. Although the syntax permits table hints
on views, these hints have no effect.

● procedure-name A stored procedure that returns a result set. This clause applies to the FROM
clause of SELECT statements only. The parentheses following the procedure name are required even
if the procedure does not take parameters. DEFAULT can be specified in place of an optional
parameter.

If the stored procedure returns multiple result sets, only the first is used.

The WITH clause provides a way of specifying column name aliases for the procedure result set. If a
WITH clause is specified, the number of columns must match the number of columns in the procedure

740 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

result set, and the data types must be compatible with those in the procedure result set. If no WITH
clause is specified, the column names and types are those defined by the procedure definition. The
following query illustrates the use of the WITH clause:
SELECT sp.ident, sp.quantity, Products.name
FROM ShowCustomerProducts( 149 )
WITH ( ident INT, description CHAR(20), quantity INT ) sp
JOIN Products
ON sp.ident = Products.ID;

For embedded SQL applications. when you create a procedure without a RESULT clause and the
procedure returns a variable result set, a DESCRIBE of the SELECT statement referencing the
procedure may fail. To prevent the failure of the DESCRIBE, it is recommended that you include a
WITH clause that describes the expected result set schema.

● derived-table You can supply a SELECT statement instead of table or view name in the FROM
clause. A SELECT statement used in this way is called a derived table, and it must be given an alias.
For example, the following statement contains a derived table, MyDerivedTable, which ranks
products in the Products table by UnitPrice.
SELECT TOP 3 *
FROM ( SELECT Description,
Quantity,
UnitPrice,
RANK() OVER ( ORDER BY UnitPrice ASC )
AS Rank
FROM Products ) AS MyDerivedTable
ORDER BY Rank;

● lateral-derived-table A derived table, stored procedure, or joined table that may include
references to objects in the parent statement (outer references). You must use a lateral derived table if
you want to use an outer reference in the FROM clause.

You can use outer references only to tables that precede the lateral derived table in the FROM clause.
For example, you cannot use an outer reference to an item in the SELECT list.

The table and the outer reference must be separated by a comma. For example, the following queries
are valid:
SELECT *
FROM A, LATERAL( B LEFT OUTER JOIN C ON ( A.x = B.x ) ) myLateralDT;
SELECT *
FROM A, LATERAL( SELECT * FROM B WHERE A.x = B.x ) myLateralDT;
SELECT *
FROM A, LATERAL( procedure-name( A.x ) ) myLateralDT;

Specifying LATERAL (table-expression) is equivalent to specifying LATERAL (SELECT * FROM


table-expression).

● openstring-expression Specify an OPENSTRING clause to query within a file or a BLOB,


treating the content of these sources as a set of rows. When doing so, you also specify information
about the schema of the file or BLOB for the result set to be generated, since you are not querying a
defined structure such as a table or view. This clause applies to the FROM clause of a SELECT
statement. It is not supported for UPDATE or DELETE statements.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 741


SQL statements

The ROWID function is supported over the result set of a table generated by an OPENSTRING
expression.

The following subclauses and parameters of the OPENSTRING clause are used to define and query
data within files and BLOBs:

FILE and VALUE clauses Use the FILE clause to specify the file to query. Use the VALUE
clause to specify the BLOB expression to query. The data type for the BLOB expression is assumed to
be LONG BINARY. You can specify the READ_CLIENT_FILE function as a value to the VALUE
clause.

If neither the FILE nor VALUE keyword is specified, VALUE is assumed.

When using FORMAT SHAPEFILE, only FILE is assumed.

WITH clause Use this clause to specify the rowset schema (column names and data types) of the
data being queried. You can specify the columns directly (for example, WITH ( Surname
CHAR(30), GivenName CHAR(30) )). You can also use the TABLE subclause to reference a
table to use to obtain schema information from (for example, WITH TABLE dba.Employees
( Surname, GivenName )). You must own or have SELECT permissions on the table you
specify.

When specifying columns, you can specify filler( ) for columns you want to skip in the input data (for
example, WITH ( filler( ), Surname CHAR(30), GivenName CHAR(30) )).

OPTION clause Use the OPTION clause to specify parsing options to use for the input file, such
as escape characters, delimiters, encoding, and so on. Supported options comprise those options for
the LOAD TABLE statement that control the parsing of an input file.

● scan-option For information about each scan option, see the load options described in “LOAD
TABLE statement” on page 792.

● apply-expression Use this clause to specify a join condition where the right table-expression is
evaluated for every row in the left table-expression. For example, you can use an apply expression to
evaluate a function, procedure, or derived table for each row in a table expression.

● contains-expression Use the CONTAINS clause following a table name to filter the table and
return only those rows matching the full text query specified with contains-query. Every matching
row of the table is returned together with a score column that can be referred to using score-
correlation-name, if it is specified. If score-correlation-name is not specified, then the score column
can be referred to by the default correlation name, contains.

With the exception of the optional correlation name argument, the CONTAINS clause takes the same
arguments as those of the CONTAINS search condition.

There must be a text index on the columns listed in the CONTAINS clause.

The contains-query cannot be NULL or an empty string. If the text configuration settings cause all of
the terms in the contains-query to be dropped, rows from the base table referenced by the contains-
expression are not returned.

742 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

● correlation-name Use correlation-name to specify a substitute name for a table or view in the
FROM clause. The substitute name can then be referenced from elsewhere in the statement. For
example, emp and dep are correlation names for the Employees and Departments tables, respectively:

SELECT Surname, GivenName, DepartmentName


FROM Employees emp, Departments dep,
WHERE emp.DepartmentID=dep.DepartmentID;

● dml-statement Use dml-statement to specify the DML statement (INSERT, DELETE, UPDATE,
or MERGE) from which you want to select rows. During execution, the DML statement specified in
dml-derived-table is executed first, and the rows affected by that DML are materialized into a
temporary table whose columns are described by the REFERENCING clause. The temporary table
represents the result set of dml-derived-table.

Use REFERENCING ( ) or REFERENCING ( NONE ) if the results do not need to be materialized


into a temporary table because you are not referencing them in the query.

If you specify REFERENCING ( ) or REFERENCING ( NONE ), the updated rows are not
materialized into a temporary table that represents the result set of dml-derived-table because they are
not being referenced in the query. The temporary table in this case is an empty table. You can use this
feature if you want dml-statement to be executed before the main statement is executed.

In the results, OLD columns contain the values as seen by the scan that finds the rows to include in the
update operation. FINAL columns contain the values after referential integrity checks have been
made, computed and default columns have been updated, and all triggers have fired (excluding
AFTER triggers of type FOR STATEMENT).

Statement Supported table versions

INSERT FINAL

DELETE OLD

UPDATE FINAL and/or OLD

MERGE FINAL and/or OLD

When specifying both OLD and FINAL names, two correlation names are used; however, these are
not true correlations since they both refer to the same result set. If you specify REFERENCING (OLD
AS O FINAL AS F ), there is an implicit join predicate: O.rowid = F.rowid.

The INSERT statement only supports FINAL. Consequently the values of updated rows that are
modified by an INSERT ON EXISTING UPDATE statement do not appear in the result set of the
derived table. Instead, use the MERGE statement to perform the insert-else-update processing.

The dml-derived-table statement can only reference one updatable table; updates over multiple tables
return an error. Also, selecting from dml-statement is not allowed if the DML statement appears inside
a correlated subquery or common table expression because the semantics of these constructs can be
unclear.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 743


SQL statements

● WITH table-hint clause The WITH table-hint clause allows you to specify the behavior to be used
only for this table, and only for this statement. Use this clause to change the behavior without
changing the isolation level or setting a database or connection option. Table hints can be used for
base tables, temporary tables, and materialized views.

Caution
The WITH table-hint clause is an advanced feature that should be used only if needed, and only by
experienced database administrators. In addition, the setting may not be respected in all situations.

○ Isolation level related table hints The isolation level table hints are used to specify isolation
level behavior when querying tables. They specify a locking method that is used only for the
specified tables, and only for the current query. You cannot specify snapshot isolation levels as
table hints.

Following is the list of supported isolation level related table hints:

Table hint Description

HOLD- Sets the behavior to be equivalent to isolation level 3. This table hint is synony-
LOCK mous with SERIALIZABLE.

NOLOCK Sets the behavior to be equivalent to isolation level 0. This table hint is synony-
mous with READUNCOMMITTED.

READ- Sets the behavior to be equivalent to isolation level 1.


COMMIT-
TED

READPAST Instructs the database server to ignore, instead of block on, write-locked rows.
This table hint can only be used with isolation level 1. The READPAST hint is
respected only when the correlation name in the FROM clause refers to a base
or globally shared temporary table. In other situations (views, proxy tables, and
table functions) the READPAST hint is ignored. Queries within views may uti-
lize READPAST as long as the hint is specified for a correlation name that is a
base table. The use of the READPAST table hint can lead to anomalies due to
the interaction of locking and predicate evaluation within the server. In addition,
you cannot use the READPAST hint against tables that are the targets of a DE-
LETE, INSERT or UPDATE statement.

READUN- Sets the behavior to be equivalent to isolation level 0. This table hint is synony-
COMMIT- mous with NOLOCK.
TED

REPEATA- Sets the behavior to be equivalent to isolation level 2.


BLEREAD

SERIALIZ- Sets the behavior to be equivalent to isolation level 3. This table hint is synony-
ABLE mous with HOLDLOCK.

744 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Table hint Description

UPDLOCK Indicates that rows processed by the statement from the hinted table are locked
using intent locks. The affected rows remain locked until the end of the transac-
tion. UPDLOCK works at all isolation levels and uses intent locks.

XLOCK Indicates that rows processed by the statement from the hinted table are to be
locked exclusively. The affected rows remain locked until the end of the trans-
action. XLOCK works at all isolation levels and uses write locks.

Note
If you are writing queries for databases that participate in MobiLink synchronization, it is
recommended that you do not use the READPAST table hint in your synchronization scripts.

For more information, see:

● “download_cursor table event” [MobiLink - Server Administration]


● “download_delete_cursor table event” [MobiLink - Server Administration]
● “upload_fetch table event” [MobiLink - Server Administration]

If you are considering READPAST because your application performs many updates that affect
download performance, an alternative solution is to use snapshot isolation.

○ Optimization table hint (FASTFIRSTROW) The FASTFIRSTROW table hint allows you to
set the optimization goal for the query without setting the optimization_goal option to First-row.
When you use FASTFIRSTROW, SQL Anywhere chooses an access plan that is intended to
reduce the time to fetch the first row of the query's result.

● WITH ( index-hint ) clause The WITH ( index-hint ) clause allows you to specify index hints that
override the query optimizer plan selection algorithms, and tell the optimizer exactly how to access
the table using indexes. Index hints can be used for base tables, temporary tables, and materialized
views.

○ NO INDEX Use this clause to force a sequential scan of the table (indexes are not used).
Sequential scans may be very costly.

○ INDEX ( [ PRIMARY KEY | FOREIGN KEY ] index-name [,... ] ) Use this clause to specify
up to four indexes that the optimizer must use to satisfy the query.

If any of the specified indexes cannot be used, an error is returned.

You can specify PRIMARY KEY or FOREIGN KEY to remove ambiguity in the cases where the
PRIMARY KEY index and FOREIGN KEY index on a table have the same name.

If you specify an index name in the index hint, without the PRIMARY or FOREIGN key, and
multiple indexes with the same name exist on a table, the optimizer chooses the normal index. If a
normal index does not exist, the optimizer chooses the primary key index. If a primary key index
does not exist, the foreign key index is used instead.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 745


SQL statements

index-name can be qualified by specifying the user ID and the table name of the index.

The indexes specified in the INDEX clause must be indexes defined for that table; otherwise, an
error is returned. For example, FROM Products WITH( INDEX (Products.xx)) returns
an error if the index xx is not defined for the Products table. Likewise, FROM Products
WITH( INDEX (sales_order_items.sales_order_items)) returns an error
because the sales_order_items.sales_order_items index exists but is not defined for the Products
table.

○ INDEX ONLY { ON | OFF } Use this clause to control whether an index-only retrieval of data is
performed. If the INDEX ( index-name... ) clause is specified with INDEX ONLY ON, the
database server attempts an index-only retrieval using the specified indexes. If any of the specified
indexes cannot be used in satisfying an index-only retrieval, an error is returned (for example, if
there are no indexes, or if the existing indexes cannot satisfy the query).

Specify INDEX ONLY OFF to prevent an index-only retrieval.

● FORCE INDEX ( index-name ) The FORCE INDEX ( index-name ) syntax is provided for
compatibility, and does not support specifying more than one index. This clause is equivalent to WITH
( INDEX ( index-name)).

● CLUSTERED INDEX Use this clause to specify that the optimizer must use a clustered index if
one exists. The index name is not specified as only one clustered index can exist for a base table. If a
clustered index doesn't exist or it cannot be used, an error is returned.

Remarks
Subqueries are not allowed as arguments to a store procedures in the FROM clause. For example, the
following statement returns an error:

SELECT *, ( SELECT 12 x ) D
FROM sa_rowgenerator( 1,( SELECT 12 x ) ):

The SELECT, UPDATE, and DELETE statements require a table list to specify which tables are used by
the statement.

Note
Although the FROM clause description refers to tables, it also applies to views and derived tables unless
otherwise noted.

The FROM clause 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.

You cannot use an ON phrase with CROSS JOIN.

Permissions
The FILE clause of openstring-expression requires either DBA or READFILE authority.

746 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The TABLE clause of openstring-expression requires the user, to own or have SELECT permissions on,
the specified table.

Side effects
None.

See also
● “References to tables owned by groups” [SQL Anywhere Server - Database Administration]
● “CONTAINS search condition” on page 47
● “Text index concepts and reference” [SQL Anywhere Server - SQL Usage]
● “optimization_goal option” [SQL Anywhere Server - Database Administration]
● “Write locks” [SQL Anywhere Server - SQL Usage]
● “Intent locks” [SQL Anywhere Server - SQL Usage]
● “What to specify when creating or altering text configuration objects” [SQL Anywhere Server - SQL
Usage]
● “Example text configuration objects” [SQL Anywhere Server - SQL Usage]
● “SELECT over a DML statement” [SQL Anywhere Server - SQL Usage]
● “Data manipulation statements” [SQL Anywhere Server - SQL Usage]
● “Isolation levels and consistency” [SQL Anywhere Server - SQL Usage]
● “MobiLink isolation levels” [MobiLink - Server Administration]
● “LOAD TABLE statement” on page 792
● “DELETE statement” on page 678
● “SELECT statement” on page 871
● “UPDATE statement” on page 948
● “INSERT statement” on page 780
● “MERGE statement” on page 811
● “Querying derived tables” [SQL Anywhere Server - SQL Usage]
● “Joins: Retrieving data from several tables” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


SQL/2008 The FROM clause is a fundamental part of the SQL/2008 standard. The complexity of the
FROM clause means that you should check individual components of a FROM clause against the
appropriate portions of the standard. The following is a non-exhaustive list of optional SQL/2008
language features supported in SQL Anywhere:

○ CROSS JOIN, FULL OUTER JOIN, and NATURAL JOIN constitute optional SQL/2008 feature
F401.

○ INTERSECT and INTERSECT ALL constitute optional SQL/2008 feature F302.

○ EXCEPT ALL is optional language feature F304.

○ derived tables are SQL/2008 language feature F591.

○ procedures in the FROM clause (table functions) are feature T326. Note that the SQL/2008 standard
requires the keyword TABLE to identify the output of a procedure as a table expression, whereas in
SQL Anywhere the TABLE keyword is unnecessary.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 747


SQL statements

○ common table expressions are optional SQL/2008 language feature T121. Using a common table
expression in a derived table nested within another common table expression is language feature T122.

○ recursive table expressions are feature T131. Using a recursive table expression in a derived table
nested within a common table expression is optional SQL/2008 language feature T132.

The following components of the FROM clause are vendor extensions:

○ KEY JOIN.

○ CROSS APPLY and OUTER APPLY.

○ OPENSTRING.

○ a table-expression using CONTAINS (full text search).

○ specifying a dml-statement as a derived table.

○ all table hints, including the use of WITH, FORCE INDEX, READPAST and isolation level hints.

○ LATERAL ( table-expression ), which is a vendor extension. LATERAL ( select-statement ) is in the


SQL/2008 standard as optional SQL language feature T491.

Example
The following are valid FROM clauses:
...
FROM Employees
...

...
FROM Employees NATURAL JOIN Departments
...

...
FROM Customers
KEY JOIN SalesOrders
KEY JOIN SalesOrderItems
KEY JOIN Products
...

...
FROM Employees CONTAINS ( Street, ' Way ' )
...

The following query illustrates how to use derived tables in a query:


SELECT Surname, GivenName, number_of_orders
FROM Customers JOIN
( SELECT CustomerID, COUNT(*)
FROM SalesOrders
GROUP BY CustomerID )
AS sales_order_counts( CustomerID,
number_of_orders )
ON ( Customers.ID = sales_order_counts.CustomerID )
WHERE number_of_orders > 3;

748 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The following query illustrates how to select rows from stored procedure result sets:
SELECT t.ID, t.QuantityOrdered AS q, p.name
FROM ShowCustomerProducts( 149 ) t JOIN Products p
ON t.ID = p.ID;

The following example illustrates how to perform a query using the OPENSTRING clause to query a file.
The CREATE TABLE statement creates a table called testtable with two columns, column1 and
columns2. The UNLOAD statement creates a file called testfile.dat by unloading rows from the
RowGenerator table. The SELECT statement uses the OPENSTRING clause in a FROM clause to query
testfile.dat using the schema information from both the testtable and RowGenerator tables. The query
returns one row with the value 49.
CREATE TABLE testtable( column1 CHAR(10), column2 INT );
UNLOAD SELECT * FROM RowGenerator TO 'testfile.dat';
SELECT A.column2
FROM OPENSTRING( FILE 'testfile.dat' )
WITH ( TABLE testtable( column2 ) ) A, RowGenerator B
WHERE A.column2 = B.row_num
AND A.column2 < 50
AND B.row_num > 48;

The following example illustrates how to perform a query using the OPENSTRING clause to query a
string value. The SELECT statement uses the OPENSTRING clause in a FROM clause to query a string
value using the schema information provided in the WITH clause. The query returns two columns with
three rows.
SELECT *
FROM OPENSTRING( VALUE '1,"First"$2,"Second"$3,"Third"')
WITH (c1 INT, c2 VARCHAR(30))
OPTION ( DELIMITED BY ',' ROW DELIMITED BY '$')
AS VALS

The following example illustrates how to perform a query to select the rows modified by a data
manipulation statement. In this example, a warning is issued when the stock of blue items drops by more
than half.
SELECT old_products.name, old_products.quantity, final_products.quantity
FROM
( UPDATE Products SET quantity = quantity - 10 WHERE color = 'Blue' )
REFERENCING ( OLD AS old_products FINAL AS final_products )
WHERE final_products.quantity < 0.5 * old_products.quantity;

GET DATA statement [ESQL]


Gets string or binary data for one column of the current row of a cursor.

Syntax
GET DATA cursor-name
COLUMN column-num
OFFSET start-offset
[ WITH TEXTPTR ]
{ USING DESCRIPTOR sqlda-name | INTO hostvar, ... }

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 749


SQL statements

cursor-name : identifier | hostvar

column-num : integer | hostvar

start-offset : integer | hostvar

sqlda-name : identifier

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.

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;

The WITH TEXTPTR clause can only be used 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.

USING DESCRIPTOR clause The sqlda-name specifies the SQLDA (SQL Descriptor Area) that
receives the fetched data. The USING DESCRIPTOR clause provides a dynamic method of specifying
host variables to receive fetched data.

INTO clause Use the INTO clause to specify the host variable that receives the fetched data. The
indicator value for the target host variable is of type a_sql_len, which is currently a 16-bit value, so it is
not always large enough to 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.

Similarly, if a LONG VARCHAR, LONG NVARCHAR, or LONG BINARY host variable is used with
an offset greater than zero, the untrunc_len field does not accurately indicate the size before truncation.

Remarks
Get a piece of one column value from the row at the current cursor position. The cursor must be opened
and positioned on a row, using FETCH.

GET DATA is usually used to fetch LONG BINARY or LONG VARCHAR fields.

Permissions
None.

750 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
None.

See also
● “FETCH statement [ESQL] [SP]” on page 728
● “READTEXT statement [T-SQL]” on page 842
● “SET statement” on page 899
● “INTO clause” on page 750

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example uses GET DATA to fetch a binary large object (also called a BLOB).
EXEC SQL BEGIN DECLARE SECTION;
DECL_BINARY(1000) piece;
short ind;

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;

GET DESCRIPTOR statement [ESQL]


Retrieves information about a variable within a descriptor area, or retrieves its value.

Syntax
GET DESCRIPTOR descriptor-name
{ hostvar = COUNT | VALUE { integer | hostvar } assignment, ... }

assignment :
hostvar =
TYPE
| LENGTH
| PRECISION
| SCALE

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 751


SQL statements

| DATA
| INDICATOR
| NAME
| NULLABLE
| RETURNED_LENGTH

descriptor-name : identifier

Remarks
The GET DESCRIPTOR statement is used to retrieve information about a variable within a descriptor
area, or to retrieve its value.

The value { integer | hostvar } specifies the variable in the descriptor area about which the information is
retrieved. Type checking is performed when doing GET...DATA to ensure that the host variable and the
descriptor variable have the same data type. LONG VARCHAR and LONG BINARY are not supported
by GET DESCRIPTOR...DATA.

If an error occurs, it is returned in the SQLCA.

Permissions
None.

Side effects
None.

See also
● “ALLOCATE DESCRIPTOR statement [ESQL]” on page 398
● “DEALLOCATE DESCRIPTOR statement [ESQL]” on page 665
● “SET DESCRIPTOR statement [ESQL]” on page 882
● “The SQL descriptor area (SQLDA)” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 GET DESCRIPTOR is part of optional SQL/2008 language feature B031, "Basic
dynamic SQL".

Example
The following example returns the type of the column with position col_num in sqlda.
int get_type( SQLDA *sqlda, int col_num )
{
EXEC SQL BEGIN DECLARE SECTION;
int ret_type;
int col = col_num;
EXEC SQL END DECLARE SECTION;
EXEC SQL GET DESCRIPTOR sqlda VALUE :col :ret_type = TYPE;
return( ret_type );
}

752 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

GET OPTION statement [ESQL]


Gets the current setting of an option. It is recommended that you use the CONNECTION_PROPERTY
function instead.

Syntax
GET OPTION [ userid.]option-name
{ INTO hostvar | USING DESCRIPTOR sqlda-name }

userid : identifier, string | hostvar

option-name :
identifier
| string
| hostvar

hostvar : indicator variable allowed

sqlda-name : identifier

Remarks
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 is 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.

Permissions
None required.

Side effects
None.

See also
● “SET OPTION statement” on page 886
● “Alphabetical list of system procedures” on page 1001
● “CONNECTION_PROPERTY function [System]” on page 171

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement illustrates use of GET OPTION.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 753


SQL statements

EXEC SQL GET OPTION 'date_format' INTO :datefmt;

GOTO statement [T-SQL]


Branches to a labeled statement.

Syntax
label : GOTO label

Remarks
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.

If you nest compound statements, you can only go to (GOTO) labels within the current compound
statement and any of its ancestor compound statements. You cannot go to labels located in other
compound statements that are nested within the ancestors.

Permissions
None.

Side effects
None.

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following Transact-SQL batch prints the message "yes" in the database server messages window four
times:
DECLARE @count SMALLINT
SELECT @count = 1
restart:
PRINT 'yes'
SELECT @count = @count + 1
WHILE @count <=4
GOTO restart

GRANT CONSOLIDATE statement [SQL Remote]


Identifies the database immediately above the current database in a SQL Remote hierarchy, that will
receive messages from the current database.

Syntax
GRANT CONSOLIDATE
TO userid

754 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

TYPE message-system, ...


ADDRESS address-string, ...
[ SEND { EVERY | AT } hh:mm:ss ]

message-system :
FILE | FTP | SMTP

address : string

Parameters
userid The user ID for the user to be granted the permission.

message-system One of the message systems supported by SQL Remote.

address The address for the specified message system.

Remarks
In a SQL Remote installation, the database immediately above the current database in a SQL Remote
hierarchy must be granted CONSOLIDATE permissions. GRANT CONSOLIDATE is issued at a remote
database to identify its consolidated database. Each database can have only one user ID with
CONSOLIDATE permissions: you cannot have a database that is a remote database for more than one
consolidated database.

The consolidated user is identified by a message system, identifying the method by which messages are
sent to and received from the consolidated user. The address-name must be a valid address for the
message-system, enclosed in single quotes. There can be only one consolidated user per remote database.

For the FILE message type, the address is a subdirectory of the directory pointed to by the SQLREMOTE
environment variable.

The GRANT CONSOLIDATE statement is required for the consolidated database to receive messages,
but does not by itself subscribe the consolidated database to any data. To subscribe to data, a subscription
must be created for the consolidated user ID to one of the publications in the current database. Running
the database extraction utility at a consolidated database creates a remote database with the proper
GRANT CONSOLIDATE statement already executed.

The optional SEND EVERY and SEND AT clauses specify a frequency at which messages are sent. The
string contains a time that is a length of time between messages (for SEND EVERY) or a time of day at
which messages are sent (for SEND AT). With SEND AT, messages are sent once per day.

If a user has been granted remote permissions without a SEND EVERY or SEND AT clause, the Message
Agent processes messages, and then stops. To run the Message Agent continuously, you must ensure that
every user with REMOTE permission has either a SEND AT or SEND EVERY frequency specified.

It is anticipated that at many remote databases, the Message Agent is run periodically, and that the
consolidated database will have no SEND clause specified.

Permissions
DBA authority

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 755


SQL statements

Side effects
Automatic commit.

See also
● “CONSOLIDATE permission” [SQL Remote]
● “GRANT PUBLISH statement [SQL Remote]” on page 756
● “GRANT REMOTE statement [SQL Remote]” on page 758
● “REVOKE CONSOLIDATE statement [SQL Remote]” on page 860
● “ALTER REMOTE MESSAGE TYPE statement [SQL Remote]” on page 426
● “CREATE REMOTE MESSAGE TYPE statement [SQL Remote]” on page 596
● “CREATE SUBSCRIPTION statement [SQL Remote]” on page 626
● “Granting CONSOLIDATE permission” [SQL Remote]
● “SQL Remote message systems” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
GRANT CONSOLIDATE TO con_db
TYPE SMTP
ADDRESS 'Singer, Samuel';

GRANT PUBLISH statement [SQL Remote]


Identifies the publisher of the current database.

Syntax
GRANT PUBLISH TO userid

Remarks
Each database in a SQL Remote installation is identified in outgoing messages by a user ID, called the
publisher. The GRANT PUBLISH statement identifies the publisher user ID associated with these
outgoing messages.

Only one user ID can have PUBLISH authority. The user ID with PUBLISH authority is identified by the
special value CURRENT PUBLISHER. The following query identifies the current publisher:
SELECT CURRENT PUBLISHER;

If there is no publisher, the special constant is NULL.

The CURRENT PUBLISHER special value can be used as a default setting for columns. It is often useful
to have a CURRENT PUBLISHER column as part of the primary key for replicating tables, as this helps
prevent primary key conflicts due to updates at more than one site.

To change the publisher, you must first drop the current publisher using the REVOKE PUBLISH
statement, and then create a new publisher using the GRANT PUBLISH statement.

756 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “PUBLISH permission” [SQL Remote]
● “GRANT CONSOLIDATE statement [SQL Remote]” on page 754
● “REVOKE PUBLISH statement [SQL Remote]” on page 860
● “CREATE SUBSCRIPTION statement [SQL Remote]” on page 626
● “CURRENT PUBLISHER special value” on page 59
● “CREATE REMOTE MESSAGE TYPE statement [SQL Remote]” on page 596
● “GRANT REMOTE statement [SQL Remote]” on page 758
● “Creating a publisher” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
GRANT PUBLISH TO publisher_ID;

GRANT REMOTE DBA statement [MobiLink] [SQL Remote]


Grants remote DBA privileges to a user ID.

Syntax
GRANT REMOTE DBA
TO userid, ...
[ IDENTIFIED BY password ]

Parameters
IDENTIFIED BY clause The IDENTIFIED BY clause is optional for this statement. If included, the
password for the user is changed.

Remarks
A user ID with REMOTE DBA authority has full DBA authority only:

● In MobiLink, when the connection is made from the SQL Anywhere synchronization client (dbmlsync)
utility. The REMOTE DBA authority enables dbmlsync to have full access to the database. Any other
connection using the same user ID is granted no special authority.

● In SQL Remote, when the connection is made from the Message Agent. The REMOTE DBA authority
enables the Message Agent to have full access to the database to make any changes contained in the
messages. Any other connection using the same user ID is granted no special authority.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 757


SQL statements

The REMOTE DBA authority avoids having to grant full DBA authority to the user ID, thereby avoiding
security problems associated with distributing DBA user IDs and passwords.

For example, a SQL Remote user ID with REMOTE DBA authority has no extra permissions on any
connection apart from the Message Agent. Even if the user ID and password for a REMOTE DBA user is
widely distributed, there is no security problem. As long as the user ID has no permissions beyond
CONNECT granted on the database, no one can use this user ID to access data in the database.

Permissions
Must have DBA authority.

Side effects
Automatic commit.

See also
● MobiLink: “Synchronization initiation” [MobiLink - Client Administration]
● SQL Remote: “REMOTE DBA authority” [SQL Remote]
● SQL Remote: “Granting REMOTE DBA authority” [SQL Remote]
● SQL Remote: “Revoke REMOTE DBA authority” [SQL Remote]
● SQL Remote: “SQL Remote Message Agent (dbremote) modes” [SQL Remote]
● SQL Remote: “Security” [SQL Remote]
● “REMOTE DBA authority” [SQL Anywhere Server - Database Administration]
● “REVOKE REMOTE DBA statement [SQL Remote]” on page 861
● “Permissions for dbmlsync” [MobiLink - Client Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
You can grant REMOTE DBA authority to a user ID named dbremote as follows:
GRANT REMOTE DBA
TO dbremote
IDENTIFIED BY dbremote;

GRANT REMOTE statement [SQL Remote]


Identifies a database immediately below the current database in a SQL Remote hierarchy, that will receive
messages from the current database. These are called remote users.

Syntax
GRANT REMOTE TO userid, ...
TYPE message-system, ...
ADDRESS address-string, ...
[ SEND { EVERY | AT } send-time ]

758 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Parameters
userid The user ID for the user to be granted the permission

message-system One of the message systems supported by SQL Remote. It must be one of the
following values:

○ FILE
○ FTP
○ SMTP

address-string A string containing a valid address for the specified message system.

send-time A string containing a time specification in the form hh:mm:ss.

Remarks
In a SQL Remote installation, each database receiving messages from the current database must be
granted REMOTE permissions.

The single exception is the database immediately above the current database in a SQL Remote hierarchy,
which must be granted CONSOLIDATE permissions.

The remote user is identified by a message system, identifying the method by which messages are sent to
and received from the consolidated user. The address-name must be a valid address for the message-
system, enclosed in single quotes.

For the FILE message type, the address is a subdirectory of the directory pointed to by the SQLREMOTE
environment variable.

The GRANT REMOTE statement is required for the remote database to receive messages, but does not
by itself subscribe the remote user to any data. To subscribe to data, a subscription must be created for the
user ID to one of the publications in the current database, using the database extraction utility or the
CREATE SUBSCRIPTION statement.

The optional SEND EVERY and SEND AT clauses specify a frequency at which messages are sent. The
string contains a time that is a length of time between messages (for SEND EVERY) or a time of day at
which messages are sent (for SEND AT). With SEND AT, messages are sent once per day.

If a user has been granted remote permissions without a SEND EVERY or SEND AT clause, the Message
Agent processes messages, and then stops. To run the Message Agent continuously, you must ensure that
every user with REMOTE permission has either a SEND AT or SEND EVERY frequency specified.

It is anticipated that at many consolidated databases, the Message Agent is run continuously, so that all
remote databases would have a SEND clause specified. A typical setup may involve sending messages to
laptop users daily (SEND AT) and to remote servers every hour or two (SEND EVERY). You should use
as few different times as possible, for efficiency.

Permissions
DBA authority

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 759


SQL statements

Side effects
Automatic commit.

See also
● “REMOTE permission” [SQL Remote]
● “Granting REMOTE permission” [SQL Remote]
● “Subscriptions” [SQL Remote]
● “Setting the send frequency” [SQL Remote]
● “SQL Remote message systems” [SQL Remote]
● “GRANT PUBLISH statement [SQL Remote]” on page 756
● “REVOKE REMOTE statement [SQL Remote]” on page 862
● “GRANT CONSOLIDATE statement [SQL Remote]” on page 754
● “CREATE SUBSCRIPTION statement [SQL Remote]” on page 626
● “CREATE REMOTE MESSAGE TYPE statement [SQL Remote]” on page 596

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement grants remote permissions to user SamS, using an SMTP email system, sending
messages to the address Singer, Samuel once every two hours:
GRANT REMOTE TO SamS
TYPE SMTP
ADDRESS 'Singer, Samuel'
SEND EVERY '02:00';

GRANT statement
Grants membership in groups, creates new user IDs, grants or changes permissions for specified users,
and creates or changes passwords.

Syntax 1 - Grant authorities

GRANT authority, ...


TO userid, ...

authority :
BACKUP
| DBA
| PROFILE
| READCLIENTFILE
| READFILE
| [ RESOURCE | ALL ]
| VALIDATE
| WRITECLIENTFILE

760 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax 2 - Grant group status or membership in a group


GRANT { GROUP | MEMBERSHIP IN GROUP userid, ... }
TO userid, ...

Syntax 3 - Grant table and view permissions

GRANT permission, ...


ON [ owner.]object-name
TO userid, ...
[ WITH GRANT OPTION ]
[ FROM userid ]

permission :
ALL [ PRIVILEGES ]
| ALTER
| DELETE
| INSERT
| REFERENCES [ ( column-name, ... ) ]
| SELECT [ ( column-name, ... ) ]
| UPDATE [ ( column-name, ... ) ]

Syntax 4 - Grant execute permission

GRANT EXECUTE ON [ owner.]{ procedure-name | user-defined-function }


TO userid, ...

Syntax 5 - Grant integrated login

GRANT INTEGRATED LOGIN TO user-profile-name, ...


AS USER userid

Syntax 6 - Grant Kerberos login

GRANT KERBEROS LOGIN TO client-Kerberos-principal, ...


AS USER userid

Syntax 7 - Grant connect permissions

GRANT CONNECT TO userid, ...


[ AT starting-id ]
[ IDENTIFIED BY password, ... ]

Syntax 8 - Grant creation permission on a dbspace

GRANT CREATE ON dbspace-name


TO userid, ...

Syntax 9 - Grant permission on a sequence

GRANT USAGE ON SEQUENCE sequence-name


TO userid, ...

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 761


SQL statements

Parameters
AT starting-id clause 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 AT starting-id clause is used by the Unload utility.

GRANT authority clause Use this clause to grant one of the authorities listed below:

○ BACKUP authority This authority grants the user the ability to back up the database.

○ DBA authority This authority grants the user the ability to perform all tasks. This is usually
reserved for the person in the organization who is looking after the database.

○ PROFILE authority This authority grants the user the ability to perform profiling and diagnostic
operations.

○ READCLIENTFILE authority This authority grants the user the ability to read from a file on the
client computer, for example when loading data.

○ READFILE authority This authority grants the user the ability to execute a SELECT statement on
a file using the OPENSTRING clause.

○ RESOURCE or ALL authority This authority grants the user the ability to create tables and views.
ALL is a synonym for RESOURCE that is compatible with Adaptive Server Enterprise.

○ VALIDATE authority This authority grants the user the ability to perform the validation operations
supported by the various VALIDATE statements, such as validating the database, validating tables
and indexes, and validating checksums. It also allows the user to use the Validation utility (dbvalid),
and the Validate Database wizard in Sybase Central.

○ WRITECLIENTFILE authority This authority grants the user the ability to write to a file on the
client computer, for example when unloading data.

GROUP clause This permission allows the user(s) to have members.

MEMBERSHIP IN GROUP clause This permission grants a user membership in a group. The user
inherits the inheritable permissions and authorities set at the group level.

GRANT permission clause The GRANT permission clause allows you to grant permission on
individual tables or views. The table and view permissions can be specified individually, or you can use
ALL to grant all permissions at once. The following is a list of permissions that can be granted:

○ ALL permission This permission grants ALTER, DELETE, INSERT, REFERENCES, SELECT,
and UPDATE permissions on tables. This permission grants DELETE, INSERT, and UPDATE
permissions on views.

○ ALTER permission This permission allows the user to alter the named table with the ALTER
TABLE statement. This permission is not allowed for views.

○ DELETE permission This permission allows the user to delete rows from the named table or
view.

762 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ INSERT permission This permission allows the user to insert rows into the named table or view.

○ REFERENCES permission This permission allows the user to create indexes on the named table
and on the foreign keys that reference the named tables. If column names are specified, the user can
reference only those columns. REFERENCES permissions on columns cannot be granted for views,
only for tables. INDEX is a synonym for REFERENCES.

○ SELECT permission This permission allows the user to view information in the view or table. If
column names are specified, the users are allowed to view only those columns. SELECT permissions
on columns cannot be granted for views, only for tables.

○ UPDATE permission This permission allows the user to update rows in the view or table. If
column names are specified, the user can update only those columns.

WITH GRANT OPTION clause If WITH GRANT OPTION is specified, then the named user ID is
also given permission to GRANT the same permissions to other user IDs. Members of groups do not
inherit the WITH GRANT OPTION if it is granted to a group.

FROM clause If FROM userid is specified, the userid is recorded as a grantor user ID in the system
tables. This clause is for use by the Unload utility (dbunload). Do not use or modify this option directly.

CONNECT TO clause

Note
It is recommended that you use the CREATE USER statement to create users.

Creates a new user. GRANT CONNECT can also be used by any user to change their own password. To
create a user with an empty string as the password, use:
GRANT CONNECT TO userid IDENTIFIED BY "";

To create a user with no password, use:


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. A user ID must be a valid identifier.

○ User IDs cannot:

● begin with white space, single quotes, or double quotes


● end with white space
● contain semicolons

○ Passwords are case-sensitive and they cannot:

● begin with white space, single quotes, or double quotes


● end with white space
● contain semicolons
● be longer than 255 bytes in length

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 763


SQL statements

The verify_password_function option can be used to specify a function to implement password rules (for
example, passwords must include at least one digit). If a password verification function is used, you
cannot specify more than one user ID and password in the GRANT CONNECT statement.

CREATE ON clause Allows users to create database objects in the specified dbspace. The CREATE
permission can be inherited through group membership. Before a user can create objects, they must also
have RESOURCE authority.

GRANT USAGE ON SEQUENCE clause Allows users to evaluate the current or next value in a
sequence. You must have DBA authority or be the creator of the sequence to execute this statement. If the
sequence is part of a DEFAULT clause on a table, any user that inserts a row into the table must have
permission on the sequence.

Remarks
The GRANT statement is used to grant database permissions and authorities to individual user IDs and
groups. It is also used to create users and groups.

You can grant permissions on disabled objects. Permissions on disabled objects are stored in the database
and become effective when the object is enabled.

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 user or group profiles and an existing database user ID, allowing users who successfully log in
to their local computer to connect to a database without having to provide a user ID or password. The
user-profile-name can be of the form domain\user-name. The database user ID the integrated login is
mapped to must have a password.

Syntax 6 of the GRANT statement creates a Kerberos authenticated login mapping from one or more
Kerberos principals to an existing database user ID. This allows users who have successfully logged in to
Kerberos (users who have a valid Kerberos ticket-granting ticket) to connect to a database without having
to provide a user ID or password. The database user ID the Kerberos login is mapped to must have a
password. The client-Kerberos-principal must have the format user/instance@REALM, where /instance is
optional. The full principal, including the realm, must be specified, and principals that differ only in the
instance or realm are treated as different.

Principals are case sensitive and must be specified in the correct case. Mappings for multiple principals
that differ only in case are not supported (for example, you cannot have mappings for both
[email protected] and [email protected]).

If no explicit mapping is made for a Kerberos principal, and the Guest database user ID exists and has a
password, then the Kerberos principal connects using the Guest database user ID (the same Guest
database user ID as for integrated logins).

Permissions
● Syntax 3 If the FROM clause is specified, you must have DBA authority. Otherwise, you must
either own the table, or have been granted permissions on the table WITH GRANT OPTION.

● Syntax 4 You must either own the procedure, or have DBA authority.

764 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

● Syntax 5 and 6 You must have DBA authority.

● Syntax 7 You must either be changing your own password using GRANT CONNECT, or have
DBA authority.

Side effects
Automatic commit.

See also
● “BACKUP authority” [SQL Anywhere Server - Database Administration]
● “CREATE USER statement” on page 658
● “RESOURCE authority” [SQL Anywhere Server - Database Administration]
● “verify_password_function option” [SQL Anywhere Server - Database Administration]
● “Groups” [SQL Anywhere Server - Database Administration]
● “Kerberos authentication” [SQL Anywhere Server - Database Administration]
● “Groups” [SQL Anywhere Server - Database Administration]
● “WRITECLIENTFILE authority” [SQL Anywhere Server - Database Administration]
● “VALIDATE authority” [SQL Anywhere Server - Database Administration]
● “RESOURCE authority” [SQL Anywhere Server - Database Administration]
● “READFILE authority” [SQL Anywhere Server - Database Administration]
● “PROFILE authority” [SQL Anywhere Server - Database Administration]
● “READCLIENTFILE authority” [SQL Anywhere Server - Database Administration]
● “DBA authority” [SQL Anywhere Server - Database Administration]
● “Use of a sequence to generate unique values” [SQL Anywhere Server - SQL Usage]
● “Windows integrated logins” [SQL Anywhere Server - Database Administration]
● “REVOKE statement” on page 863
● “Permissions” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Syntax 3 is a core feature of the SQL/2008 standard. With Syntax 3, the FROM clause is
a vendor extension, as is the ALTER privilege. In the SQL/2008 standard, rather than the optional
ALL PRIVILEGES syntax, the PRIVILEGES keyword is mandatory.

Syntax 4 is also a core feature of SQL/2008, used for granting EXECUTE permissions on stored
procedures.

Syntax 9 is part of optional SQL/2008 language feature T176.

All other syntaxes are vendor extensions.

Example
Create a new database user.
GRANT CONNECT TO SQLTester
IDENTIFIED BY welcome

Grant permissions on the Employees table to user Laurel.


GRANT
SELECT, UPDATE ( Street )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 765


SQL statements

ON Employees
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;

GROUP BY clause
Groups columns, alias names, and functions as part of the SELECT statement.

Syntax
GROUP BY
| group-by-term, ... ]
| simple-group-by-term, ... WITH ROLLUP
| simple-group-by-term, ... WITH CUBE
|GROUPING SETS ( group-by-term, ... )

group-by-term :
simple-group-by-term
| ( simple-group-by-term, ... )
| ROLLUP ( simple-group-by-term, ... )
| CUBE ( simple-group-by-term, ... )

simple-group-by-term :
expression
| ( expression )
|()

Parameters
GROUPING SETS clause The GROUPING SETS clause allows you to perform aggregate operations
on multiple groupings from a single query specification. Each set specified in a GROUPING SET clause
is equivalent to a GROUP BY clause.

For example, the following two queries are equivalent:


SELECT a, b, SUM( c ) FROM t
GROUP BY GROUPING SETS ( ( a, b ), ( a ), ( b ), ( ) );
SELECT a, b, SUM( c ) FROM t
GROUP BY a, b
UNION ALL
SELECT a, NULL, SUM( c ) FROM t
GROUP BY a
UNION ALL
SELECT NULL, b, SUM( c ) FROM t
GROUP BY b
UNION ALL
SELECT NULL, NULL, SUM( c ) FROM t;

A grouping expression may be reflected in the result set as a NULL value, depending on the grouping in
which the result row belongs. This may cause confusion over whether the NULL is the result of another

766 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

grouping, or whether the NULL is the result of an actual NULL value in the underlying data. To
distinguish between NULL values present in the input data and NULL values inserted by the grouping
operator, use the GROUPING function.

Specifying an empty set of parentheses ( ) in the GROUPING SETS clause returns a single row
containing the overall aggregate.

ROLLUP clause The ROLLUP clause is similar to the GROUPING SETS clause in that it can be used
to specify multiple grouping specifications within a single query specification. A ROLLUP clause of n
simple-group-by-terms generates n+1 grouping sets, formed by starting with the empty parentheses, and
then appending successive group-by-terms from left to right.

For example, the following two statements are equivalent:


SELECT a, b, SUM( c ) FROM t
GROUP BY ROLLUP ( a, b );

SELECT a, b, SUM( c ) FROM t


GROUP BY GROUPING SETS ( ( a, b ), a, ( ) );

You can use a ROLLUP clause within a GROUPING SETS clause.

CUBE clause The CUBE clause is similar to the ROLLUP and GROUPING SETS clauses in that it
can be used to specify multiple grouping specifications within a single query specification. The CUBE
clause is used to represent all possible combinations that can be made from the expressions listed in the
CUBE clause.

For example, the following two statements are equivalent:


SELECT a, b, SUM( c ) FROM t
GROUP BY CUBE ( a, b, c );

SELECT a, b, SUM( c ) FROM t


GROUP BY GROUPING SETS ( ( a, b, c ), ( a, b ), ( a, c ),
( b, c ), a, b, c, () );

You can use a CUBE clause within a GROUPING SETS clause.

WITH ROLLUP clause This is an alternative syntax to the ROLLUP clause, and is provided for
Transact-SQL compatibility.

WITH CUBE clause This is an alternate syntax to the CUBE clause, and is provided for Transact-SQL
compatibility.

Remarks
When using the GROUP BY clause, you can group by expressions (with some limitations), columns, alias
names, or functions. The result of the query contains one row for each distinct value (or set of values) of
each grouping set.

The empty GROUP BY list, (), signifies the treatment of the entire input as a single group. For example,
the following two statements are equivalent:
SELECT COUNT(), SUM(Salary) FROM Employees;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 767


SQL statements

SELECT COUNT(), SUM(Salary) FROM Employees GROUP BY ();

See also
● “Summarizing, grouping, and sorting query results” [SQL Anywhere Server - SQL Usage]
● “SELECT statement” on page 871
● “GROUP BY clause extensions” [SQL Anywhere Server - SQL Usage]
● “GROUPING function [Aggregate]” on page 231
● “GROUP BY and the SQL/2008 standard” [SQL Anywhere Server - SQL Usage]
● “Specifying an empty grouping specification” [SQL Anywhere Server - SQL Usage]
● “The CUBE clause” [SQL Anywhere Server - SQL Usage]
● “The ROLLUP clause” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 GROUP BY is a core feature of the SQL/2008 standard. GROUPING SETS, GROUP
BY (), ROLLUP, and CUBE constitute portions of optional SQL/2008 language feature T431. SQL
Anywhere does not support optional SQL/2008 language feature T432, "Nested and concatenated
GROUPING SETS".

Vendor extensions to the GROUP BY clause include:

○ WITH ROLLUP

○ WITH CUBE

○ the ability to specify arbitrary expressions as GROUP BY terms. In the SQL/2008 standard, every
GROUP BY term must be a column reference from an underlying table in the query's FROM
clause.

Examples
The following example returns a result set showing the total number of orders, and then provides subtotals
for the number of orders in each year (2000 and 2001).
SELECT year ( OrderDate ) Year, Quarter ( OrderDate ) Quarter, count(*)
Orders
FROM SalesOrders
GROUP BY ROLLUP ( Year, Quarter )
ORDER BY Year, Quarter;

Like the preceding ROLLUP operation example, the following CUBE query example returns a result set
showing the total number of orders and provides subtotals for the number of orders in each year (2000 and
2001). Unlike ROLLUP, this query also gives subtotals for the number of orders in each quarter (1, 2, 3,
and 4).
SELECT year (OrderDate) Year, Quarter ( OrderDate ) Quarter, count(*) Orders
FROM SalesOrders
GROUP BY CUBE ( Year, Quarter )
ORDER BY Year, Quarter;

The following example returns a result set that gives subtotals for the number of orders in the years 2000
and 2001. The GROUPING SETS operation lets you select the columns to be subtotaled instead of
returning all combinations of subtotals like the CUBE operation.

768 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

SELECT year (OrderDate) Year, Quarter ( OrderDate ) Quarter, count(*) Orders


FROM SalesOrders
GROUP BY GROUPING SETS ( ( Year, Quarter ), ( Year ) )
ORDER BY Year, Quarter;

HELP statement [Interactive SQL]


Provides help in the Interactive SQL environment.

Syntax
HELP [ 'topic' ]

Remarks
The HELP statement is used to access SQL Anywhere documentation.

The topic for help can be optionally specified. You must enclose topic in single quotes. In some help
formats, the topic cannot be specified; in this case, a link to a general help page for Interactive SQL
appears.

You can specify the following topic values:

● SQL Anywhere error codes


● SQL statement keywords (such as INSERT, UPDATE, SELECT, CREATE DATABASE)

Permissions
None.

Side effects
None.

See also
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

IF statement
Controls conditional execution of SQL statements.

Syntax
IF search-condition THEN statement-list
[ ELSEIF { search-condition | operation-type } THEN statement-list ] ...
[ ELSE statement-list ]
{ END IF | ENDIF }

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 769


SQL statements

Remarks
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.

Note
Do not confuse the syntax of the IF statement with that of the IF expression.

Permissions
None.

Side effects
None.

See also
● “BEGIN statement” on page 484
● “IF expressions” on page 15
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]
● “Search conditions” on page 32

Standards and compatibility


● SQL/2008 The IF statement is part of optional SQL/2008 language feature P002, "Computational
completeness". The ENDIF keyword is a vendor extension.

Example
The following procedure illustrates the use of the IF statement:
CREATE PROCEDURE TopCustomer2 (OUT TopCompany CHAR(35), OUT TopValue INT)
BEGIN
DECLARE err_notfound EXCEPTION
FOR SQLSTATE '02000';
DECLARE curThisCust CURSOR FOR
SELECT CompanyName, CAST( sum(SalesOrderItems.Quantity *
Products.UnitPrice) AS INTEGER) VALUE
FROM Customers
LEFT OUTER JOIN SalesOrders
LEFT OUTER JOIN SalesOrderItems
LEFT OUTER JOIN Products
GROUP BY CompanyName;
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;

770 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

END IF;
IF ThisValue > TopValue THEN
SET TopValue = ThisValue;
SET TopCompany = ThisCompany;
END IF;
END LOOP CustomerLoop;
CLOSE curThisCust;
END;

IF statement [T-SQL]
Controls conditional execution of a SQL statement, as an alternative to the Watcom SQL IF statement.

Syntax
IF expression statement
[ ELSE [ IF expression ] statement ]

Remarks
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.

Permissions
None.

Side effects
None.

Standards and compatibility


● SQL/2008 Transact-SQL extension.

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'

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 771


SQL statements

ELSE IF @v1 = 1
PRINT '1'
ELSE
PRINT 'other'
/* Watcom SQL IF statement */
IF v1 = 0 THEN
PRINT '0'
ELSEIF v1 = 1 THEN
PRINT '1'
ELSE
PRINT 'other'
END IF

INCLUDE statement [ESQL]


Includes a file into a source program to be scanned by the SQL preprocessor.

Syntax
INCLUDE filename

filename : SQLDA | SQLCA | string

Remarks
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 application developer), 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.

Permissions
None.

Side effects
None.

Standards and compatibility


● SQL/2008 Vendor extension.

772 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

INPUT statement [Interactive SQL]


Imports data into a database table from an external file, from the keyboard, from an ODBC data source, or
from a shapefile.

Syntax 1 - Import from an external file or from the keyboard


INPUT INTO [ owner.]table-name input-options

input-options :
[ ( column-name, ... ) ]
[ BY { ORDER | NAME ]
[ BYTE ORDER MARK { ON | OFF } ]
[ COLUMN WIDTHS ( integer, ...) ]
[ DELIMITED BY string ]
[ ENCODING encoding ]
[ ESCAPE CHARACTER character ]
[ ESCAPES { ON | OFF }
[ FORMAT input-format ]
[ FROM filename | PROMPT ]
[ NOSTRIP ]
[ SKIP integer ]

input-format :TEXT
| FIXED ]

encoding : identifier | string

Syntax 2 - Import from an ODBC data source


INPUT USING connection-string
FROM source-table-name
INTO destination-table-name
[ CREATE TABLE { ON | OFF } ]

connection-string :
{ DRIVER=odbc-driver-name
| DSN=odbc-data-source } [ ; { connection-parameter = value } ]

Syntax 3 - Loading shapefiles

INPUT INTO [ owner.]table-name


FROM filename
FORMAT SHAPEFILE
[ SRID srid-number
[ ENCODING encoding ]

encoding : identifier | string

Parameters
BY clause Use this clause to specify whether the columns from the input file should be matched up
with the table columns based on their ordinal position in the list (ORDER being 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 have name information in the file.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 773


SQL statements

BYTE ORDER MARK clause Use this clause to specify whether to process a byte order mark (BOM)
in the data.

The BYTE ORDER MARK clause is relevant only when reading from TEXT formatted files. Attempts to
use the BYTE ORDER MARK clause with FORMAT clauses other than TEXT causes an error.

The BYTE ORDER MARK clause is used only when reading or writing files encoded with UTF-8 or
UTF-16 (and their variants). Attempts to use the BYTE ORDER MARK clause with any other encoding
causes an error.

If the ENCODING clause is specified:

○ If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding with an endian such
as UTF-16BE or UTF-16LE, Interactive SQL searches for a BOM at the beginning of the data. If a
BOM is present, it is used to verify the endianness of the data. If you specify the wrong endian, an
error is returned.
○ If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding without an explicit
endian, Interactive SQL searches for a BOM at the beginning of the data. If a BOM is present, it is
used to determine the endianness of the data. Otherwise, the operating system endianness is assumed.
○ If the BYTE ORDER MARK option is ON and you specify a UTF-8 encoding, Interactive SQL
searches for a BOM at the beginning of the data. If a BOM is present it is ignored.

If the ENCODING clause is not specified:

○ If you do not specify an ENCODING clause and the BYTE ORDER MARK option is ON, Interactive
SQL looks for a BOM at the beginning of the input data. If a BOM is located, the source encoding is
automatically selected based on the encoding of the BOM (UTF-16BE, UTF-16LE, or UTF-8) and the
BOM is not considered to be part of the data to be loaded.
○ If you do not specify an ENCODING clause and the BYTE ORDER MARK option is OFF, or a BOM
is not found at the beginning of the input data, encoding on the client computer is used.

COLUMN WIDTHS clause The COLUMN WIDTHS clause specifies the widths of the columns in the
input file and can only be specified for FIXED format. If COLUMN WIDTHS is not specified, the widths
are determined by the database column types.

CREATE TABLE clause Use the CREATE TABLE clause to specify whether to create the destination
table if it does not exist. The default is ON.

DELIMITED BY clause The DELIMITED BY clause allows you to specify a string to be used as the
delimiter between column values in TEXT input format. The default delimiter is a comma.

ENCODING clause The encoding argument specifies the encoding that is used to read the file. The
ENCODING clause can only be used with the TEXT and SHAPEFILE formats.

When running Interactive SQL, the encoding that is used to import the data is determined in the following
order:

○ The encoding specified by the ENCODING clause (if this clause is specified).

○ The encoding specified by the default_isql_encoding option (if this option is set).

774 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ If the file has a byte-order mark, the appropriate Unicode encoding is used.

○ The default encoding for the computer you are running on. On English Windows computers, the default
encoding is 1252 or 850.

If the input file was created using the OUTPUT statement and an encoding was specified, then the same
ENCODING clause should be specified on the INPUT statement.

ESCAPE CHARACTER clause The default escape character for hexadecimal codes is a backslash (\).
For example, \x0A is the linefeed character.

The newline character can be specified as \n. Other characters can be specified using 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 is interpreted as a backslash and the letter q.

The escape character can be changed using the ESCAPE CHARACTER clause. For example, to use the
exclamation mark as the escape character, specify:
... ESCAPE CHARACTER '!'

ESCAPES clause With ESCAPES turned on (the default), characters following the escape character
are interpreted as special characters by the database server. With ESCAPES turned off, the characters are
read exactly as they appear in the source.

FORMAT clause Use the FORMAT clause to specify the format of the input file.

If the FORMAT clause is not specified, then the input_format option sets the format. The default setting
is TEXT. You can also specify the input format in Interactive SQL by clicking Tools » Options »
Import/Export and specifying either Text or Fixed in the Default Import Format field.

The supported formats are:

○ TEXT Input lines are assumed to be characters, one row per line, with column values separated by
delimiters. Alphabetic strings may be enclosed in single quotes or double quotes. Strings containing
delimiters 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. 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.

Omitted values are treated as NULL. If the value in that position cannot be NULL, a zero is inserted
in numeric columns and an empty string in character columns.

○ 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 allowed by the corresponding database column.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 775


SQL statements

The FIXED format cannot be used with binary columns that contain embedded newline and end-of-
file character sequences.

○ SHAPEFILE [ SRID srid-number ] Input is in the form of an ESRI shapefile. Unlike the LOAD
statement, when loading shapefiles using the INPUT statement, the shapefile must be located on the
client computer. The associated .shx and .dbf files must be located in the same directory as the .shp
file, and have the same base file name.

If an encoding is not specified when loading a shapefile, the default is ISO-8859-1.

Use the SRID clause to specify a SRID to associate with the geometries. If you do not specify a SRID,
SRID 0 is used by default. Ideally, you should specify the same SRID as the one mentioned in the
project file (.prj) for the shapefile. If that SRID is not available, use one that is equivalent. SQL
Anywhere provides thousands of SRIDs you can add to the database using the sa_install_feature
system procedure.

If you want to use other formats such as, DBASE II, DBASE III, FoxPro, Lotus 123, or Excel 97, you
must use INPUT USING.

FROM filename clause The filename can be quoted or unquoted. If the string is quoted, it is subject to
the same formatting requirements as other SQL strings.

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 Employees table is:
INPUT INTO Employees
FROM 'c:\\temp\\input.dat';

The location of a relative filename is determined as follows:

○ If the INPUT statement is executed directly in Interactive SQL, the path to filename is resolved relative
to the directory in which Interactive SQL is running. For example, suppose you open Interactive SQL
from the directory c:\work and execute the following statement:
INPUT INTO Employees
FROM 'inputs\\inputfile.dat';

Interactive SQL looks for c:\work\inputs\inputfile.dat.

○ If the INPUT statement resides in a .sql file, Interactive SQL first attempts to resolve the path to
filename relative to the location of the file. If unsuccessful, Interactive SQL looks for filename in a path
relative to the directory in which Interactive SQL is running.
For example, suppose you had a file, c:\homework\inputs.sql, that contained the following statement:
INPUT INTO Employees
FROM 'inputs\\inputfile.dat';

Interactive SQL would first look for inputfile.dat in c:\homework\inputs. If Interactive SQL does not
find inputfile.dat in that location, Interactive SQL looks in the directory in which Interactive SQL is
running.

FROM source-table-name clause The source-table-name parameter is a quoted string containing the
name of the table in the source database. The name can be in the form database-name.owner.table-name,

776 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

owner.table-name, or table-name. Use a period to separate the components, even if that is not the native
separator in the source database. If the source database requires a database name, but not an owner name,
the format of source-table-name must be database..table (in this case the owner name is empty). Do not
quote any of the names in the parameter. For example, do not use 'dba."my-table"'; use
'dba.my-table' instead.

INTO clause The name of the table to input the data into.

PROMPT clause The PROMPT clause allows the user to enter values for each column in a row. When
running in windowed mode, a window is displayed, allowing the user to enter the values for the new row.
If you are running Interactive SQL from the command line, Interactive SQL prompts you to type the value
for each column on the command line.

NOSTRIP clause Normally, for TEXT input format, trailing blanks are 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.

SKIP clause When inserting lines from a TEXT file, the SKIP clause omits the specified number of
lines starting at the beginning of the file. The number specified must be a non-negative integer. The SKIP
clause is for TEXT format only.

If the specified number of lines exceeds the number of lines in the file, the INPUT statement inserts no
data and no error is returned.

USING clause The USING clause inputs data from an ODBC data source. You can either specify the
ODBC data source name with the DSN option, or the ODBC driver name and connection parameters with
the DRIVER option. The connection-parameter parameter is a list of database-specific connection
parameters.

The odbc-data-source parameter is the name of a user or ODBC data source name. For example, odbc-
data-source for the SQL Anywhere sample database is SQL Anywhere 12 Demo.

The odbc-driver-name parameter is the ODBC driver name. For a SQL Anywhere database, odbc-driver-
name is SQL Anywhere 12. For an UltraLite database, odbc-driver-name is UltraLite 12.

Remarks
The INPUT statement allows efficient mass insertion into a named 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 is read from the SQL script file that contains the INPUT
statement—in Interactive SQL, this can even be directly read from the SQL Statements pane. In this
case, input is ended with a line containing only the string END.

When the input is read directly from the SQL Statements pane, you must specify a semicolon before the
values for the records to be inserted at the end of the INPUT statement. For example:
INPUT INTO Owner.TableName;
value1, value2, value3
value1, value2, value3
value1, value2, value3

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 777


SQL statements

value1, value2, value3


END

The END keyword (not a semicolon) terminates data for INPUT statements that do not name a file and do
not include the PROMPT keyword.

If a column list is specified, the data is inserted into the specified columns of the named table. By default,
the INPUT statement assumes that column values in the input file appear in the same order as they appear
in the database table definition. If the input file's column order is different, you must list the input file's
actual column order at the end of the INPUT statement.

For example, if you create a table with the following statement:


CREATE TABLE inventory (
Quantity INTEGER,
item VARCHAR(60)
);

and you want to import TEXT data from the input file stock.txt that contains the name value before the
quantity value,
'Shirts', 100
'Shorts', 60

then you must list the input file's actual column order at the end of the INPUT statement for the data to be
inserted correctly:
INPUT INTO inventory
FROM stock.txt
FORMAT TEXT
(item, Quantity);

By default, 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.

Interactive SQL prints a warning on the Messages tab 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. If INPUT attempts to insert a NULL row, the input file contains an empty row.

Because the INPUT statement is an Interactive SQL command, it cannot be used in any SQL Anywhere
or UltraLite statement executed by the server.

Permissions
Must have INSERT permission on the table or view.

Side effects
None.

778 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “Import data with the INPUT statement” [SQL Anywhere Server - SQL Usage]
● “Data import” [SQL Anywhere Server - SQL Usage]
● “Importing ASCII data into a new UltraLite database” [UltraLite - Database Management and
Reference]
● “OUTPUT statement [Interactive SQL]” on page 825
● “INSERT statement” on page 780
● “SET OPTION statement [Interactive SQL]” on page 889
● “LOAD TABLE statement” on page 792
● “BYTE ORDER MARK clause, INPUT statement” on page 774
● “Interactive SQL” [SQL Anywhere Server - Database Administration]
● “Unload utility (dbunload)” [SQL Anywhere Server - Database Administration]
● “Support for ESRI shapefiles” [SQL Anywhere Server - Spatial Data Support]
● “Supported character sets” [SQL Anywhere Server - Database Administration]
● “Statements allowed in procedures, triggers, events, and batches” [SQL Anywhere Server - SQL
Usage]
● “Tutorial: Experimenting with the spatial features” [SQL Anywhere Server - Spatial Data Support]
● “input_format option [Interactive SQL]” [SQL Anywhere Server - Database Administration]
● “sa_install_feature system procedure” on page 1067
● “default_isql_encoding option [Interactive SQL]” [SQL Anywhere Server - Database Administration]
● “Inserting rows into the database from the Interactive SQL result set” [SQL Anywhere Server -
Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following is an example of an INPUT statement from a TEXT file.
INPUT INTO Employees
FROM new_emp.inp
FORMAT TEXT;

The following example copies the table, ulTest, into a table called saTest. The ulTest table is in an
UltraLite database in the file C:\test\myULDatabase.udb, and the saTest table is created in demo.db:
INPUT USING 'driver=UltraLite 12;dbf=C:\\test\\myULDatabase.udb'
FROM "ulTest" INTO "saTest";

The following example loads a fictitious shapefile, myshapefile.shp, into the myTable table, and assigns
SRID 4269 to the geometries in the shapefile.
INPUT INTO myTable
FROM 'myshapefile.shp'
FORMAT SHAPEFILE SRID 4269

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 779


SQL statements

INSERT statement
Inserts 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, ... ) ]
[ ON EXISTING {
ERROR
| SKIP
| UPDATE [ DEFAULTS { ON | OFF } ]
}]
{ DEFAULT VALUES
| VALUES row-value-constructor [, ... ] }
[ OPTION( query-hint [, ... ] ) ]

Syntax 2
INSERT [ INTO ] [ owner.]table-name [ ( [ column-name [, ... ] ] ) ]
[ ON EXISTING {
ERROR
| SKIP
| UPDATE [ DEFAULTS { ON | OFF } ]
}]
[ WITH AUTO NAME ]
select-statement
[ OPTION( query-hint[, ... ] ) ]

query-hint :
MATERIALIZED VIEW OPTIMIZATION option-value
| FORCE OPTIMIZATION
| FORCE NO OPTIMIZATION
| option-name = option-value

option-name :
identifier

option-value :
hostvar (indicator allowed)
| string
| identifier
| number

insert-expression :
expression | DEFAULT

row-value-constructor :
( [ insert-expression [, ... ] ])

Parameters
VALUES clause Use the VALUES clause to specify the values to insert. If you want to insert the
default values defined for the columns, specify DEFAULT VALUES. You can also specify VALUES ( ),
which is equivalent to DEFAULT VALUES. The VALUES clause also support row value constructors so

780 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

that you can insert multiple rows of values in a single statement. The number and order of insert-
expression values in each row-value-constructor must correspond to the column list specified in the INTO
clause. If a column list is not specified, it is assumed to be the complete ordered column list for the table.
If you specify an empty column list (), then each of the columns in the table must have a default value.

If an error occurs while inserting any of the rows, all of the changes are rolled back.

WITH AUTO NAME clause WITH AUTO NAME applies only to syntax 2. If you specify WITH
AUTO NAME, the names of the items in the query block determine which column the data belongs in.
The query block items should be either column references or aliased expressions. Destination columns not
defined in the query block are assigned their default value. This is useful when the number of columns in
the destination table is very large.

The INSERT statement returns an error if the WITH AUTO NAME clause is specified and the query
block contains columns that do not match columns in the target table. For example, executing the
following statement returns an error indicating that the operation column in the SELECT query block
does not match any of the columns in the MyTable5 table.
CREATE TABLE MyTable5(
pk INT PRIMARY KEY DEFAULT AUTOINCREMENT,
TableName CHAR(128),
TableNameLen INT );
INSERT
INTO MyTable5 WITH AUTO NAME
SELECT length(t.table_name) AS TableNameLen,
t.table_name AS TableName, 1 as operation
FROM SYS.SYSTAB t
WHERE table_id <= 10;

ON EXISTING clause The ON EXISTING clause of the INSERT statement applies to both syntaxes.
It updates existing rows in a table, based on primary key lookup, with new column values. This clause can
only be used on tables that have a primary key. Attempting to use this clause on tables without primary
keys generates a syntax error. You cannot insert values into a proxy table with the ON EXISTING clause.

Note
If you anticipate many rows qualifying for the ON EXISTING condition, consider using the MERGE
statement instead. The MERGE statement provides more control over the actions you can take for
matching rows. It also provides a more sophisticated syntax for defining what constitutes a match.

If you specify the ON EXISTING clause, the database server performs a primary key lookup for each
input row. If the corresponding row does not already exist in the table, it inserts the new row. For rows
that already exist in the table, you can choose to silently ignore the input row (SKIP), generate an error
message for duplicate key values (ERROR), or update the old values using the values from the input row
(UPDATE). By default, if you do not specify the ON EXISTING clause, attempting to insert rows into a
table where the row already exists results in a duplicate key value error, and is equivalent to specifying
the ON EXISTING ERROR clause. Rows that are skipped are included in the @@rowcount variable.

When using the ON EXISTING UPDATE clause, the input row is compared to the stored row. Any
column values explicitly stated in the input row replace the corresponding column values in the stored
row. Likewise, column values not explicitly stated in the input row result in no change to the
corresponding column values in the stored row—with the exception of columns with defaults. When

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 781


SQL statements

using the ON EXISTING UPDATE clause with columns that have defaults (including DEFAULT
AUTOINCREMENT columns), you can further specify whether to update the column value with the
default values by specifying ON EXISTING UPDATE DEFAULTS ON, or leave the column value as it
is by specifying ON EXISTING UPDATE DEFAULTS OFF. If nothing is specified, the default behavior
is ON EXISTING UPDATE DEFAULTS OFF.

Note
DEFAULTS ON and DEFAULTS OFF parameters do not affect values in DEFAULT TIMESTAMP,
DEFAULT UTC TIMESTAMP, or DEFAULT LAST USER. For these columns, the value in the stored
row is always updated during the UPDATE.

When using the ON EXISTING SKIP and ON EXISTING ERROR clauses, if the table contains default
columns, the server computes the default values even for rows that already exist. As a result, default
values such as AUTOINCREMENT cause side effects even for skipped rows. In this case of
AUTOINCREMENT, this results in skipped values in the AUTOINCREMENT sequence. The following
example illustrates this:
CREATE TABLE t1( c1 INT PRIMARY KEY, c2 INT DEFAULT AUTOINCREMENT );
INSERT INTO t1( c1 ) ON EXISTING SKIP VALUES( 20 );
INSERT INTO t1( c1 ) ON EXISTING SKIP VALUES( 20 );
INSERT INTO t1( c1 ) ON EXISTING SKIP VALUES( 30 );

The row defined in the first INSERT statement is inserted, and c2 is set to 1. The row defined in the
second INSERT statement is skipped because it matches the existing row. However, the autoincrement
counter still increments to 2 (but does not impact the existing row). The row defined in the third INSERT
statement is inserted, and the value of c2 is set to 3. So, the values inserted for the example above are:
20,1
30,3

Caution
If you are using SQL Remote, do not replicate DEFAULT LAST USER columns. When the column is
replicated the column value is set to the SQL Remote user, not the replicated value.

OPTION clause Use this clause to specify hints for executing the statement. The following hints are
supported:

○ MATERIALIZED VIEW OPTIMIZATION option-value


○ FORCE OPTIMIZATION
○ FORCE NO OPTIMIZATION
○ option-name = option-value. Note that a OPTION( isolation_level = ... ) specification
in the query text overrides all other means of specifying isolation level for a query.

Remarks
The INSERT statement is used to add new rows to a database table.

Since text indexes and materialized views are impacted by changes to the underlying table data, consider
truncating dependent text indexes or materialized views before bulk loading (LOAD TABLE, INSERT,
MERGE) data into their underlying tables.

782 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

● Syntax 1 Insert a single row, or multiple rows, with the specified expression column values.
Multiple rows, if specified, are delimited by additional parentheses. 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, 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 Perform 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.

If you specify column names, 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.

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. So, a string Value inserted into a table is always held in the
database with an uppercase V and the remainder of the letters lowercase. 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.

Inserting a significant amount of data using the INSERT statement will also update column statistics.

Note
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 perform many separate INSERT statements. Before inserting data, you can
specify the percentage of each table page that should be left free for later updates.

Permissions
Must have INSERT permission on the table.

If the ON EXISTING UPDATE clause is specified, UPDATE permissions on the table are required as
well.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 783


SQL statements

See also
● “@@rowcount global variable” on page 77
● “Data import” [SQL Anywhere Server - SQL Usage]
● “Regular views” [SQL Anywhere Server - SQL Usage]
● “ALTER TABLE statement” on page 451
● “MERGE statement” on page 811
● “INPUT statement [Interactive SQL]” on page 773
● “LOAD TABLE statement” on page 792
● “UPDATE statement” on page 948
● “SELECT statement” on page 871
● “TRUNCATE statement” on page 933
● “TRUNCATE TEXT INDEX statement” on page 935
● “DELETE statement” on page 678
● “PUT statement [ESQL]” on page 837
● “Access to data on client computers” [SQL Anywhere Server - SQL Usage]
● “Addition of data using INSERT” [SQL Anywhere Server - SQL Usage]
● “OPTION clause, SELECT statement” on page 877

Standards and compatibility


● SQL/2008 The INSERT statement is a core feature of the SQL/2008 standard. The DEFAULT
VALUES clause is optional SQL language feature F222, "INSERT statement: DEFAULT VALUES
clause". Support for row value constructors in an INSERT statement comprises part of optional SQL
language feature F641, "Row and table constructors". The VALUES keyword is a vendor extension,
mandatory with SQL Anywhere to specify the list of expressions to be inserted. However, VALUES
is not part of SQL/2008.

Several optional constructions are vendor extensions. These include:

○ The INSERT...ON EXISTING clause is a vendor extension. A SQL/2008 compliant equivalent in


many instances is the MERGE statement.

○ The OPTION clause.

○ The WITH AUTO NAME clause.

Examples
Add an Eastern Sales department to the database.
INSERT
INTO Departments ( DepartmentID, DepartmentName )
VALUES ( 230, 'Eastern Sales' );

Create the table DepartmentHead and fill it with the names of department heads and their departments
using the WITH AUTO NAME syntax.
CREATE TABLE DepartmentHead(
pk INT PRIMARY KEY DEFAULT AUTOINCREMENT,
DepartmentName VARCHAR(128),
ManagerName VARCHAR(128) );
INSERT
INTO DepartmentHead WITH AUTO NAME

784 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

SELECT GivenName || ' ' || Surname AS ManagerName,


DepartmentName
FROM Employees JOIN Departments
ON EmployeeID = DepartmentHeadID;

Create the table MyTable5 and populate it using the WITH AUTO NAME syntax.

CREATE TABLE MyTable5(


pk INT PRIMARY KEY DEFAULT AUTOINCREMENT,
TableName CHAR(128),
TableNameLen INT );
INSERT INTO MyTable5 WITH AUTO NAME
SELECT
length(t.table_name) AS TableNameLen,
t.table_name AS TableName
FROM SYS.SYSTAB t
WHERE table_id <= 10;

Insert a new department, executing the statement at isolation level 3, rather than using the current
isolation level setting of the database.

INSERT INTO Departments


(DepartmentID, DepartmentName, DepartmentHeadID)
VALUES(600, 'Foreign Sales', 129)
OPTION( isolation_level = 3 );

The following example inserts three rows into a table:

INSERT INTO T (c1,c2,c3)


VALUES (1,10,100), (2,20,200), (3,30,300);

In the following example, the INSERT statement inserts three rows into a table of four columns where
each column has a default value:

INSERT INTO T ()
VALUES (), (), ();

INSTALL EXTERNAL OBJECT statement


Installs an object that can be run in an external environment.

Syntax
INSTALL EXTERNAL OBJECT object-name
[ update-mode ]
FROM { FILE file-path | VALUE expression }
ENVIRONMENT environment-name

environment-name :
PERL
| PHP

update-mode :
NEW
| UPDATE

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 785


SQL statements

Parameters
object-name The name by which the installed object will be identified within the database.

update-mode The update mode for the object. If the update mode is omitted, then NEW is assumed.

file-path The location on the server computer from where the object is being installed.

environment-name The name of the external environment in which the external object is run.

Remarks
For more information about external environments, see “SQL Anywhere external environment support”
[SQL Anywhere Server - Programming].

Permissions
DBA authority

Side effects
None

See also
● “SQL Anywhere external environment support” [SQL Anywhere Server - Programming]
● “ALTER EXTERNAL ENVIRONMENT statement” on page 410
● “REMOVE EXTERNAL OBJECT statement” on page 851
● “START EXTERNAL ENVIRONMENT statement” on page 911
● “STOP EXTERNAL ENVIRONMENT statement” on page 919
● “SYSEXTERNENV system view” on page 1206
● “SYSEXTERNENVOBJECT system view” on page 1206

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
In this example, you install a Perl script that is located in a file into the database.
INSTALL EXTERNAL OBJECT 'PerlScript'
NEW
FROM FILE 'perlfile.pl'
ENVIRONMENT PERL;

Perl code also can be built and installed from an expression, as follows:
INSTALL EXTERNAL OBJECT 'PerlConsoleExample'
NEW
FROM VALUE 'sub WriteToServerConsole { print $sa_output_handle $_[0]; }'
ENVIRONMENT PERL;

Perl code also can be built and installed from a variable, as follows:
CREATE VARIABLE PerlVariable LONG VARCHAR;
SET PerlVariable =

786 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

'sub WriteToServerConsole { print $sa_output_handle $_[0]; }';

INSTALL EXTERNAL OBJECT 'PerlConsoleExample'


NEW
FROM VALUE PerlVariable
ENVIRONMENT PERL;

INSTALL JAVA statement


Makes Java classes available for use within a database.

Syntax
INSTALL JAVA
[ NEW | UPDATE ]
[ JAR jar-name ]
FROM { FILE filename | expression }

Parameters
NEW and UPDATE keyword clauses 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. Due to differences in compression
schemes, it is strongly recommended that jars containing textual resources be created with compression
turned off.

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 JAVA, UPDATE, and REMOVE JAVA statements.

FROM FILE clause Specifies the location of the Java class(es) to be installed.

The formats supported for filename 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.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 787


SQL statements

FROM clause Expressions must evaluate to a binary type whose value contains a valid class file or jar
file.

Remarks
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.

Permissions
DBA permissions are required to execute the INSTALL JAVA statement.

All installed classes can be referenced in any way by any user.

Not supported on Windows Mobile.

See also
● “REMOVE JAVA statement” on page 851

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement installs the user-created Java class named Demo, by providing the file name and
location of the class.
INSTALL JAVA NEW
FROM FILE 'D:\JavaClass\Demo.class';

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).

INTERSECT statement
Computes the intersection between the result sets of two or more queries.

788 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
[ WITH temporary-views ] query-block
INTERSECT [ ALL | DISTINCT ] query-block
[ ORDER BY [ integer | select-list-expression-name ] [ ASC | DESC ], ... ]
[ FOR XML xml-mode ]
[ OPTION( query-hint, ... ) ]

query-block : See “Common elements in SQL syntax” on page 395.

query-hint :
MATERIALIZED VIEW OPTIMIZATION option-value
| FORCE OPTIMIZATION
| option-name = option-value

option-name : identifier

option-value :
hostvar (indicator allowed)
| string
| identifier
| number

Parameters
FOR XML clause For information about the FOR XML clause, see “SELECT statement”
on page 871.

OPTION clause Use this clause to specify hints for executing the statement. The following hints are
supported:

○ MATERIALIZED VIEW OPTIMIZATION option-value


○ FORCE OPTIMIZATION
○ option-name = option-value. Note that a OPTION( isolation_level = ... ) specification
in the query text overrides all other means of specifying isolation level for a query.

Remarks
INTERSECT computes the set intersection between the result sets of two query blocks. Note that query
blocks can be nested, and can in turn be comprised of nested SELECT statements or the set operators
UNION, EXCEPT, or INTERSECT. Specifying INTERSECT alone is equivalent to specifying
INTERSECT DISTINCT.

INTERSECT ALL implements bag intersection rather than set intersection. For example, if the first
query-block contains 5 (duplicate) rows with specific values, and the second query-block contains 3
duplicate rows with identical values to the first, then INTERSECT ALL will return 3 rows.

The results of INTERSECT are the same as INTERSECT ALL if either query-block does not contain
duplicate rows.

The two query-block result sets must be UNION-compatible; they must each have the same number of
items in their respective SELECT lists, and the types of each expression should be comparable. If
corresponding items in two SELECT lists have different data types, SQL Anywhere chooses a data type

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 789


SQL statements

for the corresponding column in the result and automatically convert the columns in each query-block
appropriately.

The column names displayed are the same column names that are displayed for the first query-block and
these names are used to determine the expression names to be matched with the ORDER BY clause. An
alternative way of customizing result set column names is to use a common table expression (the WITH
clause).

Permissions
Must have SELECT permission for each query-block.

Side effects
None.

See also
● “EXCEPT statement” on page 717
● “UNION statement” on page 936
● “SELECT statement” on page 871
● “OPTION clause, SELECT statement” on page 877

Standards and compatibility


● SQL/2008 INTERSECT is optional SQL language feature F302 of the SQL/2008 standard.
Explicitly specifying the DISTINCT keyword with INTERSECT is optional SQL language feature
T551. Specifying an ORDER BY clause with INTERSECT is SQL language feature F850. A query-
block that contains an ORDER BY clause constitutes SQL/2008 feature F851. A query block that
contains a row-limit clause (SELECT TOP or LIMIT) comprises optional SQL language feature F857
or F858, depending on the context. The FOR XML and OPTION clauses are vendor extensions.

● Transact-SQL INTERSECT is not supported by Adaptive Server Enterprise. However, both


INTERSECT ALL and INTERSECT DISTINCT can be used in the Transact-SQL dialect supported
by SQL Anywhere.

Example
For examples of INTERSECT usage, see “Set operators and NULL” [SQL Anywhere Server - SQL
Usage].

LEAVE statement
Leaves a compound statement or loop.

Syntax
LEAVE statement-label

790 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
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.

Permissions
None.

Side effects
None.

See also
● “LOOP statement” on page 810
● “FOR statement” on page 733
● “BEGIN statement” on page 484
● “Stored procedures, triggers, batches, and user defined functions” [SQL Anywhere Server - SQL
Usage]

Standards and compatibility


● SQL/2008 The LEAVE statement is part of optional SQL/2008 language feature P002,
"Computational completeness".

Example
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
...
SET i = i + 1;
IF i >= 10 THEN
LEAVE outer_loop
END IF
END LOOP inner_loop
END LOOP outer_loop

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 791


SQL statements

LOAD STATISTICS statement


For internal use only. Loads statistics into the ISYSCOLSTAT system table. It is used by the dbunload
utility to unload column statistics from the old database. It should not be used manually.

Syntax
LOAD STATISTICS [ [ owner.]table-name.]column-name
format-id, density, max-steps, actual-steps, step-values, frequencies

Parameters
format-id Internal field used to determine the format of the rest of the row in the ISYSCOLSTAT
system table.

density An estimate of the weighted average selectivity of a single value for the column, not counting
the selectivity of large single value selectivities stored in the row.

max-steps The maximum number of steps allowed in the histogram.

actual-steps The number of steps actually used at this time.

step-values Boundary values of the histogram steps.

frequencies Selectivities of histogram steps.

Permissions
DBA authority

Side effects
None.

See also
● “ISYSCOLSTAT system table” on page 967
● “Unload utility (dbunload)” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

LOAD TABLE statement


Imports bulk data into a database table from an external file.

Syntax
LOAD [ INTO ] TABLE [ owner.]table-name
[ ( column-name, ... ) ]
load-source

792 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

[ load-option ... ]
[ statistics-limitation-option ]

load-source :
{ FROM filename-expression
| USING FILE filename-expression
| USING CLIENT FILE client-filename-expression
| USING VALUE value-expression
| USING COLUMN column-expression }

filename-expression : string | variable

client-filename-expression : string | variable

value-expression : expression

column-expression :
column-name
FROM table-name
ORDER BY column-list

load-option :
BYTE ORDER MARK { ON | OFF }
| CHECK CONSTRAINTS { ON | OFF }
| { COMPRESSED | AUTO COMPRESSED | NOT COMPRESSED }
| { ENCRYPTED KEY 'key' | NOT ENCRYPTED }
| COMMENTS INTRODUCED BY comment-prefix
| COMPUTES { ON | OFF }
| DEFAULTS { ON | OFF }
| DELIMITED BY string
| ENCODING encoding
| ESCAPE CHARACTER character
| ESCAPES { ON | OFF }
| FORMAT {
TEXT
| BCP
| XML row-xpath ( column-xpath,... ) [ NAMESPACES namespace ] }
| SHAPEFILE
| HEXADECIMAL { ON | OFF }
| ORDER { ON | OFF }
| PCTFREE percent-free-space
| QUOTE string
| QUOTES { ON | OFF }
| ROW DELIMITED BY string
| SKIP integer
| STRIP { ON | OFF | LTRIM | RTRIM | BOTH }
| WITH CHECKPOINT { ON | OFF }
| WITH { FILE NAME | ROW | CONTENT } LOGGING

statistics-limitation-option :
STATISTICS {
ON [ ALL COLUMNS ]
| ON KEY COLUMNS
| ON ( column-list )
| OFF
}

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 793


SQL statements

comment-prefix : string

encoding : string

Parameters
column-name Use this clause to specify one or more columns to load data into. Any columns not
present in the column list become NULL if DEFAULTS is OFF. If DEFAULTS is ON and the column
has a default value, that value is used. 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.

When a column list is specified, it lists the columns that are expected to exist in the file and the order in
which they are expected to appear. Column names cannot be repeated. Columns whose names do not
appear in the list are set to NULL/zero/empty or DEFAULT (depending on column nullability, data type,
and the DEFAULTS setting). Columns that exist in the input file that are to be ignored by LOAD TABLE
can be specified using filler() as a column name.

load-source Use this clause to specify the data source to load data from. There are several sources of
data from which data can be loaded. The following list gives the supported load sources:

FROM clause Use this to specify a file. The filename-expression is passed to the database server as a
string. The string is therefore subject to the same database 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 Employees table is:

LOAD TABLE Employees


FROM 'c:\\temp\\input.dat' ...

○ The path name is relative to the database server, not to the client application.

○ You can use UNC path names to load data from files on computers other than the database server.

USING FILE clause Use this clause to load data from a file. This is synonymous with specifying the
FROM filename clause.

When the LOAD TABLE statement is used with the USING FILE clause, you can request progress
messages.

You can also use the Progress connection property to determine how much of the statement has been
executed.

USING CLIENT FILE clause Use this clause to load data from a file on a client computer. When the
database server retrieves data from client-filename-expression, the data is not materialized in the server's
memory, so the database server limit on the size of BLOB expressions does not apply to the file.
Therefore, the client file can be of an arbitrary size.

File name logging is not allowed if the table is being loaded from a client file. If the logging type is not
specified, then WITH CONTENT LOGGING is used.

794 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

When the LOAD TABLE statement is used with the USING CLIENT FILE clause, you can request
progress messages.

You can also use the Progress connection property to determine how much of the statement has been
executed.

USING VALUE clause Use this clause to load data from any expression of CHAR, NCHAR,
BINARY, or LONG BINARY type, or BLOB string. The following are examples of how this clause can
be used:

○ The following syntax uses the xp_read_file system procedure to get the values to load from the target
file:
... USING VALUE xp_read_file( 'filename' )...

○ The following syntax specifies the value directly, inserting two rows with values of 4 and 5,
respectively;
... USING VALUE '4\n5'...

○ The following syntax uses the results of the READ_CLIENT_FILE function as the value:
... USING VALUE READ_CLIENT_FILE( client-filename-expression )

In this case, you can also specify USING CLIENT FILE client-filename-expression
since they are semantically equivalent.

If the ENCODING clause is not specified in the LOAD TABLE statement, then encoding for value-
expression is assumed to be in the database character set (db_charset) if value-expression is of type
CHAR or BINARY, and NCHAR database character set (nchar_charset) if value-expression is of type
NCHAR.

USING COLUMN clause Use this clause to load data from a single column in another table. This
clause is used by the database server when it replays the transaction log during recovery by replaying the
LOAD TABLE...WITH CONTENT LOGGING statements. Transaction log records for LOAD
TABLE...WITH CONTENT LOGGING statements comprise chunks of the original input file. When the
database server encounters these chunks in the transaction log during recovery, it loads the chunks into a
temporary table and then loads all the data from the original load operation.

The following clauses are required in the USING COLUMN clause:

○ table-name The name of the base or temporary table that contains the column to load data from.
When used by the database server during recovery from the transaction log, this is the table that holds
the chunks of rows to be parsed and loaded.

○ column-name The name of the column in table-name that holds the chunks of rows to be loaded.

○ column-list One or more columns in the destination table used to sort the rows before loading the
data. column-list must be a verifiable unique set of values, such as a primary key or a unique index on
non-nullable columns included within the column list.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 795


SQL statements

load-option clause There are several load options you can specify to control how data is loaded. The
following list gives the supported load options:

○ BYTE ORDER MARK clause Use this clause to specify whether the server should search for and
interpret a byte order mark (BOM) at the beginning of the data. By default, this option is ON. If
BYTE ORDER MARK is OFF, the server does not search for a BOM.

If the ENCODING clause is specified:

● If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding with an endian
such as UTF-16BE or UTF-16LE, the database server searches for a BOM at the beginning of the
data. If a BOM is present, it is used to verify the endianness of the data. If you specify the wrong
endian, an error is returned.
● If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding without an
explicit endian, the database server searches for a BOM at the beginning of the data. If a BOM is
present, it is used to determine the endianness of the data. Otherwise, the operating system
endianness is assumed.
● If the BYTE ORDER MARK option is ON and you specify a UTF-8 encoding, the database server
searches for a BOM at the beginning of the data. If a BOM is present it is ignored.

If the ENCODING clause is not specified:

● If you do not specify an ENCODING clause and the BYTE ORDER MARK option is ON, the
server looks for a BOM at the beginning of the input data. If a BOM is located, the source
encoding is automatically selected based on the encoding of the BOM (UTF-16BE, UTF-16LE, or
UTF-8) and the BOM is not considered to be part of the data to be loaded. If no BOM is found, the
database CHAR encoding is used.
● If you do not specify an ENCODING clause and the BYTE ORDER MARK option is OFF, the
database CHAR encoding is used, and the database server does not look for or interpret a BOM at
the beginning of the data.

○ CHECK CONSTRAINTS clause Use this clause to control whether constraints are checked during
loading. CHECK CONSTRAINTS is ON by default, but the Unload utility (dbunload) writes out
LOAD TABLE statements with CHECK CONSTRAINTS set to OFF. Setting CHECK
CONSTRAINTS to OFF disables check constraints, which 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 fails unless CHECK CONSTRAINTS is set to OFF.

○ COMMENTS INTRODUCED BY clause Use this clause to specify the string used in the data file
to introduce a comment. When used, LOAD TABLE ignores any line that begins with the string
comment-prefix. For example, in the following statement, lines in input.dat that start with // are
ignored.
LOAD TABLE Employees FROM 'c:\\temp\\input.dat' COMMENTS INTRODUCED BY
'//' ...

Comments are only allowed at the beginning of a new line.

If COMMENTS INTRODUCED BY is omitted, the data file must not contain comments because they
are interpreted as data.

796 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ COMPRESSED clause Specify COMPRESSED if the data being loaded is compressed in the
input file. The database server decompresses the data before loading it. If you specify COMPRESSED
and the data is not compressed, the LOAD fails and returns an error.

Specify AUTO COMPRESSED to allow the database server determine whether the data in the input
file is compressed. If so, the database server decompresses the data before loading it.

Specify NOT COMPRESSED to indicate that the data in the input file is not compressed. You can
also specify NOT COMPRESSED if the data is compressed, but you don't want the database server to
decompress it. In this case, the data remains compressed in the database. However, if a file is both
encrypted and compressed, you cannot use NOT ENCRYPTED without also using NOT
COMPRESSED.

○ COMPUTES clause By default, this option is ON, which enables recalculation of computed
columns. Setting COMPUTES to OFF disables computed column recalculations. COMPUTES OFF is
useful, for example, if you are rebuilding a database, and a table has a computed column that calls a
user-defined function that is not yet created. The rebuild would fail unless this option was set to OFF.

The Unload utility (dbunload) writes out LOAD TABLE statements with the COMPUTES set to OFF.

○ DEFAULTS clause By default, DEFAULTS is set to OFF. If DEFAULTS is OFF, any column not
present in the list of columns is assigned NULL. If DEFAULTS is set to OFF and a non-nullable
column is omitted from the list, the database server attempts to convert the empty string to the
column's type. If DEFAULTS is set to ON and the column has a default value, that value is used.

○ DELIMITED BY clause Use this clause to specify the column delimiter string. The default column
delimiter string is a comma; however, it can be any string up to 255 bytes in length (for example, ...
DELIMITED BY '###' ...). The delimiter you specify is a string and should be quoted. If you
want to specify tab-delimited values, you could specify the hexadecimal escape sequence for the tab
character (9), ... DELIMITED BY '\x09' ....

○ ENCODING clause Use this clause to specify the character encoding used for the data being
loaded into the database. The ENCODING clause cannot be used with the BCP format.

If a translation error occurs during the load operation, it is reported based on the setting of the
on_charset_conversion_failure option.

Specify the BYTE ORDER clause to interpret a byte order mark in the data.

If the ENCODING clause is specified:

● If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding with an endian
such as UTF-16BE or UTF-16LE, the database server searches for a BOM at the beginning of the
data. If a BOM is present, it is used to verify the endianness of the data. If you specify the wrong
endian, an error is returned.
● If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding without an
explicit endian, the database server searches for a BOM at the beginning of the data. If a BOM is

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 797


SQL statements

present, it is used to determine the endianness of the data. Otherwise, the operating system
endianness is assumed.
● If the BYTE ORDER MARK option is ON and you specify a UTF-8 encoding, the database server
searches for a BOM at the beginning of the data. If a BOM is present it is ignored.

If the ENCODING clause is not specified:

● If you do not specify an ENCODING clause and the BYTE ORDER MARK option is ON, the
server looks for a BOM at the beginning of the input data. If a BOM is located, the source
encoding is automatically selected based on the encoding of the BOM (UTF-16BE, UTF-16LE, or
UTF-8) and the BOM is not considered to be part of the data to be loaded.
● If you do not specify an ENCODING clause and the BYTE ORDER MARK option is OFF, the
database CHAR encoding is used, and the database server does not look for or interpret a BOM at
the beginning of the data.

○ ENCRYPTED clause Use this clause to specify encryption settings. When loading encrypted data,
specify ENCRYPTED KEY followed by the key used to encrypt the data in the input file.

Specify NOT ENCRYPTED to indicate that the data in the input file is not encrypted. You can also
specify NOT ENCRYPTED if the data is encrypted, but you don't want the database server to decrypt
it. In this case, the data remains encrypted in the database. However, if a file is both encrypted and
compressed, you cannot use NOT ENCRYPTED without also using NOT COMPRESSED.

○ ESCAPE CHARACTER clause Use this clause to specify the escape character used in the data.
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 '!'

It is recommended that the string you specify for the escape character is no longer than one multibyte
character.

○ ESCAPES clause Use this clause to control whether to recognize escape characters. With
ESCAPES turned ON (the default), characters following the escape character (which defaults to \) are
recognized and interpreted as special characters by the database server. Newline characters can be
included as the combination \n, and 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. It is recommended that the
string you specify for the escape character is no longer than one multibyte character.

○ FORMAT TEXT If you choose FORMAT TEXT (the default), input lines are assumed to be
characters (as defined by the ENCODING option), one row per line, with values separated by the
column delimiter string.

○ FORMAT BCP Specify FORMAT BCP to load Adaptive Server Enterprise-generated BCP out
files.

798 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ FORMAT SHAPEFILE Specify FORMAT SHAPEFILE to load ESRI shapefiles. The shapefile
must be on the database server computer and must be loaded using FROM filename-expression or
USING FILE filename-expression, where filename-expression refers to an ESRI shapefile with
the .shp file extension. The associated .shx and .dbf files must be located in the same directory as
the .shp file, and have the same base file name.

For FORMAT SHAPEFILE, the encoding defaults to ISO-8859-1 if the ENCODING clause is not
specified.

If you specify FORMAT SHAPEFILE, the following load options are allowed:

● CHECK CONSTRAINTS
● COMPUTES
● DEFAULTS
● ENCODING
● ORDER
● PCTFREE
● WITH CHECKPOINT
● WITH .... LOGGING

The LOAD TABLE statement gets the SRID from the second column type that you are loading into.
For example, if you created the second column with type ST_Geometry(SRID=4326), then the
geometries are loaded using SRID 4326. If your second column has type ST_Geometry (no explicit
SRID), then the geometries are loaded using SRID 0.

○ FORMAT XML If you specify FORMAT XML, the following load options are allowed:

● BYTE ORDER MARK


● CHECK CONSTRAINTS
● COMPRESSED
● COMPUTES
● DEFAULTS
● ENCODING
● ENCRYPTED
● ORDER
● PCTFREE
● WITH CHECKPOINT
● WITH .... LOGGING

If you use FORMAT XML, the input file is parsed in the same way as a query that uses the openxml
system procedure. The arguments of the SQL statement correspond to the system procedure
parameters as follows:

LOAD TABLE openxml system Details


statement clause procedure argument

row-xpath xpath

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 799


SQL statements

LOAD TABLE openxml system Details


statement clause procedure argument

— flags There is no way to specify a value with FOR-


MAT XML that corresponds to the flags argu-
ment of openxml.

NAMESPACES namespaces

The FORMAT XML clause uses the following parameters:

● row-xpath A string or variable containing an XPath query. XPath allows you to specify
patterns that describe the structure of the XML document you are querying. The XPath pattern
included in this argument selects the nodes from the XML document. Each node that matches the
XPath query in the row-xpath argument generates one row in the table.

Metaproperties can only be specified in FORMAT XML clause row-xpath arguments. A


metaproperty is accessed within an XPath query as if it was an attribute. If namespaces is not
specified, then by default the prefix mp is bound to the Uniform Resource Identifier (URI)
urn:ianywhere-com:sa-xpath-metaprop. If namespace is specified, this URI must be bound to mp
or some other prefix to access metaproperties in the query. Metaproperty names are case sensitive.
The following metaproperties are supported:

○ @mp:id returns an ID for a node that is unique within the XML document. The ID for a
given node in a given document may change if the database server is restarted. The value of
this metaproperty increases with document order.

○ @mp:localname returns the local part of the node name, or NULL if the node does not
have a name.

○ @mp:prefix returns the prefix part of the node name, or NULL if the node does not have a
name or if the name is not prefixed.

○ @mp:namespaceuri returns the URI of the namespace that the node belongs to, or NULL
if the node is not in a namespace.

○ @mp:xmltext returns a subtree of the XML document in XML form. For example, when
you match an internal node, you can use this metaproperty to return an XML string, rather than
the concatenated values of the descendant text nodes.

● column-xpath A string or variable that specifies the schema of the result set and how the value
is found for each column in the result set. If a FORMAT XML clause expression matches more
than one node, then only the first node in the document order is used. If the node is not a text
node, then the result is found by appending all the text node descendants. If a FORMAT XML
clause expression does not match any nodes, then the column for that row is NULL.

● namespace A string or variable containing an XML document. The in-scope namespaces for
the query are taken from the root element of the document.

800 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ HEXADECIMAL clause Use this clause to specify whether to read binary values as hexadecimals.
By default, HEXADECIMAL is ON. With HEXADECIMAL ON, binary column values are read as
0xnnnnnn..., where 0x is a zero followed by an x, and each n is a hexadecimal digit. It is important to
use HEXADECIMAL ON when dealing with multibyte character sets.

The HEXADECIMAL clause can be used only with the FORMAT TEXT clause.

○ ORDER clause Use this clause to specify whether to sort the data when loading. The default for
ORDER is ON. If ORDER is ON, and a clustered index has been declared, then LOAD TABLE sorts
the input data according to the clustered index and inserts rows in the same order. If the data you are
loading is already sorted, you should set ORDER to OFF.

○ PCTFREE clause Use this clause to specify the percentage of free space you want to reserve for
each table page. This setting overrides any permanent setting for the table, but only for the duration of
the load, and only for the data being loaded. The value percent-free-space is an integer between 0 and
100. A value of 0 specifies that no free space is to be left on each page—each page is to be fully
packed. A high value causes each row to be inserted into a page by itself.

○ QUOTE clause The QUOTE clause is for TEXT data only; the string is placed around string
values. The default is a single quote (apostrophe).

○ QUOTES clause Use this clause to specify whether strings are enclosed in quotes. When
QUOTES is set to ON (the default), the LOAD TABLE statement expects strings to be enclosed in
quote characters. If the QUOTES clause is omitted, the quote character is either an apostrophe (single
quote) or a quotation mark (double quote) and 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.

When QUOTES is set to ON, column delimiter strings can be included in column values. Also, quote
characters are assumed not to be part of the value. Therefore, the following line 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.
'123 High Street, Anytown',(715)398-2354

To include a quote character in a value, when QUOTES is set to 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',''''

○ ROW DELIMITED BY clause Use this clause to specify the string that indicates the end of an
input record. The default delimiter string is a newline (\n); however, it can be any string up to 255
bytes in length (for example, ROW DELIMITED BY '###'). If you wanted to specify tab-
delimited values, you could specify the hexadecimal escape sequence for the tab character (9), ROW
DELIMITED BY '\x09'. If your delimiter string contains a \n, it matches either \r\n or \n.

○ SKIP clause Use this clause to specify whether to ignore lines at the beginning of a file. The
integer argument specifies the number of lines to skip. You can use this clause to skip over a line
containing column headings, for example. If the row delimiter is not the default (newline), then
skipping may not work correctly if the data contains the row delimiter embedded within a quoted
string.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 801


SQL statements

○ STRIP clause Use this clause to specify whether unquoted values should have leading or trailing
blanks stripped off before they are inserted. The STRIP option accepts the following options:

● STRIP OFF Do not strip off leading or trailing blanks.

● STRIP LTRIM Strip leading blanks.

● STRIP RTRIM Strip trailing blanks.

● STRIP BOTH Strip both leading and trailing blanks.

● STRIP ON Deprecated. Equivalent to STRIP RTRIM.

The STRIP behavior is tied to the QUOTES clause. If you specify QUOTES OFF, then STRIP OFF,
STRIP LTRIM, STRIP RTRIM, and STRIP BOTH, work exactly as their wording suggests. If you do
not specify a QUOTES clause, or you specify QUOTES ON, unquoted strings are always left-
trimmed and right-trimmed (however, you can specify STRIP OFF or STRIP LTRIM if you don't
want the strings to be right-trimmed as well).

○ WITH CHECKPOINT clause Use this clause to specify whether to perform a checkpoint. The
default setting is OFF. If this clause is set to ON, a checkpoint is issued after successfully completing
and logging the statement. If this clause is set to ON, 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 you use FILE NAME LOGGING. If WITH CHECKPOINT ON is specified,
and recovery is subsequently required, recovery begins after the checkpoint, and the data file need not
be present.

The data files are required, regardless of what is specified for this clause, if the database becomes
corrupt and you need to use a backup and apply the current log file if you use FILE NAME
LOGGING.

○ WITH { FILE NAME | ROW | CONTENT } LOGGING Use this clause to control the level of detail
logged in the transaction log during a load operation. The levels of logging are as follows:

● WITH FILE NAME LOGGING clause The WITH FILE NAME LOGGING clause causes only
the LOAD TABLE statement to be recorded in the transaction log. To guarantee consistent results
when the transaction log is used during recovery, the file used for the original load operation must
be present in its original location, and must contain the original data. This level of logging has the
best performance; however, you should not use it if your database is involved in mirroring or
synchronization. Also, this level can not be used when loading from an expression or a client file.

When you do not specify a logging level in the LOAD TABLE statement, WITH ROW
LOGGING is the default level when specifying:

○ FROM filename-expression
○ USING FILE filename-expression

● WITH ROW LOGGING clause The WITH ROW LOGGING clause causes each row that is
loaded to be recorded in the transaction log as an INSERT statement. This level of logging is
recommended for databases involved in synchronization and is the default for database mirroring

802 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

when using FROM filename-expression or USING FILE filename-expression. However, when


loading large amounts of data, this logging type can impact performance, and results in a much
longer transaction log.

If there are no non-deterministic value, WITH CONTENT LOGGING likely results in better
performance

This level is also ideal for databases where the table being loaded into contains non-deterministic
values, such as computed columns, or CURRENT TIMESTAMP defaults.

● WITH CONTENT LOGGING clause The WITH CONTENT LOGGING clause causes the
database server to copy the input file to the transaction log in chunks. These chunks can be
reconstituted into a copy of the input file later, for example during recovery from the transaction
log. When loading large amounts of data, this logging type has a very low impact on performance,
and offers increased data protection, but it does result in a longer transaction log. This level of
logging is recommended for databases involved in mirroring, or where it is desirable to not
maintain the original data files for later recovery provided there are no non-deterministic values.

The WITH CONTENT LOGGING clause cannot be used if the database is involved in
synchronization. The WITH CONTENT LOGGING clause is required if the table is being loaded
from a client file.

When you do not specify a logging level in the LOAD TABLE statement, WITH CONTENT
LOGGING is the default level when specifying:

○ USING CLIENT FILE client-filename-expression

○ USING VALUE value-expression

○ USING COLUMN column-expression

statistics-limitation-option Allows you to limit the columns for which statistics are generated during
the execution of LOAD TABLE. Otherwise, statistics are generated for all columns. You should only use
this clause if you are certain that statistics will not be used on some columns. You can specify ON ALL
COLUMNS (the default), OFF, ON KEY COLUMNS, or a list of columns for which statistics should be
generated.

Remarks
LOAD TABLE allows efficient mass insertion into a database table from a file. LOAD TABLE is more
efficient than the Interactive SQL statement INPUT.

LOAD TABLE places a write lock on the whole table. For base tables, global temporary tables, and local
temporary tables, a commit is performed.

If you attempt to use LOAD TABLE on a table on which an immediate text index is built, or that is
referenced by an immediate view, the load fails. This does not occur for non-immediate text indexes or
materialized views; however, it is strongly recommended that you truncate the data in dependent indexes
and materialized views before executing the LOAD TABLE statement, and then refresh the indexes and
views after.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 803


SQL statements

Do not use the LOAD TABLE statement on a temporary table for which ON COMMIT DELETE ROWS
was specified, either explicitly or by default, at creation time. However, you can use LOAD TABLE if
ON COMMIT PRESERVE ROWS or NOT TRANSACTIONAL was specified.

With FORMAT TEXT, a NULL value is indicated by specifying no value. For example, if three values
are expected and the file contains 1,,'Fred',, then the values inserted are 1, NULL, and Fred. If the
file contains 1,2,, then the values 1, 2, and NULL are inserted. Values that consist only of spaces are
also considered NULL values. For example, if the file contains 1, ,'Fred',, then values 1, NULL,
and Fred are inserted. All other values are considered not NULL. For example, '' (a single quote followed
by single quote) is an empty string. 'NULL' is a string containing four letters.

If a column being loaded by LOAD TABLE does not allow NULL values and the file value is NULL,
then numeric columns are given the value 0 (zero), character columns are given an empty string (''). If a
column being loaded by LOAD TABLE allows NULL values and the file value is NULL, then the
column value is NULL (for all types).

If the table contains columns a, b, and c, and the input data contains a, b, and c, but the LOAD statement
only specifies only a and b as columns to load data into, the following values are inserted into column c:

● if DEFAULTS ON is specified, and column c has a default value, the default value is used.

● if column c does not have a default defined for it and it allows NULLs, then a NULL is used.

● if column c does not have a default defined for it and it does not allow NULLs, then either a zero (0) or
an empty string ('') is used, or an error is returned, depending on the data type of the column.

● LOAD TABLE and database mirroring If you are using database mirroring and execute a LOAD
TABLE statement on a base table, you must specify either WITH ROW LOGGING or WITH
CONTENT LOGGING as the logging level for the statement. These clauses allow the loaded data to
be recorded in the transaction log so that it can be loaded into the mirroring database as well. If these
clauses are not specified, an error is reported.

● LOAD TABLE and column statistics To create histograms on table columns, LOAD TABLE
captures column statistics when it loads data. The histograms are used by the optimizer.

Following are additional tips about loading and column statistics:

○ LOAD TABLE saves statistics on base tables for future use. It does not save statistics on global
temporary tables.

○ If you are loading into an empty table that may have previously contained data, it may be beneficial
to drop the statistics for the column before executing the LOAD TABLE statement.

○ If column statistics exist when LOAD TABLE is performed on a column, statistics for the column
are not recalculated. Instead, statistics for the new data are inserted into the existing statistics. This
means that if the existing column statistics are out-of-date, they will still be out of date after loading
new data into the column. If you suspect that the column statistics are out of date, you should
consider updating them either before, or after, executing the LOAD TABLE statement.

804 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ LOAD TABLE adds statistics only if the table has five or more rows. If the table has at least five
rows, histograms are modified as follows:

Data already in table? Histogram present? Action taken

Yes Yes Integrate changes into the existing histograms

Yes No Do not build histograms

No Yes Integrate changes into the existing histograms

No No Build new histograms

○ LOAD TABLE does not generate statistics for columns that contain NULL values for more than
90% of the rows being loaded.

● Using dynamically constructed file names You can execute a LOAD TABLE statement with a
dynamically constructed file name by assigning the file name to a variable and using the variable
name in the LOAD TABLE statement.

Permissions
The permissions required to execute a LOAD TABLE statement depend on the database server -gl option,
as follows:

● If the -gl option is set to ALL, you must be the owner of the table or have DBA authority or have
ALTER privileges.

● If the -gl option is set to DBA, you must have DBA authority.

● If the -gl option is set to NONE, LOAD TABLE is not permitted.

Requires an exclusive lock on the table.

When reading from a file on a client computer:

● READCLIENTFILE authority is required.

● Read permissions are required on the directory being read from.

● The allow_read_client_file database option must be enabled.

● The read_client_file secured feature must be enabled.

Side effects
Automatic commit.

Inserts are not recorded in the transaction log file unless WITH ROW LOGGING clause is specified, so
the inserted rows may not be recovered in the event of a failure depending upon the logging type. The
original file is required if you need to recover the rows and WITH FILE NAME LOGGING is used. In
addition, the LOAD TABLE statement should not be used without the WITH ROW LOGGING clause in

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 805


SQL statements

databases that are used as MobiLink clients, or in a database involved in SQL Remote replication, because
these technologies replicate changes through analysis of the log file.

The LOAD TABLE statement does not fire any triggers associated with the table.

A checkpoint is carried out at the beginning of the operation. A second checkpoint is performed at the end
if WITH CHECKPOINT ON is specified.

Column statistics are updated if a significant amount of data is loaded.

See also
● “Clustered indexes” [SQL Anywhere Server - SQL Usage]
● “Supported character sets” [SQL Anywhere Server - Database Administration]
● “TRUNCATE statement” on page 933
● “TRUNCATE TEXT INDEX statement” on page 935
● “on_charset_conversion_failure option” [SQL Anywhere Server - Database Administration]
● “Progress connection property” [SQL Anywhere Server - Database Administration]
● “progress_messages option” [SQL Anywhere Server - Database Administration]
● “Data import” [SQL Anywhere Server - SQL Usage]
● “LOAD TABLE statement” on page 792
● “UNLOAD statement” on page 937
● “INSERT statement” on page 780
● “INPUT statement [Interactive SQL]” on page 773
● “Access to data on client computers” [SQL Anywhere Server - SQL Usage]
● “Optimizer estimates and statistics” [SQL Anywhere Server - SQL Usage]
● “-sf dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “allow_read_client_file option” [SQL Anywhere Server - Database Administration]
● “READCLIENTFILE authority” [SQL Anywhere Server - Database Administration]
● “Update column statistics” [SQL Anywhere Server - SQL Usage]
● “-gl dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “CREATE TABLE statement” on page 633
● “Support for ESRI shapefiles” [SQL Anywhere Server - Spatial Data Support]
● “Data import and export” [SQL Anywhere Server - SQL Usage]
● “Import data with the LOAD TABLE statement” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Following is an example of LOAD TABLE. First, you create a table, and then load data into it using a file
called input.txt.
CREATE TABLE t( a CHAR(100), let_me_default INT DEFAULT 1, c CHAR(100) );

Following is the content of a file called input.txt:


ignore_me, this_is_for_column_c, this_is_for_column_a

The following LOAD statement loads the file called input.txt:

806 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

LOAD TABLE T ( filler(), c, a ) FROM 'input.txt' FORMAT TEXT DEFAULTS ON;

The command SELECT * FROM t yields the result set:

a let_me_default c

this_is_for_column_a 1 this_is_for_column_c

The following example executes the LOAD TABLE statement with a dynamically constructed file name,
via the EXECUTE IMMEDIATE statement:
CREATE PROCEDURE LoadData( IN from_file LONG VARCHAR )
BEGIN
DECLARE path LONG VARCHAR;
SET path = 'd:\\data\\' || from_file;
LOAD TABLE MyTable FROM path;
END;

The following example loads UTF-8-encoded table data into mytable:


LOAD TABLE mytable FROM 'mytable_data_in_utf8.dat' ENCODING 'UTF-8';

LOCK FEATURE statement


Prevents other concurrent connections from using a database server feature.

Syntax
LOCK FEATURE feature-name { ON | OFF }

feature-name :
synchronization schema
| all

Parameters
feature-name The name of the feature to be locked or unlocked. Specify all to unlock all the features
locked by a connection.

ON | OFF Specify ON to prevent other connections from using the feature. Specify OFF to allow
connections to use the feature.

Remarks
You cannot lock a feature more than once for the same connection. If you attempt to unlock a feature that
is not locked by the current connection and you do not specify all as the feature name, an error is returned.
When a feature is locked by two or more connections, the feature must be unlocked by all connections
before it can be used by other connections. Feature locks created by a connection are removed when the
connection is dropped. Feature locks are removed when the database server is shut down.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 807


SQL statements

When the synchronization schema feature is locked, the following statements cannot be executed by other
connections:

● START SYNCHRONIZATION SCHEMA CHANGE


● CREATE SYNCHRONIZATION SUBSCRIPTION
● DROP SYNCHRONIZATION SUBSCRIPTION
● ALTER SYNCHRONIZATION SUBSCRIPTION
● ALTER PUBLICATION

Permissions
DBA authority

Side effects
None

See also
● “LOCK TABLE statement” on page 808

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement prevents other connections from using the synchronization schema feature:

LOCK FEATURE 'synchronization schema' ON;

LOCK TABLE statement


Prevents other concurrent transactions from accessing or modifying a table.

Syntax
LOCK TABLE table-name
[ WITH HOLD ]
IN { SHARE | EXCLUSIVE } MODE

Parameters
table-name The name of the table. 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 Specify this clause to lock the table until the end of the connection. If the clause
is not specified, the lock is released when the current transaction is committed or rolled back.

IN SHARE MODE clause Specify this clause to obtain a shared table lock on the table, preventing
other transactions from modifying the table but allowing them read access. If a transaction puts a shared
lock on a table, it can change data in the table provided no other transaction holds a lock of any kind on

808 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

the row(s) being modified. Read locks on individual rows are not acquired when the IN SHARE MODE
clause is selected.

IN EXCLUSIVE MODE clause Specify this clause to obtain an exclusive table lock on the table,
preventing other transactions from accessing the table. No other transaction can execute queries, updates,
or any other action against the table. If a table is locked exclusively with a statement such as LOCK
TABLE...IN EXCLUSIVE MODE, the default behavior is to not acquire row locks for the table. This
behavior can be disabled by setting the subsume_row_locks option to Off.

Remarks
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.

You cannot execute the LOCK TABLE statement on a view. However, if you execute the LOCK TABLE
statement on a base table, a shared schema lock is created, which locks dependent views. A shared
schema lock persists until the transaction is committed or rolled back.

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
● “Table locks” [SQL Anywhere Server - SQL Usage]
● “SELECT statement” on page 871
● “sa_locks system procedure” on page 1071
● “How locking works” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement prevents other transactions from modifying the Customers table for the duration
of the current transaction:
LOCK TABLE Customers
IN SHARE MODE;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 809


SQL statements

LOOP statement
Repeats the execution of a statement list.

Syntax
[ statement-label : ]
[ WHILE search-condition ] LOOP
statement-list
END LOOP [ statement-label ]

Remarks
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.

Permissions
None.

Side effects
None.

See also
● “FOR statement” on page 733
● “CONTINUE statement” on page 507
● “WHILE statement [T-SQL]” on page 960

Standards and compatibility


● SQL/2008 The LOOP/END LOOP statement is part of optional SQL/2008 language feature P002,
"Computational completeness". In SQL/2008, the WHILE DO/END WHILE statement is a separate
statement that is also part of language feature P002. The syntax combination WHILE search-condition
LOOP supported in SQL Anywhere is a vendor extension.

● Transact-SQL LOOP is not supported in the Transact-SQL dialect. Looping within Transact-SQL
stored procedures is done with the Transact-SQL WHILE statement.

Example
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.

810 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

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

MERGE statement
Merges tables, views, and procedure results into a table or view.

Syntax
MERGE
INTO target-object [ into-column-list ]
USING [ WITH AUTO NAME ] source-object
ON merge-search-condition
merge-operation [...]
[ OPTION ( query-hint, ... ) ]

target-object :
[ userid.]target-table-name [ [ AS ] target-correlation-name ]
| [ userid.]target-view-name [ [ AS ] target-correlation-name ]
| ( select-statement ) [ AS ] target-correlation-name

source-object :
[ userid.]source-table-name [ [ AS ] source-correlation-name ] [ WITH ( table-hints ) ]
| [ userid.]source-view-name [ [ AS ] source-correlation-name ]
| [ userid.]source-mat-view-name [ [ AS ] source-correlation-name ]
| ( select-statement ) [ AS ] source-correlation-name [ using-column-list ]
| procedure

procedure :
[ owner.]procedure-name ( procedure-syntax )
[ WITH ( column-name data-type, ... ) ]
[ [ AS ] source-correlation-name ]

merge-search-condition :
search-condition
| PRIMARY KEY

merge-operation :
WHEN MATCHED [ AND search-condition ] THEN match-action
| WHEN NOT MATCHED [ AND search-condition ] THEN not-match-action

match-action :
DELETE
| RAISERROR [ error-number ]
| SKIP

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 811


SQL statements

| UPDATE SET set-item, ...


| UPDATE [ DEFAULTS { ON | OFF } ]

not-match-action :
INSERT
| INSERT [ insert-column-list ] VALUES ( value, ... )
| RAISERROR [ error-number ]
| SKIP

set-item :
[target-correlation-name.]column-name = { expression | DEFAULT }
| [ owner-name.]target-table-name.column-name = { expression | DEFAULT }

insert-column-list :
( column-name, ... )

query-hint :
MATERIALIZED VIEW OPTIMIZATION option-value
| FORCE OPTIMIZATION
| option-name = option-value

into-column-list :
( column-name, ... )

using-column-list :
( column-name, ... )

error-number : positive integer or variable greater than 17000

option-name : identifier

option-value :
hostvar (indicator allowed)
| string
| identifier
| number

table-hints : See “FROM clause” on page 738.

search-condition : See “Search conditions” on page 32.

set-clause-list : See “SET statement” on page 899.

Parameters
INTO clause Use this clause to define the target object for the MERGE statement. target-object can be
the name of a base table, regular view, or derived table; it cannot be a materialized view. The derived
table or view must represent an updatable query block. For example, if the view or derived table
definition contains UNION, INTERSECT, EXCEPT, or GROUP BY, then it cannot be used as a target
object for the MERGE statement.

When target-object is a derived table, the optional into-column-list can be used to provide alternate names
for the columns of the derived table. When used in this manner, the size of the into-column-list must
match the column list for the derived table, and the ordering of the two lists must be the same.

812 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

When target-object is a base table or view, into-column-list can be used to specify a subset of the table or
view columns as relevant for the rest of the MERGE statement.

The database server uses into-column-list to resolve:

○ UPDATE without a SET clause in WHEN MATCHED clause

○ INSERT without a VALUES clause in a WHEN NOT MATCHED clause

○ PRIMARY KEY search condition in the ON clause

○ WITH AUTO NAME clause in the USING clause

If you do not specify into-column-list, then into-column-list is assumed to contain all the columns of the
target-object.

USING clause Use this clause to define the source of the data you are merging from. source-object can
be a base table (including table hints), a view, a materialized view, a derived table, or a procedure. If
source-object is a derived table, you can specify using-column-list. All columns of source-object are used
if you do not specify using-column-list.

WITH AUTO NAME clause Use this clause to get the server to automatically use column names to
match columns in the into-column-list columns in target-object for the merge operation. The following
examples are equivalent and demonstrate that the order of the columns in into-column-list changes to
match the names of the columns in the source-object when WITH AUTO Name is specified:
... INTO T ( Name, ID, Description )
USING WITH AUTO NAME ( SELECT Description, Name, ID FROM PRODUCTS WHERE
Description LIKE '%cap%')
... INTO T ( Description, Name, ID )
USING ( SELECT Description, Name, ID FROM PRODUCTS WHERE Description LIKE
'%cap%' )

ON clause Use this clause to specify the condition to match a row in source-object with rows in
target-object.

You can specify ON PRIMARY KEY to match source-object rows based on the target-object primary
key definition. source-object does not need a primary key. However, target-object must have a primary
key. When specifying ON PRIMARY KEY:

○ An error is returned if target-object is not a base table, or if it does not have a primary key.

○ An error is returned if one or more primary key columns are not included in into-column-list.

○ The number of columns in into-column-list and using-column-list can be different as long as every
primary key column in into-column-list has a corresponding matching column in using-column-list. For
example, if into-column-list is (I1, I2, I3), using-column-list is (U1, U2), and the primary key columns
are (I2, I3), an error is returned because column (I3) of the target-object primary key does not have a
match in the using-column-list.

○ Regardless of the definition of the primary key, matching of primary key columns in into-column-list to
expressions in using-column-list is based on the position of the primary key columns in into-column-

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 813


SQL statements

list. For example, suppose the primary key on target-object is defined as (B, C), and the into-column-
list is (E, C, F, A, D, B). When ON PRIMARY KEY is specified, target-object column B is compared
to the sixth element of using-column-list because column B is in the sixth position in the into-column-
list. Likewise, target-object column C is compared to the second element of using-column-list.
ON PRIMARY KEY is syntactic shorthand for a corresponding ON condition. For example, assume
that into-column-list is (I1, I2, .. In), and that the corresponding matched using-column-list is (U1,
U2, .. Um). Also assume that the primary key columns of target-object are I1, I2, I3 and all the primary
key columns are contained in into-column-list. In this case, merge-search-condition is defined as the
conjunct "I1=U1 AND I2=U2 AND I3=U3".

WHEN MATCHED and WHEN NOT MATCHED clauses Use the WHEN MATCHED and WHEN
NOT MATCHED clauses to define an action to take when a row from source-object matches or does not
match a row in target-object. You specify the action after the THEN keyword. You can control the
actions to take for subsets of matching or non-matching rows by specifying an additional AND clause.

The ON clause determines how rows from source-object are separated into matching and non-matching
rows. A row in source-object is considered a matching row when the ON clause is TRUE for at least one
row in target-object. A row from source-object is considered a non-matching row when the ON clause is
not TRUE for any rows in target-object. Use multiple WHEN MATCHED and WHEN NOT MATCHED
clauses to partition sets of matching and non-matching rows into disjoint subsets. Each subset is
processed by a WHEN clause. WHEN MATCHED and WHEN NOT MATCHED clauses are processed
in the order they appear in the MERGE statement.

The search condition specified in the AND clause of a WHEN MATCHED or WHEN NOT MATCHED
clause determines if a candidate row is processed by the specific clause. When you specify a WHEN
MATCHED or WHEN NOT MATCHED clause without the AND clause the search condition in the
AND clause is assumed to be TRUE. If a row satisfies the AND condition for more than one clause, the
row is processed by the clause that appears first in the MERGE statement.

An error is returned when any of the WHEN MATCHED clauses process the same target-object row
more than once. A target-object row can belong to the same subset of the same WHEN MATCHED
clause more than once if it matches two different input rows from the source-object.

In the following example an error is returned because the row with ID 300 from the target-object Products
matches 111 rows from the source-object SalesOrderItems. All the matches belong to the same subset
corresponding to the WHEN MATCHED THEN UPDATE clause.
MERGE INTO Products
USING SalesOrderItems S
ON S.ProductID = Products.ID
WHEN MATCHED THEN UPDATE SET Products.Quantity = 20;

WHEN MATCHED: For a matching row, you can specify one of the following actions for match-action:

○ DELETE Specify DELETE to delete the row from target-object.

○ RAISERROR Specify RAISERROR to terminate the merge operation, roll back any changes, and
return an error. By default, when you specify RAISERROR, the database server returns SQLSTATE
23510 and SQLCODE -1254.

814 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Optionally, you can customize the SQLCODE that is returned by specifying the error-number
parameter after the RAISERROR keyword. The custom SQLCODE must be a positive integer greater
than 17000, and can be specified either as a number or a variable. When you specify a custom
SQLCODE, the number returned is a negative number.

For example, if you specify WHEN MATCHED AND search-condition THEN RAISERROR
17001, then, when a row is found that satisfies the conditions of the WHEN clause, the merge
operation fails, changes are rolled back, and the error returned has SQLSTATE 23510 and SQLCODE
-17001.

○ SKIP Specify SKIP to skip the row; no action is taken.

○ UPDATE Specify UPDATE SET to update the row using the set-item values. set-item is a simple
assignment expression where a column is set to the value of expression. There are no restrictions on
the expression. You can also specify DEFAULT to set the column to the default defined for the
column.

For example, UPDATE SET target-column1=DEFAULT, target-column2=source-


column2 sets target-column1 to its default value and sets target-column2 to be the same as the
modify row from source-column2 in source-object.

If you do not specify the SET clause, the SET clause is defined by into-column-list and using-column-
list. For example, if into-column-list is (I1, I2, .. In), and using-column-list is (U1, U2, .. Un) the SET
clause is assumed to be "SET I1=U1 , I2=U2 , .. In=Un".

WHEN NOT MATCHED: For a non-matching row, you can specify one of the following actions for
non-match-action:

○ INSERT Specify INSERT...VALUES to insert the row using the specified values. When you
specify the INSERT clause without a VALUES clause, the VALUES clause is defined by into-
column-list and using-column-list. For example, if into-column-list is (I1, I2, .. In), and using-column-
list is (U1, U2, .. Un), the INSERT without a VALUES clause is equivalent to INSERT (I1,
I2, .. In) VALUES (U1, U2, .. Un).

○ RAISERROR Specify RAISERROR to terminate the merge operation, roll back any changes, and
return an error. When you specify RAISERROR, the database server returns SQLSTATE 23510 and
SQLCODE -1254 by default. Optionally, you can customize the SQLCODE that is returned by
specifying the error-number parameter after the RAISERROR keyword. The custom SQLCODE must
be a positive integer greater than 17000, and can be specified either as a number or a variable. When
you specify a custom SQLCODE, the number returned is a negative number.

For example, if you specify WHEN NOT MATCHED AND search-condition THEN
RAISERROR 17001, then, when a row is found that satisfies the conditions of the WHEN clause,
the merge operation fails, changes are rolled back, and the error returned has SQLSTATE 23510 and
SQLCODE -17001.

○ SKIP Specify SKIP to skip the row; no action is taken.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 815


SQL statements

OPTION clause Use this clause to specify hints for executing the statement. The following hints are
supported:

○ MATERIALIZED VIEW OPTIMIZATION option-value


○ FORCE OPTIMIZATION
○ option-name = option-value. Note that a OPTION( isolation_level = ... ) specification
in the query text overrides all other means of specifying isolation level for a query.

Remarks
Rows in source-object are compared to rows in target-object and found to be matching or non-matching
depending on whether they satisfy the conditions of the ON clause. Rows in source-object are considered
a match if there exists at least one row in target-table such that merge-search-condition evaluates to true.
Matching rows and non-matching rows are then grouped by the actions defined for them in the WHEN
MATCHED and WHEN NOT MATCHED clauses according to the search conditions specified by the
AND clauses. The process of grouping rows by matched and non-matched actions is referred to as
branching, and each group is referred to as a branch.

Once branching is complete, the database begins executing the action defined for the rows of the branch.
Branches are processed in the order in which they occur, which matches the order in which the WHEN
clauses occur in the statement. If, during branching, more than one row in source-object has an action
defined for the same row in target-object, the merge operation fails and an error is returned. This prevents
the merge operation from performing more than one action on any given row in target-object.

As branches are processed, the insert, update, and delete actions are recorded in the transaction log as
their respective INSERT, UPDATE, and DELETE statements.

Permissions
DBA authority, or:

● INSERT, UPDATE, and DELETE permissions on target-object if the INSERT, UPDATE or DELETE
action is specified in the MERGE statement.

● SELECT permission is required on any objects referenced in the MERGE statement.

● EXECUTE permission is required on any procedure referenced in the MERGE statement.

Side effects
Any triggers defined for target-object are fired.

816 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “Import data with the MERGE statement” [SQL Anywhere Server - SQL Usage]
● “UPDATE statement” on page 948
● “INSERT statement” on page 780
● “DELETE statement” on page 678
● “SELECT statement” on page 871
● “Search conditions” on page 32
● “MERGE statement for table '%1' failed because of a RAISERROR specification in the statement”
[Error Messages]
● “Using the RAISERROR action” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 The MERGE statement comprises features F312 and F313 of the SQL/2008 standard.
The MERGE statement in SQL Anywhere is compliant with the MERGE statement specification in
the SQL/2008 standard, with additional extensions. The SQL Anywhere-specific extensions to the
MERGE statement include:

○ DELETE in a WHEN MATCHED clause

○ RAISERROR in a WHEN [NOT] MATCHED clause

○ SKIP in a WHEN [NOT] MATCHED clause

○ OPTION clause

○ PRIMARY KEY clause

○ DEFAULTS clause

○ INSERT clause without a VALUES clause

○ WITH AUTO NAME clause

○ UPDATE clause without the SET clause

Examples
The following example merges a row from a derived table into the Products table, effectively adding a
new tee shirt with the same attributes as an existing tee shirt, but with a new color, quantity, and product
identifier. In this example if the product with identification number 304 already exists in the Products
table then the row is not inserted:
MERGE INTO Products ( ID, Name, Description, Size, Color, Quantity,
UnitPrice, Photo )
USING WITH AUTO NAME (
SELECT 304 AS ID,
'Purple' AS Color,
100 AS Quantity,
Name,
Description,
Size,
UnitPrice,
Photo

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 817


SQL statements

FROM Products WHERE Products.ID = 300 ) AS DT


ON PRIMARY KEY
WHEN NOT MATCHED THEN INSERT;

The following example is equivalent to the previous, but does not use syntactic shorthand:
MERGE INTO Products ( ID, Name, Description, Size, Color, Quantity,
UnitPrice, Photo )
USING (
SELECT 304 AS ID,
'Purple' AS Color,
100 AS Quantity,
Name,
Description,
Size,
UnitPrice,
Photo
FROM Products WHERE Products.ID = 300 )
AS DT ( ID, Name, Description, Size, Color, Quantity, UnitPrice,
Photo )
ON ( Products.ID = DT.ID )
WHEN NOT MATCHED
THEN INSERT ( ID, Name, Description, Size, Color, Quantity, UnitPrice,
Photo )
VALUES ( DT.ID, DT.Name, DT.Description, DT.Size, DT.Color,
DT.Quantity, DT.UnitPrice, DT.Photo );

MESSAGE statement
Displays a message.

Syntax
MESSAGE expression
[ TYPE { INFO | ACTION | WARNING | STATUS } ]
[ TO { CONSOLE
| CLIENT [ FOR { CONNECTION conn-id-number [ IMMEDIATE ] | ALL } ]
| [ EVENT | SYSTEM ] LOG }
[ DEBUG ONLY ] ]

conn-id : integer

Parameters
TYPE clause This clause specifies the message type. The client application must decide how to handle
the message. For example, if you specify TO CLIENT, Interactive SQL displays messages in the
following locations:

○ INFO The Messages tab. INFO is the default type.

○ ACTION A window with an OK button.

○ WARNING A window with an OK button.

○ STATUS The Messages tab.

TO clause This clause specifies the destination of a message:

818 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ CONSOLE Send messages to the database server messages window and the database server
message log file if one has been specified. 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 database server message log file specified by the -o option. If EVENT
or SYSTEM is specified, the message is also written to the database server messages window and to
the Windows event log under event source SQLANY 12.0 Admin and to the Unix Syslog under the
name SQLANY 12.0 Admin (servername). Messages in the database server message log are identified
as follows:

● i Messages of type INFO or STATUS.

● w Messages of type WARNING.

● e Messages of type ACTION.

FOR clause For messages TO CLIENT, this clause specifies which connections receive notification
about the message. By default, the connection receives the message the next time a SQL statement or a
WAITFOR DELAY statement is executed.

○ CONNECTION conn-id-number Specify the recipient's connection ID number. If IMMEDIATE


is specified, the connection receives the message within a few seconds regardless of when the SQL
statement is executed.

○ ALL Specify that all open connections receive the message.

DEBUG ONLY This clause allows you to control whether debugging messages added to stored
procedures and triggers are enabled or disabled by changing the setting of the debug_messages option.
When DEBUG ONLY is specified, the MESSAGE statement is executed only when the debug_messages
option is set to On.

Note
DEBUG ONLY messages are inexpensive when the debug_messages option is set to Off, so these
statements can usually be left in stored procedures on a production system. However, they should be used
sparingly in locations where they would be executed frequently; otherwise, they may result in a small
performance penalty.

Remarks
The MESSAGE statement displays a message, which can be any expression. Clauses can specify the
message type and where the message appears.

If the size of expression exceeds the database page size, expression is truncated to fit within the database
page size. To check the page size in effect for the database, you can query the PageSize database property
(SELECT DB_PROPERTY( 'PageSize' );).

The procedure executing a MESSAGE...TO CLIENT statement must be associated with a connection.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 819


SQL statements

For example, the window is not displayed in the following example because the event occurs outside a
connection.

CREATE EVENT CheckIdleTime


TYPE ServerIdle
WHERE event_condition( 'IdleTime' ) > 100
HANDLER
BEGIN
MESSAGE 'Idle server' TYPE WARNING TO CLIENT;
END;

However, in the following example, the message is written to the database server messages window.

CREATE EVENT CheckIdleTime


TYPE ServerIdle
WHERE event_condition( 'IdleTime' ) > 100
HANDLER
BEGIN
MESSAGE 'Idle server' TYPE WARNING TO CONSOLE;
END;

Valid expressions can include a quoted string or other constant, variable, or function.

The FOR clause can be used to notify another application of an event detected on the database server
without the need for the application to explicitly check for the event. When the FOR clause is used,
recipients receive the message the next time that they execute a SQL statement. If the recipient is
currently executing a SQL statement, the message is received when the statement completes. If the
statement being executed is a stored procedure call, the message is received before the call is completed.

If an application requires notification within a short time after the message is sent and when the
connection is not executing SQL statements, use the IMMEDIATE clause to implement client notification
and not multiple concurrent WAITFOR DELAY statements.

Typically, messages sent using the IMMEDIATE clause are delivered in less than five seconds, even if
the destination connection is not making database server requests. Message delivery could be delayed if
the client connection makes several requests per second, receives very large BLOB data, or if the client's
message callback executes for more than a second. In addition, sending more than one IMMEDIATE
message to a single connection every two seconds could delay message delivery or generate an error
message. If the client connection is disconnected, a successful MESSAGE...IMMEDIATE statement may
not be delivered.

Messages sent without the IMMEDIATE clause are only delivered when the client executes a specific
request, or a WAITFOR DELAY statement. As a result, the delivery time of messages is unlimited.

The IMMEDIATE clause requires a SQL Anywhere 11 or later DBLib, ODBC, or SQL Anywhere JDBC
driver. The IMMEDIATE clause is not supported by non-threaded Unix client libraries. An error message
is generated when a message is sent to a destination connection that does not support the IMMEDIATE
clause. An error message is generated when an IMMEDIATE message is sent to the same connection
executing the MESSAGE statement.

MESSAGE 'Please disconnect' TYPE WARNING TO CLIENT


FOR CONNECTION 16 IMMEDIATE;

820 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

A MESSAGE...TO CLIENT expression can be truncated to 2048 bytes. For messages sent with the
IMMEDIATE clause, the message expression can be truncated to the smaller of the packet size of the
connection or 2048 bytes.

Embedded SQL and ODBC clients receive messages via message callback functions. In each case, these
functions must be registered. In embedded SQL, the message callback is registered with
db_register_a_callback using the DB_CALLBACK_MESSAGE parameter. In ODBC, the message
callback is registered with SQLSetConnectAttr using the SA_REGISTER_MESSAGE_CALLBACK
parameter.

Permissions
DBA authority is required to execute a MESSAGE statement containing a FOR clause or a TO EVENT
LOG or TO SYSTEM LOG clause.

Side effects
None.

See also
● “sa_conn_info system procedure” on page 1020
● “CREATE PROCEDURE statement” on page 585
● “debug_messages option” [SQL Anywhere Server - Database Administration]
● “db_register_a_callback function” [SQL Anywhere Server - Programming]
● “WAITFOR statement” on page 957

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following procedure displays a message in the database server messages window:
CREATE PROCEDURE message_text( )
BEGIN
MESSAGE 'The current date and time: ', Now( );
END;

The following statement displays the string The current date and time, followed by the current
date and time, in the database server messages window.
CALL message_text( );

OPEN statement [ESQL] [SP]


Opens a previously declared cursor to access information from the database.

Syntax 1 [ESQL]
OPEN cursor-name
[ USING { DESCRIPTOR sqlda-name | hostvar, ... } ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 821


SQL statements

[ WITH HOLD ]
[ ISOLATION LEVEL isolation-level ]
[ BLOCK n ]

Syntax 2 [SP]
OPEN cursor-name
[ WITH HOLD ]
[ ISOLATION LEVEL isolation-level ]

cursor-name : identifier | hostvar

sqlda-name : identifier

isolation-level : 0 | 1 | 2 | 3 | SNAPSHOT | STATEMENT SNAPSHOT | READONLY STATEMENT


SNAPSHOT

Parameters
USING DESCRIPTOR clause The USING DESCRIPTOR clause is for embedded SQL only. It
specifies the host variables to be bound to the placeholder bind variables in the SELECT statement for
which the cursor has been declared.

OPEN...USING cannot be used in a stored procedure.

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 remains 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.

Upon COMMIT or ROLLBACK, all long-term row locks held by the connection are released, including
those rows that constitute the result set of a WITH HOLD cursor. However, cursor stability locks, which
are acquired at isolation levels 1, 2, and 3, are retained for the life of the cursor and are only released
when the cursor is closed or when the connection terminates.

Upon completion of a ROLLBACK statement, the contents of, and positioning within, a WITH HOLD
cursor are unpredictable and are not guaranteed. You can use the ansi_close_cursors_on_rollback option
to control whether or not a ROLLBACK statement will close WITH HOLD cursors automatically.

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
are 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.

822 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The following values are supported:

○ 0
○ 1
○ 2
○ 3
○ SNAPSHOT
○ STATEMENT SNAPSHOT
○ READONLY STATEMENT SNAPSHOT

The cursor is positioned before the first row.

BLOCK clause This clause is for embedded SQL use only. 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 BLOCK clause can reduce the number of rows prefetched. Specifying the BLOCK clause
on OPEN is the same as specifying the BLOCK clause on each FETCH.

Remarks
The OPEN statement opens the named cursor. The cursor must be previously declared.

The OPEN statement may return a SQL warning if the cursor type does not match the characteristics of
the cursor's underlying statement.

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.

● 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 is 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, but this can be expensive.

If cursor-name is specified by an identifier or string, the corresponding DECLARE CURSOR


statement must appear before 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.

Permissions
Must have SELECT permission on all tables in a SELECT statement, or EXECUTE permission on the
procedure in a CALL statement.

Side effects
OPEN causes the complete materialization of an INSENSITIVE cursor's result set.

If access plan caching is enabled, some SQL warnings that would be returned to the application at OPEN
time may be suppressed. The suppressed warnings include warnings to indicate that the cursor type has

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 823


SQL statements

changed, that the underlying query is not deterministic, or that string truncation has occurred with one or
more literal constants embedded in the statement.

See also
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “RESUME statement” on page 857
● “PREPARE statement [ESQL]” on page 833
● “FETCH statement [ESQL] [SP]” on page 728
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “RESUME statement” on page 857
● “CLOSE statement [ESQL] [SP]” on page 498
● “FOR statement” on page 733
● “ansi_close_cursors_on_rollback option” [SQL Anywhere Server - Database Administration]
● “Plan caching” [SQL Anywhere Server - SQL Usage]
● “Insensitive cursors” [SQL Anywhere Server - Programming]
● “row_counts option” [SQL Anywhere Server - Database Administration]
● “close_on_endtrans option” [SQL Anywhere Server - Database Administration]
● “Cursors in embedded SQL” [SQL Anywhere Server - Programming]
● “Cursors in procedures, triggers, user-defined functions, and batches” [SQL Anywhere Server - SQL
Usage]
● “How locking works” [SQL Anywhere Server - SQL Usage]
● “Lock duration” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Use of the OPEN statement within embedded SQL is part of optional SQL language
feature B031, "Basic dynamic SQL". The use of the OPEN statement within a stored procedure is a
core feature of SQL/2008. The ISOLATION LEVEL and BLOCK clauses are vendor extensions, as is
the ability to OPEN a cursor over a CALL statement. In the SQL/2008 standard, WITH HOLD is
specified as part of the DECLARE CURSOR statement, and not on OPEN.

The setting of specific values in the SQLCA is a vendor extension.

● Transact-SQL The OPEN statement is supported by Adaptive Server Enterprise. Adaptive Server
Enterprise does not support the ISOLATION LEVEL, BLOCK, and WITH HOLD clauses.

Example
The following examples show the use of OPEN in embedded SQL.
EXEC SQL OPEN employee_cursor;

and
EXEC SQL PREPARE emp_stat FROM
'SELECT empnum, empname FROM Employees 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

824 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

SELECT Surname
FROM Employees;
DECLARE name CHAR(40);
OPEN cur_employee;
LP: LOOP
FETCH NEXT cur_employee INTO name;
IF SQLCODE <> 0 THEN LEAVE LP END IF;
...
END LOOP
CLOSE cur_employee;
END

OUTPUT statement [Interactive SQL]


Outputs the current query results to a file or ODBC data source.

Syntax 1 - Output to a file


OUTPUT TO filename
[ APPEND ]
[ BYTE ORDER MARK { ON | OFF }
[ COLUMN WIDTHS ( integer, ... ) ]
[ DELIMITED BY string ]
[ ENCODING encoding ]
[ ESCAPE CHARACTER character ]
[ ESCAPES { ON | OFF }
[ FORMAT output-format ]
[ HEXADECIMAL { ON | OFF | ASIS } ]
[ QUOTE string [ ALL ] ]
[ VERBOSE ]
[ WITH COLUMN NAMES ]

output-format :
TEXT
| FIXED
| HTML
| SQL
| XML

encoding : string | identifier

Syntax 2 - Output to an ODBC data source


OUTPUT
USING connection-string
INTO destination-table-name
[ CREATE TABLE { ON | OFF } ]

connection-string :
{ DSN = odbc-data-source
| DRIVER = odbc-driver-name [; connection-parameter = value [; ... ] ] }

Parameters
APPEND clause This optional keyword is used to append the results of the query to the end of an
existing output file without overwriting the previous contents of the file. If the APPEND clause is not

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 825


SQL statements

used, the OUTPUT statement overwrites the contents of the output file by default. The APPEND keyword
is valid if the output format is TEXT, FIXED, or SQL.

BYTE ORDER MARK clause Use this clause to specify whether to include a byte order mark (BOM)
at the start of a Unicode file. By default, this option is ON, which directs Interactive SQL to write a byte
order mark (BOM) at the beginning of the file. If BYTE ORDER MARK is OFF, DBISQL does not write
a BOM.

The BYTE ORDER MARK clause is relevant only when writing TEXT formatted files. Attempts to use
the BYTE ORDER MARK clause with FORMAT clauses other than TEXT returns an error.

The BYTE ORDER MARK clause is used only when reading or writing files encoded with UTF-8 or
UTF-16 (and their variants). Attempts to use the BYTE ORDER MARK clause with any other encoding
returns an error.

COLUMN WIDTHS clause The COLUMN WIDTHS clause is used to specify the column widths for
the FIXED format output.

CREATE TABLE clause Use the CREATE TABLE clause to specify whether to create the destination
table if it does not exist. The default is ON.

DELIMITED BY clause The DELIMITED BY clause is for the TEXT output format only. The
delimiter string is placed between columns. The default is comma.

ENCODING clause The ENCODING clause allows you to specify the encoding that is used to write
the file. The ENCODING clause can only be used with the TEXT format.

The ENCODING clause is useful when you have data that cannot be represented in the operating system
character set. In this case, if you do not use the ENCODING clause, characters that cannot be represented
in the default encoding are lost in the output (that is, a lossy conversion occurs).

If the input file was created using the OUTPUT statement and an encoding was specified, then the same
ENCODING clause should be specified on the INPUT statement.

When running Interactive SQL, the encoding that is used to export the data is determined in the following
order:

○ The encoding specified by the ENCODING clause (if this clause is specified)

○ The encoding specified with the default_isql_encoding option (if this option is set).

○ The default encoding for the platform you are running on. On English Windows computers, the default
encoding is 1252.

ESCAPE CHARACTER clause The default escape character for characters stored as hexadecimal
codes and symbols is a backslash (\). For example, \x0A is the linefeed character.

This can be changed using the ESCAPE CHARACTER clause. For example, to use the exclamation mark
as the escape character, specify:
... ESCAPE CHARACTER '!'

826 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The new line character can be specified as '\n'. Other characters can be specified using 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 is interpreted as a backslash and the letter q.

ESCAPES clause With ESCAPES turned on (the default), characters following the backslash
character are recognized and interpreted as special characters by the database server. With ESCAPES
turned off, the characters are written exactly as they appear in the source data.

FORMAT clause The FORMAT clause allows you to specify the file format for the output. If you do
not specify the FORMAT clause, the format specified by the output_format option is used. If you specify
the FORMAT clause, the setting of the output_format option is ignored. The default output format is
TEXT. Allowable output formats are:

○ TEXT The output is a TEXT 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) are quoted. TEXT is the default output type.

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.

If you want to output to TEXT but do not want to include quotes or newlines in your output, turn off
quotes and escapes as follows: QUOTE '' ESCAPES OFF.

○ FIXED The output is fixed format with each column having a fixed width. The width for each
column can be specified using the COLUMN WIDTHS clause. No column headings are output in this
format.

If the COLUMN WIDTHS 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 default to 32 KB.

○ HTML The output is in the Hyper Text Markup Language format.

○ SQL The output is an Interactive SQL INPUT statement (required to recreate the information in the
table) in a .sql file.

○ XML The output is an XML file encoded in UTF-8 and containing an embedded DTD. Binary
values are encoded in CDATA blocks with the binary data rendered as 2-hex-digit strings.

HEXADECIMAL clause The HEXADECIMAL clause specifies how binary values are output for the
TEXT format. Allowable values are:

○ ON When set to ON, binary values are written with an Ox prefix followed by a series of
hexadecimal pairs; for example, 0xabcd.

○ OFF When set to OFF, unprintable character values are prefixed with the escape character, such as
a backslash, followed by an x, and then followed by the hexadecimal pair for the byte. Printable
characters are output as-is.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 827


SQL statements

For example, the following command outputs a file which contains 'one\x0Atwo\x0Athree':
SELECT 'one\ntwo\nthree'
OUTPUT TO 'test.txt' HEXADECIMAL OFF;

○ ASIS When set to ASIS, values are written as is, without any escaping, even if the values contain
control characters. ASIS is useful for text that contains formatting characters such as tabs or carriage
returns.

QUOTE clause The QUOTE clause is for the TEXT output format only. The quote string is placed
around string values. The default is a single quote ('). If ALL is specified in the QUOTE clause, the quote
string is placed around all values, not just around strings. To suppress quoting, specify empty single
quotes. For example, QUOTE ''.

USING clause The USING clause exports data to an ODBC data source. You can either specify the
ODBC data source name with the DSN option, or the ODBC driver name and connection parameters with
the DRIVER option. Connection-parameter is an optional list of database-specific connection parameters.

Odbc-data-source is the name of a user or ODBC data source name. For example, odbc-data-source for
the SQL Anywhere sample database is SQL Anywhere 12 Demo.

Odbc-driver-name is the ODBC driver name. For a SQL Anywhere database, the odbc-driver-name is
SQL Anywhere; for an UltraLite database, odbc-driver-name is UltraLite 12.

VERBOSE clause When the optional VERBOSE keyword is included, error messages about the
query, the SQL statement used to select the data, and the data itself are written to the output file. Lines
that do not contain data are prefixed by two hyphens. If VERBOSE is omitted (the default) only the data
is written to the file. The VERBOSE keyword is valid if the output format is TEXT, FIXED, or SQL.

WITH COLUMN NAMES clause The WITH COLUMN NAMES clause inserts the column names in
the first line of the text file. The WITH COLUMN NAMES clause is for TEXT format only.

Remarks
The OUTPUT statement outputs data to a file or database. The OUTPUT statement is used directly after a
statement that retrieves the data to be output.

To export multiple result sets, use syntax 1 and set the isql_show_multiple_result_sets option to On.
Interactive SQL creates a file for each result set. The files are named filename-x, where x is a counter
starting at 1. For example, specifying OUTPUT TO a file named data.txt results in files named data-1.txt,
data-2.txt, and so on.

You cannot use syntax 2 to export multiple result sets.

The output format can be specified with the optional FORMAT clause. The default format is TEXT. If no
FORMAT clause is specified, the Interactive SQL output_format option setting is used.

Because the OUTPUT statement is an Interactive SQL command, it cannot be used in any compound
statement (such as IF), or in a stored procedure.

When exporting columns containing BINARY or LONG BINARY data to a Microsoft Excel workbook,
you must convert the data to a string or number. In addition, when data is exported to a Microsoft Excel

828 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

workbook, the data is read-only unless the ReadOnly parameter is set to zero or turned off when the DSN
option is selected.

Permissions
None.

Side effects
In Interactive SQL, the Results tab displays the results of the current query.

See also
● “SELECT statement” on page 871
● “INPUT statement [Interactive SQL]” on page 773
● “UNLOAD statement” on page 937
● “output_format option [Interactive SQL]” [SQL Anywhere Server - Database Administration]
● “Data import and export” [SQL Anywhere Server - SQL Usage]
● “default_isql_encoding option [Interactive SQL]” [SQL Anywhere Server - Database Administration]
● “isql_show_multiple_result_sets option [Interactive SQL]” [SQL Anywhere Server - Database
Administration]
● “Interactive SQL” [SQL Anywhere Server - Database Administration]
● “Export data with the OUTPUT statement” [SQL Anywhere Server - SQL Usage]
● “Statements allowed in procedures, triggers, events, and batches” [SQL Anywhere Server - SQL
Usage]
● “Returning multiple result sets from procedures” [SQL Anywhere Server - SQL Usage]
● “output_format option [Interactive SQL]” [SQL Anywhere Server - Database Administration]
● “Supported character sets” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
Place the contents of the Employees table in a text file:
SELECT *
FROM Employees;
OUTPUT TO 'Employees.txt'
FORMAT TEXT;

Place the contents of the Employees table at the end of an existing text file, and include any messages
about the query in this file as well:
SELECT *
FROM Employees;
OUTPUT TO 'Employees.txt'
APPEND VERBOSE;

Suppose you need to export a value that contains an embedded line feed character. A line feed character
has the numeric value 10, which you can represent as the string '\x0a' in a SQL statement. For example,
execute the following statement, with HEXADECIMAL set to ON:
SELECT CAST ('line1\x0aline2' AS VARBINARY);
OUTPUT TO 'file.txt' HEXADECIMAL ON;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 829


SQL statements

You get a file with one line in it containing the following text:
0x6c696e65310a6c696e6532

But if you execute the same statement with HEXADECIMAL set to OFF, you get the following:
'line1\x0Aline2'

Finally, if you set HEXADECIMAL to ASIS, you get a file with two lines:
'line1
line2'

You get two lines when you use ASIS because the embedded line feed character has been exported
without being converted to a two digit hexadecimal representation, and without being prefixed by
anything.

The following example outputs the data from the Customers table to a new table, Customers2:
SELECT * FROM Customers;
OUTPUT USING 'dsn=SQL Anywhere 12 Demo'
INTO "Customers2";

The following example copies the Customers table from the sample database to a database called
mydatabase.db, using the DRIVER option.
SELECT * FROM Customers;
OUTPUT USING 'DRIVER=SQL Anywhere 12;uid=dba;pwd=sql;dbf=c:\test
\mydatabase.db'
INTO "Customers";

The following example copies the Customers table from the SQL Anywhere sample database into a table
called Customers in a fictitious UltraLite database, myULDatabase.db, using the DRIVER option.
SELECT * FROM Customers;
OUTPUT USING 'DRIVER=UltraLite 12;dbf=c:\test\myULDatabase.udb'
INTO "Customers";

The following example copies the Customers table into a fictitious MySQL database called mydatabase,
using the DRIVER option.
SELECT * FROM Customers;
OUTPUT USING 'DRIVER=MySQL ODBC 5.1
Driver;DATABASE=mydatabase;SERVER=mySQLHost;UID=me;PWD=secret'
INTO "Customers";

PARAMETERS statement [Interactive SQL]


Specifies parameters to an Interactive SQL script file.

Syntax
PARAMETERS parameter1, parameter2, ...

830 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
The PARAMETERS statement names the parameters for a script file, so that they can be referenced later
in the script file.

Parameters are referenced by putting {parameter1} into the file where you want the named parameter
to be substituted. There must be no spaces between the braces and the parameter name.

If a script file is invoked with less than the required number of parameters, Interactive SQL prompts for
values of the missing parameters.

Permissions
None.

Side effects
None.

See also
● “READ statement [Interactive SQL]” on page 840
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following Interactive SQL script file takes two parameters.
PARAMETERS department_id, file;
SELECT Surname
FROM Employees
WHERE DepartmentID = {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]

PASSTHROUGH statement [SQL Remote]


Starts or stops passthrough mode for SQL Remote administration. Syntaxes 1 and 2 start passthrough
mode, while syntax 3 stops passthrough mode.

Syntax 1
PASSTHROUGH [ ONLY ] FOR userid, ...

Syntax 2
PASSTHROUGH [ ONLY ] FOR SUBSCRIPTION
TO [ owner. ]publication-name [ ( constant ) ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 831


SQL statements

Syntax 3
PASSTHROUGH STOP

Remarks
In passthrough mode, any SQL statements are executed by the database server, and are also placed into
the transaction log to be sent in messages to subscribers. If the ONLY keyword is used to start
passthrough mode, the statements are not executed at the server; they are sent to recipients only. When a
passthrough session contains calls to stored procedures, the procedures must exist in the server that is
issuing the passthrough commands, even if they are not being executed locally at the server. The
recipients of the passthrough SQL statements are either a list of user IDs (syntax 1) or all subscribers to a
given publication. Passthrough mode may be used to apply changes to a remote database from the
consolidated database or send statements from a remote database to the consolidated database.

Syntax 2 sends statements to remote databases whose subscriptions are started, and does not send
statements to remote databases whose subscriptions are created and not started.

Syntax 3 stops passthrough mode on the current connection. You must execute the PASSTHROUGH
STOP statement on the same connection that initiated the passthrough mode. If you use syntax 1 or 2 to
start passthrough mode on a connection and it disconnects before a PASSTHROUGH STOP statement is
executed, the disconnect implicitly executes a PASSTHROUGH STOP statement.

Permissions
DBA authority.

Side effects
None.

Standards and compatibility


● SQL/2008 Vendor extension.

See also
● “FORWARD TO statement” on page 736
● “UNLOAD statement” on page 937
● “Connectivity tests” [SQL Anywhere Server - SQL Usage]
● “SQL Remote passthrough mode” [SQL Remote]
● “Start and stop passthrough mode” [SQL Remote]
● “Passthrough mode limitations” [SQL Remote]
● “Changes to avoid on a running system” [SQL Remote]
● “Upgrades and resynchronization” [SQL Remote]
● “Subscription resynchronization” [SQL Remote]

Example
PASSTHROUGH FOR rem_db ;
...
( SQL statements to be executed at the remote database )
...
PASSTHROUGH STOP ;

832 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

PREPARE statement [ESQL]


Prepares a statement to be executed later, or defines a cursor.

Syntax
PREPARE statement-name
FROM statement [ FOR { UPDATE [ cursor-concurrency ] | READ ONLY } ]
[ DESCRIBE describe-type INTO [ [ SQL ] DESCRIPTOR ] descriptor ]
[ WITH EXECUTE ]

statement-name : identifier | hostvar

statement : string | hostvar

describe-type :
[ ALL | BIND VARIABLES | INPUT | OUTPUT | SELECT LIST ]
[ LONG NAMES [ [ [ OWNER. ]TABLE. ]COLUMN ]
| WITH VARIABLE RESULT ]

cursor-concurrency :
BY { VALUES | TIMESTAMP | LOCK }

Parameters
statement-name The statement name can be an identifier or host variable. However, you should not
use an identifier when using multiple SQLCAs. If you do, two prepared statements may have the same
statement number, which could cause the wrong statement to be executed or opened. Also, using an
identifier for a statement name is not recommended for multithreaded applications where the statement
name may be referenced by multiple threads concurrently.

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.

FOR UPDATE | FOR READ ONLY Defines the cursor updatability if the statement is used by a
cursor. A FOR READ ONLY cursor cannot be used in an UPDATE (positioned) or a DELETE
(positioned) operation. FOR READ ONLY is the default.

In response to any request for a cursor that specifies FOR UPDATE, SQL Anywhere provides either a
value-sensitive cursor or a sensitive cursor. Insensitive and asensitive cursors are not updatable.

BY VALUES | BY TIMESTAMP The database server utilizes a keyset-driven cursor to enable the
application to be informed when rows have been modified or deleted as the result set is scrolled.

BY LOCK clause The database server acquires intent row locks on fetched rows of the result set.
These are long-term locks that are held until the transaction is committed or rolled back.

● 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.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 833


SQL statements

The DESCRIBE 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 re-describing is required.

Note
For compatibility reasons, preparing COMMIT, PREPARE TO COMMIT, and ROLLBACK
statements is still supported. However, it is recommended 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.

Remarks
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 or CALL 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 defined by the database during the PREPARE
statement, and you do not need to initialize it.

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.

834 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “DESCRIBE statement [ESQL]” on page 681
● “OPEN statement [ESQL] [SP]” on page 821
● “EXECUTE statement [ESQL]” on page 722
● “DROP STATEMENT statement [ESQL]” on page 706
● “Statement cannot be executed” [Error Messages]
● “Dynamic SQL statements” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 PREPARE is part of optional SQL/2008 language feature B031, "Basic dynamic SQL".
The optional FOR UPDATE, FOR READ ONLY, DESCRIBE, and WITH EXECUTE clauses are
vendor extensions.

Example
The following statement prepares a simple query:
EXEC SQL PREPARE employee_statement FROM
'SELECT Surname FROM Employees';

PREPARE TO COMMIT statement


Checks whether a COMMIT can be performed successfully.

Syntax
PREPARE TO COMMIT

Remarks
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.

The PREPARE TO COMMIT statement cannot be used in stored procedures, triggers, events, or batches.

Permissions
None.

Side effects
None.

See also
● “COMMIT statement” on page 501
● “ROLLBACK statement” on page 865

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 835


SQL statements

Example
The following sequence of statements leads to an error because of foreign key checking on the Employees
table.
EXECUTE IMMEDIATE
"SET OPTION wait_for_commit = 'On'";
EXECUTE IMMEDIATE "DELETE FROM Employees
WHERE EmployeeID = 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 Departments
WHERE DepartmentID = 100;
PREPARE TO COMMIT;

PRINT statement [T-SQL]


Returns a message to the client, or display a message in the database server messages window.

Syntax
PRINT format-string [, arg-list ]

Remarks
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 in the database server messages 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.

Permissions
None.

Side effects
None.

See also
● “MESSAGE statement” on page 818

Standards and compatibility


● SQL/2008 Transact-SQL extension.

Example
The following statement displays a message:

836 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

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

PUT statement [ESQL]


Inserts a row into the specified cursor.

Syntax
PUT cursor-name
{ USING DESCRIPTOR sqlda-name | FROM hostvar-list }
[ INTO { DESCRIPTOR sqlda-name | hostvar-list } ]
[ ARRAY :row-count ]

cursor-name : identifier | hostvar

sqlda-name : identifier

hostvar-list : may contain indicator variables

row-count : integer | hostvar

Remarks
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 is used; otherwise, a NULL value is used.

The second SQLDA or host variable list contains the results of the PUT statement.

The optional ARRAY clause can be used to perform wide puts, 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.

Note
For scroll (value-sensitive) cursors, the inserted row will appear if the new row matches the WHERE
clause and the keyset cursor has not finished populating. For dynamic cursors, if the inserted row matches
the WHERE clause, the row may appear. Insensitive cursors cannot be updated.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 837


SQL statements

Permissions
Must have INSERT permission.

Side effects
When inserting rows into a value-sensitive (keyset driven) cursor, the inserted rows appear at the end of
the result set, even when they do not match the WHERE clause of the query or if an ORDER BY clause
would normally have placed them at another location in the result set.

See also
● “UPDATE statement” on page 948
● “UPDATE (positioned) statement [ESQL] [SP]” on page 943
● “DELETE statement” on page 678
● “DELETE statement (positioned) [ESQL] [SP]” on page 676
● “INSERT statement” on page 780
● “SET statement” on page 899
● “Cursors used to modify rows” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement illustrates the use of PUT in embedded SQL:
EXEC SQL PUT cur_employee FROM :employeeID, :surname;

RAISERROR statement
Signals an error and sends a message to the client.

Syntax
RAISERROR error-number [ format-string ] [, arg-list ]

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 SQL 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
ISYSUSERMESSAGE system table.

To create new error messages, use the CREATE ERROR statement. To view the messages in the
ISYSUSERMESSAGE system table, query the SYSUSERMESSAGE system view.

In SQL Anywhere, the format-string length can be up to 255 bytes.

838 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The extended values supported by the Adaptive Server Enterprise RAISERROR statement are not
supported in SQL 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.

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.

Remarks
The RAISERROR statement allows user-defined errors to be signaled and sends a message on the client.

Permissions
None.

Side effects
None.

See also
● “BEGIN statement” on page 484
● “CREATE MESSAGE statement [T-SQL]” on page 563
● “SYSUSERMESSAGE system view” on page 1256
● “CREATE TRIGGER statement [T-SQL]” on page 657
● “CREATE TRIGGER statement” on page 651
● “on_tsql_error option” [SQL Anywhere Server - Database Administration]
● “login_procedure option” [SQL Anywhere Server - Database Administration]
● “continue_after_raiserror option” [SQL Anywhere Server - Database Administration]
● “SIGNAL statement [SP]” on page 906

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL The RAISERROR statement cannot be used in Transact-SQL compound statements


and procedures.

Example
The following statement raises error 23000, which is in the range for user-defined errors, and sends a
message to the client. Note that 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.
RAISERROR 23000 'Invalid entry for this column: %1!', @val

The next example uses RAISERROR to disallow connections.


CREATE PROCEDURE DBA.login_check()
BEGIN

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 839


SQL statements

// Allow a maximum of 3 concurrent connections


IF( DB_PROPERTY('ConnCount') > 3 ) THEN
RAISERROR 28000
'User %1! is not allowed to connect -- there are ' ||
'already %2! users logged on',
Current User,
CAST( DB_PROPERTY( 'ConnCount' ) AS INT )-1;
ELSE
CALL sp_login_environment;
END IF;
END
go
GRANT EXECUTE ON DBA.login_check TO PUBLIC
go
SET OPTION PUBLIC.login_procedure='DBA.login_check'
go

READ statement [Interactive SQL]


Reads Interactive SQL statements from a file.

Syntax
READ [ ENCODING encoding ] filename [ parameter ] ...

encoding : identifier | string

Parameters
● ENCODING The ENCODING clause allows you to specify the encoding that is used to read the
file. The READ statement does not process escape characters when it reads a file. It assumes that the
entire file is in the specified encoding.

When running Interactive SQL, the encoding that is used to read the data is determined in the
following order:

1. The encoding specified by the ENCODING clause (if this clause is specified).

2. The encoding specified by the byte order mark (BOM) in the file (if a BOM is specified).

3. The encoding specified with the default_isql_encoding option (if this option is set).

4. The default encoding for the platform you are running on. On English Windows computers, the
default encoding is 1252.

Remarks
The READ statement reads a sequence of Interactive SQL statements from the named file. This file can
contain any valid Interactive SQL statements, including other READ statements. READ statements can be
nested to any depth.

If filename has no file extension, Interactive SQL searches for the same file name with the extension .sql.

If filename does not contain an absolute path, Interactive SQL searches for the file. The location of
filename is determined based on the location of the READ statement, as follows:

840 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

● If the READ statement is executed directly in Interactive SQL, Interactive SQL first attempts to resolve
the path to filename relative to the directory in which Interactive SQL is running. If unsuccessful,
Interactive SQL looks for filename in the directories specified in the environment variable SQLPATH,
and then the directories specified in the environment variable PATH.

● If the READ statements reside in an external file (for example, a .sql file), Interactive SQL first
attempts to resolve the path to filename relative to the location of the external file. If unsuccessful,
Interactive SQL looks for filename in a path relative to the directory in which Interactive SQL is
running. If still unsuccessful, Interactive SQL looks in the directories specified in the environment
variable SQLPATH, and then the directories specified in the environment variable PATH.

Parameters can be listed after the name of the SQL script file. These parameters correspond to the
parameters named in the PARAMETERS statement at the beginning of the statement file.

Parameter names must be enclosed in square brackets. 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 script 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
that are not identifiers, numbers, or strings (contain spaces or tabs) must be enclosed in square brackets
([ ]). This allows for arbitrary textual substitution in the script file.

If not enough parameters are passed to the script file, Interactive SQL prompts for values for the missing
parameters.

When executing a reload.sql file with Interactive SQL, you must specify the encryption key as a
parameter. If you do not provide the key in the READ statement, Interactive SQL prompts for the key.

Permissions
None.

Side effects
None.

See also
● “PARAMETERS statement [Interactive SQL]” on page 830
● “default_isql_encoding option [Interactive SQL]” [SQL Anywhere Server - Database Administration]
● “Interactive SQL” [SQL Anywhere Server - Database Administration]
● “Interactive SQL utility (dbisql)” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following are examples of the READ statement.
READ status.rpt '160';
READ birthday.sql [>= '1988-1-1'] [<= '1988-1-30'];

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 841


SQL statements

To process a file that uses a specific OEM codepage, you need to specify the codepage. For example:
dbisql READ ENCODING 'cp437' myfile.sql

READTEXT statement [T-SQL]


Reads text and image values from the database, starting from a specified offset and reading a specified
number of bytes. This feature is provided solely for compatibility with Transact-SQL and its use is not
recommended.

Syntax
READTEXT table-name.column-name
text-pointer-offset text-size
[ HOLDLOCK ]

Remarks
READTEXT is used to read CHAR, NCHAR, and BINARY columns from a database. You cannot
perform READTEXT operations on views.

Permissions
SELECT permissions on the table.

Side effects
None.

See also
● “WRITETEXT statement [T-SQL]” on page 963
● “GET DATA statement [ESQL]” on page 749
● “TEXTPTR function [Text and image]” on page 360

Standards and compatibility


● SQL/2008 Transact-SQL extension.

Example
The following embedded SQL example uses TEXTPTR to locate the Description column associated with
ProductID 500 in the MarketingInformation table.

The text pointer is stored in the variable txtptr and supplied as a parameter to the READTEXT statement
which returns 55 bytes, starting at column offset 181.
EXEC SQL BEGIN DECLARE SECTION;
char hostvar[100];
EXEC SQL END DECLARE SECTION;

EXEC SQL create variable txtptr binary(16);


EXEC SQL set txtptr =
( SELECT textptr(Description)
FROM GROUPO.MarketingInformation

842 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

WHERE ProductID = '500' );


EXEC SQL PREPARE S1 FROM
'READTEXT GROUPO.MarketingInformation.Description txtptr 181 55';
EXEC SQL EXECUTE S1 INTO :hostvar;
printf( "hostvar: %s\n", hostvar );

READTEXT returns the following string.


Lightweight 100% organically grown cotton construction.

REFRESH MATERIALIZED VIEW statement


Initializes or refreshes the data in a materialized view by executing its query definition.

Syntax
REFRESH MATERIALIZED VIEW view-list
[ WITH {
ISOLATION LEVEL isolation-level
| { EXCLUSIVE | SHARE } MODE } ]
[ FORCE BUILD ]

view-list :
[ owner.]materialized-view-name [, ... ]

isolation-level :
READ UNCOMMITTED
| READ COMMITTED
| SERIALIZABLE
| REPEATABLE READ
| SNAPSHOT

Parameters
WITH clause Use the WITH clause to specify the type of locking to use on the underlying base tables
during the refresh. The type of locking determines how the materialized view is populated and how
concurrency for transactions is affected. The WITH clause setting does not impact the type of lock placed
on the materialized view itself, which is always an exclusive lock. The possible locking clauses you can
specify are:

○ ISOLATION LEVEL isolation-level Use WITH ISOLATION LEVEL to change the isolation
level for the execution of the refresh operation. The original isolation level is restored for the
connection when the statement completes.

For immediate views, isolation-level can only be SERIALIZABLE.

For snapshot isolation, only the transaction snapshot level is supported by the REFRESH
MATERIALIZED VIEW statement. You should specify SNAPSHOT as the isolation level. The
statement-snapshot and readonly-statement-snapshot levels are not supported.

○ EXCLUSIVE MODE Use WITH EXCLUSIVE MODE if you do not want to change the isolation
level, but want to guarantee that the data is updated to be consistent with committed data in the
underlying tables. When using WITH EXCLUSIVE MODE, exclusive table locks are placed on all

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 843


SQL statements

underlying base tables and no other transaction can execute queries, updates, or any other action
against the underlying table(s) until the refresh operation is complete. If exclusive table locks cannot
be obtained, the refresh operation fails and an error is returned.

○ SHARE MODE Use WITH SHARE MODE to give read access on underlying tables to other
transactions while the refresh operation takes place. When this clause is specified, shared table locks
are obtained on all underlying base tables before the refresh operation is performed and until the
refresh operation completes.

FORCE BUILD clause By default, when you execute a REFRESH MATERIALIZED VIEW
statement, the database server checks whether the materialized view is stale (that is, underlying tables
have changed since the materialized view was last refreshed). If it is not stale, the refresh does not take
place. Specify the FORCE BUILD clause to force a refresh of the materialized view regardless of whether
the materialized view is stale.

Remarks
Use this statement to initialize or refresh the materialized views listed in view-list.

If a REFRESH MATERIALIZED VIEW statement is executed against a materialized view that is not
stale, a refresh is not performed unless the FORCE BUILD clause is specified.

The default refresh behavior for locking and data concurrency is as follows:

● If the view is an immediate view, the default refresh behavior is WITH SHARE MODE, regardless of
whether snapshot isolation is enabled.

● If the view is a manual view and snapshot isolation is in use, the default is WITH ISOLATION LEVEL
SNAPSHOT.

● If the view is a manual view and snapshot isolation is not in use, the default is WITH SHARE MODE.

Several options need to have specific values for a REFRESH MATERIALIZED VIEW to succeed, and
for the view to be used in optimization. Additionally, there are option settings that are stored for each
materialized view when it is created. To refresh the view, or to use the view in optimization these option
settings must match the current options.

When a refresh fails after having done partial work, the view is left in an uninitialized state, and the data
cannot be restored to what it was before the refresh started. Examine the error that occurred when the
refresh failed, resolve the issue that caused the failure, and execute the REFRESH MATERIALIZED
VIEW statement again.

You can also use the IMMEDIATE REFRESH clause of the ALTER MATERIALIZED VIEW statement
to change the view to be refreshed immediately when underlying data changes.

This statement cannot be executed when the connection has cursors opened with the WITH HOLD clause
that use either statement or transaction snapshots.

Permissions
Must have INSERT permission on the materialized view, and SELECT permission on the tables in the
materialized view definition.

844 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
Any open cursors that reference the materialized view are closed.

A checkpoint is performed at the beginning of execution.

Automatic commits are performed at the beginning and end of execution.

While executing, an exclusive schema lock is placed on the materialized view being refreshed using the
connection blocking option, and shared schema locks, without blocking, are placed on all tables
referenced by the materialized view. If the WITH clause is specified, extra locks may be acquired on the
underlying tables. Also, until refreshing is complete, the materialized view is in an uninitialized state,
making it unavailable to the database server for either query optimization or query execution.

If the REFRESH MATERIALIZED VIEW statement executes using snapshot isolation, the database's
transaction log will contain both the REFRESH statement text and copies of all of the individual rows that
are inserted to the materialized view. The individual rows are necessary to ensure that, should the
database require recovery, the contents of the view after recovery matches precisely the view's contents
upon the original completion of the REFRESH MATERIALIZED VIEW statement. Moreover, the
individual rows in the transaction log are applied individually when the database is mirrored. For this
reason, you may wish to limit the frequency of REFRESH MATERIALIZED VIEW statements when
using snapshot isolation, or truncate the transaction log periodically, using the BACKUP statement, to
reduce the amount of disk space required for the transaction log.

See also
● “Materialized views” [SQL Anywhere Server - SQL Usage]
● “CREATE MATERIALIZED VIEW statement” on page 560
● “Transactions and isolation levels” [SQL Anywhere Server - SQL Usage]
● “Isolation levels and consistency” [SQL Anywhere Server - SQL Usage]
● “ALTER MATERIALIZED VIEW statement” on page 417
● “Isolation levels and consistency” [SQL Anywhere Server - SQL Usage]
● “blocking option” [SQL Anywhere Server - Database Administration]
● “Table locks” [SQL Anywhere Server - SQL Usage]
● “Schema locks” [SQL Anywhere Server - SQL Usage]
● “BACKUP statement” on page 477
● “allow_snapshot_isolation option” [SQL Anywhere Server - Database Administration]
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]
● “Materialized views restrictions” [SQL Anywhere Server - SQL Usage]
● “sa_refresh_materialized_views system procedure” on page 1108
● “sa_materialized_view_info system procedure” on page 1077
● “sa_materialized_view_can_be_immediate system procedure” on page 1076

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Suppose you create a materialized view, EmployeeConfid99, and then populate it with data using the
following statements:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 845


SQL statements

CREATE MATERIALIZED VIEW EmployeeConfid99 AS


SELECT EmployeeID, Employees.DepartmentID, SocialSecurityNumber, Salary,
ManagerID,
Departments.DepartmentName, Departments.DepartmentHeadID
FROM Employees, Departments
WHERE Employees.DepartmentID=Departments.DepartmentID;
REFRESH MATERIALIZED VIEW EmployeeConfid99;

Later, after the view has been in use, you want to refresh the view using the READ COMMITTED
isolation level (isolation level 1), and you want the view to be rebuilt. You could execute the following
statement:
REFRESH MATERIALIZED VIEW EmployeeConfid99
WITH ISOLATION LEVEL READ COMMITTED
FORCE BUILD;

Caution
When you are done with this example, you should drop the materialized view you created. Otherwise, you
cannot make schema changes to its underlying tables, Employees and Departments, when trying out other
examples. You cannot alter the schema of a table that has enabled, dependent materialized view. See
“Dropping a materialized view” [SQL Anywhere Server - SQL Usage].

REFRESH TEXT INDEX statement


Refreshes a text index.

Syntax
REFRESH TEXT INDEX text-index-name ON [ owner.]table-name
[ WITH {
ISOLATION LEVEL isolation-level
| EXCLUSIVE MODE
| SHARE MODE } ]
[ FORCE { BUILD | INCREMENTAL } ]

Parameters
WITH clause Use the WITH clause to specify what kind of locks to obtain on the underlying base
tables during the refresh. The types of locks obtained determine how the text index is populated and how
concurrency for transactions is affected. If you do not specify the WITH clause, the default is WITH
ISOLATION LEVEL READ UNCOMMITTED, regardless of any isolation level set for the connection.

You can specify the following WITH clause options:

○ ISOLATION LEVEL isolation-level Use WITH ISOLATION LEVEL to change the isolation
level for the execution of the refresh operation.

The original isolation level of the connection is restored at the end of the statement execution.

○ EXCLUSIVE MODE Use WITH EXCLUSIVE MODE if you do not want to change the isolation
level, but want to guarantee that the data is updated to be consistent with committed data in the
underlying table. When using WITH EXCLUSIVE MODE, exclusive table locks are placed on the
underlying base table and no other transaction can execute queries, updates, or any other action

846 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

against the underlying table(s) until the refresh operation is complete. If table locks cannot be
obtained, the refresh operation fails and an error is returned.

○ SHARE MODE Use WITH SHARE MODE to give read access on the underlying table to other
transactions while the refresh operation takes place. When this clause is specified, shared table locks
are obtained on the underlying base table before the refresh operation is performed and are held until
the refresh operation completes.

FORCE clause Use this clause to specify the refresh method. If this clause is not specified, the
database server decides whether to do an incremental update or a full rebuild based on how much of the
table has changed.

○ FORCE BUILD clause Refreshes the text index by recreating it. Use this clause to force a
complete rebuild of the text index.

○ FORCE INCREMENTAL clause Refreshes the text index based only on what has changed in the
underlying table. An incremental refresh takes less time to complete if there have not been a
significant amount of updates to the underlying table. Use this clause to force an incremental update
of the text index.

An incremental refresh does not remove deleted entries from the text index. As a result, the size of the
text index may be larger than expected to contain the current and historic data. Typically, this issue
occurs with text indexes that are always manually refreshed with the FORCE INCREMENTAL
clause. On automatically refreshed text indexes, historic data is automatically deleted when it makes
up 50% of the total size of the text index.

Remarks
This statement can only be used on text indexes defined as MANUAL REFRESH or AUTO REFRESH.

When using the FORCE clause, you can examine the results of the sa_text_index_stats system procedure
to decide whether a complete rebuild (FORCE BUILD), or incremental update (FORCE
INCREMENTAL) is most appropriate.

You cannot execute the REFRESH TEXT INDEX statement on a text index that is defined as
IMMEDIATE REFRESH.

For MANUAL REFRESH text indexes, use the sa_text_index_stats system procedure to determine
whether the text index should be refreshed. Divide pending_length by doc_length, and use the percentage
as a guide for deciding whether a refresh is required. To determine the type of rebuild required, use the
same process for deleted_length and doc_count.

Permissions
Must be the owner of the underlying table, or have either DBA authority or REFERENCES permission.

This statement cannot be executed when there are cursors opened with the WITH HOLD clause that use
either statement or transaction snapshots.

Side effects
Automatic commit.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 847


SQL statements

See also
● “Text index concepts and reference” [SQL Anywhere Server - SQL Usage]
● “Transactions and isolation levels” [SQL Anywhere Server - SQL Usage]
● “Isolation levels and consistency” [SQL Anywhere Server - SQL Usage]
● “CREATE TEXT INDEX statement” on page 649
● “ALTER TEXT INDEX statement” on page 468
● “DROP TEXT INDEX statement” on page 713
● “TRUNCATE TEXT INDEX statement” on page 935
● “Table locks” [SQL Anywhere Server - SQL Usage]
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]
● “Text index refresh types” [SQL Anywhere Server - SQL Usage]
● “sa_refresh_text_indexes system procedure” on page 1109
● “sa_text_index_stats system procedure” on page 1149

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement refreshes a text index called MarketingTextIndex, forcing it to be rebuilt.
REFRESH TEXT INDEX MarketingTextIndex ON MarketingInformation
FORCE BUILD;

REFRESH TRACING LEVEL statement


Reloads the tracing levels from the sa_diagnostic_tracing_level table while a tracing session is in
progress.

Syntax
REFRESH TRACING LEVEL

Remarks
This statement is used to reload the tracing level information from the sa_diagnostic_tracing_level table.
It must be called from the database being profiled.

When a tracing session is first started, rows from the sa_diagnostic_tracing_level table are loaded into
server memory to control what kind of information is traced. If you want to change the types of data being
traced, without stopping and restarting the tracing session to do so, you can do so by manually deleting or
inserting the appropriate rows in the sa_diagnostic_tracing_level table, and then executing the REFRESH
TRACING LEVEL statement to reload the settings.

To see the current tracing levels, query the sa_diagnostic_tracing_level table as follows:
SELECT * FROM sa_diagnostic_tracing_level WHERE enabled = 1;

Permissions
DBA authority

848 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
None.

See also
● “ATTACH TRACING statement” on page 475
● “DETACH TRACING statement” on page 687
● “Diagnostic tracing” [SQL Anywhere Server - SQL Usage]
● “sa_diagnostic_tracing_level table” on page 991

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Suppose you are troubleshooting a performance problem. You turn on a high level of tracing for the entire
database to capture the queries that are causing the problem. After starting the tracing session, you find
that capturing all queries for all users on your system slows down your database too much, so you decide
you would rather limit tracing to one user and wait for that user to report a problem. However, you do not
want to stop the tracing session to change the settings.

You can do this in Sybase Central by using the Database Tracing wizard, which is the recommended
method. However, you can also do this from the command line by replacing the rows in
sa_diagnostic_tracing_level table where scope=DATABASE and enabled=1, with equivalent rows where
scope=USER, identifier=userid, enabled=1, and so on. Then, you execute a REFRESH TRACING
LEVEL statement to continue tracing using use the new settings.

RELEASE SAVEPOINT statement


Releases a savepoint within the current transaction.

Syntax
RELEASE SAVEPOINT [ savepoint-name ]

Remarks
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.

Permissions
There must have been a corresponding SAVEPOINT within the current transaction.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 849


SQL statements

See also
● “BEGIN TRANSACTION statement [T-SQL]” on page 488
● “COMMIT statement” on page 501
● “ROLLBACK statement” on page 865
● “ROLLBACK TO SAVEPOINT statement” on page 866
● “SAVEPOINT statement” on page 870
● “Savepoints within transactions” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 RELEASE SAVEPOINT is part of optional SQL/2008 language feature T271,
"Savepoints".

REMOTE RESET statement [SQL Remote]


Starts all subscriptions for a remote user in a single transaction in custom database-extraction procedures.

Syntax
REMOTE RESET userid

Remarks
This statement starts all subscriptions for a remote user in a single transaction. It sets the log_sent and
confirm_sent values in ISYSREMOTEUSER table to the current position in the transaction log. It also
sets the created and started values in ISYSSUBSCRIPTION to the current position in the transaction log
for all subscriptions for this remote user. The statement does not do a commit. You must do an explicit
commit after this call.

To write an extraction process that is safe on a live database, the data must be extracted at isolation level 3
in the same transaction as the subscriptions are started.

This statement is an alternative to start subscription. START SUBSCRIPTION has an implicit commit as
a side effect, so that if a remote user has several subscriptions, it is impossible to start them all in one
transaction using START SUBSCRIPTION.

Permissions
DBA authority

Side effects
No automatic commit is done by this statement.

See also
● “START SUBSCRIPTION statement [SQL Remote]” on page 914
● “ISYSREMOTEUSER system table” on page 974
● “Creating multiple remote databases” [SQL Remote]
● “Starting subscriptions” [SQL Remote]

850 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement resets the subscriptions for remote user SamS:
REMOTE RESET SamS;
COMMIT;

REMOVE EXTERNAL OBJECT statement


Removes an external object from the database.

Syntax
REMOVE EXTERNAL OBJECT object-name

Parameters
object-name The name of the external object.

Remarks
For more information about external environments, see “SQL Anywhere external environment support”
[SQL Anywhere Server - Programming].

Permissions
DBA authority

Side effects
None

See also
● “SQL Anywhere external environment support” [SQL Anywhere Server - Programming]
● “ALTER EXTERNAL ENVIRONMENT statement” on page 410
● “INSTALL EXTERNAL OBJECT statement” on page 785
● “START EXTERNAL ENVIRONMENT statement” on page 911
● “STOP EXTERNAL ENVIRONMENT statement” on page 919
● “SYSEXTERNENV system view” on page 1206
● “SYSEXTERNENVOBJECT system view” on page 1206

Standards and compatibility


● SQL/2008 Vendor extension.

REMOVE JAVA statement


Removes a class or a JAR file from a database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 851


SQL statements

Syntax
REMOVE JAVA classes-to-remove

classes-to-remove :
CLASS java-class-name, ... | JAR jar-name, ...

Parameters
CLASS clause 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 clause The jar-name is a single-quoted 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.

Remarks
Removes a class or jar file from the database. The class or jar must already be installed. When a class is
removed it is no longer available for use as a column or variable type.

This statement is not supported on Windows Mobile.

Permissions
● DBA authority

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement removes a Java class named Demo from the current database:

REMOVE JAVA CLASS Demo;

The following statement removes a Java jar named myJar from the current database:

REMOVE JAVA JAR 'myJar';

REORGANIZE TABLE statement


Defragments tables when a full rebuild of the database is not possible due to the requirements for
continuous access to the database.

Syntax
REORGANIZE TABLE [ owner.]table-name
[ { PRIMARY KEY
| FOREIGN KEY foreign-key-name
| INDEX index-name } ]

852 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Parameters
Reorganize the table according to the values in one of the following:

PRIMARY KEY clause Reorganizes the primary key index for the table.

FOREIGN KEY clause Reorganizes the specified foreign key.

INDEX clause Reorganizes the specified index.

Remarks
Table fragmentation can impede performance. Use this statement to defragment rows in a table, or to
compress indexes which have become sparse due to DELETEs. It may also reduce the total number of
pages used to store the table and its indexes, and it may reduce the number of levels in an index tree.
However, it will not result in a reduction of the total size of the database file. It is recommended that you
use the sa_table_fragmentation and sa_index_density system procedures to select tables worth processing.

If an index or key is not specified, the reorganization process defragments rows in the table by deleting
and re-inserting groups of rows. For each group, an exclusive lock on the table is obtained. Once the
group has been processed, the lock is released and re-acquired (waiting if necessary), providing an
opportunity for other connections to access the table. Checkpoints are suspended while a group is being
processed; once a group is finished, a checkpoint may occur. The rows are processed in order of the
clustered index if one exists; otherwise, they are processed inorder of the primary key. If the table does
not have a clustered index or a primary key, an error is returned. The processed rows are re-inserted at the
end of the table, resulting in the rows being clustered by primary key at the end of the process. Note that
the same amount of work is required, regardless of how fragmented the rows initially were.

If an index or key is specified, the specified index is processed. For the duration of the operation, an
exclusive lock is held on the table and checkpoints are suspended. Any attempts to access the table by
other connections will block or fail, depending on their setting of the blocking option. The duration of the
lock is minimized by pre-reading the index pages before obtaining the exclusive lock.

Since reorganization may modify many pages, the checkpoint log can become large. This can result in a
increase in the database file size. However, this increase is temporary since the checkpoint log is deleted
at shutdown and the file is truncated at that point.

This statement is not logged to the transaction log.

This statement cannot be executed when there are cursors opened with the WITH HOLD clause that use
either statement or transaction snapshots.

During the execution of this statement, you can request progress messages.

You can also use the Progress connection property to determine how much of the statement has been
executed.

Permissions
● Must be either the owner of the table, or a user with DBA authority.

● Not supported on Windows Mobile.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 853


SQL statements

Side effects
Before starting the reorganization, a checkpoint is done to try to maximize the number of free pages. Also,
when executing the REORGANIZE TABLE statement, there is an implied commit for approximately
every 100 rows, so reorganizing a large table causes multiple commits to take place.

Standards and compatibility


● SQL/2008 Vendor extension.

See also
● “Progress connection property” [SQL Anywhere Server - Database Administration]
● “progress_messages option” [SQL Anywhere Server - Database Administration]
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]

Examples
The following statement reorganizes the primary key index for the Employees table:
REORGANIZE TABLE Employees
PRIMARY KEY;

The following statement reorganizes the table pages of the Employees table:
REORGANIZE TABLE Employees;

The following statement reorganizes the index IX_product_name on the Products table:
REORGANIZE TABLE Products
INDEX IX_product_name;

The following statement reorganizes the foreign key FK_DepartmentID_DepartmentID for the Employees
table:
REORGANIZE TABLE Employees
FOREIGN KEY FK_DepartmentID_DepartmentID;

RESIGNAL statement [SP]


Resignals an exception condition.

Syntax
RESIGNAL [ exception-name ]

Remarks
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 is handled by another exception
handler or returned to the application.

Permissions
None.

854 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
None.

See also
● “SIGNAL statement [SP]” on page 906
● “BEGIN statement” on page 484
● “Exception handlers” [SQL Anywhere Server - SQL Usage]
● “RAISERROR statement” on page 838

Standards and compatibility


● SQL/2008 The RESIGNAL statement is part of optional SQL/2008 language feature P002,
"Computational completeness".

● Transact-SQL The RESIGNAL statement cannot be used in Transact-SQL compound statements


and procedures.

Example
The following fragment returns all exceptions except SQLSTATE 52003 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;

RESTORE DATABASE statement


Restores a backed up database from an archive.

Syntax
RESTORE DATABASE filename
FROM archive-root
[ CATALOG ONLY
| [ RENAME dbspace-name TO new-dbspace-name ] ... ]
[ HISTORY { ON | OFF } ]
[ KEY encryption-key ]

filename : string | variable


archive-root : string | variable
new-dbspace-name : string | variable

Parameters
CATALOG ONLY clause Retrieves information about the named archive, and places it in the backup
history file (backup.syb), but does not restore any data from the archive.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 855


SQL statements

RENAME clause Allows you to specify a new location for each dbspace. You cannot use the
RENAME clause to change the dbspace name. However, you can use the RENAME clause to change the
file name.

HISTORY clause Allows you to control whether the RESTORE DATABASE operation is recorded in
the history file, backup.syb.

KEY clause Allows you to specify the encryption key to restore an archived strongly encrypted
database that was backed up with free page elimination on. If the back up was made with free page
elimination off, then you do not need to specify the encryption key to restore the database.

As of version 12, you cannot restore archive backups created with version 11 or earlier database servers.

Remarks
Unless HISTORY OFF is specified, each RESTORE DATABASE operation updates a backup history file
called backup.syb. This file records the BACKUP and RESTORE operations that have been performed on
a database server. You may want to prevent the RESTORE DATABASE operation from being recorded
in backup.syb if the following conditions apply:

● your RESTORE DATABASE operations occur frequently

● there is no procedure to periodically archive or delete the backup.syb file

● disk space is very limited

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.

During the execution of this statement, you can request progress messages.

You can also use the Progress connection property to determine how much of the statement has been
executed.

Permissions
The permissions required to execute this statement are set on the server command line, using the -gu
option. The default setting is to require DBA authority.

This statement is not supported on Windows Mobile.

Side effects
None.

856 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “Predefined dbspaces” [SQL Anywhere Server - Database Administration]
● “BACKUP statement” on page 477
● “Backup and data recovery” [SQL Anywhere Server - Database Administration]
● “SALOGDIR environment variable” [SQL Anywhere Server - Database Administration]
● “FREE PAGE ELIMINATION clause, BACKUP statement” on page 480
● “-gu dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “Progress connection property” [SQL Anywhere Server - Database Administration]
● “progress_messages option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

● Windows Mobile Not supported on Windows Mobile.

Example
The following example restores a database from a tape drive. The number of backslashes that are required
depends on which database you are connected to when you execute RESTORE DATABASE. The
database affects the setting of the escape_character option. It is normally set to On, but is set to Off in
utility_db. When connected to any database other than utility_db, the extra backslashes are required.
RESTORE DATABASE 'd:\\dbhome\\mydatabase.db'
FROM '\\\\.\\tape0';

RESUME statement
Resumes execution of a cursor that returns result sets.

Syntax
RESUME cursor-name

cursor-name : identifier | hostvar

Remarks
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.

The RESUME statement is not supported in Interactive SQL. If you want to view multiple result sets in
Interactive SQL, you can set the isql_show_multiple_result_sets option to ON, or choose Tools » Options,
and then select Show Multiple Result sets on the Results tab.

Permissions
The cursor must have been previously opened.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 857


SQL statements

Side effects
None.

See also
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “FETCH statement [ESQL] [SP]” on page 728
● “Result sets” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Following are embedded SQL examples.
1. EXEC SQL RESUME cur_employee;
2. EXEC SQL RESUME :cursor_var;

RETURN statement
Exits from a function, procedure, or batch unconditionally, optionally providing a return value.

Syntax
RETURN [ expression ]

Remarks
A RETURN statement causes an immediate exit from a block of SQL. If expression is supplied, the value
of expression is returned as the value of the function or procedure. Subqueries can not be used in
expression.

If the RETURN appears inside an inner BEGIN block, it is the outer BEGIN block that is terminated.

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.

Permissions
None.

Side effects
None.

858 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “CREATE FUNCTION statement” on page 548
● “CREATE FUNCTION statement [External call]” on page 535
● “CREATE FUNCTION statement [Web service]” on page 541
● “CREATE PROCEDURE statement” on page 585
● “CREATE PROCEDURE statement [External call]” on page 567
● “CREATE PROCEDURE statement [Web service]” on page 575
● “BEGIN statement” on page 484
● “Returning a value using the RETURN statement” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Core feature.

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

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 Customers)
OR customer_ID IS NULL THEN
RETURN
ELSE
SELECT Products.ID,sum(
SalesOrderItems.Quantity )
FROM Products,
SalesOrderItems,
SalesOrders
WHERE SalesOrders.CustomerID=customer_ID
AND SalesOrders.ID=SalesOrderItems.ID
AND SalesOrderItems.ProductID=Products.ID
GROUP BY Products.ID
END IF
END;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 859


SQL statements

REVOKE CONSOLIDATE statement [SQL Remote]


Stops a consolidated database from receiving SQL Remote messages from this database.

Syntax
REVOKE CONSOLIDATE FROM userid

Remarks
CONSOLIDATE permissions must be granted at a remote database for the user ID representing the
consolidated database. The REVOKE CONSOLIDATE statement removes the consolidated database user
ID from the list of users receiving messages from the current database.

Permissions
DBA authority

Side effects
Automatic commit. Drops all subscriptions for the user.

See also
● “REVOKE PUBLISH statement [SQL Remote]” on page 860
● “REVOKE REMOTE statement [SQL Remote]” on page 862
● “REVOKE REMOTE DBA statement [SQL Remote]” on page 861
● “GRANT CONSOLIDATE statement [SQL Remote]” on page 754
● “Revoke CONSOLIDATE permission” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
● The following statement revokes consolidated status from the condb user ID:
REVOKE CONSOLIDATE FROM condb;

REVOKE PUBLISH statement [SQL Remote]


Terminates the identification of the named user ID as the current publisher.

Syntax
REVOKE PUBLISH FROM userid

Remarks
Each database in a SQL Remote installation is identified in outgoing messages by a publisher user ID.
The current publisher user ID can be found using the CURRENT PUBLISHER special value. The
following query identifies the current publisher:

860 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

SELECT CURRENT PUBLISHER;

The REVOKE PUBLISH statement ends the identification of the named user ID as the publisher.

You should not REVOKE PUBLISH from a database while the database has active SQL Remote
publications or subscriptions.

Executing a REVOKE PUBLISH statement at a database has several consequences for a SQL Remote
installation:

● You will not be able to insert data into any tables with a CURRENT PUBLISHER column as part of
the primary key. Any outgoing messages will not be identified with a publisher user ID, and so will not
be accepted by recipient databases.

If you change the publisher user ID at any consolidated or remote database in a SQL Remote installation,
you must ensure that the new publisher user ID is granted REMOTE permissions on all databases
receiving messages from the database. This will generally require all subscriptions to be dropped and
recreated.

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “GRANT PUBLISH statement [SQL Remote]” on page 756
● “REVOKE REMOTE statement [SQL Remote]” on page 862
● “REVOKE REMOTE DBA statement [SQL Remote]” on page 861
● “REVOKE CONSOLIDATE statement [SQL Remote]” on page 860
● “CURRENT PUBLISHER special value” on page 59
● “Revoking PUBLISH permission” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
REVOKE PUBLISH FROM publisher_ID;

REVOKE REMOTE DBA statement [SQL Remote]


Revokes REMOTE DBA authority from a user ID.

Syntax 1
REVOKE REMOTE DBA
FROM userid, ...

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 861


SQL statements

Remarks
In MobiLink, REMOTE DBA authority is a level of permission required by the SQL Anywhere
synchronization client (dbmlsync).

In SQL Remote, REMOTE DBA authority enables the SQL Remote Message Agent to have full access to
the database to make any changes contained in the messages, while avoiding security problems associated
with distributing DBA user IDs passwords.

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “REVOKE PUBLISH statement [SQL Remote]” on page 860
● “REVOKE REMOTE statement [SQL Remote]” on page 862
● “GRANT REMOTE DBA statement [MobiLink] [SQL Remote]” on page 757
● “REVOKE CONSOLIDATE statement [SQL Remote]” on page 860
● “Synchronization initiation” [MobiLink - Client Administration]
● “REMOTE DBA authority” [SQL Remote]
● “Revoke REMOTE DBA authority” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following statement revokes REMOTE DBA permission from user S_Beaulieu.
REVOKE REMOTE DBA FROM S_Beaulieu;

REVOKE REMOTE statement [SQL Remote]


Stops a user from being able to receive SQL Remote messages from this database.

Syntax
REVOKE REMOTE FROM userid, ...

Remarks
REMOTE permissions are required for a user ID to receive messages in a SQL Remote replication
installation. The REVOKE REMOTE statement removes a user ID from the list of users receiving
messages from the current database.

Permissions
DBA authority

862 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
Automatic commit. Drops all subscriptions for the user.

See also
● “REVOKE PUBLISH statement [SQL Remote]” on page 860
● “GRANT REMOTE statement [SQL Remote]” on page 758
● “REVOKE REMOTE DBA statement [SQL Remote]” on page 861
● “REVOKE CONSOLIDATE statement [SQL Remote]” on page 860
● “Revoke REMOTE permission” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
REVOKE REMOTE FROM SamS;

REVOKE statement
Removes permissions from users.

Syntax 1 - Revoke authorities

REVOKE permission, ... FROM userid, ...

permission :
BACKUP
| CONNECT
| CREATE ON dbspace
| DBA
| GROUP
| INTEGRATED LOGIN
| KERBEROS LOGIN
| MEMBERSHIP IN GROUP userid, ...
| PROFILE
| READCLIENTFILE
| READFILE
| RESOURCE
| VALIDATE
| WRITECLIENTFILE

Syntax 2 - Revoke database object permissions

REVOKE table-permission, ...


ON [ owner.]table-name
FROM userid, ...

table-permission :
ALL [PRIVILEGES]
| ALTER

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 863


SQL statements

| DELETE
| INSERT
| REFERENCES [ ( column-name, ... ) ]
| SELECT [ ( column-name, ... ) ]
| UPDATE [ ( column-name, ... ) ]

Syntax 3
REVOKE EXECUTE
ON [ owner.]procedure-name
FROM userid, ...

Syntax 4

REVOKE USAGE ON SEQUENCE sequence-name


FROM userid, ...

Remarks
The REVOKE statement removes permissions given using the GRANT statement. Syntax 1 revokes
special user permissions. Syntax 2 revokes table permissions. Syntax 3 revokes permission to execute a
procedure. Syntax 4 revokes sequence permissions.

REVOKE CONNECT removes a user ID from a database, and also destroys any objects (tables, views,
procedures, and so on) owned by that user and any permissions granted by that user. You cannot execute a
REVOKE CONNECT on a user if the user being dropped owns a table referenced by a view owned by
another user.

REVOKE GROUP automatically revokes MEMBERSHIP IN GROUP from all members of the group.

When you add a user to a group, the user inherits all the permissions assigned to that group. SQL
Anywhere does not allow you to revoke a subset of the permissions that a user inherits as a member of a
group because you can only revoke permissions that are explicitly given by a GRANT statement. If you
need to have different permissions for different users, you can create different groups with the appropriate
permissions, or you can explicitly grant each user the permissions they require.

When you grant or revoke group permissions for tables, views, or procedures, all members of the group
inherit those changes. The DBA, RESOURCE, and GROUP permissions are not inherited: you must
assign them to each individual user ID that requires them.

If you revoke a permission for a user and they also had WITH GRANT OPTION for that permission, then
everyone who that user granted the permission to also has their permission revoked. For example, suppose
you granted UserA SELECT...WITH GRANT OPTION permissions on a table and UserA then grants the
SELECT permission on the table to UserB. If you revoke the SELECT permission from UserA, it will be
revoked for UserB as well.

REVOKE USAGE ON SEQUENCE removes a user's permission to evaluate the current or next value in
a sequence. You must have DBA authority or be the creator of the sequence to execute this statement.

Permissions
Must be the grantor of the permissions that are being revoked or have DBA authority.

864 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

If you are revoking connect permissions or table permissions from another user, the other user must not be
connected to the database. You cannot revoke connect permissions from DBO.

When you are connected to the utility database, executing REVOKE CONNECT FROM DBA disables
future connections to the utility database. This means that no future connections can be made to the utility
database unless you use a connection that existed before the REVOKE CONNECT was done, or restart
the database server.

Side effects
Automatic commit.

See also
● “GRANT statement” on page 760

Standards and compatibility


● SQL/2008 Syntax 1 is a vendor extension. Syntax 2 and Syntax 3 are core features of the SQL/
2008 standard. With Syntax 2, in SQL Anywhere the PRIVILEGES keyword is optional, while in the
SQL/2008 standard "ALL PRIVILEGES" is mandatory.

Syntax 4 is part of optional SQL/2008 language feature T176, "Sequence generator support".

Example
Prevent user Dave from updating the Employees table.
REVOKE UPDATE ON Employees FROM Dave;

Revoke resource permissions from user Jim.


REVOKE RESOURCE FROM Jim;

Revoke an integrated login mapping from the user profile named Administrator.
REVOKE INTEGRATED LOGIN FROM Administrator;

Disallow the Finance group from executing the procedure ShowCustomers.


REVOKE EXECUTE ON ShowCustomers FROM Finance;

Drop the user ID FranW from the database.


REVOKE CONNECT FROM FranW;

ROLLBACK statement
Ends a transaction and undo any changes made since the last COMMIT or ROLLBACK.

Syntax
ROLLBACK [ WORK ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 865


SQL statements

Remarks
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.

In Interactive SQL, you can also execute a ROLLBACK by:

● Pressing Ctrl+Shift+R.

● Clicking SQL » Rollback.

In Interactive SQL, executing a ROLLBACK from the SQL menu or the keyboard shortcut does not
modify the contents of the SQL Statements pane; however, the Results tab in the Results pane is
cleared.

Permissions
None.

Side effects
Closes all cursors not opened WITH HOLD.

See also
● “COMMIT statement” on page 501
● “Executing COMMIT and ROLLBACK statements in Interactive SQL” [SQL Anywhere Server -
Database Administration]
● “ROLLBACK TO SAVEPOINT statement” on page 866
● “Interactive SQL options” [SQL Anywhere Server - Database Administration]
● “Cancellation of changes” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Core feature.

ROLLBACK TO SAVEPOINT statement


Cancels any changes made since a SAVEPOINT.

Syntax
ROLLBACK TO SAVEPOINT [ savepoint-name ]

Remarks
The ROLLBACK TO SAVEPOINT statement will undo any changes that have been made since the
SAVEPOINT was established. Changes made before the SAVEPOINT are not undone; they are still
pending.

866 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

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.

Permissions
There must have been a corresponding SAVEPOINT within the current transaction.

Side effects
None.

See also
● “BEGIN TRANSACTION statement [T-SQL]” on page 488
● “COMMIT statement” on page 501
● “RELEASE SAVEPOINT statement” on page 849
● “ROLLBACK statement” on page 865
● “SAVEPOINT statement” on page 870
● “Savepoints within transactions” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 ROLLBACK TO SAVEPOINT is part of optional SQL language feature T271 of the
SQL/2008 standard.

ROLLBACK TRANSACTION statement [T-SQL]


Cancels any changes made since a SAVE TRANSACTION.

Syntax
ROLLBACK TRANSACTION [ savepoint-name ]

Remarks
The ROLLBACK TRANSACTION statement undoes any changes that have been made since a savepoint
was established using SAVE TRANSACTION. Changes made before the SAVE TRANSACTION are
not undone; they are still pending.

The savepoint-name is an identifier that was specified on a SAVE TRANSACTION statement within the
current transaction. If savepoint-name is omitted, all outstanding changes are rolled back. Any savepoints
since the named savepoint are automatically released.

Permissions
There must be a corresponding SAVE TRANSACTION within the current transaction.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 867


SQL statements

See also
● “ROLLBACK TO SAVEPOINT statement” on page 866
● “BEGIN TRANSACTION statement [T-SQL]” on page 488
● “COMMIT statement” on page 501
● “SAVE TRANSACTION statement [T-SQL]” on page 869

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example displays five rows with values 10, 20, and so on. The effect of the DELETE, but
not the prior INSERTs or UPDATE, is undone by the ROLLBACK TRANSACTION statement.
BEGIN
SELECT row_num INTO #tmp
FROM sa_rowgenerator( 1, 5 )
UPDATE #tmp SET row_num=row_num*10
SAVE TRANSACTION before_delete
DELETE FROM #tmp WHERE row_num >= 3
ROLLBACK TRANSACTION before_delete
SELECT * FROM #tmp
END

ROLLBACK TRIGGER statement


Undoes any changes made in a trigger.

Syntax
ROLLBACK TRIGGER [ WITH raiserror-statement ]

Remarks
The ROLLBACK TRIGGER statement rolls back the work done in a trigger, including the data
manipulation that caused the trigger to fire.

Optionally, a RAISERROR statement can executed. If a RAISERROR statement is executed, an error is


returned to the application. If no RAISERROR statement is executed, 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.

Permissions
None.

Side effects
None

868 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “CREATE TRIGGER statement” on page 651
● “ROLLBACK statement” on page 865
● “ROLLBACK TO SAVEPOINT statement” on page 866
● “RAISERROR statement” on page 838

Standards and compatibility


● SQL/2008 Vendor extension.

● Transact-SQL ROLLBACK TRIGGER is supported in both Watcom SQL and Transact-SQL


stored procedures. ROLLBACK TRIGGER is supported by Adaptive Server Enterprise.

SAVE TRANSACTION statement [T-SQL]


Establishes a savepoint within the current transaction.

Syntax
SAVE TRANSACTION savepoint-name

Remarks
Establish a savepoint within the current transaction. The savepoint-name is an identifier that can be used
in a ROLLBACK TRANSACTION statement. All savepoints are automatically released when a
transaction ends.

Permissions
None.

Side effects
None.

See also
● “SAVEPOINT statement” on page 870
● “Savepoints within transactions” [SQL Anywhere Server - SQL Usage]
● “BEGIN TRANSACTION statement [T-SQL]” on page 488
● “COMMIT statement” on page 501
● “ROLLBACK TRANSACTION statement [T-SQL]” on page 867

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example displays five rows with values 10, 20, and so on. The effect of the DELETE, but
not the prior INSERTs or UPDATE, is undone by the ROLLBACK TRANSACTION statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 869


SQL statements

BEGIN
SELECT row_num INTO #tmp
FROM sa_rowgenerator( 1, 5 )
UPDATE #tmp SET row_num=row_num*10
SAVE TRANSACTION before_delete
DELETE FROM #tmp WHERE row_num >= 3
ROLLBACK TRANSACTION before_delete
SELECT * FROM #tmp
END

SAVEPOINT statement
Establishes a savepoint within the current transaction.

Syntax
SAVEPOINT [ savepoint-name ]

Remarks
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.

Savepoints that are established while a trigger or atomic compound statement is executing are
automatically released when the atomic operation ends.

You cannot modify data in a proxy table from within a savepoint.

Permissions
None.

Side effects
None.

See also
● “RELEASE SAVEPOINT statement” on page 849
● “ROLLBACK TO SAVEPOINT statement” on page 866
● “SAVE TRANSACTION statement [T-SQL]” on page 869
● “Savepoints within transactions” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 The SAVEPOINT statement is part of optional SQL/2008 language feature T271,
"Savepoints".

● Transact-SQL In Transact-SQL, creating a savepoint is accomplished with the SAVE


TRANSACTION statement.

870 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

SELECT statement
Retrieves information from the database.

Syntax
[ WITH temporary-views ]
SELECT [ ALL | DISTINCT ] [ row-limitation-option-1 ] select-list
[ INTO { hostvar-list | variable-list | table-name } ]
[ INTO LOCAL TEMPORARY TABLE { table-name } ]
[ FROM from-expression ]
[ WHERE search-condition ]
[ GROUP BY group-by-expression ]
[ HAVING search-condition ]
[ WINDOW window-expression ]
[ ORDER BY { expression | integer } [ ASC | DESC ], ... ]
[ FOR READ ONLY | for-update-clause ]
[ FOR XML xml-mode ]
[ row-limitation-option-2 ]
[ OPTION( query-hint, ... ) ]

temporary-views :
regular-view, ...
| RECURSIVE { regular-view | recursive-view }, ...

regular-view :
view-name [ ( column-name, ... ) ]
AS ( subquery )

recursive-view :
view-name ( column-name, ... )
AS ( initial-subquery UNION ALL recursive-subquery )

row-limitation-option-1 :
FIRST
| TOP { ALL | limit-expression } [ START AT startat-expression ]

row-limitation-option-2 :
LIMIT { [ offset-expression, ] limit-expression | limit-expression OFFSET offset-expression }

limit-expression : simple-expression

startat-expression : simple-expression

offset-expression : simple-expression

simple-expression :
integer
| variable
| ( simple-expression )
| ( simple-expression { + | - | * } simple-expression )

select-list :
expression [ [ AS ] alias-name ], ...
|*

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 871


SQL statements

| window-function OVER { window-name | window-spec }


[ [ AS ] alias-name ]
| sequence-expression

sequence-expression
sequence-name [ CURRVAL | NEXTVAL ]
FROM table-name

sequence-expression : See “Expressions” on page 12.

from-expression : See “FROM clause” on page 738.

group-by-expression : See “GROUP BY clause” on page 766.

search-condition : See “Search conditions” on page 32.

window-name : identifier

window-expression : See “WINDOW clause” on page 961.

window-spec : See “WINDOW clause” on page 961.

window-function :
RANK( )
| DENSE_RANK( )
| PERCENT_RANK( )
| CUME_DIST( )
| ROW_NUMBER( )
| aggregate-function

for-update-clause
FOR UPDATE
| FOR UPDATE cursor-concurrency
| FOR UPDATE OF [ ( column-name, ... ) ]

cursor-concurrency :
BY { VALUES | TIMESTAMP | LOCK }

xml-mode :
RAW [ , ELEMENTS ]
| AUTO [ , ELEMENTS ]
| EXPLICIT

query-hint :
MATERIALIZED VIEW OPTIMIZATION option-value
| FORCE OPTIMIZATION
| FORCE NO OPTIMIZATION
| option-name=option-value

option-name : identifier

option-value :
hostvar (indicator allowed)
| string
| identifier
| number

872 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Parameters
WITH or WITH RECURSIVE clause Define one or more common table expressions, also known as
temporary views, to be used elsewhere in the remainder of the statement. These expressions may be non-
recursive, or may be self-recursive. Recursive common table expressions may appear alone, or intermixed
with non-recursive table expressions, only if the RECURSIVE keyword is specified. Mutually recursive
common table expressions are not supported.

This clause is permitted only if the SELECT query block appears in one of the following locations:

○ Within top-level SELECT query block including the top-level SELECT query block of a view
definition

○ Within a top-level SELECT statement within an INSERT query block

○ Within a nested SELECT query block defining a derived table in any type of SQL statement

Recursive expressions consist of an initial subquery and a recursive subquery. The initial-query implicitly
defines the schema of the view. The recursive subquery must contain a reference to the view within the
FROM clause. During each iteration, this reference refers only to the rows added to the view in the
previous iteration. The reference must not appear on the null-supplying side of an outer join. A recursive
common table expression must not use aggregate functions and must not contain a GROUP BY, ORDER
BY, or DISTINCT clause.

The WITH clause is not supported with remote tables. The WITH clause may also be used in
INTERSECT, UNION, and EXCEPT query blocks.

ALL or DISTINCT clause 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.

row-limitation clauses The row limitation clauses allow you to return only a subset of the rows that
satisfy the WHERE clause. Only one row-limitation clause can be specified at a time. When specifying
these clauses, an ORDER BY clause is required to order the rows in a meaningful manner.

○ row-limitation-option-1 The TOP and START AT arguments can be simple arithmetic


expressions over host variables, integer constants, or integer variables. The TOP argument must
evaluate to a value greater than or equal to 0. The START AT argument must evaluate to a value
greater than 0.

If startat-expression is not specified, the default is 1. If the argument of TOP is ALL, all rows starting
at startat-expression are returned. The TOP limit-expression START AT startat-
expression clause is equivalent to LIMIT ( startat-expression -1 ), limit-
expression or LIMIT limit-expression OFFSET ( startat-expression -1 ).

○ row-limitation-option-2 The LIMIT and OFFSET arguments can be simple arithmetic expressions
over host variables, integer constants, or integer variables. The LIMIT argument must evaluate to a
value greater than or equal to 0. The OFFSET argument must evaluate to a value greater than or equal
to 0. If offset-expression is not specified, the default is 0.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 873


SQL statements

The row limitation clause LIMIT offset-expression, limit-expression is equivalent


to LIMIT limit-expression OFFSET offset-expression. Both of these constructs are
equivalent to TOP limit-expression START AT ( offset-expression + 1 ).

The LIMIT keyword is disabled by default. Use the reserved_keywords option to enable the LIMIT
keyword.

select-list clause The select-list is a list of expressions, separated by commas, specifying what is
retrieved from the database. An asterisk (*) means select all columns of all tables in the FROM clause.

Aggregate functions are allowed in the select-list. Subqueries are also allowed in the select-list. 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 displays the
expression.

INTO clause Following are the three uses of the INTO clause:

○ INTO hostvar-list clause This clause is used in embedded SQL only. It specifies where the results
of the SELECT statement 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.

If the query results in no rows being selected, the variables are not updated, and a row not found
warning appears.

○ INTO variable-list clause This clause is used in procedures and triggers only. It specifies where
the results of the SELECT statement go. There must be one variable for each item in the select-list.
select-list items are put into the variables in order.

○ INTO table-name clause This clause is used to create a table and fill it with data.

For permanent tables to be created, the query must satisfy one of the following conditions:

● The select-list contains more than one item, and the INTO target is a single table-name identifier.

● The select-list contains a * and the INTO target is specified as owner.table.

To create a permanent table with one column, the table name must be specified as owner.table.

This statement causes a COMMIT before execution as a side effect of creating the table. RESOURCE
authority is required to execute this statement. No permissions are granted on the new table: the
statement is a short form for CREATE TABLE followed by INSERT...SELECT.

Tables created using this clause do not have a primary key defined. You can add a primary key using
ALTER TABLE. A primary key should be added before applying any UPDATEs or DELETEs to the
table; otherwise, these operations result in all column values being logged in the transaction log for
the affected rows.

874 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

INTO LOCAL TEMPORARY TABLE This clause is used to create a local, temporary table and
populate it with the results of the query. When you use this clause, you do not need to start the temporary
table name with #.

FROM clause Rows are retrieved from the tables and views specified in the table-expression. A
SELECT statement with no FROM clause can be used to display the values of expressions not derived
from tables. For example, these two statements are equivalent and display the value of the global variable
@@version.

SELECT @@version;
SELECT @@version FROM DUMMY;

WHERE clause This clause specifies which rows are selected from the tables named in the FROM
clause. It can be used to do joins between multiple tables, as an alternative to the ON phrase (which is part
of the FROM clause).

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. As with
DISTINCT and the set operations UNION, INTERSECT, and EXCEPT, the GROUP BY clause treats
NULL values in the same manner as any other value in each domain. In other words, multiple NULL
values in a grouping attribute form a single group. 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 can 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.

WINDOW clause This clause defines all or part of a window for use with window functions such as
AVG and RANK.

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 are sorted by the nth item in the select-list.

The only way to ensure that rows are returned in a particular order is to use ORDER BY. In the absence
of an ORDER BY clause, SQL Anywhere returns rows in whatever order is most efficient. This means
that the appearance of result sets may vary depending on when you last accessed the row and other
factors.

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.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 875


SQL statements

FOR UPDATE or FOR READ ONLY clause These clauses specify whether updates are allowed
through a cursor opened on the query, and if so, what concurrency semantics can be used. This clause
cannot be used with the FOR XML clause.

If you do not use a FOR clause in the SELECT statement, the updatability of a cursor depends on the
cursor's declaration and how cursor concurrency is specified by the API. In ODBC, JDBC, OLE DB,
ADO.NET, and embedded SQL, statement updatability is explicit and a read-only cursor is used unless it
is overridden by the application. In Open Client and within stored procedures, cursor updatability does not
have to be specified, and the default is FOR UPDATE.

For Open Client and stored procedures, cursor updatability and statement updatability is dependent on the
setting of the ansi_update_constraints database option and the specific characteristics of the statement,
including whether the statement contains ORDER BY, DISTINCT, GROUP BY, HAVING, UNION,
aggregate functions, joins, or non-updatable views. For stored procedures, cursors default to FOR
UPDATE for single-table queries without an ORDER BY clause, or if the ansi_update_constraints option
is set to Off. When the ansi_update_constraints option is set to Cursors or Strict, then cursors over a query
containing an ORDER BY clause default to READ ONLY. However, you can explicitly mark cursors as
updatable using the FOR UPDATE clause. Because it is expensive to allow updates over cursors with an
ORDER BY clause or a join, cursors over a query containing a join of two or more tables are READ
ONLY and cannot be made updatable unless the ansi_update_constraints database option is Off.

A cursor declared FOR READ ONLY cannot be used in UPDATE (positioned), DELETE (positioned), or
PUT statements. FOR READ ONLY is the default for embedded SQL.

The FOR UPDATE clause explicitly makes a cursor updatable. The use of FOR UPDATE alone does not,
by itself, affect concurrency control on the rows in the result set of the statement. To do this, you must
specify either FOR UPDATE BY LOCK or FOR UPDATE BY [ VALUES | TIMESTAMP ].

○ FOR UPDATE BY LOCK clause The database server acquires intent row locks on fetched rows of
the result set. These are long-term locks that are held until the transaction is committed or rolled back.

○ FOR UPDATE BY { VALUES | TIMESTAMP } When you specify FOR UPDATE BY


TIMESTAMP or FOR UPDATE BY VALUES, the database server uses optimistic concurrency by
using a keyset-driven (value-sensitive) cursor. In this situation, lost updates can occur if the
application modifies a row outside of the cursor (using a separate statement) or if the application does
not heed the warnings and/or errors generated by the server indicating that the row has been modified
by another connection.

To ensure that a statement acquires an intent lock, you must do one of the following:

○ specify FOR UPDATE BY LOCK in the query

○ specify HOLDLOCK, WITH ( HOLDLOCK ), WITH ( UPDLOCK ), or WITH ( XLOCK ) in the


FROM clause of the query

○ open the cursor with API calls that specify CONCUR_LOCK

○ fetch the rows with attributes indicating fetch for update

876 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The FOR UPDATE OF clause explicitly names the columns that can be modified with an UPDATE
(positioned), DELETE (positioned), or PUT statement. You cannot use this clause in combination with
any other FOR UPDATE, FOR READ ONLY, or FOR XML clause.

○ FOR UPDATE OF column-list clause When you specify the FOR UPDATE OF clause, the
database server restricts the columns that can be modified with a positioned UPDATE or positioned
DELETE statement to those columns that are explicitly named in that clause. An attempt to modify
another column results in an error indicating that the column cannot be found. No check is made to
determine if a column referenced within the list actually exists, or if that column's table is an
updatable table.

FOR XML clause This clause specifies that the result set is to be returned as an XML document. The
format of the XML depends on the mode you specify. This clause cannot be used with the FOR UPDATE
or FOR READ ONLY clause. Cursors declared with FOR XML are implicitly READ ONLY.

When you specify RAW mode, each row in the result set is represented as an XML <row> element, and
each column is represented as an attribute of the <row> element.

AUTO mode returns the query results as nested XML elements. Each table referenced in the select-list is
represented as an element in the XML. The order of nesting for the elements is based on the order that
tables are referenced in the select-list.

EXPLICIT mode allows you to control the form of the generated XML document. Using EXPLICIT
mode offers more flexibility in naming elements and specifying the nesting structure than either RAW or
AUTO mode.

OPTION clause This clause provides hints about how to process the query. The following query hints
are supported:

○ MATERIALIZED VIEW OPTIMIZATION clause Use the MATERIALIZED VIEW


OPTIMIZATION clause to specify how the optimizer should make use of materialized views when
processing the query. The specified option-value overrides the materialized_view_optimization
database option for this query only. Possible values for option-value are the same values available for
the materialized_view_optimization database option.

○ FORCE OPTIMIZATION clause When a query specification contains only simple queries (single-
block, single-table queries that contain equality conditions in the WHERE clause that uniquely
identify a specific row), it typically bypasses cost-based optimization during processing. Sometimes
you may want cost-based optimization to occur. For example, if you want materialized views to be
considered during query processing, view matching must occur. However, view matching only occurs
during cost-based optimization. If you want cost-based optimization to occur for a query, but your
query specification contains only simple queries, specify the FORCE OPTIMIZATION option to
ensure that the optimizer performs cost-based optimization on the query.

Similarly, specifying the FORCE OPTIMIZATION option in a SELECT statement inside of a


procedure forces the use of the optimizer for any call to the procedure. In this case, plans for the
statement are not cached.

○ FORCE NO OPTIMIZATION clause Specify the FORCE NO OPTIMIZATION clause if you


want the statement to bypass the optimizer. If the statement is too complex to process in this way—

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 877


SQL statements

possibly due to the setting of database options or characteristics of the schema or query—the
statement fails and the database server returns an error.

○ option-name = option-value Specify an option setting. The setting you specify is only applicable
to the current statement and takes precedence over any public or temporary option settings, including
those set by ODBC-enabled applications. The supported options are:

● “isolation_level option” [SQL Anywhere Server - Database Administration]


● “max_query_tasks option” [SQL Anywhere Server - Database Administration]
● “optimization_goal option” [SQL Anywhere Server - Database Administration]
● “optimization_level option” [SQL Anywhere Server - Database Administration]
● “optimization_workload option” [SQL Anywhere Server - Database Administration]
● “user_estimates option” [SQL Anywhere Server - Database Administration]

If you specify the isolation_level option in a query, the value specified in the query takes precedence
over all other isolation level settings (such as setting the isolation_level option for the database or the
setting for the cursor) for the current query.

sequence-expression You can select the current value (CURRVAL) or next value (NEXTVAL)
from a sequence generator.

Remarks
The SELECT statement can be used:

● for retrieving results from the database.

● in Interactive SQL to browse data in the database, or to export data from the database to an external
file.

● in procedures and triggers or in embedded SQL. A 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.

● to return a result set from a procedure.

Permissions
Must have SELECT permission on the named tables and views.

To select the CURRVAL or NEXTVAL values from a sequence generator, you must have DBA
authority, be the owner of the sequence, or have been granted permission to use the sequence generator.

Side effects
None.

878 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “Eligibility to skip query processing phases” [SQL Anywhere Server - SQL Usage]
● “Advanced: Query processing phases” [SQL Anywhere Server - SQL Usage]
● “Expressions” on page 12
● “FROM clause” on page 738
● “GROUP BY clause” on page 766
● “WINDOW clause” on page 961
● “Search conditions” on page 32
● “DECLARE CURSOR statement [ESQL] [SP]” on page 666
● “UNION statement” on page 936
● “EXCEPT statement” on page 717
● “INTERSECT statement” on page 788
● “WITH table-hint clause, FROM clause” on page 744
● “materialized_view_optimization option” [SQL Anywhere Server - Database Administration]
● “ansi_update_constraints option” [SQL Anywhere Server - Database Administration]
● “reserved_keywords option” [SQL Anywhere Server - Database Administration]
● “Column '%1' not found” [Error Messages]
● “Row limitation clauses in SELECT, UPDATE, and DELETE query blocks” [SQL Anywhere Server -
SQL Usage]
● “Joins: Retrieving data from several tables” [SQL Anywhere Server - SQL Usage]
● “Common table expressions” [SQL Anywhere Server - SQL Usage]
● “Use of a sequence to generate unique values” [SQL Anywhere Server - SQL Usage]
● “Using FOR XML EXPLICIT” [SQL Anywhere Server - SQL Usage]
● “Use of the FOR XML clause to retrieve query results as XML” [SQL Anywhere Server - SQL Usage]
● “ODBC cursor characteristics” [SQL Anywhere Server - Programming]
● “Updatable statements” [SQL Anywhere Server - Programming]
● “SQL Anywhere cursors” [SQL Anywhere Server - Programming]
● “Transact-SQL outer joins (*= or =*)” [SQL Anywhere Server - SQL Usage]
● “Queries that are compatible with Transact-SQL” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 Core feature. The complexity of the SELECT statement means that you should check
individual clauses against the standard. For example, the ROLLUP keyword, which can be specified
in a GROUP BY clause, is part of optional SQL/2008 language feature T431. Some of the SQL/2008
optional language features supported by SQL Anywhere include:

○ The WINDOW clause and WINDOW aggregate functions comprise optional SQL/2008 language
features T611 and T612.

○ Sequence expressions are part of feature T176.

○ Common table expressions are optional SQL/2008 language feature T121. A common table
expression included in a nested query expression is feature T122. WITH RECURSIVE is optional
SQL/2008 language feature T131; if included in a nested query it constitutes feature T132.

○ The ability to specify an ORDER BY clause with a query expression involving UNION, EXCEPT,
or INTERSECT is optional feature F850. The ability to specify ORDER BY in a subquery is
feature F851.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 879


SQL statements

○ In the SQL standard, FOR UPDATE and FOR READ ONLY are part of a cursor declaration.

SQL Anywhere offers support for many extensions to the SQL/2008 definition of the SELECT
statement. Some of these include:

○ The optional cursor-concurrency clause (FOR UPDATE BY { LOCK | VALUES | TIMESTAMP})


is a vendor extension.

○ The FOR XML, OPTION, and INTO clauses are vendor extensions.

○ The row limitation clause is a vendor extension. In the SQL/2008 standard, row limitation is
supported using FETCH FIRST syntax, which is optional language feature F856. The syntax for
feature F856 is not supported by SQL Anywhere.

○ The ability to specify ORDER BY n is a vendor extension.

○ In SQL/2008, all cursors except INSENSITIVE cursors are updatable by default. The read-only
default with embedded SQL programs is a vendor extension.

● Transact-SQL There are substantial differences in SELECT statement support between SQL
Anywhere and Adaptive Server Enterprise. Several features of the SELECT statement are not
supported by Adaptive Server Enterprise.

These differences include:

○ Sybase ASE does not support SQL Anywhere's cursor concurrency clause; to acquire a lock on a
fetched row, you must use the HOLDLOCK table hint.

○ Adaptive Server Enterprise does not support recursive queries or common table expressions.

○ There are differences between Adaptive Server Enterprise and SQL Anywhere with respect to
Transact-SQL outer joins.

In Transact-SQL you use the SELECT statement to assign a value to a variable, rather than with the
Watcom SQL SET statement.

Example
This query returns the total number of employees in the Employees table.
SELECT COUNT(*)
FROM Employees;

This query lists all customers and the total value of their orders.
SELECT CompanyName,
CAST( SUM( SalesOrderItems.Quantity *
Products.UnitPrice ) AS INTEGER ) VALUE
FROM Customers
JOIN SalesOrders
JOIN SalesOrderItems
JOIN Products
GROUP BY CompanyName
ORDER BY VALUE DESC;

880 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The following statement shows an embedded SQL SELECT statement where the number of employees in
the Employees table is selected into the :size host variable:

SELECT COUNT(*) INTO :size


FROM Employees;

The following statement is optimized to return the first row in the result set quickly:

SELECT Name
FROM Products
GROUP BY Name
HAVING COUNT( * ) > 1
AND MAX( UnitPrice ) > 10
OPTION( optimization_goal = 'first-row' );

SET CONNECTION statement [Interactive SQL] [ESQL]


Changes the active database connection.

Syntax
SET CONNECTION [ connection-name ]

connection-name :
identifier
| string
| hostvar

Remarks
The SET CONNECTION statement changes the active database connection to connection-name. The
current connection state is saved, and is 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.

Permissions
None.

Side effects
None.

See also
● “CONNECT statement [ESQL] [Interactive SQL]” on page 504
● “DISCONNECT statement [ESQL] [Interactive SQL]” on page 688
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 881


SQL statements

Standards and compatibility


● SQL/2008 SET CONNECTION is part of optional SQL/2008 language feature F771, "Connection
management". Its usage within an Interactive SQL session is a vendor extension.

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;

SET DESCRIPTOR statement [ESQL]


Describes the variables in a SQL descriptor area and to place data into the descriptor area.

Syntax
SET DESCRIPTOR descriptor-name
{ COUNT = { integer | hostvar }
| VALUE { integer | hostvar } assignment, ... }

assignment :
{ TYPE | SCALE | PRECISION | LENGTH | INDICATOR }
= { integer | hostvar }
| DATA = hostvar

descriptor-name : identifier

Remarks
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 { integer | hostvar } specifies the variable in the descriptor area upon which the assignment(s)
is 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. LONG VARCHAR and LONG BINARY are not supported by
SET DESCRIPTOR...DATA.

If an error occurs, the code is returned in the SQLCA.

Permissions
None.

882 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
None.

See also
● “ALLOCATE DESCRIPTOR statement [ESQL]” on page 398
● “DEALLOCATE DESCRIPTOR statement [ESQL]” on page 665
● “The SQL descriptor area (SQLDA)” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 SET DESCRIPTOR is part of optional SQL/2008 language feature B031, "Basic
dynamic SQL".

Example
The following example sets the type of the column with position col_num in sqlda.
void set_type( SQLDA *sqlda, int col_num, int new_type )
{
EXEC SQL BEGIN DECLARE SECTION;
INT new_type1 = new_type;
INT col = col_num;
EXEC SQL END DECLARE SECTION;
EXEC SQL SET DESCRIPTOR sqlda VALUE :col TYPE = :new_type1;
}

SET MIRROR OPTION statement


Note
Read-only scale-out and database mirroring each require a separate license. See “Separately licensed
components” [SQL Anywhere 12 - Introduction].

Changes the values of options that control the settings for database mirroring and read-only scale-out.

Syntax
SET MIRROR OPTION option-name={ option-value | NULL }

option-name :
authentication_string
auto_add_fan_out
auto_add_server
auto_failover
child_creation
page_timeout
max_disconnected_time
max_retry_connect_time
synchronization_mode

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 883


SQL statements

Parameters

option-name Applies to Values Default Description

authentica- database string null Specifies the authentication string used by


tion_string mirroring all the servers in the database mirroring sys-
tem. The authentication string is required
for database mirroring.

au- read-only integer 10 Specifies the maximum number of children


to_add_fan_out scale-out for each branch. The minimum value that
can be specified is 2.

auto_add_server read-only string null Specifies the name of the database server
scale-out that acts as the parent of the automatic as-
signment tree.

auto_failover database on, off null Specifies whether the mirror server auto-
mirroring matically takes over as the primary server
when the current primary server goes down.
This option does not apply to synchronous
mode.

This option accepts Boolean values (auto-


matic failover is turned on with YES, ON,
TRUE, or 1, and is turned off with any of
NO, OFF, FALSE, and 0). The parameters
are case insensitive.

If you are using asynchronous or asyncfull-


page mode, it is recommended that you set
the auto_failover option to on. Then, if the
primary server goes down, the mirror server
automatically takes over as the primary
server.

child_creation read-only automat- automat- Controls whether copy nodes are created
scale-out ic, off, ic automatically.
manual

page_timeout database integer, in 5 Specifies how often, in seconds, transaction


mirroring seconds log pages are sent to the mirror server,
whether or not they are full. This option ap-
plies only when using asyncfullpage mode.

884 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

option-name Applies to Values Default Description

max_disconnec- read-only integer, in no time Specifies the length of time that the copy
ted_time scale-out seconds limit server attempts to connect to the root data-
base server after a parent connection is lost.
If the copy server fails to connect within the
specified time, the database is shut down.

max_retry_con- read-only integer, in 120 Specifies the length of time that a copy
nect_time scale-out seconds node attempts to reconnect to its parent
once the parent becomes unavailable.

synchroniza- database synchro- synchro- Specifies the synchronization mode used for
tion_mode mirroring nous, nous database mirroring: synchronous (sync),
asynchro- asynchronous (async), or asyncfullpage
nous, (page). The synchronization mode controls
asyncfull- when and how transactions are recorded on
page the mirror server.

Remarks
Cloud note: This statement is not supported on tenant databases in the cloud.

Once you create a database server for a database mirroring system or a read-only scale-out system using
the CREATE MIRROR SERVER statement, you can use the SET MIRROR OPTION statement to
configure the settings for the system.

Permissions
Must have DBA authority.

Side effects
Automatic commit.

See also
● “Automatically assign the parent of a copy node” [SQL Anywhere Server - Database Administration]
● “Handle the loss of a parent connection” [SQL Anywhere Server - Database Administration]
● “Database mirroring modes” [SQL Anywhere Server - Database Administration]
● “How child copy nodes are added” [SQL Anywhere Server - Database Administration]
● “-xa dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “Database mirroring” [SQL Anywhere Server - Database Administration]
● “SQL Anywhere read-only scale-out” [SQL Anywhere Server - Database Administration]
● “CREATE MIRROR SERVER statement” on page 564
● “ALTER MIRROR SERVER statement” on page 420
● “DROP MIRROR SERVER statement” on page 699

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 885


SQL statements

Example
The following statement sets the authentication string for a database mirroring system to abc:
SET MIRROR OPTION authentication_string = 'abc';

SET OPTION statement


Changes the values of database and connection options.

Syntax 1
SET [ EXISTING ] [ TEMPORARY ] OPTION
[ userid.| PUBLIC.]option-name = [ option-value ]

Syntax 2 (deprecated)
SET [ EXISTING ] [ TEMPORARY ] OPTION
[ userid.| PUBLIC.]option-name = [ identifier ]

userid : identifier

option-name : identifier

option-value : ON, OFF, NULL, string literal, number, hostvar, or @variable-name

Parameters
option-value With Syntax 1, option-value can be one of:

○ the keywords ON, OFF, or NULL


○ a string literal value, within single quotation marks
○ a number of any valid format, including NUMERIC
○ within an embedded SQL program, the value of a host variable hostvar
○ the value of a SQL variable with a variable name that must begin with an @ sign

With Syntax 2, you can specify any valid identifier as an option value. Also, the database server treats the
name of the identifier as if it were a string literal enclosed within single quotes. For example, the
following two statements are equivalent:
SET TEMPORARY OPTION ansi_update_constraints = 'strict';

SET TEMPORARY OPTION ansi_update_constraints = strict;

Remarks
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 (public), for an individual user, or for
the current connection. The new setting can be made either temporary or permanent.

886 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The classes of options that can be set with the SET OPTION statement are:

● Transact-SQL compatibility options.


● connection and database options.
● synchronization options.
● user-defined options

Option scope With most options, you can set their value at three levels of scope: public, user, and
connection. Some specific options, such as login_mode, are restricted to the public level only. A
connection option takes precedence over the other two levels, and user options take precedence over
public options. You set a connection-level option by using the TEMPORARY keyword. If you set a user-
level option for the current user, the corresponding connection-level option is set at the same time.

If you specify a user ID, the option value applies to that user. If you specify PUBLIC, the option value
applies to all users who do not have an individual setting for the option. By default, the option value
applies to the currently logged on user ID that executed the SET OPTION statement.

For example, the following statement applies an option change to the user DBA, if DBA is the user
executing the SQL statement:
SET OPTION precision = 40;

However the following statement applies the change to the PUBLIC user ID, a group to which all users
belong:
SET OPTION PUBLIC.login_mode = 'Standard';

TEMPORARY options By default, a new option value is made permanent unless the TEMPORARY
keyword is specified. Adding the TEMPORARY keyword to the SET OPTION statement affects the
duration of the change.

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 domain is
not compromised if the database is shut down and copied to a local computer. 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.

Removing option settings If option-value is omitted, the specified option setting is deleted from the
database. If it was a user-level 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 that user.

Option data types Options can have Boolean, numeric, or string values, but are always stored as
strings in the database. Option settings are always returned as strings as the result of a property function

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 887


SQL statements

or when returned as a result of a function or system stored procedure. Option values cannot be larger than
the database page size.

User-defined options Any option, whether user-defined or not, must have a public setting before a
user-specific value can be assigned. The database server does not support setting TEMPORARY values
for user-defined options. For example, to create a user-defined option named ApplicationControl, you first
execute the statement:
SET OPTION PUBLIC.ApplicationControl = 'Default';

This statement sets the ApplicationControl option to Default for all users, and takes effect with each new
connection to the server. Subsequently, an individual user may establish their own setting for this option
by executing a separate SET OPTION statement.

Restrictions Only users with DBA authority have the authority to set an option for the PUBLIC user
ID or for other database users.

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.

Caution
Do not change option settings while fetching rows from an open cursor because it can result in ill-defined
behavior whose semantics are not guaranteed. 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.

There are several ways you can query the value of specific options for a connection or user.

The SET OPTION statement is ignored by the SQL Flagger.

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.

888 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “Database options” [SQL Anywhere Server - Database Administration]
● “Compatibility options” [SQL Anywhere Server - Database Administration]
● “Synchronization options” [SQL Anywhere Server - Database Administration]
● “SQL Remote options” [SQL Anywhere Server - Database Administration]
● “Finding option settings” [SQL Anywhere Server - Database Administration]
● “Database options” [SQL Anywhere Server - Database Administration]
● “SYSOPTION system view” on page 1221
● “sa_conn_options system procedure” on page 1024
● “sa_conn_options system procedure” on page 1024
● “CONNECTION_PROPERTY function [System]” on page 171
● “GET OPTION statement [ESQL]” on page 753
● “SET OPTION statement [Interactive SQL]” on page 889
● “SET statement [T-SQL]” on page 901
● “SET REMOTE OPTION statement [SQL Remote]” on page 892

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Set the date format option for all users without an individual setting:
SET OPTION PUBLIC.date_format = 'Mmm dd yyyy';

Set the wait_for_commit option to On:


SET OPTION wait_for_commit = 'On';

The following is an embedded SQL example:


EXEC SQL SET TEMPORARY OPTION date_format = :value;

Set the date_format option for the user that is currently connected. Future connections for the same user
ID use this option value.
SET OPTION date_format = 'yyyy/mm/dd';

The following statement removes the setting of the date_format option for the current user ID. After
executing this statement, the date_format setting for PUBLIC is used instead.
SET OPTION date_format=;

SET OPTION statement [Interactive SQL]


Changes the values of Interactive SQL options.

Syntax 1 - Set an Interactive SQL option


SET OPTION option-name = [ option-value ] | SET TEMPORARY OPTION option-name = [ option-value ]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 889


SQL statements

option-name : identifier | string | hostvar

option-value : string | identifier | number

Syntax 2 - Save current Interactive SQL options permanently


SET PERMANENT

Syntax 3 - List current database option settings


SET

Remarks
When you set an option using the SET OPTION syntax, the option setting is stored permanently and does
not change unless another SET OPTION statement changes it.

Using the SET TEMPORARY OPTION syntax allows you to temporarily change an option setting. The
temporary setting remains in effect until you close Interactive SQL. The next time you start Interactive
SQL, the option reverts to its permanent setting.

Use the SET PERMANENT syntax to permanently save all current Interactive SQL option settings (any
temporary settings become permanent).

If option-value is omitted, the specified option is set to its default value.

Use Syntax 3 to display all the current database option settings in a window. If there are temporary
options settings for the database server, they are displayed instead of the permanent settings.

Interactive SQL option settings are stored on the client computer, not in the database.

The following table lists the Interactive SQL options.

Option Values Default

“auto_commit option [Interactive SQL]” On, Off Off


[SQL Anywhere Server - Database Adminis-
tration]

“auto_refetch option [Interactive SQL]” On, Off On


[SQL Anywhere Server - Database Adminis-
tration]

“bell option [Interactive SQL]” [SQL Any- On, Off On


where Server - Database Administration]

“command_delimiter option [Interactive String ';'


SQL]” [SQL Anywhere Server - Database
Administration]

890 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Option Values Default

“commit_on_exit option [Interactive SQL]” On, Off On


[SQL Anywhere Server - Database Adminis-
tration]

“default_isql_encoding option [Interactive String Empty string


SQL]” [SQL Anywhere Server - Database
Administration]

“echo option [Interactive SQL]” [SQL Any- On, Off On


where Server - Database Administration]

“input_format option [Interactive SQL]” TEXT, FIXED TEXT


[SQL Anywhere Server - Database Adminis-
tration]

“isql_allow_read_client_file option [Interac- On, Off, Prompt Prompt


tive SQL]” [SQL Anywhere Server - Data-
base Administration]

“isql_allow_write_client_file option [Inter- On, Off, Prompt Prompt


active SQL]” [SQL Anywhere Server - Data-
base Administration]

“isql_command_timing option [Interactive On, Off On


SQL]” [SQL Anywhere Server - Database
Administration]

“isql_escape_character option [Interactive Character '\'


SQL]” [SQL Anywhere Server - Database
Administration]

“isql_field_separator option [Interactive String ','


SQL]” [SQL Anywhere Server - Database
Administration]

“isql_maximum_displayed_rows option [In- All or a non-negative integer 500


teractive SQL]” [SQL Anywhere Server -
Database Administration]

“isql_print_result_set option [Interactive Last, All, None Last


SQL]” [SQL Anywhere Server - Database
Administration]

“isql_quote option [Interactive SQL]” [SQL String '


Anywhere Server - Database Administra-
tion]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 891


SQL statements

Option Values Default

“isql_show_multiple_result_sets option [In- On, Off Off


teractive SQL]” [SQL Anywhere Server -
Database Administration]

“nulls option [Interactive SQL]” [SQL Any- String '(NULL)'


where Server - Database Administration]

“on_error option [Interactive SQL]” [SQL Stop, Continue, Prompt, Exit, Prompt
Anywhere Server - Database Administra- Notify_Continue, Notify_Stop,
tion] Notify_Exit

“output_format option [Interactive SQL]” TEXT, FIXED, HTML, SQL, TEXT


[SQL Anywhere Server - Database Adminis- XML
tration]

“output_length option [Interactive SQL]” Integer 0


[SQL Anywhere Server - Database Adminis-
tration]

“output_nulls option [Interactive SQL]” String Empty string


[SQL Anywhere Server - Database Adminis-
tration]

“truncation_length option [Interactive SQL]” Integer 256


[SQL Anywhere Server - Database Adminis-
tration]

Standards and compatibility


● SQL/2008 Vendor extension.

See also
● “Interactive SQL options” [SQL Anywhere Server - Database Administration]
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Example
The following statement changes the value of the on_error option:
SET OPTION on_error='continue';

SET REMOTE OPTION statement [SQL Remote]


Sets a message control parameter for a SQL Remote message link.

892 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
SET REMOTE link-name OPTION
[ userid.| PUBLIC.]link-option-name = link-option-value

link-name :
file
| ftp
| http
| smtp

link-option-name :
common-options
| file-options
| ftp-options
| smtp-options

common-options :
debug
| encode_dll
| max_retries
| output_log_send_on_error
| output_log_send_limit
| output_log_send_now
| pause_after_failure

file-options :
directory
| invalid_extensions
| unlink_delay

ftp-options :
active_mode
| host
| invalid_extensions
| password
| port
| root_directory
| reconnect_retries
| reconnect_pause
| suppress_dialogs
| user

http-options :
| certificate
| client_port
| https
| password
| proxy
| reconnect_retries
| reconnect_pause
| root_directory
| url
| user

smtp-options :
local_host

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 893


SQL statements

| pop3_host
| pop3_password
| pop3_userid
| smtp_authenticate
| smtp_option
| smtp_password
| smtp_userid
| suppress_dialogs
| top_supported

link-option-value : string

Parameters
userid If you do not specify a userid, then the current publisher is assumed.

common-options These options are common to the FILE, FTP, HTTP, and SMTP message systems:

○ debug This parameter is set either to YES or NO. The default is NO. When set to YES, debug
output specific to the message system is displayed. This information can be used for troubleshooting
problems in the message system.

○ max_retries By default, when SQL Remote is running in continuous mode and an error occurs
when accessing the message system, it shuts down after the send and/or received phases. Use this
parameter to specify the number of times you want SQL Remote to retry the send and/or receive
phases before it shuts down.

○ output_log_send_on_error Sends log information when an error occurs.

○ output_log_send_limit Limits the amount of information that is sent to the consolidated database.
The output_log_send_limit option specifies the number of bytes at the end of the output log (that is,
the most recent entries) that are sent to the consolidated database. The default is 5K.

○ output_log_send_now When set to YES, sends output log information to the consolidated
database. On the next poll, the remote database sends the output log information and then resets the
output_log_send_now option to NO.

○ pause_after_failure This parameter applies when the max_retries parameter is specified to a value
other than zero and SQL Remote is running in continuous mode. When an error occurs in the message
system, this parameter defines the number of seconds SQL Remote waits between retrying the send
and/or receive phases.

○ encode_dll If you have implemented a custom encoding scheme, you must set this to the full path
of the custom encoding DLL that you created.

file-options These options apply to the FILE message system only:

○ directory The directory under which the messages are stored. This parameter is an alternative to
the SQLREMOTE environment variable.

○ invalid_extensions A comma-separated list of file extensions that you do not want the SQL
Remote Message Agent (dbremote) to use when generating files in the messaging system.

894 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ unlink_delay The number of seconds to wait before attempting to delete a file if the previous
attempt to delete the file failed. If no value is defined for unlink_delay, then the default behavior is set
to pause for 1 second after the first failed attempt, 2 seconds after the second failed attempt, 3 seconds
after the third failed attempt, and 4 seconds after the fourth failed attempt.

ftp-options These options apply to the FTP message system only:

○ active_mode This parameter controls how SQL Remote establishes the server/client connection.
This parameter is set either to YES or NO. The default is NO (passive mode). Passive mode is the
preferred transfer mode and the default for the FTP message link. In passive mode, all data transfer
connections are initiated by the client, in this case, the message link. In active mode, the FTP server
initiates all data connections.

○ host The host name of the computer where the FTP server is running. This parameter can be a host
name (such as FTP.ianywhere.com) or an IP address (such as 192.138.151.66).

○ invalid_extensions A comma-separated list of file extensions that you do not want dbremote to
use when generating files in the messaging system.

○ password The password for accessing the FTP host.

○ port The IP port number used for the FTP connection. This parameter is usually not required.

○ reconnect_retries The number of times the link should try to open a socket with the server before
failing. The default value is 4. When you set this parameter, only reconnections are affected. The
initial connection made by the FTP link is not affected.

○ reconnect_pause The time in seconds to pause between each connection attempt. The default
setting is 30 seconds. When you set this parameter, only reconnections are affected. The initial
connection made by the FTP link is not affected.

○ root_directory The root directory within the FTP host site that the messages are stored under.

○ suppress_dialogs This parameter is set to TRUE or FALSE. If it is set to TRUE, the Connect
window does not appear after failed attempts to connect to the FTP server. Instead, an error is
generated.

○ user The user name for accessing the FTP host.

http-options These options apply to the HTTP message system only:

○ certificate To make a secure (HTTPS) request, a client must have access to the certificate used by
the HTTPS server. The necessary information is specified in a string of semicolon-separated key/value
pairs. You can use the file key to specify the file name of the certificate. You cannot specify a file and
certificate key together. The following keys are available:

Key Abbreviation Description

file The file name of the certificate

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 895


SQL statements

Key Abbreviation Description

certificate cert The certificate itself

company co The company specified in the certificate

unit The company unit specified in the certificate

name The common name specified in the certificate

Certificates are required only for requests that are either directed to an HTTPS server or can be
redirected from a non-secure to a secure server. Only PEM formatted certificates are supported.
certificate='file=filename'

○ client_port Identifies the port number on which SQL Remote communicates using HTTP. It is
provided for, and recommended only for, connections through firewalls that filter "outgoing" TCP/IP
connections. You can specify a single port number, ranges of port numbers, or a combination of the
two. Specifying a low number of client ports could result in SQL Remote being unable to send and
receive messages if the operating system has not released the ports in a timely manner after SQL
Remote closes the port on a previous run.

○ debug When set to YES, all HTTP commands and responses are displayed in the output log. This
information can be used for troubleshooting HTTP support problems. The default is NO.

○ https Specify whether to use HTTPS (https=yes) or HTTP (https=no).

○ password The message server database password. The password authenticates to third-party
HTTP servers and gateways using RFC 2617 Basic authentication.

○ proxy_host Specifies the URI of a proxy server. For use when SQL Remote must access the
network through a proxy server. Indicates that SQL Remote is to connect to the proxy server and send
the request to the message server through it.

'

○ reconnect_retries The number of times the link should try to open a socket with the server before
failing. The default value is 4. When you set this parameter, only reconnections are affected. The
initial connection made by the FTP link is not affected.

○ reconnect_pause The time in seconds to pause between each connection attempt. The default
setting is 30 seconds. When you set this parameter, only reconnections are affected. The initial
connection made by the FTP link is not affected.

○ root_directory This HTTP control parameter is ignored when specified at the client side. You
define this control parameter in the message server prior to calling the sr_add_message_server or
sr_update_message_server stored procedure. When using the HTTP message system, the address
specified for a remote user or publisher can only contain a single subdirectory, and not multiple
subdirectories.

896 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

○ url Specify the server name or IP address and optionally the port number of the HTTP server being
used, separated by a semicolon. If requests are being passed through the Relay Server, you can
optionally add a URL extension to indicate which server farm the request should be passed to.

○ user The message server database user ID. Authenticates to third-party HTTP servers and gateways
using RFC 2617 Basic authentication.

smtp-options These options apply to the SMTP message system only:

○ local_host The name of the local computer. It is useful on computers where SQL Remote is unable
to determine the local host name. The local host name is needed to initiate a session with any SMTP
server. In most network environments, the local host name can be determined automatically and this
entry is not needed.

○ pop3_host The name of the computer on which the POP host is running. Typically, it is the same
name as the SMTP host. It corresponds to the POP3 host field in the SMTP/POP3 login window.

○ pop3_password The password used to retrieve mail. It corresponds to the password field in the
SMTP/POP3 login window.

○ pop3_userid The user ID used to retrieve mail. The POP user ID corresponds to the user ID field
in the SMTP/POP3 login window. You must obtain a user ID from your POP host administrator.

○ smtp_host The name of the computer on which the SMTP server is running. It corresponds to the
SMTP host field in the SMTP/POP3 login window

○ top_supported SQL Remote uses a POP3 command called TOP when enumerating incoming
messages. The TOP command may not be supported by all POP servers. When you set the
top_supported parameter to NO, SQL Remote uses the RETR command, which is less efficient but
works with all POP servers. The default is YES.

○ smtp_authenticate Determines whether the SMTP link authenticates the user. The default value is
YES. Set this parameter to NO to turn off SMTP authentication.

○ smtp_userid The user ID for SMTP authentication. By default, this parameter takes the same
value as the pop3_userid parameter. The smtp_userid only needs to be set if the user ID is different
from that of the POP server.

○ smtp_password The password for SMTP authentication. By default, this parameter takes the
same value as the pop3_password parameter. The smtp_password only needs to be set if the user ID is
different from that of the POP server.

○ suppress_dialogs When this parameter is set to true, the Connect window does not appear after
failed attempts to connect to the mail server. Instead, an error is generated.

Remarks
The SQL Remote (dbremote) Message Agent saves message link parameters when the user enters them in
the message link window when the message link is first used. In this case, it is not necessary to use this
statement explicitly. This statement is most useful when preparing a consolidated database for extracting
many databases.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 897


SQL statements

The option names are case sensitive. The case sensitivity of option values depends on the option: Boolean
values are case insensitive, while the case sensitivity of passwords, directory names, and other strings
depend on the case sensitivity of the file system (for directory names), or the database (for user IDs and
passwords).

Permissions
DBA authority. The publisher can set their own options.

Side effects
Automatic commit.

See also
● “Collecting errors from the remote database” [SQL Remote]
● “Setting remote message type control parameters” [SQL Remote]
● “Custom encoding schemes” [SQL Remote]
● “SET OPTION statement” on page 886
● “The FTP message system” [SQL Remote]
● “The FILE message system” [SQL Remote]
● “The HTTP message system” [SQL Remote]
● “Tutorial: Setting up a replication system using the HTTP message system” [SQL Remote]
● “The SMTP message system” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following statement sets the FTP host to ftp.mycompany.com for the FTP link for user myuser:
SET REMOTE FTP OPTION myuser.host = 'ftp.mycompany.com';

The following statement stops SQL Remote from using the specified file extensions for messages that are
generated:
SET REMOTE FTP OPTION
"Public"."invalid_extensions"='exe,pif,dll,bat,cmd,vbs';

The following statement sets the URL to point to the localhost for the HTTP link for user myuser:
SET REMOTE HTTP OPTION myuser.url='localhost:8033';

The following statement sets the HTTP URL to point to a Relay Server that forwards the request to the
srhttp farm:
SET REMOTE HTTP OPTION "public"."url"='iis7.company.com:80/rs/client/
rs_client.dll/srhttp';

SET SQLCA statement [ESQL]


Instructs the SQL preprocessor to use a SQLCA other than the default, global sqlca.

898 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
SET SQLCA sqlca

sqlca : identifier | string

Remarks
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.

The sqlca should reference a local variable. Any global or module static variable is subject to being
modified by another thread.

Permissions
None.

Side effects
None.

See also
● “SQLCA management for multithreaded or reentrant code” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 Vendor extension.

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 );
}

SET statement
Assigns a value to a SQL variable.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 899


SQL statements

Syntax
SET identifier = expression

Remarks
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 OUTPUT parameter
for a procedure. The variable name can optionally use the Transact-SQL convention of an @ sign
preceding the name. For example:
SET @localvar = 42

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 32767 bytes.

Permissions
None.

Side effects
None.

See also
● “CREATE VARIABLE statement” on page 660
● “DECLARE statement” on page 673
● “SET statement [T-SQL]” on page 901
● “DROP VARIABLE statement” on page 716
● “Expressions” on page 12
● “Host variable usage” [SQL Anywhere Server - Programming]

Standards and compatibility


● SQL/2008 The SET statement is part of optional SQL/2008 language feature P002, "Computational
completeness".

● Transact-SQL The SET statement is supported by Adaptive Server Enterprise. In ASE, a single
SET statement can be used to assign values to multiple variables, with individual assignment clauses
separated by commas.

Example
This simple example shows the creation of a variable called birthday, and uses SET to set the date to
CURRENT DATE.
CREATE VARIABLE @birthday DATE;
SET @birthday = CURRENT DATE;

900 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The following code fragment inserts a large text value into the database.

EXEC SQL BEGIN DECLARE SECTION;


DECL_VARCHAR( 5000 ) buffer;
/* Note: maximum DECL_VARCHAR size is 32765 */
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 inserts 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;

SET statement [T-SQL]


Sets database options for the current connection in an Adaptive Server Enterprise-compatible manner.

Syntax
SET option-name option-value

Remarks
The available options are as follows:

Option name Option value

ansinull On or Off

ansi_permissions On or Off

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 901


SQL statements

Option name Option value

close_on_endtrans On or Off

datefirst 1, 2, 3, 4, 5, 6, or 7

The setting of this option affects the DATEPART function when obtaining
a weekday value.

quoted_identifier On | Off

rowcount integer

self_recursion On | Off

string_rtruncation On | Off

textsize integer

transaction isolation level 0, 1, 2, 3, snapshot, statement snapshot, or read only statement snapshot

Database options in SQL Anywhere are set using the SET OPTION statement. However, SQL Anywhere
also provides support for the Adaptive Server Enterprise SET statement for options that are useful for
compatibility.

The following options can be set using the Transact-SQL SET statement in SQL Anywhere and Adaptive
Server Enterprise:

● SET ansinull { On | Off } The default behavior for comparing values to NULL is different in SQL
Anywhere and Adaptive Server Enterprise. Setting ansinull to Off provides Transact-SQL compatible
comparisons with NULL.

SQL Anywhere also supports the following syntax:

SET ansi_nulls { On | Off }

For more information, see “ansinull option” [SQL Anywhere Server - Database Administration].

● SET ansi_permissions { On | Off } The default behavior is different in SQL Anywhere and
Adaptive Server Enterprise regarding permissions required to perform an UPDATE or DELETE
containing a column reference. Setting ansi_permissions to Off provides Transact-SQL-compatible
permissions on UPDATE and DELETE.

● SET close_on_endtrans { On | Off } The default behavior is different in SQL Anywhere and
Adaptive Server Enterprise for closing cursors at the end of a transaction. Setting close_on_endtrans
to Off provides Transact-SQL compatible behavior.

● SET datefirst { 1 | 2 | 3 | 4 | 5 | 6 | 7 } The default is 7, which means that the first day of the week
is by default Sunday.

902 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

● SET quoted_identifier { On | Off } Controls whether strings enclosed in double quotes are
interpreted as identifiers (On) or as literal strings (Off).

● SET rowcount integer The Transact-SQL ROWCOUNT option limits the number of rows fetched
for any cursor to the specified integer. This includes rows fetched by re-positioning the cursor. Any
fetches beyond this maximum return a warning. The option setting is considered when returning the
estimate of the number of rows for a cursor on an OPEN request.

SET ROWCOUNT also limits the number of rows affected by a searched UPDATE or DELETE
statement to integer. This might be used, for example, to allow COMMIT statements to be performed
at regular intervals to limit the size of the rollback log and lock table. The application (or procedure)
would need to provide a loop to cause the update/delete to be re-issued for rows that are not affected
by the first operation. A simple example is given below:
BEGIN
DECLARE @count INTEGER
SET rowcount 20
WHILE(1=1) BEGIN
UPDATE Employees SET Surname='new_name'
WHERE Surname <> 'old_name'
/* Stop when no rows changed */
SELECT @count = @@rowcount
IF @count = 0 BREAK
PRINT string('Updated ',
@count,' rows; repeating...')
COMMIT
END
SET rowcount 0
END

In SQL Anywhere, if the ROWCOUNT setting is greater than the number of rows that Interactive
SQL can display, Interactive SQL may do some extra fetches to reposition the cursor. So, the number
of rows actually displayed may be less than the number requested. Also, if any rows are re-fetched
due to truncation warnings, the count may be inaccurate.

A value of zero resets the option to get all rows.

● SET self_recursion { On | Off } The self_recursion option is used within triggers to enable (On)
or prevent (Off) operations on the table associated with the trigger from firing other triggers.

● SET string_rtruncation { On | Off } The default behavior is different between SQL Anywhere
and Adaptive Server Enterprise when non-space characters are truncated during assignment of SQL
string data. Setting string_rtruncation to On provides Transact-SQL-compatible string comparisons.

● SET textsize Specifies the maximum size (in bytes) of TEXT or IMAGE type data to be returned
with a SELECT statement. The @@textsize global variable stores the current setting. To reset to the
default size (32 KB), use the command:
set textsize 0

● SET transaction isolation level { 0 | 1 | 2 | 3 | snapshot | statement snapshot | readonly


statement snapshot } Sets the locking isolation level for the current connection.

For Adaptive Server Enterprise, only 1 and 3 are valid options. For SQL Anywhere, any of 0, 1, 2, 3,
snapshot, statement snapshot, and read only statement snapshot is a valid option.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 903


SQL statements

The SET statement is allowed by SQL Anywhere for the prefetch option, for compatibility, but has no
effect.

Permissions
None.

Side effects
None.

See also
● “Isolation levels and consistency” [SQL Anywhere Server - SQL Usage]
● “Options for Transact-SQL compatibility” [SQL Anywhere Server - SQL Usage]
● “Compatibility options” [SQL Anywhere Server - Database Administration]
● “isolation_level option” [SQL Anywhere Server - Database Administration]
● “ansi_permissions option” [SQL Anywhere Server - Database Administration]
● “close_on_endtrans option” [SQL Anywhere Server - Database Administration]
● “quoted_identifier option” [SQL Anywhere Server - Database Administration]
● “string_rtruncation option” [SQL Anywhere Server - Database Administration]
● “first_day_of_week option” [SQL Anywhere Server - Database Administration]
● “DATEPART function [Date and time]” on page 192
● “SET OPTION statement” on page 886

Standards and compatibility


● SQL/2008 Transact-SQL extension.

SETUSER statement
Allows a database administrator to assume the identity of another authorized user on the same connection.

Syntax
{ SET SESSION AUTHORIZATION | SETUSER }
[ [ WITH OPTION ] userid ]

Parameters
WITH OPTION clause By default, only permissions (including group membership) are altered. If
WITH OPTION is specified, the database options in effect are changed to the current database options of
userid.

userid The user ID is an identifier (SETUSER syntax) or a string (SET SESSION AUTHORIZATION
syntax).

904 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Remarks
The SETUSER statement is provided for administrative use and should not be used for connection
pooling. After executing a SETUSER statement, you can execute one of the following commands to
verify which user authorization you have assumed:

● SELECT USER
● SELECT CURRENT USER

SETUSER with no user ID undoes all earlier SETUSER statements.

The SETUSER statement cannot be used inside a procedure, trigger, event handler or batch.

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 database administrator can test the permissions and name resolution of queries, procedures, views,
and so on.

● Providing a safer environment for administrators The database administrator has permission
to perform any action in the database. If you want to ensure that you do not accidentally perform an
unintended action, you can use SETUSER to switch to a different user ID with fewer permissions.

Note
The SETUSER statement cannot be used within procedures, triggers, events, or batches.

Permissions
DBA authority.

See also
● “EXECUTE IMMEDIATE statement [SP]” on page 719
● “GRANT statement” on page 760
● “REVOKE statement” on page 863
● “SET OPTION statement” on page 886
● “Identifiers” on page 4
● “Strings” on page 5

Standards and compatibility


● SQL/2008 The SET SESSION AUTHORIZATION syntax is part of optional SQL/2008 language
feature F321, "User authorization". The SETUSER syntax is a vendor extension. You can use the
WITH OPTION syntax with both variants, but WITH OPTION is a vendor extension.

Example
The following statements, executed by a user named DBA, change the user ID to be Joe, then Jane, and
then back to DBA.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 905


SQL statements

SETUSER "Joe"
// ... operations...
SETUSER WITH OPTION "Jane"
// ... operations...
SETUSER

The following statement sets the user to Jane. The user ID is supplied as a string rather than as an
identifier.
SET SESSION AUTHORIZATION 'Jane';

SIGNAL statement [SP]


Signals an exception condition.

Syntax
SIGNAL exception-name

Remarks
SIGNAL allows you to raise an exception.

Use exception-name to specify 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.

Permissions
None.

Side effects
None.

See also
● “RESIGNAL statement [SP]” on page 854
● “BEGIN statement” on page 484
● “Exception handlers” [SQL Anywhere Server - SQL Usage]
● “RAISERROR statement” on page 838

Standards and compatibility


● SQL/2008 The SIGNAL statement is part of optional SQL/2008 language feature P002,
"Computational completeness".

● Transact-SQL The SIGNAL statement cannot be used in Transact-SQL compound statements and
procedures.

906 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Example
The following compound statement declares and signals a user-defined exception. If you execute this
example from Interactive SQL, the message My exception signaled appears on the Messages tab in the
Results area.

BEGIN
DECLARE myexception EXCEPTION
FOR SQLSTATE '99001';
SIGNAL myexception;
EXCEPTION
WHEN myexception THEN
MESSAGE 'My exception signaled'
TO CLIENT;
END

START DATABASE statement


Starts a database on the current database server.

Syntax
START DATABASE database-file [ start-options ... ]

start-options :
[ AS database-name ]
[ ON database-server-name ]
[ WITH TRUNCATE AT CHECKPOINT ]
[ FOR READ ONLY ]
[ AUTOSTOP { ON | OFF } ]
[ KEY key ]
[ WITH SERVER NAME alternative-database-server-name ]
[ DIRECTORY dbspace-directory ]
[ CHECKSUM { ON | OFF } ]

Parameters
database-file 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.

start-options clause The start-options clauses can be listed in any order:

○ 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:\Database Files
\demo.db would be given the default name of demo. The database-name parameter is an identifier.

○ ON clause This clause is supported from Interactive SQL only. In Interactive SQL, if server-name
is not specified, the default server is the first started server among those currently running. The server-
name parameter is an identifier.

○ WITH TRUNCATE AT CHECKPOINT clause Starts a database with log truncation on checkpoint
enabled.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 907


SQL statements

○ FOR READ ONLY clause Starts a database in read-only mode. When used on a database requiring
recovery, the statement fails and the error message is returned.

○ 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.

○ KEY clause If the database is strongly encrypted, enter the KEY value (password) using this
clause.

○ WITH SERVER NAME clause Use this clause to specify an alternate name for the database server
when connecting to this database.

Note
When using database mirroring, an alternate server name must be specified for client applications to
be able to connect to the current primary server without knowing in advance which server is the
primary server and which is the mirror server. Both partner servers must use the same name for the
alternate server name. Use the CREATE MIRROR SERVER statement to create the alternate server
names for the primary and mirror servers in a mirroring system.

○ DIRECTORY clause Use this clause to specify the directory where the dbspace files are located
for the database that is being started. For example, if the database server is started in the same
directory as the dbspaces, and you include the DIRECTORY '.' clause, then this instructs the
database server to find all dbspaces in the current directory.

○ CHECKSUM clause Use this clause to enable write checksums for newly written pages for
databases that were not created with global checksums enabled. This clause has the same behavior as
the -wc database option.

The difference between the CHECKSUM clause and creating a database with global checksums
enabled is that when you specify CHECKSUM ON, database pages are checksummed only when they
are written out to disk. Pages that are read from disk are only verified if a checksum value was
calculated before the pages were written. If a database has global checksums enabled, checksums are
calculated for all pages when they are written and checksums are verified for all pages when they are
read.

If the database server detects that the database is running on Windows Mobile or a removable storage
device, such as a network share or USB device, then the database server automatically enables write
checksums for all database pages.

By default, databases created with version 10 and 11 of SQL Anywhere do not have global checksums
enabled. If you start a database created with SQL Anywhere 10 or 11 on a version 12 or later database
server, then by default the database server creates write checksums for pages when they are written to
disk (CHECKSUM ON). Version 12 and later databases have global checksums enabled by default,
so the database server defaults to CHECKSUM OFF for these databases because by default all
database pages have checksums. You can use either the -wc option or the START DATABASE

908 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

statement to change the database server's checksum behavior if you do not want to use the default
checksum settings.

You can check whether a database was created with global checksums enabled by executing the
following statement:
SELECT DB_PROPERTY ( 'Checksum' );

You can check whether write checksums are enabled by executing the following statement:
SELECT DB_PROPERTY ( 'WriteChecksum' );

Remarks
Cloud note: This statement is not supported on tenant databases in the cloud.

Starts a specified database on the current database server.

If you are not connected to a database and you want to use the START DATABASE statement, you must
first connect to a database, such as the utility database.

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.

You can only use the database name utility_db to connect to the SQL Anywhere utility database.

Permissions
The required permissions are specified by the database server -gd option. This option defaults to all on the
personal database server, and DBA on the network server.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 909


SQL statements

See also
● “STOP DATABASE statement” on page 918
● “CREATE MIRROR SERVER statement” on page 564
● “CONNECT statement [ESQL] [Interactive SQL]” on page 504
● “VALIDATE statement” on page 955
● “-gd dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “-ds dbeng12/dbsrv12 database option” [SQL Anywhere Server - Database Administration]
● “-ek dbeng12/dbsrv12 database option” [SQL Anywhere Server - Database Administration]
● “-m dbeng12/dbsrv12 database option” [SQL Anywhere Server - Database Administration]
● “-r dbeng12/dbsrv12 database option” [SQL Anywhere Server - Database Administration]
● “-n dbeng12/dbsrv12 database option” [SQL Anywhere Server - Database Administration]
● “-wc dbeng12/dbsrv12 database option” [SQL Anywhere Server - Database Administration]
● “-sn dbsrv12 database option” [SQL Anywhere Server - Database Administration]
● “Database mirroring system setup” [SQL Anywhere Server - Database Administration]
● “Utility databases” [SQL Anywhere Server - Database Administration]
● “Corruption detection using checksums” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Start the database file C:\Database Files\sample_2.db on the current server.
START DATABASE 'c:\database files\sample_2.db';

From Interactive SQL, start the database file c:\Database Files\sample_2.db as sam2 on the server named
sample.
START DATABASE 'c:\database files\sample_2.db'
AS sam2
ON sample;

START SERVER statement [Interactive SQL]


Starts a database server.

Syntax
START SERVER AS database-server-name [ STARTLINE command-string ]

Remarks
The START SERVER statement starts a database server. If you want to specify a set of options for the
database server, use the STARTLINE keyword together with a command string.

START ENGINE is accepted for compatibility reasons, but is deprecated.

Permissions
None

910 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Side effects
None

See also
● “STOP SERVER statement” on page 921
● “SQL Anywhere database server syntax” [SQL Anywhere Server - Database Administration]
● “Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Start a database server named sample without starting any databases on it.

START SERVER AS sample;

The following example shows the use of a STARTLINE clause.

START SERVER AS eng1 STARTLINE 'dbsrv12 -c 8M';

START EXTERNAL ENVIRONMENT statement


Starts an external environment.

Syntax
START EXTERNAL ENVIRONMENT environment-name

environment-name :
JAVA
| PERL
| PHP
| CLR
| C_ESQL32
| C_ESQL64
| C_ODBC32
| C_ODBC64

Parameters
environment-name The name of the external environment to start.

Remarks
For more information about external environments, see “SQL Anywhere external environment support”
[SQL Anywhere Server - Programming].

Permissions
DBA authority

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 911


SQL statements

Side effects
None

See also
● “SQL Anywhere external environment support” [SQL Anywhere Server - Programming]
● “ALTER EXTERNAL ENVIRONMENT statement” on page 410
● “STOP EXTERNAL ENVIRONMENT statement” on page 919
● “INSTALL EXTERNAL OBJECT statement” on page 785
● “REMOVE EXTERNAL OBJECT statement” on page 851
● “SYSEXTERNENV system view” on page 1206
● “SYSEXTERNENVOBJECT system view” on page 1206

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Start the Perl external environment.
START EXTERNAL ENVIRONMENT PERL;

START JAVA statement


Starts the Java VM.

Syntax
START JAVA

Remarks
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.

The database server must be set up to locate a Java VM. Since you can specify different Java VMs for
each database, the java_location option can be used to indicate the location (path) of the Java VM.

Permissions
A Java VM must be installed, and the database must be Java-enabled.

This statement is not supported on Windows Mobile.

Side effects
None

912 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “STOP JAVA statement” on page 920
● “Starting and stopping the Java VM” [SQL Anywhere Server - Programming]
● “java_location option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Start the Java VM.
START JAVA;

START LOGGING statement [Interactive SQL]


Starts logging executed SQL statements to a log file.

Syntax
START LOGGING filename

Remarks
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.

Execution times are included in the log file when logging and execution time reporting are both enabled.

Permissions
None.

Side effects
None.

See also
● “STOP LOGGING statement [Interactive SQL]” on page 921
● “isql_command_timing option [Interactive SQL]” [SQL Anywhere Server - Database Administration]
● “Statement logging in Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 913


SQL statements

Example
Start logging to a file called filename.sql, located in the c: directory.
START LOGGING 'c:\filename.sql';

START SUBSCRIPTION statement [SQL Remote]


Starts a subscription for a user to a publication.

Syntax
START SUBSCRIPTION
TO publication-name [ ( subscription-value ) ]
FOR subscriber-id, ...

Parameters
publication-name The name of the publication to which the user is being subscribed. This may
include the owner of the publication.

subscription-value A string that is compared to the subscription expression of the publication. The
value is required here because each subscriber may have more than one subscription to a publication.

subscriber-id The user ID of the subscriber to the publication. This user must have a subscription to
the publication.

Remarks
A SQL Remote subscription is said to be started when publication updates are being sent from the
consolidated database to the remote database.

The START SUBSCRIPTION statement is one of a set of statements that manage subscriptions. The
CREATE SUBSCRIPTION statement defines the data that the subscriber is to receive. The
SYNCHRONIZE SUBSCRIPTION statement ensures that the consolidated and remote databases are
consistent with each other. The START SUBSCRIPTION statement is required to start messages being
sent to the subscriber.

Data at each end of the subscription must be consistent before a subscription is started. It is recommended
that you use the database extraction utility to manage the creation, synchronization, and starting of
subscriptions. If you use the database extraction utility, you do not need to execute an explicit START
SUBSCRIPTION statement. Also, the Message Agent starts subscriptions once they are synchronized.

Permissions
DBA authority.

Side effects
Automatic commit.

914 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “CREATE SUBSCRIPTION statement [SQL Remote]” on page 626
● “REMOTE RESET statement [SQL Remote]” on page 850
● “SYNCHRONIZE SUBSCRIPTION statement [SQL Remote]” on page 930
● “STOP SUBSCRIPTION statement [SQL Remote]” on page 922
● “Extraction utility (dbxtract)” [SQL Remote]
● “Starting subscriptions” [SQL Remote]
● “Creating multiple remote databases” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement starts the subscription of user SamS to the pub_contact publication.
START SUBSCRIPTION TO pub_contact
FOR SamS;

START SYNCHRONIZATION DELETE statement [MobiLink]


Restarts logging of deletes for MobiLink synchronization.

Syntax
START SYNCHRONIZATION DELETE

Remarks
Ordinarily, SQL Anywhere and UltraLite automatically log any changes made to tables or columns that
are part of a synchronization, and upload these changes to the consolidated database during the next
synchronization. You can temporarily suspend automatic logging of delete operations using the STOP
SYNCHRONIZATION DELETE statement. The START SYNCHRONIZATION DELETE statement
allows you to restart the automatic logging.

When a STOP SYNCHRONIZATION DELETE statement is executed, none of the delete operations
executed on that connection are synchronized. The effect continues until a START
SYNCHRONIZATION DELETE statement is executed. Repeating STOP SYNCHRONIZATION
DELETE has no additional effect.

A single START SYNCHRONIZATION DELETE statement restarts the logging, regardless of the
number of STOP SYNCHRONIZATION DELETE statements preceding it.

Do not use START SYNCHRONIZATION DELETE if your application does not synchronize data.

Permissions
DBA authority

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 915


SQL statements

Side effects
None.

See also
● “STOP SYNCHRONIZATION DELETE statement [MobiLink]” on page 924
● “ULConnection.StartSynchronizationDelete method [UltraLite.NET]” [UltraLite - .NET
Programming]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following sequence of SQL statements illustrates how to use START SYNCHRONIZATION
DELETE and STOP SYNCHRONIZATION DELETE:
-- Prevent deletes from being sent
-- to the consolidated database
STOP SYNCHRONIZATION DELETE;

-- Remove all records older than 1 month


-- from the remote database,
-- NOT the consolidated database
DELETE FROM PROPOSAL
WHERE last_modified < months( CURRENT TIMESTAMP, -1 )

-- Re-enable all deletes to be sent


-- to the consolidated database
-- DO NOT FORGET to start this
START SYNCHRONIZATION DELETE;

-- Commit the entire operation,


-- otherwise rollback everything
-- including the stopping of the deletes
commit;

START SYNCHRONIZATION SCHEMA CHANGE statement


[MobiLink]
Starts a MobiLink synchronization schema change.

Syntax
START SYNCHRONIZATION SCHEMA CHANGE
FOR TABLES table-list
[ set-script-version
| set-script-version-on-subscription [ ... ] ]

set-script-version :
SET SCRIPT VERSION = script-version

set-script-version-on-subscription :
SET SCRIPT VERSION = script-version ON SUBSCRIPTION subscription_name

916 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

script-version : string

subscription-name : identifier

Parameters
FOR TABLES clause This clause specifies the tables that are affected by the schema change.

SET SCRIPT VERSION clause Specifies the new script version for all subscriptions that contain any
table specified in the FOR TABLES clause. The new script version may be the same as the existing script
version.

Cloud note: You can specify NULL for the script-version value for cloud tenant databases.

ON SUBSCRIPTION clause Specifies the new script version for specified subscription. When used,
this clause must be repeated for each subscription that contains any table specified in the FOR TABLES
clause. The new script version may be the same as the existing script version.

Remarks
All tables to which you want to apply a schema change must be listed in table-list. A table cannot be
listed more than once. An error message is reported if there is an existing lock on any of the tables in
table-list.

Only one synchronization schema change can be executed on a database at a time. The START
SYNCHRONIZATION SCHEMA CHANGE statement fails when another schema change is in progress.

The database server obtains locks on all tables specified in table-list. The database server ignores the
setting of the blocking option when attempting to obtain locks. If a lock cannot be obtained, all previously
acquired locks are released and an error message is reported.

During a synchronization schema change:

● You cannot execute a data manipulation statement.

● You cannot execute additional START SYNCHRONIZATION SCHEMA CHANGE statements.

● You can alter a publication to change the column subsetting of any table in table-list.

● You can alter a publication to drop any table in table-list.

● You can alter any of the tables listed in table-list.

An implicit commit is performed both before and after the START SYNCHRONIZATION SCHEMA
CHANGE statement is executed. A synchronization schema change ends with the execution of a STOP
SYNCHRONIZATION SCHEMA CHANGE statement. When the STOP SYNCHRONIZATION
SCHEMA CHANGE statement is executed, all table locks are released.

Permissions
DBA authority

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 917


SQL statements

Side effects
None.

See also
● “STOP SYNCHRONIZATION SCHEMA CHANGE statement [MobiLink]” on page 929
● “SynchronizationSchemaChangeActive database property” [SQL Anywhere Server - Database
Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following sequence of SQL statements illustrates how to use START SYNCHRONIZATION
SCHEMA CHANGE and STOP SYNCHRONIZATION SCHEMA CHANGE:
START SYNCHRONIZATION SCHEMA CHANGE
FOR TABLES DBA.Sales, DBA.Products
SET SCRIPT VERSION = 'version_2';
ALTER TABLE DBA.Sales ADD SUBTOTAL NUMERIC (10,2);
ALTER TABLE DBA.Products ALTER QUANTITY BIGINT;
STOP SYNCHRONIZATION SCHEMA CHANGE;

STOP DATABASE statement


Stops a database on the current database server.

Syntax
STOP DATABASE database-name
[ ON database-server-name ]
[ UNCONDITIONALLY ]

Parameters
STOP DATABASE clause The database-name is the name of a database (other than the current
database) running on the current server.

ON clause This clause is supported in Interactive SQL only. If database-server-name is not specified
in Interactive SQL, all running servers are 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 clause Stop the database even if there are connections to the database. By
default, the database is not stopped if there are connections to it.

Remarks
Cloud note: This statement is not supported on tenant databases in the cloud.

The STOP DATABASE statement stops a specified database on the current database server.

918 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Permissions
The required permissions are specified by the database server -gd 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 907
● “DISCONNECT statement [ESQL] [Interactive SQL]” on page 688
● “-gd dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “Stop Server utility (dbstop)” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Stop the database named sample on the current server.

STOP DATABASE sample;

STOP EXTERNAL ENVIRONMENT statement


Stops an external environment.

Syntax
STOP EXTERNAL ENVIRONMENT environment-name

environment-name :
JAVA
| PERL
| PHP
| CLR
| C_ESQL32
| C_ESQL64
| C_ODBC32
| C_ODBC64

Parameters
environment-name The name of the external environment to stop.

Remarks
For more information about external environments, see “SQL Anywhere external environment support”
[SQL Anywhere Server - Programming].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 919


SQL statements

Permissions
DBA authority

Side effects
None

See also
● “SQL Anywhere external environment support” [SQL Anywhere Server - Programming]
● “ALTER EXTERNAL ENVIRONMENT statement” on page 410
● “START EXTERNAL ENVIRONMENT statement” on page 911
● “INSTALL EXTERNAL OBJECT statement” on page 785
● “REMOVE EXTERNAL OBJECT statement” on page 851
● “SYSEXTERNENV system view” on page 1206
● “SYSEXTERNENVOBJECT system view” on page 1206

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Stop the Perl external environment.
STOP EXTERNAL ENVIRONMENT PERL;

STOP JAVA statement


Stops the Java VM.

Syntax
STOP JAVA

Remarks
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.

Permissions
This statement is not supported on Windows Mobile.

Side effects
None

See also
● “START JAVA statement” on page 912

920 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Stop the Java VM.
STOP JAVA;

STOP LOGGING statement [Interactive SQL]


Stops logging of SQL statements in the current session.

Syntax
STOP LOGGING

Remarks
The STOP LOGGING statement stops Interactive SQL from writing each SQL statement you execute to a
log file. You can start logging with the START LOGGING statement.

You can also stop logging by clicking SQL » Stop Logging.

Permissions
None.

Side effects
None.

See also
● “START LOGGING statement [Interactive SQL]” on page 913
● “Statement logging in Interactive SQL” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example stops the current logging session.
STOP LOGGING;

STOP SERVER statement


Stops a database server.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 921


SQL statements

Syntax
STOP SERVER [ database-server-name ] [ UNCONDITIONALLY ]

Parameters
UNCONDITIONALLY clause 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.

Remarks
Cloud note: This statement is not supported on tenant databases in the cloud.

You can only use database-server-name in Interactive SQL only. If you do not execute this statement
from Interactive SQL, the current database server is stopped.

By default, the database server is not stopped if there are other connections to it. If the
UNCONDITIONALLY clause is used, the database server is stopped even if there are other connections
to the database server. If the STOP SERVER statement is executed on a client connection and the server
successfully shuts down, a communication error occurs.

The STOP SERVER statement cannot be used in stored procedures, triggers, events, or batches.

STOP ENGINE is accepted for compatibility reasons, but is deprecated.

Permissions
The permissions to shut down a server depend on the -gk 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 SERVER statement [Interactive SQL]” on page 910
● “-gk dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
Stop the current database server, as long as there are no other connections.
STOP SERVER;

STOP SUBSCRIPTION statement [SQL Remote]


Stops a subscription for a user to a publication.

922 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Syntax
STOP SUBSCRIPTION
TO publication-name [ ( subscription-value ) ]
FOR subscriber-id, ...

Parameters
publication-name The name of the publication to which the user is being subscribed. This may
include the owner of the publication.

subscription-value A string that is compared to the subscription expression of the publication. The
value is required here because each subscriber may have more than one subscription to a publication.

subscriber-id The user ID of the subscriber to the publication. This user must have a subscription to
the publication.

Remarks
A SQL Remote subscription is said to be started when publication updates are being sent from the
consolidated database to the remote database.

The STOP SUBSCRIPTION statement prevents any further messages being sent to the subscriber. The
START SUBSCRIPTION statement is required to restart messages being sent to the subscriber. However,
you should ensure that the subscription is properly synchronized before restarting: that no messages have
been missed.

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “DROP SUBSCRIPTION statement [SQL Remote]” on page 707
● “START SUBSCRIPTION statement [SQL Remote]” on page 914
● “SYNCHRONIZE SUBSCRIPTION statement [SQL Remote]” on page 930
● “Extraction utility (dbxtract)” [SQL Remote]
● “Stopping subscriptions” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement stops the subscription of user SamS to the pub_contact publication.
STOP SUBSCRIPTION TO pub_contact
FOR SamS;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 923


SQL statements

STOP SYNCHRONIZATION DELETE statement [MobiLink]


Temporarily stops logging of deletes for MobiLink synchronization.

Syntax
STOP SYNCHRONIZATION DELETE

Remarks
Ordinarily, SQL Anywhere and UltraLite remote databases automatically log any changes made to tables
or columns that are being synchronized, and then upload these changes to the consolidated database
during the next synchronization. This statement allows you to temporarily suspend logging of delete
operations to a SQL Anywhere or UltraLite remote database.

None of the delete operations executed on a connection between the time the connection executes STOP
SYNCHRONIZATION DELETE and the time the connection executes START SYNCHRONIZATION
DELETE are synchronized.

A single START SYNCHRONIZATION DELETE statement restarts the logging, regardless of the
number of STOP SYNCHRONIZATION DELETE statements preceding it.

This statement can be useful to make corrections to a remote database, but should be used with caution as
it effectively disables MobiLink synchronization.

Do not use STOP SYNCHRONIZATION DELETE if your application does not synchronize data.

Permissions
DBA authority

Side effects
None.

See also
● “ULConnection.StartSynchronizationDelete method [UltraLite.NET]” [UltraLite - .NET
Programming]
● “ULConnection.StopSynchronizationDelete method [UltraLite.NET]” [UltraLite - .NET
Programming]
● “START SYNCHRONIZATION DELETE statement [MobiLink]” on page 915

Standards and compatibility


● SQL/2008 Vendor extension.

Example
For an example, see “START SYNCHRONIZATION DELETE statement [MobiLink]” on page 915.

924 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

SYNCHRONIZE statement [MobiLink]


Synchronizes a SQL Anywhere database with a MobiLink server. The synchronization options can be
specified in the statement itself.

Syntax
SYNCHRONIZE {
PROFILE sync-profile-name [ MERGE sync-option [ ;... ] ]
| USING sync-option [ ;... ]
| START
| STOP
}

[ PORT port-number ]
[ VERBOSITY { LOW | NORMAL | HIGH } ]
[ TIMEOUT timeout ]
[ USER user-name IDENTIFIED BY password ]

sync-option : string

Parameters
sync-profile-name The name of the synchronization profile to use for this synchronization.

MERGE clause Use this clause to add or override synchronization profile options.

USING clause Use this clause to specify synchronization profile options when you are not using a
synchronization profile.

sync-option A string of one or more synchronization profile option value pairs, separated by
semicolons. For example, 'option1=value1;option2=value2'.

PORT clause Use this clause to specify the port number that the database server uses to communicate
with the dbmlsync utility. The default is 4433.

VERBOSITY clause This clause controls the amount of information that is added to the
synchronize_results and synchronize_parameters shared global temporary tables during synchronization.

The following is a list of client API events that are returned by each VERBOSITY option.

Option Returns

LOW ○ DBSC_EVENTTYPE_SYNC_START
○ DBSC_EVENTTYPE_SYNC_DONE
○ DBSC_EVENTTYPE_ERROR_MSG
○ DBSC_EVENTTYPE_WARNING_MSG

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 925


SQL statements

Option Returns

NORMAL (default) ○ DBSC_EVENTTYPE_SYNC_START


○ DBSC_EVENTTYPE_SYNC_DONE
○ DBSC_EVENTTYPE_ERROR_MSG
○ DBSC_EVENTTYPE_WARNING_MSG
○ DBSC_EVENTTYPE_INFO_MSG

HIGH ○ DBSC_EVENTTYPE_SYNC_START
○ DBSC_EVENTTYPE_SYNC_DONE
○ DBSC_EVENTTYPE_ERROR_MSG
○ DBSC_EVENTTYPE_WARNING_MSG
○ DBSC_EVENTTYPE_INFO_MSG
○ DBSC_EVENTTYPE_PROGRESS_INDEX
○ DBSC_EVENTTYPE_PROGRESS_TEXT
○ DBSC_EVENTTYPE_TITLE

Be careful not to confuse the VERBOSITY clause of the SYNCHRONIZE statement with the
VERBOSITY option that you can specify in a synchronization profile. The VERBOSITY clause of the
SYNCHRONIZE statement controls the type of events that are recorded in the synchronize_results and
synchronize_parameters tables. The VERBOSITY option in a synchronization profile controls the number
of DBSC_EVENTTYPE_INFO_MSG events that are generated during synchronization.
SYNCHRONIZE PROFILE SalesData VERBOSITY NORMAL;
SYNCHRONIZE PROFILE SalesData MERGE 'Verbosity=BASIC,ROW_DATA' VERBOSITY
NORMAL;

TIMEOUT clause This clause specifies how long the database server waits, in seconds, for the
synchronization to complete before attempting to cancel the synchronization. The default is 240 seconds.

USER/IDENTIFIED BY clause Use this clause to specify the database user ID and password that the
dbmlsync utility uses to synchronize the database. The user ID specified must have REMOTE DBA or
DBA authority. By default, synchronization uses the user ID for the database connection that executed the
SYNCHRONIZE statement.

START clause Starts the dbmlsync utility running in server mode and leaves it running. No
synchronization is performed. When you are performing more than one synchronization in a short period,
you can improve performance by explicitly starting the dbmlsync server using this clause, performing
your synchronizations, then explicitly stopping the dbmlsync server using the STOP clause.

STOP clause Stops a dbmlsync server that was previously started using the START clause. No
synchronization is performed.

Remarks
This statement can only be used if the MobiLink client for SQL Anywhere including the Dbmlsync C++
API is installed.

The MobiLink client for SQL Anywhere is not available on all platforms where the database server may
run. For a list of supported platforms, see http://www.sybase.com/detail?id=1061806.

926 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

When synchronization is complete, you can view the results of the synchronization in the
synchronize_results and synchronize_parameters shared global temporary tables. The synchronize_results
and synchronize_parameters tables store the results of all synchronizations that have been executed with
the SYNCHRONIZE statement since the database server was started. The synchronize_results and
synchronize_parameters tables are truncated each time the database server is shut down.

The synchronize_results table contains the following columns:

Column Data type Description


name

row_id UNSIGNED BI- The primary key of the table used to determine the order in
GINT which rows were inserted into the table.

conn_id UNSIGNED INT The connection id number of the connection that executed the
SYNCHRONIZE statement that generated this event.

result_time TIMESTAMP The time the event was added to the synchronize_results ta-
ble.

result_type CHAR(128) The type of event.

Each event shown in the synchronize_results table has 0 or more parameters associated with it that
contain additional information about the event. The parameters are stored in the synchronize_parameters
table, which contains the following columns:

Column Data type Description


name

row_id UNSIGNED A foreign key to the row_id column in the synchronize_results ta-
BIGINT ble. Use this value to match each parameter back to the event to
which it belongs.

parm_id UNSIGNED Contains the numeric ID of the parameter. For events with more
INT than 1 parameter, use this value to locate the specific parameter you
need.

parm_mes- LONG VAR- The value associated with the parameter.


sage CHAR

To view information about past or current synchronizations, you can use the
sp_get_last_synchronize_result system procedure as an alternative to directly querying the
synchronize_results and synchronize_parameters tables.

Alternately, you can use the following statement to view the results of all the synchronizations that have
taken place since the database server was started.
SELECT *
FROM synchronize_results sr

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 927


SQL statements

KEY JOIN synchronize_parameters sp


ORDER BY sr.row_id , sp.parm_id

You can use the synchronize_results and synchronize_parameters tables to monitor the progress of a
synchronization on a connection that is different from your current connection. To monitor the progress of
a synchronization on a different connection:

● Execute a SELECT CONNECTION_PROPERTY statement to determine the connection ID of the


current connection.

● Execute a SYNCHRONIZE statement to start synchronization.

● On a separate connection, use the sp_get_last_synchronize_results system procedure to retrieve results


using the connection ID you determined above.

To view the results of a synchronization that is complete or in progress on a specific connection, you can
use the sp_get_last_synchronize_results system procedure.

The SYNCHRONIZE statement is similar to the UltraLite SYNCHRONIZE statement. However, the
SQL Anywhere SYNCHRONIZE statement launches the dbmlsync utility in server mode to perform the
synchronization. The UltraLite SYNCHRONIZE statement uses UltraLite runtime.

The database server functions as a dbmlsync API client and uses TCP/IP to communicate with a
dbmlsync server. By default, this communication occurs on port 4433. Use the PORT clause to specify a
different port.

Use the SYNCHRONIZE PROFILE and SYNCHRONIZE USING statements to perform a


synchronization. Use the SYNCHRONIZE START and SYNCHRONIZE STOP statements to start or
stop a dbmlsync server. When executing a SYNCHRONIZE PROFILE or SYNCHRONIZE USING
statement, the database server attempts to connect to a dbmlsync server that is already running. If a
dbmlsync server that is already running cannot be located, a dbmlsync server is started. When the
synchronization is complete, the database server shuts down the dbmlsync server it started. If the
statement connected to a dbmlsync server that was already running, the dbmlsync server is not shut down.
If you are performing multiple synchronizations and do not want to start and stop the dbmlsync server for
each synchronization, you can execute a SYNCHRONIZE START statement, followed by multiple
SYNCHRONIZE PROFILE or SYNCHRONIZE USING statements, and end with a SYNCHRONIZE
STOP statement.

Permissions
REMOTE DBA or DBA authority

Side effects
None

928 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “CREATE SYNCHRONIZATION PROFILE statement [MobiLink]” on page 628
● “Events and parm_id values from the synchronize_parameters table” on page 1162
● “DBSC_Event structure [Dbmlsync .NET]” [MobiLink - Client Administration]
● “MobiLink synchronization” [MobiLink - Getting Started]
● “MobiLink synchronization profiles” [MobiLink - Client Administration]
● “SQL Anywhere MobiLink client deployment” [MobiLink - Server Administration]
● “sp_get_last_synchronize_result system procedure” on page 1161

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example shows the syntax for synchronizing a synchronization profile named Test1:
SYNCHRONIZE PROFILE Test1;

STOP SYNCHRONIZATION SCHEMA CHANGE statement


[MobiLink]
Stops a MobiLink synchronization schema change.

Syntax
STOP SYNCHRONIZATION SCHEMA CHANGE

Remarks
The STOP SYNCHRONIZATION SCHEMA CHANGE statement stops a schema change started by a
START SYNCHRONIZATION SCHEMA CHANGE statement. All locks obtained by the START
SYNCHRONIZATION SCHEMA CHANGE statement are released.

Permissions
DBA authority

Side effects
None.

See also
● “START SYNCHRONIZATION SCHEMA CHANGE statement [MobiLink]” on page 916
● “SYSARTICLE system view” on page 1196
● “SynchronizationSchemaChangeActive database property” [SQL Anywhere Server - Database
Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 929


SQL statements

Example
The following sequence of SQL statements illustrates how to use START SYNCHRONIZATION
SCHEMA CHANGE and STOP SYNCHRONIZATION SCHEMA CHANGE:
START SYNCHRONIZATION SCHEMA CHANGE
ON DBA.Sales, DBA.Products
SET SCRIPT VERSION = 'version 2';
ALTER TABLE DBA.Sales ADD SUBTOTAL NUMERIC (10,2);
ALTER TABLE DBA.Products ALTER QUANTITY BIGINT;
STOP SYNCHRONIZATION SCHEMA CHANGE;

SYNCHRONIZE SUBSCRIPTION statement [SQL Remote]


Synchronizes a subscription for a user to a publication.

Syntax
SYNCHRONIZE SUBSCRIPTION
TO publication-name [ ( subscription-value ) ]
FOR remote-user, ...

Parameters
publication-name The name of the publication to which the user is being subscribed. This may
include the owner of the publication.

subscription-value A string that is compared to the subscription expression of the publication. The
value is required here because each subscriber may have more than one subscription to a publication.

remote-user The user ID of the subscriber to the publication. This user must have a subscription to the
publication.

Remarks
A SQL Remote subscription is said to be synchronized when the data in the remote database is consistent
with that in the consolidated database, so that publication updates sent from the consolidated database to
the remote database will not result in conflicts and errors.

To synchronize a subscription, a copy of the data in the publication at the consolidated database is sent to
the remote database. The SYNCHRONIZE SUBSCRIPTION statement does this through the message
system. It is recommended that where possible you use the database extraction utility (dbxtract) instead to
synchronize subscriptions without using a message system.

Permissions
DBA authority

Side effects
Automatic commit.

930 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “CREATE SUBSCRIPTION statement [SQL Remote]” on page 626
● “START SUBSCRIPTION statement [SQL Remote]” on page 914
● “STOP SUBSCRIPTION statement [SQL Remote]” on page 922
● “Extraction utility (dbxtract)” [SQL Remote]
● “Synchronize with the SQL Remote Message Agent (dbremote)” [SQL Remote]
● “Subscription resynchronization” [SQL Remote]
● “Synchronize” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following statement synchronizes the subscription of user SamS to the pub_contact publication.
SYNCHRONIZE SUBSCRIPTION
TO pub_contact
FOR SamS;

SYSTEM statement [Interactive SQL]


Launches an executable file from within Interactive SQL.

Syntax
SYSTEM '[ path ] filename'

Remarks
Launches the specified executable file. The path and file name must be enclosed in single quotation
marks.

Permissions
None.

Side effects
None.

See also
● “CONNECT statement [ESQL] [Interactive SQL]” on page 504
● “Interactive SQL” [SQL Anywhere Server - Database Administration]
● “Interactive SQL utility (dbisql)” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 931


SQL statements

Example
The following statement launches the Notepad program if the Notepad executable is in your path.
SYSTEM 'notepad.exe';

TRIGGER EVENT statement


Triggers a named event. The event may be defined for event triggers or be a scheduled event.

Syntax
TRIGGER EVENT event-name [ ( parm = value, ... ) ]

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, to simulate a context for the event
handler.

Remarks
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.

Each value is a string. The maximum length of each value is limited by the maximum page size specified
by the -gp server option. If the length of value exceeds the page size, the string is truncated at the point at
which the page is full.

Permissions
DBA authority

Side effects
None

See also
● “-gp dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “ALTER EVENT statement” on page 408
● “CREATE EVENT statement” on page 526
● “EVENT_PARAMETER function [System]” on page 217

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example shows how to pass a string parameter to an event. The event displays the time it
was triggered in the database server messages window.

932 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

CREATE EVENT ev_PassedParameter


HANDLER
BEGIN
MESSAGE 'ev_PassedParameter - was triggered at ' ||
event_parameter( 'time' );
END;
TRIGGER EVENT ev_PassedParameter( "Time"=string( current timestamp ) );

TRUNCATE statement
Deletes all rows from a table without deleting the table definition.

Syntax
TRUNCATE
TABLE [ owner.]table-name
| MATERIALIZED VIEW [ owner.]materialized-view-name

Remarks
The TRUNCATE statement deletes all rows from the table or materialized view.

Note
The TRUNCATE TABLE statement should be used with great care on a database involved in
synchronization or replication because the statement deletes all rows from a table, similar to a DELETE
statement that doesn't have a WHERE clause. However, no triggers are fired as a result of a TRUNCATE
statement. Furthermore, the row deletions are not entered into the transaction log and therefore are not
synchronized or replicated. This can lead to inconsistencies that can cause synchronization or replication
to fail.

After a TRUNCATE statement, the object's schema and all the indexes continue to exist until you execute
a DROP statement. The schema definitions and constraints remain intact, and triggers and permissions
remain in effect.

table-name can be the name of a base table or a temporary table.

With TRUNCATE TABLE, if 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.

● 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, individual DELETEs are not recorded in the transaction log, and a
COMMIT is carried out before and after the operation. Fast truncation cannot be used within snapshot
transactions.

If you attempt to use TRUNCATE TABLE on a table on which an immediate text index is built, or that is
referenced by an immediate view, the truncation fails. This does not occur for non-immediate text indexes

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 933


SQL statements

or materialized views; however, it is strongly recommended that you truncate the data in dependent
indexes and materialized views before executing the TRUNCATE TABLE statement on a table, and then
refreshing the indexes and materialized views after.

Permissions
● Must be the table owner, or have DBA authority, or have ALTER permissions on the table.

● For base tables and materialized views, the TRUNCATE statement requires exclusive access to the
table, as the operation is atomic (either all rows are deleted, or none are). This means that any cursors
that were previously opened and that reference the table being truncated must be closed and a
COMMIT or ROLLBACK must be executed to release the reference to the table.

● For temporary tables, each user has their own copy of the data, and exclusive access is not required
when executing the TRUNCATE statement.

Side effects
● When you truncate a materialized view, you change the status of the view to uninitialized.

● Delete triggers are not fired by the TRUNCATE statement.

● A COMMIT is performed before and after a TRUNCATE statement is executed.

● Individual deletions of rows are not entered into the transaction log, so the TRUNCATE operation is
not replicated. Do not use this statement in SQL Remote replication or on a MobiLink remote database.

● If the table contains a column defined as DEFAULT AUTOINCREMENT or DEFAULT GLOBAL


AUTOINCREMENT, the truncation operation resets the next available value for the column.

See also
● “DELETE statement” on page 678
● “TRUNCATE TEXT INDEX statement” on page 935
● “Deletion of all rows from a table” [SQL Anywhere Server - SQL Usage]
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]
● “Advanced: Status and properties for materialized views” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 The TRUNCATE TABLE statement is optional language feature F200 of the SQL/2008
standard. TRUNCATE MATERIALIZED VIEW is a vendor extension.

Example
Delete all rows from the Departments table:
TRUNCATE TABLE Departments;

934 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

TRUNCATE TEXT INDEX statement


Deletes the data in a MANUAL or an AUTO REFRESH text index.

Syntax
TRUNCATE TEXT INDEX text-index-name
ON [ owner.]table-name

Parameters
ON clause The name of the table on which the text index is built.

Remarks
Use the TRUNCATE TEXT INDEX statement when you want to delete data from a manual text index
without dropping the text index definition. For example, if you want to alter the text configuration object
for the text index to change the stoplist, you must first truncate the text index, change the text
configuration object it refers to, and then refresh the text index to populate it with new data.

You cannot perform a TRUNCATE TEXT INDEX statement on a text index defined as IMMEDIATE
REFRESH (the default). For IMMEDIATE REFRESH text indexes, you must drop the index instead.

Permissions
● Must be the owner of the table the text index is built on, or have DBA authority, or have ALTER
permissions on the table.

● The TRUNCATE TEXT INDEX requires exclusive access to the table. This means that any open
cursors that reference the table being truncated must be closed, and a COMMIT or ROLLBACK
statement must be executed to release the reference to the table.

Side effects
Automatic commit

See also
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Text index concepts and reference” [SQL Anywhere Server - SQL Usage]
● “CREATE TEXT INDEX statement” on page 649
● “ALTER TEXT INDEX statement” on page 468
● “DROP TEXT INDEX statement” on page 713
● “REFRESH TEXT INDEX statement” on page 846

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The first statement creates the txt_index_manual text index. The second statement populates the text
index with data. The third statement truncates the text index data.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 935


SQL statements

CREATE TEXT INDEX txt_index_manual ON MarketingInformation ( Description )


MANUAL REFRESH;
REFRESH TEXT INDEX txt_index_manual ON MarketingInformation;
TRUNCATE TEXT INDEX txt_index_manual ON MarketingInformation;

The truncated text index is repopulated with data the next time it is refreshed.

UNION statement
Combines the results of two or more SELECT statements or query expressions.

Syntax
[ WITH temporary-views ] query-block
UNION [ ALL | DISTINCT ] query-block
[ ORDER BY [ integer | select-list-expression-name ] [ ASC | DESC ], ... ]
[ FOR XML xml-mode ]
[ OPTION( query-hint, ... ) ]

query-block : See “Common elements in SQL syntax” on page 395.

query-hint :
MATERIALIZED VIEW OPTIMIZATION option-value
| FORCE OPTIMIZATION
| option-name = option-value

option-name : identifier

option-value :
hostvar (indicator allowed)
| string
| identifier
| number

Parameters
FOR XML clause For information about the FOR XML clause, see “SELECT statement” on page 871.

OPTION clause Use this clause to specify hints for executing the statement. The following hints are
supported:

○ MATERIALIZED VIEW OPTIMIZATION option-value


○ FORCE OPTIMIZATION
○ option-name = option-value. Note that a OPTION( isolation_level = ... ) specification
in the query text overrides all other means of specifying isolation level for a query.

Remarks
UNION ALL concatenates the results of the two query blocks into a single (larger) result set. Each query
block may be nested. UNION DISTINCT eliminates duplicate rows in the final result. Eliminating
duplicates requires extra processing, so UNION ALL should be used instead of UNION where possible.
UNION DISTINCT is identical to UNION.

936 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

The result sets of the two query-blocks must be UNION-compatible; they must each have the same
number of items in their respective SELECT lists, and the types of each expression should be comparable.
If corresponding items in two SELECT lists have different data types, SQL Anywhere chooses a data type
for the corresponding column in the result and automatically convert the columns in each query-block
appropriately.

The column names displayed are the same column names that are displayed for the first query-block and
these names are used to determine the expression names to be matched with the ORDER BY clause. An
alternative way of customizing result set column names is to use a common table expression (the WITH
clause).

Permissions
Must have SELECT permission for each query-block.

Side effects
None.

See also
● “EXCEPT statement” on page 717
● “INTERSECT statement” on page 788
● “OPTION clause, SELECT statement” on page 877
● “SELECT statement” on page 871
● “Set operators and NULL” [SQL Anywhere Server - SQL Usage]

Standards and compatibility


● SQL/2008 UNION is a core feature of the SQL/2008 standard. Explicitly specifying the
DISTINCT keyword with UNION is optional SQL language feature T551. Specifying an ORDER BY
clause with UNION is SQL language feature F850. A query-block that contains an ORDER BY clause
constitutes SQL/2008 feature F851. A query block that contains a row-limit clause (SELECT TOP or
LIMIT) comprises optional SQL language feature F857 or F858, depending on the context. The FOR
XML and OPTION clauses are vendor extensions.

● Transact-SQL UNION and UNION ALL are supported by Adaptive Server Enterprise. The FOR
XML and OPTION clauses are not supported.

Example
List all distinct surnames of employees and customers.
SELECT Surname
FROM Employees
UNION
SELECT Surname
FROM Customers;

UNLOAD statement
Unloads data from a data source into a file.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 937


SQL statements

Syntax
UNLOAD data-source
{ TO filename
| INTO FILE filename
| INTO CLIENT FILE client-filename
| INTO VARIABLE variable-name }
[ unload-option ... ]

data-source
[ FROM ] [ TABLE ] [ owner.]table-name
| [ FROM ] [ MATERIALIZED VIEW ] [ owner.]materialized-view-name
| select-statement

filename : string | variable

client-filename : string | variable

Syntax
unload-option :
APPEND { ON | OFF }
| BYTE ORDER MARK { ON | OFF }
| { COMPRESSED | NOT COMPRESSED }
| COLUMN DELIMITED BY string
| DELIMITED BY string
| ENCODING encoding
| { ENCRYPTED KEY 'key' [ ALGORITHM 'algorithm' ] | NOT ENCRYPTED }
| ESCAPE CHARACTER character
| ESCAPES { ON | OFF }
| FORMAT { TEXT | BCP }
| HEXADECIMAL { ON | OFF }
| ORDER { ON | OFF }
| QUOTE string
| QUOTES { ON | OFF }
| ROW DELIMITED BY string

encoding : string

Parameters
TO clause The name of the file to unload data into. The filename path is relative to the database
server's starting directory. If the file does not exist, it is created. If it already exists, it is overwritten unless
APPEND ON is also specified.

INTO FILE clause Semantically equivalent to TO filename.

INTO CLIENT FILE clause The file on the client computer into which the data is unloaded. If the file
doesn't exist, it is created. If it already exists, it is overwritten unless APPEND ON is also specified. The
path is resolved on the client computer relative to the current working directory of the client application.

INTO VARIABLE clause The variable to unload the data into. The variable must already exist and be
of CHAR, NCHAR or BINARY type. The APPEND option causes the unloaded data to be concatenated
to the current contents of the variable.

938 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

APPEND clause When APPEND is ON, unloaded data is appended to the end of the file specified.
When APPEND is OFF, unloaded data replaces the contents of the file specified. APPEND is OFF by
default. This clause cannot be specified when specifying the COMPRESSED or ENCRYPTED clauses,
and cannot be used if the file being appended to is compressed or encrypted.

BYTE ORDER MARK clause Use this clause to specify whether a byte order mark (BOM) should be
written. By default, this option is ON, provided the destination for the unload is a local or client file.
When the BYTE ORDER MARK option is ON and the ENCODING is UTF-8 or UTF-16, then a BOM is
written. If BYTE ORDER MARK is OFF, a BOM is not unloaded.

COMPRESSED clause Specifies whether to compress the data. The default is NOT COMPRESSED.
You cannot compress the data if you want the data to be appended (APPEND ON).

COLUMN DELIMITED BY and DELIMITED BY clauses The string used between columns. The
default column delimiter is a comma. You can specify an alternative column delimiter by providing a
string up to 255 bytes in length.

ENCODING clause All database data is translated from the database character encoding to the
specified CHAR or NCHAR encoding. When ENCODING is not specified, the database's CHAR
encoding is used.

If a translation error occurs during the unload operation, it is reported based on the setting of the
on_charset_conversion_failure option.

The following example unloads the data using the UTF-8 character encoding:
UNLOAD TABLE mytable TO 'mytable_data_in_utf8.dat' ENCODING 'UTF-8';

Specify the BYTE ORDER MARK clause to include a byte order mark in the data.

ENCRYPTED clause Specifies whether to encrypt the data. If you specify NOT ENCRYPTED (the
default), the data is not encrypted. If you specify ENCRYPTED KEY with a key and no algorithm, the
data is encrypted using AES128 and the specified key. If you specify ENCRYPTED KEY with a key and
algorithm, the data is encrypted using the specified key and algorithm. The algorithm can be any of the
algorithms accepted by the CREATE DATABASE statement. You cannot specify simple encryption.

You cannot encrypt the data if you want the data to be appended (APPEND ON).

ESCAPES clause With ESCAPES turned ON (the default), the database server writes escape
sequences. Newline characters can be written 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 written as a single backslash. A backslash followed by any character other than n, x, X,
or \ is written as two separate characters. For example, \q inserts a backslash and the letter q. It is
recommended that the string you specify for the escape character is no longer than one multibyte
character.

FORMAT clause Outputs data in either TEXT format or in BCP out format. If you choose TEXT,
output lines are written as text characters, one row per line, with values separated by the column delimiter
string. If you choose BCP, data including BLOBs are exported as BCP input files for use with Adaptive
Server Enterprise. The default format is TEXT.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 939


SQL statements

HEXADECIMAL clause By default, HEXADECIMAL is ON. Binary column values are written as
0xnnnnnn..., where 0x is a zero followed by an x, and each n is a hexadecimal digit. It is important to use
HEXADECIMAL ON when dealing with multibyte character sets.

The HEXADECIMAL clause can be used only with the FORMAT TEXT clause.

ESCAPE CHARACTER clause Use this clause to specify the escape character used in the data. The
default escape character for characters written 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 '!'

It is recommended that the string you specify for the escape character is no longer than one multibyte
character.

ORDER clause With ORDER ON (the default), the exported data is ordered by clustered index if one
exists. If a clustered index does not exist, 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.

For UNLOAD select-statement, the ORDER clause is ignored. However, you can still order the data by
specifying an ORDER BY clause in the SELECT statement.

QUOTE clause The QUOTE clause is for TEXT data only; the string is placed around string values.
The default is a single quote (apostrophe).

QUOTES clause With QUOTES turned on (the default), the quote character, which defaults to a
single quote (apostrophe), is placed around all exported strings.

ROW DELIMITED BY clause Use this clause to specify the string that indicates the end of a record.
The default delimiter string is a newline (\n). However, it can be any string up to up to 255 bytes in
length; for example, ... ROW DELIMITED BY '###' .... If you want to specify tab-delimited
values, you could specify the hexadecimal escape sequence for the tab character (9), ... ROW
DELIMITED BY '\x09' .... If your delimiter string contains a \n, it matches either \r\n or \n.

Remarks
The UNLOAD select-statement statement allows data from a SELECT statement to be exported to a
comma-delimited file. The result set is not ordered unless the SELECT statement contains an ORDER BY
clause.

The UNLOAD TABLE statement allows efficient mass exporting from a database table or materialized
view into a file. The UNLOAD TABLE statement is more efficient than the Interactive SQL statement
OUTPUT, and can be called from any client application.

The database server, or the client application, depending upon whether INTO FILE or INTO CLIENT
FILE was specified, respectively, must have operating system permissions to write to the specified file.

940 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

When unloading table columns with binary data types, UNLOAD TABLE writes hexadecimal strings, of
the form \xnnnn, where n is a hexadecimal digit.

When unloading and reloading a database that has proxy tables, you must create an external login to map
the local user to the remote user, even if the user has the same password on both the local and remote
databases. If you do not have an external login, the reload may fail because you cannot connect to the
remote server.

When unloading into a variable (INTO VARIABLE), the output is converted to a character set as follows:

● CHAR write to the variable in CHAR encoding. The ENCODING clause must match the CHAR
encoding.

● NCHAR write to the variable in NCHAR encoding. The ENCODING clause must match the
NCHAR encoding.

● BINARY write to the variable in BINARY encoding. The ENCODING clause must match the
BINARY encoding; otherwise, the CHAR encoding is used.

If you choose to compress and encrypt the unloaded data, it is compressed first.

UNLOAD TABLE places an exclusive lock on the whole table or materialized view.

During the execution of this statement, you can request progress messages.

You can also use the Progress connection property to determine how much of the statement has been
executed.

To retain maximum precision of date values, set the date_format to YYYY-MM-DD.

To retain maximum precision of TIMESTAMP values, set the timestamp_format to YYYY-MM-DD


HH:NN:SS.SSSSSS.

To retain maximum precision of TIMESTAMP WITH TIMEZONE values, set the


timestamp_with_time_zone_format to YYYY-MM-DD HH:NN:SS.SSSSSS+HH:NN.

Permissions
When unloading into a variable, no permissions are required (other than the normal permissions required
to access the data source).

The permissions required to execute an UNLOAD statement depend on the database server -gl option, as
follows:

● If the -gl option is set to ALL, you must have SELECT permissions on the table or tables referenced in
the UNLOAD statement.

● If the -gl option is set to DBA, you must have DBA authority.

● If the -gl option is set to NONE, UNLOAD is not permitted.

When writing to a file on a client computer:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 941


SQL statements

● WRITECLIENTFILE authority is required.

● Write permissions are required for the directory being written to.

● The allow_write_client_file database option must be enabled.

● The write_client_file secured feature must be enabled.

Side effects
None. The query is executed at the current isolation level.

See also
● “CREATE DATABASE statement” on page 508
● “LOAD TABLE statement” on page 792
● “PASSTHROUGH statement [SQL Remote]” on page 831
● “Clustered indexes” [SQL Anywhere Server - SQL Usage]
● “Supported character sets” [SQL Anywhere Server - Database Administration]
● “OUTPUT statement [Interactive SQL]” on page 825
● “Export data with the UNLOAD statement” [SQL Anywhere Server - SQL Usage]
● “Access to data on client computers” [SQL Anywhere Server - SQL Usage]
● “Data import and export” [SQL Anywhere Server - SQL Usage]
● “Export data with the UNLOAD TABLE statement” [SQL Anywhere Server - SQL Usage]
● “-sf dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “allow_write_client_file option” [SQL Anywhere Server - Database Administration]
● “-gl dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “timestamp_format option” [SQL Anywhere Server - Database Administration]
● “date_format option” [SQL Anywhere Server - Database Administration]
● “on_charset_conversion_failure option” [SQL Anywhere Server - Database Administration]
● “Progress connection property” [SQL Anywhere Server - Database Administration]
● “progress_messages option” [SQL Anywhere Server - Database Administration]
● “WRITECLIENTFILE authority” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example unloads the contents of the Products table to a UTF-8-encoded file, productsT.dat:
UNLOAD TABLE Products TO 'productsT.dat' ENCODING 'UTF-8';

The following example creates a variable called @myProducts and then unloads the Products.Name
column into the variable:
CREATE VARIABLE @myProducts LONG VARCHAR;
UNLOAD SELECT NAME FROM Products INTO VARIABLE @myProducts;

942 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

UPDATE (positioned) statement [ESQL] [SP]


Modifies the data at the current location of a cursor.

Syntax 1 [ESQL only]


UPDATE WHERE CURRENT OF cursor-name
{ USING [ SQL ] DESCRIPTOR sqlda-name | { [ FROM ] | [ USING ] } hostvar-list }

Syntax 2
UPDATE update-table, ...
SET set-item, ...
WHERE CURRENT OF cursor-name

hostvar-list : indicator variables allowed

update-table :
[owner-name.]object-name [ [ AS ] correlation-name ]

set-item :
[ correlation-name.]column-name = { expression | DEFAULT }
| [owner-name.]object-name.column-name = { expression | DEFAULT }

object-name : identifier (a table or view name)

sqlda-name : identifier

Parameters
USING DESCRIPTOR clause When assigning a variable, the variable must already be declared, and
its name must begin with the "at" sign (@). Variable and column assignments can be mixed together, and
any number can be used. If a name on the left side of an assignment in the SET list matches a column in
the updated table and the variable name, the statement updates the column.

SET clause The columns that are referenced in set-item must be in the table or view that is updated.
They cannot refer to aliases, nor to columns from other tables or views. If the table or view you are
updating is given a correlation name in the cursor specification, you must use the correlation name in the
SET clause.

Each set-item is associated with a single update-table, and the corresponding column of the matching
table in the cursor's query is modified. The expression references columns of the tables identified in the
UPDATE list and may use constants, host variables, variables, expressions from the SELECT list of the
query, or combinations of the above using operators such as +, -, ..., COALESCE, IF, and so on. The
expression can not reference aliases of expressions from the cursor's query, nor can they reference
columns of other tables of the cursor's query which do not appear in the UPDATE list. Subselects,
subquery predicates, and aggregate functions can not be used in the set-items.

Each update-table is matched to a table in the query for the cursor as follows:

○ If a correlation name is specified, it is matched to a table in the cursor's query that has the same table-
or-view-name and the same correlation-name.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 943


SQL statements

○ Otherwise, if there is a table in the cursor's query that has the same table-or-view-name that does not
have a correlation name specified, or has a correlation name that is the same as the table-or-view-name,
then the update table is matched with this table in the cursor's query.

○ Otherwise, if there is a single table in the cursor's query that has the same table-or-view-name as the
update table, then the update table is matched with this table in the cursor's query.

If a column has a default defined, you can use the SET clause to set a column to its default value. For an
example of this, see the Examples section of “UPDATE statement” on page 948.

Remarks
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.

Also, when assigning a variable, the variable must already be declared, and its name must begin with the
"at" sign (@). Variable and column assignments can be mixed together, and any number can be used. If a
name on the left side of an assignment in the SET list matches a column in the updated table and the
variable name, the statement updates the column.

The USING DESCRIPTOR, FROM hostvar-list, and hostvar formats are for embedded SQL only.

Permissions
Must have UPDATE permission on the columns being modified.

Side effects
None.

See also
● “INSERT statement” on page 780
● “LOAD TABLE statement” on page 792
● “MERGE statement” on page 811
● “DELETE statement” on page 678
● “DELETE statement (positioned) [ESQL] [SP]” on page 676
● “UPDATE statement” on page 948

Standards and compatibility


● SQL/2008 Syntax 1 is a vendor extension. Syntax 2 is a core feature of the SQL/2008 standard. If
used within an embedded SQL program, Syntax 2 comprises part of optional SQL language feature

944 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

B031, "Basic dynamic SQL". The ability to specify more than one table to be updated is a vendor
extension.

The range of cursors that can be updated is dependent upon the setting of the ansi_update_constraints
option. The ability to perform a positioned update over a cursor that is ordered—that is the SQL query
has an ORDER BY clause—comprises optional SQL/2008 language feature F831, "Full cursor
update". Performing a positioned update over more complex SQL constructions may involve
additional vendor extensions.

Example
The following is an example of an UPDATE statement WHERE CURRENT OF cursor:
UPDATE Employees
SET Surname = 'Jones'
WHERE CURRENT OF emp_cursor;

UPDATE statement [SQL Remote]


Modifies data in the database.

Syntax 1
UPDATE table-list
SET column-name = expression, ...
[ VERIFY ( column-name, ... ) VALUES ( expression, ... ) ]
[ WHERE search-condition ]
[ ORDER BY expression [ ASC | DESC ], ... ]

Syntax 2
UPDATE table-name
PUBLICATION publication-name
{ SUBSCRIBE BY subscription-expression |
OLD SUBSCRIBE BY old-subscription-expression
NEW SUBSCRIBE BY new-subscription-expression }
WHERE search-condition

expression : value | subquery

Parameters
table-name The table-name indicates the table that must be modified on the remote databases.

publication-name The publication-name indicates the publication for which subscriptions must be
changed.

subscription-expression The value of subscription-expression is used by SQL Remote to determine


both new and existing recipients of the rows. The subscription-expression is either a value or a subquery.
Alternatively, you can provide both OLD and NEW subscription expressions.

WHERE clause The WHERE clause specifies which rows are to be transferred between subscribed
databases.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 945


SQL statements

Remarks
The UPDATE statement is used to modify rows of one or more tables. Each named column is set to the
value of the expression on the right side of the equal sign. There are no restrictions on the expression.
Even column-name can be used in the expression—the old value is used.

If no WHERE clause is specified, every row is updated. If a WHERE clause is specified, then only those
rows which satisfy the search condition are updated.

Normally, the order that rows are updated does not matter. However, in conjunction with the
NUMBER(*) function, an ordering can be useful to get increasing numbers added to the rows in some
specified order. Also, if you want to do something like add 1 to the primary key values of a table, it is
necessary to do this in descending order by primary key, so that you do not get duplicate primary keys
during the operation.

Views can be updated provided the SELECT statement defining the view does not contain a GROUP BY
clause, an aggregate function, or involve a UNION clause.

Character strings inserted into tables are always stored in the case they are entered, regardless of whether
the database is case sensitive or not. So, a character data type column updated with a string Value is
always held in the database with an uppercase V and the remainder of the letters lowercase. 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.

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 immediately
following the UPDATE keyword.

If a FROM clause is used, it is important to qualify the table name that is being updated 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 in the other. Otherwise, an error is generated.

Syntax 1 and Syntax 2 are applicable only to SQL Remote.

Syntax 2 with no OLD and NEW SUBSCRIBE BY expressions must be used in a BEFORE trigger.

Syntax 2 with OLD and NEW SUBSCRIBE BY expressions can be used anywhere.

Syntax 1 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 if the VERIFY clause fails to match. When the VERIFY clause is
specified, only one table can be updated at a time.

Syntax 2 is intended for use with SQL Remote only. If no OLD and NEW expressions are used, it must be
used inside a BEFORE trigger so that it has access to the relevant values. The purpose is to provide 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.

946 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

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 affected by
the UPDATE statement.

Syntax 2 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, this
extra work can be avoided.

The OLD and NEW SUBSCRIBE BY syntax is especially useful when many tables are being updated in
the same trigger with the same subscribe by expressions. This can dramatically increase performance.

The SUBSCRIBE BY expression is either a value or a subquery.

Syntax 2 of the UPDATE statement is used to implement a specific SQL Remote feature, and is to be
used inside a BEFORE trigger.

For publications created using a subquery in a subscription expression, you must write a trigger
containing syntax 2 of the UPDATE statement to ensure that the rows are kept in their proper
subscriptions.

Syntax 2 of the UPDATE statement makes an entry in the transaction log, but does not change the
database table.

Permissions
Must have UPDATE permission for the columns being modified.

Side effects
None.

See also
● “BEFORE UPDATE triggers” [SQL Remote]

Standards and compatibility


● SQL/2008 Vendor extension.

Example
The following example transfers employee Philip Chin (employee 129) from the sales department to the
marketing department.

UPDATE Employees
VERIFY( DepartmentID ) VALUES( 300 )
SET DepartmentID = 400
WHERE EmployeeID = 129;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 947


SQL statements

UPDATE statement
Modifies existing rows in database tables.

Syntax 1
UPDATE [ row-limitation ] table-expression [, ...]
SET set-item[, ...]
[ WHERE search-condition ]
[ ORDER BY expression [ ASC | DESC ] , ...]
[ OPTION( query-hint, ... ) ]

table-expression : A table expression that can include joins, outer joins, views and derived tables.
See “FROM clause” on page 738.

Syntax 2
UPDATE [ row-limitation ] table-name
SET set-item[, ...]
FROM table-expression [, ...] ]
[ WHERE search-condition ]
[ ORDER BY expression [ ASC | DESC ] , ...]
[ OPTION( query-hint, ... ) ]

table-name :
[ owner.]table-name [ [ AS ] correlation-name ]
| [ owner.]view-name [ [ AS ] correlation-name ]
| derived-table

derived-table :
( select-statement )
[ AS ] correlation-name [ ( column-name [, ...] ) ]

Syntax 3
UPDATE table-name
SET set-item, ...
VERIFY ( column-name, ... ) VALUES ( expression, ... )
[ WHERE search-condition ]
[ ORDER BY expression [ ASC | DESC ], ...]
[ OPTION( query-hint, ... ) ]

Syntax 4
UPDATE [ owner.]table-name
PUBLICATION publication
{ SUBSCRIBE BY expression
| OLD SUBSCRIBE BY expression NEW SUBSCRIBE BY expression
}
WHERE search-condition

row-limitation :
FIRST
| TOP { ALL | limit-expression } [ START AT startat-expression ]

limit-expression : simple-expression
startat-expression : simple-expression

948 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

simple-expression :
integer
| variable
| ( simple-expression )
| ( simple-expression { + | - | * } simple-expression )

set-item :
[ correlation-name.]column-name = { expression | DEFAULT }
| [owner-name.]table-name.column-name = { expression | DEFAULT }
| @variable-name = expression

query-hint :
MATERIALIZED VIEW OPTIMIZATION option-value
| FORCE OPTIMIZATION
| FORCE NO OPTIMIZATION
| option-name = option-value

table-name :
[ owner.]base-table-name
| temporary-table-name
| derived-table-name
| [ owner.]view-name

option-name : identifier

option-value :
hostvar (indicator allowed)
| string
| identifier
| number

Parameters
UPDATE clause For Syntax 1 and Syntax 2, table-expression can include temporary tables, global
temporary tables, derived tables, or views. Views and derived tables can be updated unless they are non-
updatable. For Syntax 1, a list of more than one table-expression results in a Cartesian product of the rows
formed by the underlying table expressions, which can then be restricted via the use of the WHERE
clause. Both Syntax 1 and Syntax 2 permit the updating of joins. For Syntax 3 and Syntax 4, table-name
must be a base table.

UPDATES can be performed on views only if the query specification defining the view is updatable.

row-limitation clause The row limitation clause allows you to restrict the rows being updated to only
a subset of the rows that satisfy the WHERE clause. The TOP and START AT arguments can be simple
arithmetic expressions over host variables, integer constants, or integer variables. The TOP argument
must evaluate to a value greater than or equal to 0. The START AT argument must evaluate to a value
greater than 0. An ORDER BY clause should be used to order the rows in a meaningful manner.

SET clause The set clause specifies the columns and how the values are changed.

You can use the SET clause to set the column to a computed column value using this format:

SET column-name = expression, ...

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 949


SQL statements

Each named column is set to the value of the expression on the right side of the equal sign. There are no
restrictions on the expression. If the expression is a column-name, the old value from that column is used.

If a column has a default defined, you can use the SET clause to set a column to its default value. See the
Examples section for an example of this usage.

You can also use the SET clause to assign a variable using the following format:
SET @variable-name = expression, ...

When assigning a value to a variable, the variable must already be declared, and its name must begin with
the at sign (@). If the variable name matches the name of a column in the table to be updated, the
UPDATE statement updates the column value and leaves the variable unchanged. Variable and column
assignments can be mixed together in any order.

FROM clause The FROM table-expression clause allows tables to be updated based on joins. table-
expression can contain arbitrary complex table expressions, such as OUTER, CROSS, and NATURAL
joins.

If the FROM clause is present, table-name must specify the sole table to be updated, and it must qualify
the name in the same way as it appears in the FROM clause. If correlation names are used in the FROM
clause, the identical correlation name must be specified as table-name. If the table expression to be
updated is a derived table, the derived table must be repeated in the table-name specification.

Syntax 2 cannot be used if the ansi_update_constraints option is set to Strict.

If a FROM clause is specified, the SET clause may specify only columns from table-name to be updated.
Otherwise, an error is generated.

The following statement illustrates a potential ambiguity in table names in UPDATE statements using
Syntax 2 that contain table expressions which use correlation names:
UPDATE table_1
SET column_1 = ...
FROM table_1 AS alias_1, table_1 AS alias_2
WHERE ...

Here, each instance of table_1 in the FROM clause has a correlation name, denoting a self-join of table_1
to itself. However, the UPDATE statement fails to specify which of the rows that make up the self-join
are to be updated. This can be corrected by specifying the correlation name in the UPDATE statement as
follows:
UPDATE table_1 as alias_1
SET column_1 = ...
FROM table_1 AS alias_1, table_1 AS alias_2
WHERE ...

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.

950 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

You cannot use ordinal column numbers in the ORDER BY clause.

In order to use the ORDER BY clause, the ansi_update_constraints option must not be set to Strict.

In order to update columns that appear in the ORDER BY clause, the ansi_update_constraints option must
be set to Off.

OPTION clause Use this clause to specify hints for executing the statement. The following hints are
supported:

○ MATERIALIZED VIEW OPTIMIZATION option-value


○ FORCE OPTIMIZATION
○ FORCE NO OPTIMIZATION
○ option-name = option-value. Note that a OPTION( isolation_level = ... ) specification
in the query text overrides all other means of specifying isolation level for a query.

Remarks
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 the string Street is
always held in the database with an uppercase S and the remainder of the letters lowercase. SELECT
statements return the string as Street. If the database is not case sensitive, however, all comparisons make
Street the same as street, STREET, and so on. Further, if a single-column primary key already contains an
entry Street, an UPDATE of another row's primary key to street is rejected, as it would make the primary
key not unique.

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 the new value differs from the old
value. AFTER UPDATE triggers fire only if the new value is different from the old value.

Syntax 3 and 4 are applicable only to SQL Remote.

Syntax 3 is intended for use with SQL Remote only, in single-row updates of a single table 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 4 of the UPDATE statement is used to implement a specific SQL Remote feature, and is to be
used inside a BEFORE trigger. 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 affected by
the UPDATE statement.

For publications created using a subquery in a SUBSCRIBE BY clause, you must write a trigger
containing syntax 4 of the UPDATE statement to ensure that the rows are kept in their proper
subscriptions.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 951


SQL statements

Syntax 4 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 4 of the UPDATE statement makes an entry in the transaction log, but does not change the
database table.

Updating a significant amount of data using the UPDATE statement also updates column statistics.

Permissions
Must have UPDATE permission for the columns being modified.

Side effects
Column statistics are updated to reflect the modified values.

If a table has a primary key, a UNIQUE constraint, or a UNIQUE index, the processing of the UPDATE
statement may involve the use of a temporary table if the table manipulations cannot be performed
without violating the uniqueness constraint. The temporary table stores rows modified by the UPDATE
statement that violate one or more uniqueness constraints. These rows are temporarily deleted from the
base table during the execution of the UPDATE statement, and are subsequently re-inserted. This
behavior may have implications for AFTER triggers and other concurrent connections.

952 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “DELETE statement” on page 678
● “DELETE statement (positioned) [ESQL] [SP]” on page 676
● “INSERT statement” on page 780
● “UPDATE statement [SQL Remote]” on page 945
● “CREATE TRIGGER statement” on page 651
● “CREATE TABLE statement” on page 633
● “PUT statement [ESQL]” on page 837
● “OPTION clause, SELECT statement” on page 877
● “MERGE statement” on page 811
● “ALTER TABLE statement” on page 451
● “UPDATE (positioned) statement [ESQL] [SP]” on page 943
● “UPDATE statements with a VERIFY clause” [SQL Remote]
● “TSEQUAL function [System] (deprecated)” on page 368
● “FROM clause” on page 738
● “Views” [SQL Anywhere Server - SQL Usage]
● “Joins: Retrieving data from several tables” [SQL Anywhere Server - SQL Usage]
● “Locks during updates” [SQL Anywhere Server - SQL Usage]
● “UPDATE statement replication” [SQL Remote]
● “Row limitation clauses in SELECT, UPDATE, and DELETE query blocks” [SQL Anywhere Server -
SQL Usage]
● “Data changes using UPDATE” [SQL Anywhere Server - SQL Usage]
● “ansi_update_constraints option” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Syntax 1 of the UPDATE statement is a core feature of the SQL/2008 standard. Syntax
2 is a vendor extension. Syntax 3 and 4 are vendor extensions for use only with SQL Remote.

Syntax 1 includes support for two optional SQL language features:

○ Support for updating a join, possibly including one or more derived tables, comprises part of
optional SQL language feature T111, "Updatable joins, unions, and columns".

○ Support for modifying a table referenced in a nested subquery that forms part of the search
condition for the UPDATE statement comprises optional SQL/2008 language feature F781, "Self-
referencing operations".

The following features of Syntax 1 are vendor extensions:

○ The FROM and ORDER BY clauses.

○ The row-limitation clause.

○ The ability to specify more than one table-expression.

○ The ability to update a variable using the SET clause.

○ The OPTION clause.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 953


SQL statements

With Syntax 1, the setting of the ansi_update_constraints option controls which forms of table
expressions can be modified. To enforce SQL/2008 core feature compatibility, ensure that the
ansi_update_constraints option is set to Strict.

Examples
Using the sample database, this example transfers employee Philip Chin (employee 129) from the sales
department to the marketing department.
UPDATE Employees
SET DepartmentID = 400
WHERE EmployeeID = 129;

Using the sample database, this example renumbers all existing sales orders by subtracting 2000 from the
ID.
UPDATE SalesOrders AS orders
SET orders.ID = orders.ID - 2000
ORDER BY orders.ID ASC;

This update is possible only if the foreign key of the SalesOrderItems table (referencing the primary key
SalesOrders.ID) is defined with the action ON UPDATE CASCADE. The SalesOrderItems table is then
updated as well. Because the statement specifies an ORDER BY clause, and the ordering attribute is also
specified in the SET clause, the ansi_update_constraints option must be set to Off or an error is returned.

Using the sample database, this third example changes the price of a product at isolation level 2, rather
than using the current isolation level setting of the database.
UPDATE Products
SET UnitPrice = 7.00
WHERE ID = 501
OPTION( isolation_level = 2 );

Again using the sample database, this fourth example uses Syntax 2 to reset the quantity-on-hand of those
Tee Shirts where there exists at least one order whose quantity exceeds the current quantity-on-hand:
UPDATE Products AS a
SET Quantity = 0
FROM Products a JOIN SalesOrderItems b ON a.ID = b.ProductID
WHERE a.Name = 'Tee Shirt' AND b.Quantity > a.Quantity;

In this fifth example, Syntax 1 is used to both reset the quantity-on-hand for those Tee Shirts, and reset
the ShipDate for the Tee Shirt order to today's date:
UPDATE Products a JOIN SalesOrderItems b on a.ID = b.ProductID
SET a.Quantity = 0, b.ShipDate = CAST( NOW() AS DATE)
WHERE a.Name = 'Tee Shirt' AND b.Quantity > a.Quantity

Examples four and five require the ansi_update_constraints option to be set to a value other than Strict.

This sixth example shows how to update a table to set a column to its default value. In this example, you
create a table, MyTable, populate it with data, and then execute an UPDATE statement specifying the
SET clause to change the column values to their defaults.
CREATE TABLE MyTable(
PK INT PRIMARY KEY DEFAULT AUTOINCREMENT,

954 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

TableName CHAR(128) NOT NULL,


TableNameLen INT DEFAULT 20,
LastUser CHAR(10) DEFAULT last user,
LastTime TIMESTAMP DEFAULT TIMESTAMP,
LastTimestamp TIMESTAMP DEFAULT @@dbts );

INSERT INTO MyTable WITH AUTO NAME


SELECT
LENGTH(t.table_name) AS TableNameLen,
t.table_name AS TableName
FROM SYS.SYSTAB t
WHERE table_id<=10;

UPDATE MyTable SET LastTime = DEFAULT, LastTimestamp = DEFAULT


WHERE TableName LIKE '%sys%';

VALIDATE statement
Validates the current database, or a single table, materialized view, or index in the current database.

Syntax 1 - Validating a database


VALIDATE { CHECKSUM | DATABASE }

Syntax 2 - Validating tables and materialized views


VALIDATE {
TABLE [ owner.]table-name
| MATERIALIZED VIEW [ owner.]materialized-view-name }
[ WITH EXPRESS CHECK ]

Syntax 3 - Validating indexes


VALIDATE {
INDEX index-name
| [ INDEX ] FOREIGN KEY role-name
| [ INDEX ] PRIMARY KEY }
ON [ owner.]object-name
}

object-name :
table-name
| materialized-view-name

Syntax 4 - Validating text indexes


VALIDATE TEXT INDEX index-name
ON [ owner.]table-name

Remarks
Use the VALIDATE CHECKSUM statement to validate the checksum on each page of a database. The
VALIDATE CHECKSUM statement ensures that database pages have not been modified on disk. When a
database is created with checksums enabled, a checksum is calculated for each database page before it is
written to disk. VALIDATE CHECKSUM reads each database page directly from disk—not via the
database server's cache—and calculates the checksum for each page. If the calculated checksum for a

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 955


SQL statements

page does not match the stored checksum for that page, an error occurs and information about the invalid
page appears in the database server messages window. The VALIDATE CHECKSUM statement is not
recommended for databases that have checksums disabled because it reads the entire database from disk.

Use the VALIDATE DATABASE statement to ensure that the free map correctly identifies pages as
either allocated or free and that no BLOBs have been orphaned. VALIDATE DATABASE also performs
checksum validation and verifies that each database page belongs to the correct object. For example, on a
table page, the table ID must identify a valid table whose definition must include the current page in its set
of table pages. The VALIDATE DATABASE statement brings pages into the database server's cache in
sequential order. This results in their validation, as the database server always verifies the contents and
checksums of pages brought into the cache. If you start database validation while the database cleaner is
running, the validation does not run until the database cleaner is finished running.

The VALIDATE TABLE statement validates the specified table and all of its indexes by checking that the
set of all rows and values in the base table matches the set of rows and values contained in each index.
VALIDATE TABLE also traverses all the table's BLOBs, verifies BLOB allocation maps, and detects
orphaned BLOBs. The VALIDATE TABLE statement checks the physical structure of the table's index
pages and verifies the order of the index hash values, and the index's uniqueness requirements (if any are
specified). For foreign key indexes, unless the WITH EXPRESS CHECK clause is specified, each value
is looked up in the primary key table to verify that referential integrity is intact. Because the VALIDATE
TABLE statement, like VALIDATE DATABASE, uses the database server's cache, the database server
also verifies the checksums and basic validity of all pages in use by a table and its indexes.

The VALIDATE INDEX statement performs the same operations as the VALIDATE TABLE statement
except that it only validates the specified index and its underlying table; other indexes are not checked.
For foreign key indexes, unless the WITH EXPRESS CHECK clause is specified, each value is looked up
in the primary key table to verify that referential integrity is intact. Specifying the WITH EXPRESS
CHECK clause disables referential integrity checking and can therefore significantly improve
performance. If the specified index is not a foreign key index, WITH EXPRESS CHECK has no effect.

Use the VALIDATE TEXT INDEX statement to verify that the positional information for the terms in the
index is intact. If the positional information is not intact, an error is generated and you must rebuild the
text index. If the text index is either auto or manual, you can rebuild the text index by executing the
REFRESH TEXT INDEX statement.

If the generated error concerns an immediate text index, you must drop the immediate index and create a
new one.

Caution
Validating a table or an entire database should be performed while no connections are making changes to
the database; otherwise, errors may be reported indicating some form of database corruption even though
no corruption actually exists.

Permissions
DBA or VALIDATE authority

Side effects
None.

956 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

See also
● “REFRESH TEXT INDEX statement” on page 846
● “DROP TEXT INDEX statement” on page 713
● “CREATE TEXT INDEX statement” on page 649
● “Validation utility (dbvalid)” [SQL Anywhere Server - Database Administration]
● “sa_validate system procedure” on page 1157
● “sa_clean_database system procedure” on page 1012
● “Database validation” [SQL Anywhere Server - Database Administration]
● “CREATE DATABASE statement” on page 508
● “CREATE INDEX statement” on page 553

Standards and compatibility


● SQL/2008 Vendor extension.

WAITFOR statement
Delays processing for the current connection for a specified amount of time or until a given time.

Syntax
WAITFOR {
DELAY time
| TIME time }
[ CHECK EVERY integer ]
[ AFTER MESSAGE BREAK ]

time : string

Parameters
DELAY clause If DELAY is used, processing is suspended for the given interval.

TIME clause If TIME is specified, processing is suspended until the database server time reaches the
time specified. If the current server time is greater than the time specified, processing is suspended until
that time on the following day.

CHECK EVERY clause This optional clause controls how often the WAITFOR statement wakes up.
By default, it wakes up every 5 seconds. The value is in milliseconds, and the minimum value is 250
milliseconds.

AFTER MESSAGE BREAK clause The WAITFOR statement can be used to wait for a message from
another connection. When a message is received it is usually forwarded to the application that executed
the WAITFOR statement and the WAITFOR statement continues to wait. If the AFTER MESSAGE
BREAK clause is specified, when a message is received from another connection, the WAITFOR
statement completes. The message text is not forwarded to the application, but it can be accessed by
obtaining the value of the MessageReceived connection property.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 957


SQL statements

Remarks
The WAITFOR statement wakes up periodically (every 5 seconds by default) to check if it has been
canceled or if messages have been received. If neither of these has happened, the statement continues to
wait.

Because scheduled events execute on their own connection, scheduled events are often a better choice
than using WAITFOR TIME.

Permissions
None

Side effects
The implementation of the WAITFOR statement causes the worker servicing the statement to block while
it is waiting. This reduces the number of available workers in the worker pool.

See also
● “SQL Anywhere threading” [SQL Anywhere Server - Database Administration]
● “CREATE EVENT statement” on page 526
● “MESSAGE statement” on page 818
● “MessageReceived connection property” [SQL Anywhere Server - Database Administration]

Standards and compatibility


● SQL/2008 Vendor extension.

Examples
The following example waits for three seconds:
WAITFOR DELAY '00:00:03';

The following example waits for 0.5 seconds (500 milliseconds):


WAITFOR DELAY '00:00:00:500';

The following example waits until 8 PM:


WAITFOR TIME '20:00';

In the following example, connection 1's WAITFOR statement completes when it receives the message
from connection 2:
// connection 1:
BEGIN
DECLARE msg LONG VARCHAR;
LOOP // forever
WAITFOR DELAY '00:05:00' AFTER MESSAGE BREAK;
SET msg = CONNECTION_PROPERTY('MessageReceived');
IF msg != '' THEN
MESSAGE 'Msg: ' || msg TO CONSOLE;
END IF;
END LOOP
END;

958 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

// connection 2:
MESSAGE 'here it is' FOR connection 1

WHENEVER statement [ESQL]


Specifies error handling in embedded SQL programs.

Syntax
WHENEVER {
SQLERROR
| SQLWARNING
| NOTFOUND }
GOTO
label
| STOP
| CONTINUE
| { C-code; }

label : identifier

Remarks
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.

Note
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. In fact, all the WHENEVER statement does is cause
the preprocessor to generate an if ( SQLCODE ) test after each statement.

Permissions
None.

Side effects
None.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 959


SQL statements

Standards and compatibility


● SQL/2008 An exception condition declaration made with the WHENEVER statement is a core
feature of the SQL/2008 standard. The standard uses the keyword SQLEXCEPTION rather than
SQLERROR. The ability to directly include C code in the WHENEVER statement, rather than merely
a statement label, is a vendor extension. The action STOP is also a vendor extension.

Example
The following are examples of the WHENEVER statement:

EXEC SQL WHENEVER NOTFOUND GOTO done;


EXEC SQL WHENEVER SQLERROR
{
PrintError( &sqlca );
return( FALSE );
};

WHILE statement [T-SQL]


Provides repeated execution of a statement or compound statement.

Syntax
WHILE search-condition statement

Remarks
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.

Permissions
None.

Side effects
None.

See also
● “LOOP statement” on page 810
● “CONTINUE statement” on page 507

Standards and compatibility


● SQL/2008 Transact-SQL extension. The WHILE statement is part of optional SQL/2008 language
feature P002, "Computational completeness". The Transact-SQL variant of the WHILE statement
does not include END WHILE.

960 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

Example
The following code illustrates the use of WHILE:
WHILE ( SELECT AVG(UnitPrice) FROM Products ) < $30
BEGIN
UPDATE Products
SET UnitPrice = UnitPrice + 2
IF ( SELECT MAX(UnitPrice) FROM Products ) > $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.

WINDOW clause
Defines all or part of a window for use with window functions such as AVG and RANK in a SELECT
statement.

Syntax
WINDOW window-expression, ...

window-expression : new-window-name AS ( window-spec )

window-spec :
[ existing-window-name ]
[ PARTITION BY expression, ... ]
[ ORDER BY expression [ ASC | DESC ], ... ]
[ { ROWS | RANGE } { window-frame-start | window-frame-between } ]

window-frame-start :
{ UNBOUNDED PRECEDING
| unsigned-integer PRECEDING
| CURRENT ROW }

window-frame-between :
BETWEEN window-frame-bound1 AND window-frame-bound2

window-frame-bound :
window-frame-start
| UNBOUNDED FOLLOWING
| unsigned-integer FOLLOWING

Parameters
PARTITION BY clause The PARTITION BY clause organizes the result set into logical groups based
on the unique values of the specified expression. When this clause is used with window functions, the
functions are applied to each partition independently. For example, if you follow PARTITION BY with a
column name, the result set is partitioned by distinct values in the column.

If this clause is omitted, the entire result set is considered a partition.

The PARTITION BY expression cannot be an integer literal.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 961


SQL statements

ORDER BY clause The ORDER BY clause defines how to sort the rows in each partition of the result
set. You can further control the order by specifying ASC for ascending order (the default) or DESC for
descending order.

The ORDER BY expression cannot be an integer literal.

If this clause is omitted, SQL Anywhere returns rows in whatever order is most efficient, and the
appearance of result sets may vary depending on when you last accessed the row.

ROWS clause and RANGE clause Use either a ROWS or RANGE clause to express the size of the
window. The window size can be one, many, or all rows of a partition. You can express the size of the
window as a range of data values offset from the value in the current row (RANGE), or the number of
physical rows offset from the current row (ROWS).

When using the RANGE clause, you must also specify an ORDER BY clause because range calculations
require values to be sorted. The ORDER BY clause for ranges must contain one expression, and that
expression must result in either a date or a numeric value.

If you do not specify a ROWS or RANGE clause, the database server uses default window sizes based on
whether an ORDER BY clause is present.

○ PRECEDING clause Use the PRECEDING clause to define the first row of the window using the
current row as a reference point. The starting row is expressed as the number of rows preceding the
current row. For example, 5 PRECEDING sets the window to start with the fifth row preceding the
current row.

Use UNBOUNDED PRECEDING to set the first row in the window to be the first row in the
partition.

○ BETWEEN clause Use the BETWEEN clause to define the first and last row of the window, using
the current row as a reference point. First and last rows are expressed as the number of rows preceding
and following the current row, respectively. For example, BETWEEN 3 PRECEDING AND 5
FOLLOWING sets the window to start with the third row preceding the current row, and end with the
fifth row following the current row.

Use BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to set the first
and last rows in the window to be the first and last row in the partition, respectively. This is equivalent
to the default behavior if no ROW or RANGE clause is specified.

○ FOLLOWING clause Use the FOLLOWING clause to define the last row of the window using the
current row as a reference point. The last row is expressed as the number of rows following the
current row.

Use UNBOUNDED FOLLOWING to set the last row in the window to be the last row in the
partition.

Remarks
The WINDOW clause must appear before the ORDER BY clause in a SELECT statement.

With the exception of the LIST function, all aggregate functions can be used as window functions.
However, ranking aggregate functions (RANK, DENSE_RANK, PERCENT_RANK, CUME_DIST, and

962 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL statements

ROW_NUMBER) require an ORDER BY clause, and do not allow a ROW or RANGE clause in the
WINDOW clause or inline definition. For all other window functions, you can use any of the clauses.

See also
● “SELECT statement” on page 871
● “OLAP support” [SQL Anywhere Server - SQL Usage]
● “Window definitions” [SQL Anywhere Server - SQL Usage]
● “Window definition: Inlining using the OVER clause and WINDOW clause” [SQL Anywhere Server -
SQL Usage]

Standards and compatibility


● SQL/2008 The WINDOW clause and window aggregate functions comprise SQL/2008 optional
language features T611, "Elementary OLAP operations", and T612, "Advanced OLAP operations".
The window functions FIRST_VALUE and LAST_VALUE are vendor extensions.

Example
The following example returns an employee's salary and the average salary for all employees in the
selected state. The results are ordered by state and then by surname.
SELECT EmployeeID, Surname, Salary, State,
AVG( Salary ) OVER Salary_Window
FROM Employees
WINDOW Salary_Window AS ( PARTITION BY State )
ORDER BY State, Surname;

WRITETEXT statement [T-SQL]


Permits non-logged updating of a CHAR, NCHAR, or BINARY column. This feature is provided solely
for compatibility with Transact-SQL and its use is not recommended.

Syntax
WRITETEXT table-name.column-name
text-pointer [ WITH LOG ] data

Remarks
Updates an existing column value. The update is not recorded in the transaction log, unless the WITH
LOG option is supplied. You cannot perform WRITETEXT operations on views.

Permissions
None.

Side effects
WRITETEXT does not fire triggers, and by default WRITETEXT operations are not recorded in the
transaction log.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 963


SQL statements

See also
● “READTEXT statement [T-SQL]” on page 842
● “TEXTPTR function [Text and image]” on page 360

Standards and compatibility


● SQL/2008 Transact-SQL extension.

Example
The following embedded SQL 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
Description column on the specified row with a new value.
EXEC SQL create variable txtptr binary(16);
EXEC SQL set txtptr =
( SELECT textptr(Description)
FROM MarketingInformation
WHERE ProductID = '500' );
EXEC SQL writetext MarketingInformation.Description
txtptr 'newdata';

964 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Tables

System tables
The structure of every database is described in several system tables. System tables are owned by the user
SYS. The contents of these tables can be changed only by the database server. The UPDATE, DELETE,
and INSERT statements 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 statements.

Data in system tables are exposed via their corresponding system views. Each system table name start
with capital i (I). Each corresponding system view has the same name but without the i at the beginning.

See also
● “System views” on page 1195

DUMMY system table


Column name Column type Column constraint Table 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;

SELECT USER, today(*);

dummy_col This column is not used. It is present because a table cannot be created with no columns.

The cost of reading from the SYS.DUMMY table is less than the cost of reading from a similar user-
created table because there is no latch placed on the table page of SYS.DUMMY.

Access plans are not constructed with scans of the SYS.DUMMY table. Instead, references to
SYS.DUMMY are replaced with a Row Constructor algorithm, which virtualizes the table reference. This
eliminates contention associated with the use of SYS.DUMMY. Note that DUMMY still appears as the
table and/or correlation name in short, long, and graphical plans.

ISYSARTICLE system table


Each row in the ISYSARTICLE system table describes an article in a publication.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 965


Tables

See also
● “SYSARTICLE system view” on page 1196

ISYSARTICLECOL system table


Each row in the ISYSARTICLECOL system table identifies a column in an article.

See also
● “SYSARTICLECOL system view” on page 1196

ISYSATTRIBUTE system table


This table is for internal use only.

ISYSATTRIBUTENAME system table


This table is for internal use only.

ISYSCAPABILITY system table


Each row in the ISYSCAPABILITY system table identifies a capability of a remote server.

See also
● “SYSCAPABILITY system view” on page 1197

ISYSCHECK system table


Each row in the ISYSCHECK system table identifies a named check constraint in a table.

See also
● “SYSCHECK system view” on page 1198

ISYSCOLPERM system table


Each row in the ISYSCOLPERM system table describes an UPDATE, SELECT, or REFERENCES
permission on a column.

966 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System tables

See also
● “SYSCOLPERM system view” on page 1198

ISYSCOLSTAT system table


The ISYSCOLSTAT system table contains the column statistics used by the optimizer.

Note
For databases created using SQL Anywhere 12 or later, this table is always encrypted to protect the data
from unauthorized access.

See also
● “SYSCOLSTAT system view” on page 1199

ISYSCONSTRAINT system table


Each row in the ISYSCONSTRAINT system table describes a named constraint for all tables except the
system tables.

See also
● “SYSCONSTRAINT system view” on page 1200

ISYSDEPENDENCY system table


Each row in the ISYSDEPENDENCY system table describes a table or view dependency.

See also
● “SYSDEPENDENCY system view” on page 1203

ISYSDBFILE system table


Each row in the ISYSDBFILE system table describes a dbspace.

See also
● “SYSDBFILE system view” on page 1201

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 967


Tables

ISYSDBSPACE system table


Each row in the ISYSDBSPACE system table describes a dbspace.

See also
● “SYSDBSPACE system view” on page 1202

ISYSDBSPACEPERM system table


Each row in the ISYSDBSPACEPERM system table describes permission on a dbspace.

See also
● “SYSDBSPACEPERM system view” on page 1202

ISYSDOMAIN system table


Each of the predefined data types (also called domains) is assigned a unique number. The ISYSDOMAIN
table is provided for informational purposes, to show the association between these numbers and the
appropriate data types. This table is never changed.

See also
● “SYSDOMAIN system view” on page 1203

ISYSEVENT system table


Each row in the ISYSEVENT system table describes an event created with CREATE EVENT.

See also
● “SYSEVENT system view” on page 1204

ISYSEXTERNLOGIN system table


Each row in the ISYSEXTERNLOGIN system table describes an external login for remote data access.

Note
For databases created using SQL Anywhere 12 or later, this table is always encrypted to protect the data
from unauthorized access.

968 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System tables

See also
● “SYSEXTERNLOGIN system view” on page 1207

ISYSFKEY system table


Each row in the ISYSFKEY system table describes a foreign key in the database

See also
● “SYSFKEY system view” on page 1208

ISYSGROUP system table


Each row in the ISYSGROUP system table defines a member of a group. This table describes the many-
to-many relationship between groups and members.

See also
● “SYSGROUP system view” on page 1209

ISYSHISTORY system table


Each row in the ISYSHISTORY system table indicates a time in which the database was started with a
different version of the software and/or on a different platform.

See also
● “SYSHISTORY system view” on page 1209

ISYSIDX system table


Each row in the ISYSIDX system table describes an index in the database.

See also
● “SYSIDX system view” on page 1211

ISYSIDXCOL system table


Each row in the ISYSIDXCOL system table describes a column in an index.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 969


Tables

See also
● “SYSIDXCOL system view” on page 1213

ISYSJAR system table


Each row in the ISYSJAR system table defines a JAR file in the system.

See also
● “SYSJAR system view” on page 1214

ISYSJARCOMPONENT system table


Each row in the ISYSJAR system table defines a JAR file component.

See also
● “SYSJARCOMPONENT system view” on page 1214

ISYSJAVACLASS system table


Each row in the ISYSJAVACLASS system table describes a Java class.

See also
● “SYSJAVACLASS system view” on page 1215

ISYSLOGINMAP system table


The ISYSLOGINMAP system table contains all the User Profile names that can be used to connect to the
database using either an integrated login or a Kerberos login. As a security measure, only users with DBA
authority can view the contents of this table.

See also
● “SYSLOGINMAP system view” on page 1216

ISYSLOGINPOLICY system table


Each row in the ISYSLOGINPOLICY system table describes a login policy.

970 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System tables

See also
● “SYSLOGINPOLICY system view” on page 1216

ISYSLOGINPOLICYOPTION system table


Each row in the ISYSLOGINPOLICYOPTION system table describes an option for a login policy.

See also
● “SYSLOGINPOLICYOPTION system view” on page 1217

ISYSMIRROROPTION system table


Each row in the ISYSMIRROROPTION system table describes an option for a mirror server.

See also
● “SYSMIRROROPTION system view” on page 1217

ISYSMIRRORSERVER system table


Each row in the ISYSMIRRORSERVER system table describes an option for a mirror server.

See also
● “SYSMIRRORSERVER system view” on page 1217

ISYSMIRRORSERVEROPTION system table


Each row in the SYSMIRRORSERVEROPTION system table describes an option for a mirror server.

See also
● “SYSMIRRORSERVEROPTION system view” on page 1218

ISYSMVOPTION system table


Each row in the ISYSMVOPTION system table gives the value of a creation option for a materialized
view or text index in the database.

See also
● “SYSMVOPTION system view” on page 1219

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 971


Tables

ISYSMVOPTIONNAME system table


Each row in the ISYSMVOPTIONNAME system table provides the name of a creation option listed in
ISYSMVOPTION for a materialized view or text index.

See also
● “SYSMVOPTIONNAME system view” on page 1219

ISYSOBJECT system table


Each row in the ISYSOBJECT system view describes an object in the database. Examples of database
objects include tables, views, columns, indexes, and procedures.

See also
● “SYSOBJECT system view” on page 1220

ISYSOPTION system table


Each row in the ISYSOPTION system table describes the settings for an option for one user ID. Options
settings are stored in the ISYSOPTION table by the SET statement, and each user can have their own
setting for each option.

See also
● “SYSOPTION system view” on page 1221

ISYSOPTSTAT system table


The ISYSOPTSTAT system table stores the cost model calibration information as computed by the
ALTER DATABASE CALIBRATE statement.

See also
● “SYSOPTSTAT system view” on page 1221

ISYSPHYSIDX system table


Each row in the ISYSPHYSIDX system table describes a physical index in the database.

See also
● “SYSPHYSIDX system view” on page 1222

972 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System tables

ISYSPROCEDURE system table


Each row in the ISYSPROCEDURE system table describes a procedure in the database.

See also
● “SYSPROCEDURE system view” on page 1223

ISYSPROCPARM system table


Each row in the ISYSPROCPARM system table describes a parameter to a procedure in the database.

See also
● “SYSPROCPARM system view” on page 1224

ISYSPROCPERM system table


Each row in the ISYSPROCPERM system table describes a user granted permission to call one
procedure.

See also
● “SYSPROCPERM system view” on page 1225

ISYSPROXYTAB system table


Each row in the ISYSPROXYTAB system table describes a proxy table.

See also
● “SYSPROXYTAB system view” on page 1226

ISYSPUBLICATION system table


Each row in the ISYSPUBLICATION system table describes a SQL Remote or MobiLink publication.

See also
● “SYSPUBLICATION system view” on page 1226

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 973


Tables

ISYSREMARK system table


Each row in the ISYSREMARK system table describes a remark (or comment) for an object.

See also
● “SYSREMARK system view” on page 1227

ISYSREMOTEOPTION system table


Each row in the ISYSREMOTEOPTION system table describes the values of a SQL Remote message
link parameter.

See also
● “SYSREMOTEOPTION system view” on page 1228

ISYSREMOTEOPTIONTYPE system table


Each row in the ISYSREMOTEOPTIONTYPE system table describes one of the SQL Remote message
link parameters.

See also
● “SYSREMOTEOPTIONTYPE system view” on page 1228

ISYSREMOTETYPE system table


The ISYSREMOTETYPE system table contains information about SQL Remote.

See also
● “SYSREMOTETYPE system view” on page 1229

ISYSREMOTEUSER system table


Each row in the ISYSREMOTEUSER system table describes a user ID with REMOTE permissions (a
subscriber), together with the status of SQL Remote messages that were sent to and from that user.

See also
● “SYSREMOTEUSER system view” on page 1229
● “REMOTE RESET statement [SQL Remote]” on page 850

974 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System tables

ISYSSCHEDULE system table


Each row in the ISYSSCHEDULE system table describes a time at which an event is to fire, as specified
by the SCHEDULE clause of CREATE EVENT.

See also
● “SYSSCHEDULE system view” on page 1231

ISYSSEQUENCE system table


The ISYSSEQUENCE system table contains one row for each user-defined sequence.

See also
● “SYSSEQUENCE system view” on page 1232

ISYSSEQUENCEPERM system table


The ISYSSEQUENCEPERM system table records the privileges that users or groups hold on sequences.

See also
● “SYSSEQUENCEPERM system view” on page 1233

ISYSSERVER system table


Each row in the ISYSSERVER system table describes a remote server.

See also
● “SYSSERVER system view” on page 1233

ISYSSOURCE system table


Each row in the ISYSSOURCE system view contains the source for an object listed in the ISYSOBJECT
system table.

See also
● “SYSSOURCE system view” on page 1234

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 975


Tables

ISYSSPATIALREFERENCESYSTEM system table


Each row in the ISYSSPATIALREFERENCESYSTEM system table describes a spatial reference system
defined in the database.

See also
● “SYSSPATIALREFERENCESYSTEM system view” on page 1234

ISYSSQLSERVERTYPE system table


The ISYSSQLSERVERTYPE system table contains information relating to compatibility with Adaptive
Server Enterprise.

See also
● “SYSSQLSERVERTYPE system view” on page 1237

ISYSSUBSCRIPTION system table


Each row in the ISYSSUBSCRIPTION system table describes a subscription from one user ID (which
must have REMOTE permissions) to one publication.

See also
● “SYSSUBSCRIPTION system view” on page 1238

ISYSSYNC system table


This table contains information relating to MobiLink synchronization. Some columns in this table contain
potentially sensitive data. For that reason, access to this table is restricted to users with DBA authority.
The SYSSYNC2 view provides public access to the data in this table except for the potentially sensitive
columns.

See also
● “SYSSYNC system view” on page 1238

ISYSSYNCPROFILE system table


This table contains information relating to synchronization profiles for MobiLink.

See also
● “SYSSYNCPROFILE system view” on page 1240

976 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System tables

ISYSSYNCSCRIPT system table


This table contains information relating to MobiLink synchronization scripts.

See also
● “SYSSYNCSCRIPT system view” on page 1240

ISYSTAB system table


Each row in the ISYSTAB system table describes one table in the database.

See also
● “SYSTAB system view” on page 1241

ISYSTABCOL system table


Each row in the ISYSTABCOL system table describes a column of a table in the database.

See also
● “SYSTABCOL system view” on page 1244

ISYSTEXTCONFIG system table


Each row in the ISYSTEXTCONFIG system table describes a text configuration, for use with the full text
search feature.

See also
● “SYSTEXTCONFIG system view” on page 1248

ISYSTEXTIDX system table


Each row in the ISYSTEXTIDX system table describes a text index, for use with the full text search
feature.

See also
● “SYSTEXTIDX system view” on page 1249

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 977


Tables

ISYSTEXTIDXTAB system table


Each row in the ISYSTEXTIDXTAB system table describes a text index, for use with the full text search
feature.

See also
● “SYSTEXTIDXTAB system view” on page 1250

ISYSTABLEPERM system table


Each row in the ISYSTABLEPERM system table corresponds to one table, one user ID granting the
permission (grantor) and one user ID granted the permission (grantee).

See also
● “SYSTABLEPERM system view” on page 1246

ISYSTRIGGER system table


Each row in the ISYSTRIGGER system table describes a trigger in the database.

See also
● “SYSTRIGGER system view” on page 1251

ISYSTYPEMAP system table


The ISYSTYPEMAP system table contains the compatibility mapping values for the
ISYSSQLSERVERTYPE system table.

See also
● “SYSTYPEMAP system view” on page 1253

ISYSUNITOFMEASURE system table


Each row in the ISYSUNITOFMEASURE system table describes a unit of measure defined in the
database.

See also
● “SYSUNITOFMEASURE system view” on page 1254

978 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System tables

ISYSUSER system table


Each row in the ISYSUSER system table describes a user in the system.

Note
As of SQL Anywhere 12, this table is always encrypted to protect the data from unauthorized access.

See also
● “SYSUSER system view” on page 1254

ISYSUSERAUTHORITY system table


Each row in the ISYSUSERAUTHORITY system table describes the authority granted to a user.

See also
● “SYSUSERAUTHORITY system view” on page 1255

ISYSUSERMESSAGE system table


Each row in the ISYSUSERMESSAGE system table holds a user-defined message for an error condition.

See also
● “SYSUSERMESSAGE system view” on page 1256

ISYSUSERTYPE system table


Each row in the ISYSUSERTYPE system table describes a user-defined data type. \\

See also
● “SYSUSERTYPE system view” on page 1256

ISYSVIEW system table


Each row in the ISYSVIEW system table describes a view in the database. \\

See also
● “SYSVIEW system view” on page 1257

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 979


Tables

ISYSWEBSERVICE system table


Each row in the ISYSWEBSERVICE system table describes a web service. \\

See also
● “SYSWEBSERVICE system view” on page 1259

Diagnostic tracing tables


Following are the main tables that are used for application profiling and diagnostic tracing. These tables
are owned by the dbo user. For many of these tables, there exists a global shared temporary table with a
similar name and schema. For example, the sa_diagnostic_blocking table has a global temporary table
counterpart, sa_tmp_diagnostic_blocking table, which has the same schema. During a tracing session,
diagnostic data is written to these temporary tables. Because temporary tables are not logged, they provide
superior performance during a tracing session, where it is important to minimize the impact on the server.

See also
● “Application profiling” [SQL Anywhere Server - SQL Usage]
● “Diagnostic tracing” [SQL Anywhere Server - SQL Usage]

sa_diagnostic_auxiliary_catalog table
The sa_diagnostic_auxiliary_catalog table is owned by the dbo user, and is used to map database objects
between the production database and tracing database. Objects include user tables, procedures, and
functions. This table is used primarily by the Index Consultant and the TRACED_PLAN function.

Columns
Column name Column type Description

original_ob- UNSIGNED BI- The object ID of this object in the main tracing database.
ject_id GINT

local_object_id UNSIGNED BI- The object ID of this object in the auxiliary tracing database.
GINT

pages_if_table UNSIGNED INT If the object is a table, this is the number of pages in the ta-
ble. If the object is not a table, this value is NULL.

rows_if_table UNSIGNED BI- If the object is a table, this is the number of rows in the table.
GINT If the object is not a table, this value is NULL.

980 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Diagnostic tracing tables

See also
● “TRACED_PLAN function [Miscellaneous]” on page 364
● “Index Consultant” [SQL Anywhere Server - SQL Usage]

sa_diagnostic_blocking table
The sa_diagnostic_blocking table is owned by the dbo user, and records blocking events. If logging of
blocking events is enabled, a row is inserted in this table each time a connection is blocked while trying to
access a resource. Typically, this is caused by either a table or a row lock. A large number of blocks may
indicate that you should examine the concurrency in your application to reduce contention for tables and
rows.

There are two versions of this table: sa_diagnostic_blocking, and sa_tmp_diagnostic_blocking.

Columns
Column name Column type Description

logging_ses- UNSIGNED A number uniquely identifying the logging session during which
sion_id INT the diagnostic information was gathered.

lock_id UNSIGNED BI- The ID of the lock that caused the blocking if a row or table lock
GINT caused the block, otherwise NULL.

request_id UNSIGNED BI- The ID of the request that was blocked if the block did not occur
GINT because of a cursor, otherwise NULL. This value corresponds to
the ID assigned to the request in sa_diagnostic_request.

cursor_id UNSIGNED BI- The ID of the cursor if the block occurred because of a cursor,
GINT otherwise NULL. This value corresponds to the ID assigned to
the cursor in sa_diagnostic_cursor.

original_ta- UNSIGNED BI- If the block occurred because of a table lock, the ID of the table
ble_object_id GINT on which the block occurred, otherwise NULL.

rowid UNSIGNED BI- If the block occurred because of a row lock, the ID of the row on
GINT which the block occurred, otherwise NULL.

block_time TIMESTAMP The time at which the block occurred.

unblock_time TIMESTAMP The time at which the block ended.

blocked_by UNSIGNED The ID of the connection that held the lock, causing the block.
INT

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 981


Tables

See also
● “Transaction blocking and deadlock” [SQL Anywhere Server - SQL Usage]
● “How locking works” [SQL Anywhere Server - SQL Usage]

sa_diagnostic_cachecontents table
The sa_diagnostic_cachecontents table is owned by the dbo user. When diagnostic tracing is enabled,
periodic snapshots of the cache contents are taken. The sa_diagnostic_cachecontents table records the
number of table pages for each table in the cache at the time the snapshot was taken, and the number of
rows in each table. The optimizer can use this information to recreate the conditions under which a query
was originally optimized, and then make optimization decisions.

Data in the sa_diagnostic_cachecontents table is updated every 20 seconds, as long as there is query
activity.

There are two versions of this table: sa_diagnostic_cachecontents, and sa_tmp_diagnostic_cachecontents.

Columns
Column name Column type Description

logging_session_id UNSIGNED INT A number uniquely identifying the logging session during
which the diagnostic information was gathered.

"time" TIMESTAMP The time at which the snapshot of the cache was taken.

original_table_ob- UNSIGNED BI- The object ID of each table represented in the snapshot.
ject_id GINT

pages_in_cache UNSIGNED INT For a specified table in the snapshot, the total number of pa-
ges in cache at the moment of the snapshot.

num_table_pages UNSIGNED INT For a specified table in the snapshot, the total number of pa-
ges for the table.

num_table_rows UNSIGNED BI- For a specified table in the snapshot, the total number of
GINT rows in the table.

sa_diagnostic_connection table
The sa_diagnostic_connection table is owned by the dbo user, and has one row for every database
connection that is active during the logging session. Connect and disconnect times, if they occur within
the logging session, can be derived from the sa_diagnostic_request table.

Most of the values in this table mirror values of connection properties.

982 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Diagnostic tracing tables

There are two versions of this table: sa_diagnostic_connection, and sa_tmp_diagnostic_connection.

Columns
Column name Column type Description

logging_session_id UNSIGNED INT A number uniquely identifying the


logging session during which the di-
agnostic information was gathered.

connection_number UNSIGNED INT A number assigned by the database


server to identify the connection of a
specific user to the database. This val-
ue reflects the value of the Number
connection property.

connection_name LONG VARCHAR Optional name property for the con-


nection. This value reflects the value
of the Name connection property.

user_name LONG VARCHAR The name of the user connected to the


database.

comm_link CHAR(40) Specifies the client-side network pro-


tocol options. This value reflects the
value of the CommLinks connection
property.

node_address LONG VARCHAR The node for the client in a client/


server connection. This value reflects
the value of the NodeAddress connec-
tion property.

appinfo LONG VARCHAR Information about the client process,


such as the IP address of the client
computer, the operating system it is
running on, and so on. This value re-
flects the value of the AppInfo con-
nection property.

See also
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]

sa_diagnostic_cursor table
The sa_diagnostic_cursor table is owned by the dbo user. Each row describes either an internal or external
cursor opened during the logging session.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 983


Tables

There are two versions of this table: sa_diagnostic_cursor, and sa_tmp_diagnostic_cursor.

Columns
Column name Column type Description

logging_session_id UNSIGNED INT A number uniquely identifying the logging session during
which the diagnostic information was gathered.

cursor_id UNSIGNED BI- A unique number identifying the cursor.


GINT

query_id UNSIGNED BI- Identifies the query over which this cursor ranges.
GINT

isolation_level TINYINT Isolation level at which this cursor was opened.

flags UNSIGNED INT Internal use.

forward_fetches UNSIGNED INT Number of forward fetches, including prefetches, done on


the cursor.

reverse_fetches UNSIGNED INT Number of reverse fetches, including prefetches, done on


the cursor.

absolute_fetches UNSIGNED INT Number of absolute fetches done on the cursor.

first_fetch_time_ms UNSIGNED INT Duration of time spent fetching the first row.

total_fetch_time_ms UNSIGNED INT Duration of time spent fetching. This value does not in-
clude application processing time between actual fetches
(think time).

plan_xml LONG VAR- Detailed plan for cursors that were dumped at the time the
CHAR cursor was closed. These plans contain detailed statistics
where appropriate.

See also
● “Cursor usage” [SQL Anywhere Server - Programming]

sa_diagnostic_deadlock table
The sa_diagnostic_deadlock table is owned by the dbo user. When diagnostic tracing is enabled and is set
to include tracing of deadlock events, a set of rows is inserted into this table every time a deadlock occurs
(one row for each connection that was part of the deadlock is inserted). The set of all rows that comprise a
single deadlock event is uniquely identified by a snapshot_id.

984 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Diagnostic tracing tables

Columns
Column name Column type Description

logging_ses- UNSIGNED INT A number uniquely identifying the logging session during
sion_id which the diagnostic information was gathered.

snapshot_id UNSIGNED BI- A number identifying which deadlock event this row is a
GINT part of. Note that this column has nothing to do with snap-
shot isolation.

snapshot_at TIMESTAMP The time at which the deadlock occurred.

waiter UNSIGNED INT The connection number of the connection that this row rep-
resents.

request_id UNSIGNED BI- The ID of the request that this connection was processing
GINT when the deadlock occurred.

original_ta- UNSIGNED BI- The object ID of the table on which this connection was
ble_object_id GINT blocked.

rowid UNSIGNED BI- The record ID of the row on which this connection was
GINT blocked.

owner UNSIGNED INT The connection number of the connection that locked the de-
sired row.

rollback_opera- UNSIGNED INT The number of uncommitted operations.


tion_count

See also
● “Transaction blocking and deadlock” [SQL Anywhere Server - SQL Usage]

sa_diagnostic_hostvariable table
The sa_diagnostic_hostvariable table is owned by the dbo user, and contains the values of host variables
used by the specified cursor.

There are two versions of this table: sa_diagnostic_hostvariable, and sa_tmp_diagnostic_hostvariable.

Columns
Column name Column type Description

logging_ses- UNSIGNED INT A number uniquely identifying the logging session during
sion_id which the diagnostic information was gathered.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 985


Tables

Column name Column type Description

request_id UNSIGNED BI- The ID of the request to which the host variables belong.
GINT

cursor_id UNSIGNED BI- The ID of the cursor to which the host variables pertain.
GINT

hostvar_num UNSIGNED The ordinal position of the host variable in the SQL state-
SMALLINT ment.

hostvar_type UNSIGNED TI- The domain number of the host variable, typically a string,
NYINT integer, or a float.

hostvar_value LONG NVARCHAR A string representing the value of the host variable. Even if
the host variable is an integer or a float, the value is still rep-
resented here as a string.

See also
● “Host variables in embedded SQL” [SQL Anywhere Server - Programming]

sa_diagnostic_internalvariable table
The sa_diagnostic_internalvariable table is owned by the dbo user, and contains the values of internal
(local) variables used by a given statement. This table is primarily used by the Index Consultant, and the
traced_plan function.

There are two versions of this table: sa_diagnostic_internalvariable, and


sa_tmp_diagnostic_internalvariable.

Columns
Column name Column type Description

logging_session_id UNSIGNED INT A number uniquely identifying the logging session dur-
ing which the diagnostic information was gathered.

request_id UNSIGNED BIGINT The ID of the request that contains the internal variable.

rowvariable_id UNSIGNED INT The column number in the row variable of this value.

variable_domain UNSIGNED SMALL- The data type of the internal variable.


INT

variable_name CHAR(128) The name of the internal variable.

986 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Diagnostic tracing tables

Column name Column type Description

variable_value LONG NVARCHAR A string representing the value of the internal variable.

See also
● “Local variables” on page 73

sa_diagnostic_query table
The sa_diagnostic_query table is owned by the dbo user, and stores optimization information for queries,
especially the context in which they were optimized. A row in this table represents an invocation of the
optimizer for a query. Plans captured at optimization time are stored here.

Some of the values in this table mirror database option values.

There are two versions of this table: sa_diagnostic_query, and sa_tmp_diagnostic_query.

Columns
Column name Column type Description

logging_session_id UNSIGNED The ID of the logging session during which the query or re-
INT quest occurred.

query_id UNSIGNED A number uniquely identifying the query.


BIGINT

statement_id UNSIGNED A number uniquely identifying a statement in a query.


BIGINT

user_object_id UNSIGNED The object ID of the user under which this query was execu-
BIGINT ted. If the query was run from a procedure, this would be the
user ID of the procedure owner.

start_time TIME- The time at which this query was optimized.


STAMP

cache_size_bytes UNSIGNED The size, in bytes, of the cache at the time this query was opti-
BIGINT mized.

optimization_goal TINYINT Determines whether query processing is optimized towards


returning the first row quickly, or minimizing the cost of re-
turning the complete result set. This value reflects the value of
the optimization_goal database option.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 987


Tables

Column name Column type Description

optimization_level TINYINT Controls the amount of effort made by the SQL Anywhere
query optimizer to find an access plan for a SQL statement.
This value reflects the value of the optimization_level data-
base option.

user_estimates TINYINT Controls whether user selectivity estimates in query predi-


cates are respected or ignored by the query optimizer. This
value reflects the value of the user_estimates database option.

optimization_work- TINYINT Determines whether query processing is optimized towards a


load workload that is a mix of updates and reads or a workload that
is predominantly read-based. This value reflects the value of
the optimization_workload database option.

available_requests TINYINT Used internally to compute the level of intra-query parallel-


ism.

active_requests TINYINT Used internally to compute the level of intra-query parallel-


ism.

max_tasks TINYINT Used internally to compute the level of intra-query parallel-


ism.

used_bypass TINYINT Whether a simple query bypass was used. A value of 1 indi-
cates a bypass was used; a value of 0 indicates that the query
was fully optimized.

estimated_cost_ms TINYINT The estimated cost, in milliseconds.

plan_explain LONG VAR- A text plan representation of this query.


CHAR

plan_xml LONG VAR- A graphical plan representation of the query (if one was recor-
CHAR ded).

sql_rewritten LONG VAR- Text of a query after applying optimizations. A value will on-
CHAR ly be present in this column if optimization logging is ena-
bled.

See also
● “Database options” [SQL Anywhere Server - Database Administration]
● “How the optimizer works” [SQL Anywhere Server - SQL Usage]
● “optimization_level option” [SQL Anywhere Server - Database Administration]
● “optimization_workload option” [SQL Anywhere Server - Database Administration]
● “user_estimates option” [SQL Anywhere Server - Database Administration]

988 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Diagnostic tracing tables

sa_diagnostic_request table
The sa_diagnostic_request table is owned by the dbo user, and is the master table for all requests. A
request is an event related to query processing and generally includes:

● connect or disconnect events

● statement executions

● statement preparations

● open or drop cursor events

There are two versions of this table: sa_diagnostic_request and sa_tmp_diagnostic_request.

Columns
Column name Column type Description

logging_ses- UNSIGNED INT The logging session during which the request occurred.
sion_id

request_id UNSIGNED BI- A number uniquely identifying the request.


GINT

start_time TIMESTAMP The time at which the event started.

finish_time TIMESTAMP For statement execution, the time when the statement comple-
ted; otherwise, NULL.

duration_ms UNSIGNED INT The duration of the event in milliseconds.

connec- UNSIGNED INT The ID of the connection that caused the event to happen.
tion_number

request_type UNSIGNED The type of request. Values include: New diagnostic tracing
SMALLINT session started, SQL Statement executed, Cursor opened, Cur-
sor closed, Client connect, Client disconnect, and Checkpoint.

statement_id UNSIGNED BI- If the event was statement-related, the ID assigned to the state-
GINT ment for tracing purposes.

query_id UNSIGNED BI- If the event was query-related, the ID assigned to the query for
GINT tracing purposes.

cursor_id UNSIGNED BI- If the event was cursor-related, the ID assigned to the cursor
GINT for tracing purposes.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 989


Tables

Column name Column type Description

sql_code SMALLINT Since rows in this table represent operations on statements,


cursors, or queries, most return a SQL code. This column con-
tains the SQL code returned. If a SQL code of 0 is returned, the
column contains NULL.

sa_diagnostic_statement table
The sa_diagnostic_statement table is owned by the dbo user, and stores the text of statements. A row in
this table represents a SQL statement that was executed by the server. Such statements may have been
issued by an external source, such as a client request, or by an internal source such as a procedure, trigger,
or user-defined function. Internal statements only appear here once per session.

There are two versions of this table: sa_diagnostic_statement, and sa_tmp_diagnostic_statement.

Columns
Column name Column type Description

logging_ses- UNSIGNED INT The logging session during which the statement was sub-
sion_id mitted.

statement_id UNSIGNED BI- A unique number assigned to the statement for tracing pur-
GINT poses.

database_object UNSIGNED BI- If the statement came from a procedure, trigger, or func-
GINT tion, this is the ID as specified in the ISYSOBJECT system
table.

line_number UNSIGNED If the statement formed part of a compound statement, this


SMALLINT reflects the ordinal position of the statement within the
compound statement.

signature UNSIGNED INT Used internally to group similar queries.

statement_text LONG VARCHAR The statement text.

sa_diagnostic_statistics table
The sa_diagnostic_statistics table is owned by the dbo user, and contains a history of performance
counters maintained in the server. Each row represents the value of a given performance counter at a
given moment in time.

There are two versions of this table: sa_diagnostic_statistics, and sa_tmp_diagnostic_statistics.

990 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Diagnostic tracing tables

Columns
Column name Column type Description

logging_session_id UNSIGNED INT A number uniquely identifying the


logging session during which the di-
agnostic information was gathered.

"time" TIMESTAMP The time at which the performance


counter value was captured.

counter_id UNSIGNED SMALLINT A number uniquely identifying the


performance counter. You can get the
name of the property that this coun-
ter_id represents using the PROPER-
TY_NAME function.

type TINYINT Indicates whether this is a database,


server, or connection statistic. Possi-
ble values are 0 for server, 1 for data-
base, 2 for connection, and 4 for ex-
ternal database.

connection_number UNSIGNED INT For a connection statistic, the connec-


tion number from which this property
was captured. For an extended data-
base statistic, the file number for the
file from which this property was
captured. Otherwise, the value is 0.

counter_value UNSIGNED INT The value of the performance coun-


ter.

See also
● “PROPERTY_NAME function [System]” on page 298

sa_diagnostic_tracing_level table
The sa_diagnostic_tracing_level table is owned by the dbo user, and each row in this table is a condition
that determines what kind of diagnostic information to send to the tracing database. If a piece of logging
data meets the conditions of one or more rows in this table, then the corresponding data is logged.

Data in this table is populated using the CONNECT TRACING or REFRESH TRACING LEVEL
statements.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 991


Tables

Columns
Column Column type Description
name

id UNSIGNED For internal use only.


INT

scope CHAR(32) The scope of the diagnostic tracing, as listed below.

● DATABASE
● ORIGIN
● USER
● CONNECTION_NAME
● CONNECTION_NUMBER
● FUNCTION
● PROCEDURE
● EVENT
● TRIGGER
● TABLE

identifier CHAR(128) The identifier for the scope. This value changes, depending on the
specified scope. For example:

● if scope is DATABASE, identifier may not be present.

● if scope is ORIGIN, identifier must be either Internal or External.

● if scope is USER, identifier is the ID of the user.

● if scope is CONNECTION_NAME, or CONNECTION_NUMBER,


identifier is the name or number, respectively, for the connection.

● if scope is FUNCTION, PROCEDURE, EVENT, TRIGGER, or TA-


BLE, identifier is the fully qualified identifier for the object.

trace_type CHAR(32) The type of data to trace for the specified scope, as listed below.

● VOLATILE_STATISTICS
● NONVOLATILE_STATISTICS
● CONNECTION_STATISTICS
● BLOCKING
● PLANS
● PLANS_WITH_STATISTICS
● STATEMENTS
● STATEMENTS_WITH_VARIABLES
● OPTIMIZATION_LOGGING
● OPTIMIZATION_LOGGING_WITH_PLANS

992 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Other tables

Column Column type Description


name

trace_con- CHAR(32) Applies only to plans, and controls whether to trace large, expensive
dition queries, or queries for which the optimizer did not make optimal
choices. Possible values are listed below.

● NONE, or NULL
● SAMPLE_EVERY
● ABSOLUTE_COST
● RELATIVE_COST_DIFFERENCE

value UNSIGNED The value associated with the condition. For example, if condition is
INT SAMPLE_EVERY, the condition_value would be a positive integer re-
flecting time in milliseconds. Additional rules are as follows:

● If condition is NULL or NONE, there is no condition_value.

● If condition is ABSOLUTE_COST, condition_value reflects the total


actual cost of executing the statement, in milliseconds.

● If condition is RELATIVE_COST_DIFFERENCE, condition_value


reflects the cost of executing, as a percentage of the estimated cost.

enabled BIT Whether the row is enabled. That is, whether the tracing settings in the
row are active. 1 is enabled; 0 is disabled.

See also
● “Diagnostic tracing conditions” [SQL Anywhere Server - SQL Usage]
● “Diagnostic tracing scopes” [SQL Anywhere Server - SQL Usage]
● “ATTACH TRACING statement” on page 475
● “REFRESH TRACING LEVEL statement” on page 848

Other tables
Following is information about other tables such as system tables used by Java in the database and SQL
Remote.

RowGenerator table (dbo)


The dbo.RowGenerator table is provided as a read-only table that has 255 rows. This table can be useful
for queries which produce small result sets and which need a range of numeric values.

The RowGenerator table is used by system procedures and views, and should not be modified in any way.

You can also use the sa_rowgenerator system procedure to generate a range of numeric values.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 993


Tables

Column name Column type

row_num SMALLINT

row_num A value between 1 and 255.

See also
● “sa_rowgenerator system procedure” on page 1113

Java system tables


The system tables that are used for Java are listed below. Foreign key relations between tables are
indicated by arrows: the arrow leads from the foreign table to the primary table.

MobiLink system tables


For information about the MobiLink system tables, see “MobiLink server system tables” [MobiLink -
Server Administration].

SQL Remote system tables


For information about the SQL Remote system tables, see “SQL Remote system tables” [SQL Remote].

UltraLite system tables


For information about the UltraLite system tables, see “UltraLite system tables” [UltraLite - Database
Management and Reference].

994 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System procedures
This section documents the system procedures included with SQL Anywhere. A few system procedures,
such as sa_get_table_definition, are implemented as functions. However, because they are used in the
same context and manner as system procedures, they are included with the system procedures, and their
naming is similar to the system procedures (sa_xxx).

SQL Anywhere includes the following kinds of system procedures:

● System procedures, for displaying system information in tabular form.

● SOAP and HTTP services system procedures, for supporting web services.

● MAPI and SMTP system procedures, for sending electronic mail.

● Transact-SQL system and catalog procedures.

See also
● “Adaptive Server Enterprise system and catalog procedures” on page 999

Viewing details about system procedures and


functions
Database administrators can access the definitions for system procedures and functions from Sybase
Central.

Prerequisites

DBA authority.

Context and remarks

Many.

View details about system procedures and functions

1. Use the SQL Anywhere 12 plug-in to connect to the database as a user with DBA authority.

2. Right-click the database and then click Configure Owner Filter.

3. Click DBO and then click OK.

Note
The openxml system procedure is the only procedure that is not owned by the dbo user. You cannot
view information about openxml from Sybase Central.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 995


System procedures

4. In the left pane, double-click Procedures & Functions.

5. In the left pane, select the procedure and in the right pane click the SQL tab.

Results

The procedure or function definition appears on the SQL tab.

Next

None.

Web services system procedures


The following system procedures are for use with web services:

● “sa_http_header_info system procedure”


● “sa_http_php_page system procedure”
● “sa_http_php_page_interpreted system procedure”
● “sa_http_variable_info system procedure”
● “sa_set_http_header system procedure”
● “sa_set_http_option system procedure”
● “sa_set_soap_header system procedure”

See also
● “Web services functions” on page 141
● “SQL Anywhere as an HTTP web server” [SQL Anywhere Server - Programming]
● “-xs dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]

MAPI and SMTP procedures


SQL Anywhere includes system procedures for sending electronic mail using the Microsoft Messaging
API standard (MAPI) or the Internet standard Simple Mail Transfer Protocol (SMTP). These system
procedures are implemented as extended system procedures: each procedure calls a function in an external
DLL.

These procedures are owned by the dbo user ID. Users must be granted EXECUTE permission before
they can use these procedures, unless they already have DBA authority.

To use the MAPI or SMTP system procedures, a MAPI or SMTP email system must be accessible from
the database server computer.

The MAPI and SMTP system procedures are:

● xp_startmail Starts a mail session in a specified mail account by logging onto the MAPI message
system.

996 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


MAPI and SMTP procedures

● xp_startsmtp Starts a mail session in a specified mail account by logging onto the SMTP message
system.

● xp_sendmail Sends a mail message to specified users.

● xp_stopmail Closes the MAPI mail session.

● xp_stopsmtp Closes the SMTP mail session.

Example
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;

See also
● “xp_startmail system procedure” on page 1188
● “xp_startsmtp system procedure” on page 1189
● “xp_sendmail system procedure” on page 1183
● “xp_stopmail system procedure” on page 1191
● “xp_stopsmtp system procedure” on page 1192

Return codes for MAPI and SMTP system procedures


The following codes may be returned by either the MAPI or the SMTP system procedures:

Return code Meaning

0 Success

2 xp_startmail or xp_startsmtp failed

3 xp_stopmail or xp_stopsmtp failed

5 xp_sendmail failed

12 Attachment not found

15 Insufficient memory

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 997


System procedures

Return code Meaning

20 Unknown recipient

25 Mail session failed to start

In addition, the following codes may be returned by the MAPI system procedures:

Return code Meaning

11 Ambiguous recipient

13 Disk full

14 Failure

16 Invalid session

17 Text too large

18 Too many files

19 Too many recipients

21 Login failure

22 Too many sessions

23 User abort

24 No MAPI

In addition, the following codes may be returned by the SMTP system procedures:

Return Meaning
code

100 Socket error.

101 Socket timeout.

102 Unable to resolve the SMTP server hostname.

103 Unable to connect to the SMTP server.

998 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Adaptive Server Enterprise system and catalog procedures

Return Meaning
code

104 Server error; response not understood. For example, the message is poorly formatted, or
the server is not SMTP.

This error is also returned if you specify the smtp_auth_username and smtp_auth_pass-
word to xp_startsmtp, and the server does not support the SMTP authentication capabil-
ity.

105 A TLS error occurred

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. 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.

SQL Anywhere has implemented support for some of these Adaptive Server Enterprise procedures.
However, for information about using these procedures, refer to your Adaptive Server Enterprise
documentation.

Adaptive Server Enterprise system procedures


The following list describes the Adaptive Server Enterprise system procedures that are provided in SQL
Anywhere.

While these procedures perform the same functions as they do in Adaptive Server Enterprise and
Adaptive Server IQ version 12 and earlier, 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, execute the following command.
sp_helptext 'dbo.procedure_name'

You may need to reset the width of your Interactive SQL output to see the full text, by clicking Tools »
Options » SQL Anywhere » Truncation Length, and entering a new value.

System procedure name Description

sp_addgroup Adds a group to a database

sp_addlogin Adds a new login ID to a database

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 999


System procedures

System procedure name Description

sp_addmessage Adds a user-defined message to ISYSUSERMESSAGE, for use by stored


procedure PRINT and RAISERROR calls

sp_addtype Creates a user-defined data type

sp_adduser Adds a new user ID to a database

sp_changegroup Changes a user group or adds a user to a group

sp_dropgroup Drops a group from a database

sp_droplogin Drops a login ID from a database

sp_dropmessage Drops a user-defined message

sp_droptype Drops a user-defined data type

sp_dropuser Drops a user ID from a database

sp_getmessage Retrieves a stored message string from ISYSUSERMESSAGE, for PRINT


and RAISERROR statements.

sp_helptext Displays the text of a system procedure, trigger, or view

sp_password Adds or changes a password for a user ID

Adaptive Server Enterprise catalog procedures


SQL Anywhere implements a subset of the Adaptive Server Enterprise catalog procedures. The
implemented catalog procedures are described in the following table.

Catalog procedure Description


name

sp_column_privileges Unsupported

sp_columns Returns the data types of the specified columns

sp_fkeys Returns foreign key information about the specified table

sp_pkeys Returns primary key information about the specified table

sp_special_columns Returns the optimal set of columns that uniquely identify a row in the speci-
fied table

1000 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Catalog procedure Description


name

sp_sproc_columns Returns information about the input and return parameters of a stored pro-
cedure

sp_statistics Returns information about tables and their indexes

sp_stored_procedures Returns information about one or more stored procedures

sp_tables Returns a list of objects that can appear in a FROM clause for the specified
table

Alphabetical list of system procedures


System procedures are owned by the user ID dbo, except the openxml system procedure. Some of these
procedures are for internal system use. This section documents only those not intended solely for system
and internal use. You cannot call external functions on Windows Mobile.

openxml system procedure


Generates a result set from an XML document.

Syntax 1
openxml( xml-data,
xpath [, flags [, namespaces ] ] )
WITH ( column-name column-type [ xpath ],... )

Syntax 2
openxml( { USING FILE | USING VALUE } xml-data,
xpath [, flags [, namespaces ] ] )
WITH ( column-name column-type [ xpath ],... )
[ OPTION ( scan-option ) ]
[ AS ] correlation-name

scan-option :
ENCODING encoding
| BYTE ORDER MARK { ON | OFF }

Arguments
● WITH clause Specifies the schema of the result set and how the value is found for each column in
the result set. WITH clause xpath arguments are matched relative to the matches for the xpath in the
second argument. If a WITH clause expression matches more than one node, then only the first node
in the document order is used. If the node is not a text node, then the result is found by appending all

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1001


System procedures

the text node descendants. If a WITH clause expression does not match any nodes, then the column
for that row is NULL.

The xpath arguments in the WITH clause can be literal strings or variables.

The openxml WITH clause syntax is similar to the syntax for selecting from a stored procedure.

● USING FILE | USING VALUE Use the USING FILE clause to load data from a file. DBA or
READFILE authority is required to use the USING FILE clause.

Use the USING VALUE clause to load data from any expression of CHAR, NCHAR, BINARY, or
LONG BINARY type, or BLOB string.

○ xml-data The XML on which the result set is based. This can be any string expression, such as
a constant, variable, or column.

The xml-data is parsed directly in the NCHAR encoding if there are any NCHAR columns in the
output. The xpath and namespaces arguments are also converted and parsed in the NCHAR
encoding.

○ xpath A string containing an XPath query. XPath allows you to specify patterns that describe
the structure of the XML document you are querying. The XPath pattern included in this argument
selects the nodes from the XML document. Each node that matches the XPath query in the second
xpath argument generates one row in the table.

Metaproperties can only be specified in WITH clause xpath arguments. A metaproperty is


accessed within an XPath query as if it was an attribute. If a namespaces is not specified, then by
default the prefix mp is bound to the Uniform Resource Identifier (URI) urn:ianywhere-com:sa-
xpath-metaprop. If a namespaces is specified, this URI must be bound to mp or some other prefix
to access metaproperties in the query. Metaproperty names are case sensitive. The openxml
statement supports the following metaproperties:

● @mp:id returns an ID for a node that is unique within the XML document. The ID for a
given node in a given document may change if the database server is restarted. The value of
this metaproperty increases with document order.

● @mp:localname returns the local part of the node name, or NULL if the node does not
have a name.

● @mp:prefix returns the prefix part of the node name, or NULL if the node does not have a
name or if the name is not prefixed.

● @mp:namespaceuri returns the URI of the namespace that the node belongs to, or NULL
if the node is not in a namespace.

● @mp:xmltext returns a subtree of the XML document in XML form. For example, when
you match an internal node, you can use this metaproperty to return an XML string, rather than
the concatenated values of the descendant text nodes.

○ flags Indicates the mapping that should be used between the XML data and the result set when
an XPath query is not specified in the WITH clause. If the flags parameter is not specified, the

1002 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

default behavior is to map attributes to columns in the result set. The flags parameter can have one
of the following values:

Value Description

1 XML attributes are mapped to columns in the result set (the default).

2 XML elements are mapped to columns in the result set.

○ namespace-declaration An XML document. The in-scope namespaces for the query are
taken from the root element of the document. If namespaces are specified, then you must include a
flags argument, even if all the xpath arguments are specified.

● column-name The name of the column in the result set.

● column-type The data type of the column in the result set. The data type must be compatible with
the values selected from the XML document.

● OPTION clause Use the OPTION clause to specify parsing options to use for the input file, such
as escape characters, delimiters, encoding, and so on.

○ ENCODING clause The ENCODING clause allows you to specify the encoding that is used to
read the file.

If the ENCODING clause is not specified, then encoding for values is assumed to be in the
database character set (db_charset) if the values are of type CHAR or BINARY, and NCHAR
database character set (nchar_charset) if the values are of type NCHAR.

○ BYTE ORDER MARK clause Use the BYTE ORDER MARK clause to specify whether a
byte order mark (BOM) is present in the encoding. By default, this option is ON, which enables
the server to search for and interpret a byte order mark (BOM) at the beginning of the data. If
BYTE ORDER MARK is OFF, the server does not search for a BOM.

You must specify the BYTE ORDER MARK clause if the input data is encoded.

If the ENCODING clause is specified:

● If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding with an endian
such as UTF-16BE or UTF-16LE, the database server searches for a BOM at the beginning of
the data. If a BOM is present, it is used to verify the endianness of the data. If you specify the
wrong endian, an error is returned.

● If the BYTE ORDER MARK option is ON and you specify a UTF-16 encoding without an
explicit endian, the database server searches for a BOM at the beginning of the data. If a BOM
is present, it is used to determine the endianness of the data. Otherwise, the operating system
endianness is assumed.

● If the BYTE ORDER MARK option is ON and you specify a UTF-8 encoding, the database
server searches for a BOM at the beginning of the data. If a BOM is present it is ignored.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1003


System procedures

If the ENCODING clause is not specified:

● If you do not specify an ENCODING clause and the BYTE ORDER MARK option is ON, the
server looks for a BOM at the beginning of the input data. If a BOM is located, the source
encoding is automatically selected based on the encoding of the BOM (UTF-16BE, UTF-16LE,
or UTF-8) and the BOM is not considered to be part of the data to be loaded.

● If you do not specify an ENCODING clause and the BYTE ORDER MARK option is OFF, or a
BOM is not found at the beginning of the input data, the database CHAR encoding is used.

Remarks
The openxml system procedure parses the xml-data and models the result as a tree. The tree contains a
separate node for each element, attribute, and text node, or other XML construct. The XPath queries
supplied to the openxml system procedure are used to select nodes from the tree, and the selected nodes
are then mapped to the result set.

The XML parser used by the openxml system procedure is non-validating, and does not read the external
DTD subset or external parameter entities.

When there are multiple matches for a column expression, the first match in the document order (the order
of the original XML document before it was parsed) is used. NULL is returned if there are no matching
nodes. When an internal node is selected, the result is all the descendant text nodes of the internal node
concatenated together.

Columns of type BINARY, LONG BINARY, IMAGE, and VARBINARY are assumed to be in base64-
encoded format and are decoded automatically. If you generate XML using the FOR XML clause, these
types are base64-encoded, and can be decoded using the openxml system procedure.

The openxml system procedure supports a subset of the XPath syntax, as follows:

● The child, self, attribute, descendant, descendant-or-self, and parent axes are fully supported.

● Both abbreviated and unabbreviated syntax can be used for all supported features. For example, 'a' is
equivalent to 'child::a' and '..' is equivalent to 'parent::node()'.

● Name tests can use wildcards. For example, 'a/*/b'.

● The following kind tests are supported: node(), text(), processing-instruction(), and comment().

● Qualifiers of the form expr1[expr2] and expr1[expr2="string" ] can be used, where expr2 is any
supported XPath expression. A qualifier evaluates TRUE if expr2 matches one or more nodes. For
example, 'a[b]' finds a nodes that have at least one b child, and a[b="I"] finds a nodes that have
at least one b child with a text value of I.

1004 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

See also
● “FOR XML and binary data” [SQL Anywhere Server - SQL Usage]
● “Using XPath expressions” [SQL Anywhere Server - SQL Usage]
● “SQL data types” on page 81
● “Importing XML using openxml” [SQL Anywhere Server - SQL Usage]
● “Supported character sets” [SQL Anywhere Server - Database Administration]
● “FROM clause” on page 738
● XPath query language: http://www.w3.org/TR/xpath.

Example
The following query generates a result set from the XML document supplied as the first argument to the
openxml system procedure:
SELECT * FROM openxml( '<products>
<ProductType ID="301">Tee Shirt</ProductType>
<ProductType ID="401">Baseball Cap</ProductType>
</products>',
'/products/ProductType' )
WITH ( ProductName LONG VARCHAR 'text()', ProductID CHAR(3) '@ID');

This query generates the following result:

ProductName ProductID

Tee Shirt 301

Baseball Cap 401

In the following example, the first <ProductType> element contains an entity. When you execute the
query, this node is parsed as an element with four children: Tee, &amp;, Sweater, and Set. You can use .
to concatenate the children together in the result set.
SELECT * FROM openxml( '<products>
<ProductType ID="301">Tee &amp; Sweater Set</ProductType>
<ProductType ID="401">Baseball Cap</ProductType>
</products>',
'/products/ProductType' )
WITH ( ProductName LONG VARCHAR '.', ProductID CHAR(3) '@ID');

This query generates the following result:

ProductName ProductID

Tee Shirt & Sweater Set 301

Baseball Cap 401

The following query uses an equality predicate to generate a result set from the supplied XML document.
SELECT * FROM openxml('<EmployeeDirectory>
<Employee>
<column name="EmployeeID">105</column>

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1005


System procedures

<column name="GivenName">Matthew</column>
<column name="Surname">Cobb</column>
<column name="Street">7 Pleasant Street</column>
<column name="City">Grimsby</column>
<column name="State">UT</column>
<column name="PostalCode">02154</column>
<column name="Phone">6175553840</column>
</Employee>
<Employee>
<column name="EmployeeID">148</column>
<column name="GivenName">Julie</column>
<column name="Surname">Jordan</column>
<column name="Street">1244 Great Plain Avenue</column>
<column name="City">Woodbridge</column>
<column name="State">AZ</column>
<column name="PostalCode">01890</column>
<column name="Phone">6175557835</column>
</Employee>
<Employee>
<column name="EmployeeID">160</column>
<column name="GivenName">Robert</column>
<column name="Surname">Breault</column>
<column name="Street">358 Cherry Street</column>
<column name="City">Milton</column>
<column name="State">PA</column>
<column name="PostalCode">02186</column>
<column name="Phone">6175553099</column>
</Employee>
<Employee>
<column name="EmployeeID">243</column>
<column name="GivenName">Natasha</column>
<column name="Surname">Shishov</column>
<column name="Street">151 Milk Street</column>
<column name="City">Grimsby</column>
<column name="State">UT</column>
<column name="PostalCode">02154</column>
<column name="Phone">6175552755</column>
</Employee>
</EmployeeDirectory>', '/EmployeeDirectory/Employee')
WITH ( EmployeeID INT 'column[@name="EmployeeID"]',
GivenName CHAR(20) 'column[@name="GivenName"]',
Surname CHAR(20) 'column[@name="Surname"]',
PhoneNumber CHAR(10) 'column[@name="Phone"]');

This query generates the following result set:

EmployeeID GivenName Surname PhoneNumber

105 Matthew Cobb 6175553840

148 Julie Jordan 6175557835

160 Robert Breault 6175553099

243 Natasha Shishov 6175552755

The following query uses the XPath @attribute expression to generate a result set:
SELECT * FROM openxml( '<Employee
EmployeeID="105"

1006 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

GivenName="Matthew"
Surname="Cobb"
Street="7 Pleasant Street"
City="Grimsby"
State="UT"
PostalCode="02154"
Phone="6175553840"
/>', '/Employee' )
WITH ( EmployeeID INT '@EmployeeID',
GivenName CHAR(20) '@GivenName',
Surname CHAR(20) '@Surname',
PhoneNumber CHAR(10) '@Phone');

The following query operates on an XML document like the one used in the above query, except that an
XML namespace has been introduced. It demonstrates the use of wildcards in the name test for the XPath
query, and generates the same result set as the above query.
SELECT * FROM openxml( '<Employee xmlns="http://www.iAnywhere.com/
EmployeeDemo"
EmployeeID="105"
GivenName="Matthew"
Surname="Cobb"
Street="7 Pleasant Street"
City="Grimsby"
State="UT"
PostalCode="02154"
Phone="6175553840"
/>', '/*:Employee' )

WITH ( EmployeeID INT '@EmployeeID',


GivenName CHAR(20) '@GivenName',
Surname CHAR(20) '@Surname',
PhoneNumber CHAR(10) '@Phone');

Alternatively, you could specify a namespace declaration:


SELECT * FROM openxml( '<Employee xmlns="http://www.iAnywhere.com/
EmployeeDemo"
EmployeeID="105"
GivenName="Matthew"
Surname="Cobb"
Street="7 Pleasant Street"
City="Grimsby"
State="UT"
PostalCode="02154"
Phone="6175553840"
/>', '/prefix:Employee', 1, '<r xmlns:prefix="http://www.iAnywhere.com/
EmployeeDemo"/>' )
WITH ( EmployeeID INT '@EmployeeID',
GivenName CHAR(20) '@GivenName',
Surname CHAR(20) '@Surname',
PhoneNumber CHAR(10) '@Phone');

sa_ansi_standard_packages system procedure


Returns information about the non-core SQL extensions used in a SQL statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1007


System procedures

Syntax
sa_ansi_standard_packages( standard, statement )

Arguments
● standard The standard to use for the core extensions. One of SQL:1999 or SQL:2003.

● statement The SQL statement to evaluate.

Remarks
If there are no non-core extensions used for the statement, the result set is empty.

Permissions
None

Side effects
None

See also
● “The SQL preprocessor” [SQL Anywhere Server - Programming]
● “SQLFLAGGER function [Miscellaneous]” on page 344
● “sql_flagger_error_level option” [SQL Anywhere Server - Database Administration]
● “sql_flagger_warning_level option” [SQL Anywhere Server - Database Administration]

Example
Following is an example call to the sa_ansi_standard_packages system procedure:
CALL sa_ansi_standard_packages( 'SQL:2003',
'SELECT *
FROM ( SELECT o.SalesRepresentative,
o.Region,
SUM( s.Quantity * p.UnitPrice ) AS total_sales,
DENSE_RANK() OVER ( PARTITION BY o.Region,
GROUPING( o.SalesRepresentative )
ORDER BY total_sales DESC ) AS
sales_rank
FROM Product p, SalesOrderItems s, SalesOrders o
WHERE p.ID = s.ProductID AND s.ID = o.ID
GROUP BY GROUPING SETS( ( o.SalesRepresentative, o.Region ),
o.Region ) ) AS DT
WHERE sales_rank <= 3
ORDER BY Region, sales_rank');

The query generates the following result set:

package_id package_name

T612 Advanced OLAP operations

T611 Elementary OLAP operations

1008 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

package_id package_name

F591 Derived tables

T431 Extended grouping capabilities

sa_audit_string system procedure


Adds a string to the transaction log.

Syntax
sa_audit_string( string )

Arguments
● string A string of characters to add to the transaction log.

Remarks
If auditing is turned on, this system procedure adds a comment to the auditing information stored in the
transaction log. The string can be a maximum of 200 bytes.

Permissions
DBA authority

Side effects
None

See also
● “auditing option” [SQL Anywhere Server - Database Administration]
● “Database activity audits” [SQL Anywhere Server - Database Administration]

Example
The following example uses sa_audit_string to add a comment to the transaction log:
CALL sa_audit_string( 'Auditing test' );

sa_char_terms system procedure


Breaks a CHAR string into terms and returns each term as a row along with its position.

Syntax
sa_char_terms( ' text' [, 'config-name' [, 'owner' ] ] )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1009


System procedures

Arguments
● text The CHAR string you are parsing.

● config-name The text configuration object to apply when processing the string. The default value
is 'default_char'.

● owner The owner of the specified text configuration object. The default value is NULL, and the
current user is assumed if the owner is not specified or if NULL is specified.

Remarks
You can use this system procedure to find out how a string is interpreted when the settings for a text
configuration object are applied. This can be helpful when you want to know what terms would be
dropped during indexing or from a query string.

Permissions
None

Side effects
None

See also
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Text configuration object concepts and reference” [SQL Anywhere Server - SQL Usage]
● “sa_nchar_terms system procedure” on page 1094

Example
The following statement returns the terms in the CHAR string, It's a work-at-home day!, using the default
CHAR text configuration object, default_char:
CALL sa_char_terms ('It''s a work-at-home day!', 'default_char', 'sys');

term position

It 1

s 2

a 3

work 4

at 5

home 6

day 7

1010 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

sa_check_commit system procedure


Checks for outstanding referential integrity violations before a commit.

Syntax
sa_check_commit(
tname,
keyname
)

Arguments
● tname A VARCHAR(128) parameter containing the name of a table with a row that is currently
violating referential integrity.

● keyname A VARCHAR(128) parameter containing the name of the corresponding foreign key
index.

Remarks
If the database option wait_for_commit is On, or if a foreign key is defined using CHECK ON COMMIT
in the CREATE TABLE statement, you can update the database and cause a referential integrity violation
if the 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.

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.

Permissions
None

Side effects
None

See also
● “wait_for_commit option” [SQL Anywhere Server - Database Administration]
● “CREATE TABLE statement” on page 633

Example
The following set of commands can be executed from Interactive SQL. Rows are deleted from the
Departments table in the sample database and a referential integrity violation occurs. The call to the
sa_check_commit system procedure checks which tables and keys have outstanding violations, and the
rollback cancels the change:
SET TEMPORARY OPTION wait_for_commit='On'
go
DELETE FROM Departments
go

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1011


System procedures

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_clean_database system procedure


Starts the database cleaner and sets the maximum length of time for which it can run.

Syntax
sa_clean_database( [ duration ] )

Arguments
● duration The number of seconds that the clean operation is allowed to run. If no argument is
specified, or if 0 is specified, the database cleaner runs until all pages in all dbspaces have been
cleaned.

Remarks
The database cleaner is an internal task that runs on a default schedule. You can use this system procedure
to force the database cleaner to run immediately and to specify how long the cleaner can run each time it
is invoked. If you use this system procedure to start the database cleaner while a database is being
validated, the database cleaner does not run until validation is complete.

Some database tasks, such as processing snapshot isolation transactions, index maintenance, and deleting
rows, can execute more efficiently if some portions of the request are deferred to a later time. These
deferrable activities typically involve cleanup by removing deleted, historical, and otherwise unnecessary
entries from database pages, or reorganizing database pages for more efficient access.

Postponing some of these activities not only allows the current request to finish more quickly, it
potentially allows cleanup to occur when the database server is less active. These unnecessary entries are
identified so that they are not visible to other transactions; however, they do take up space on a page, and
must be removed at some point.

The database cleaner performs any deferred cleanup activities. It is scheduled to run every 20 seconds.
When it is invoked, the database cycles sequentially through the database's dbspaces, examining and
cleaning each cleanable page before moving on to the next one. When invoked automatically by the
database server, the database cleaner is a self-tuning process. The amount of work that the database
cleaner performs, and the duration for which it executes, depend on several factors, including the fraction
of outstanding cleanable pages in a dbspace, the current amount of activity in the database server, and the
amount of time that the database cleaner has already spent cleaning. If, after running for 0.5 seconds, the
cleaner detects active requests in the server, it stops and reschedules itself to execute at its regular
interval. The database cleaner attempts to process pages when there are no other requests executing in the
server, and therefore takes advantage of periods of server inactivity.

1012 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Database cleaner statistics are available through four database properties:

● CleanablePagesAdded returns the number of pages that need to be cleaned

● CleanablePagesCleaned returns the number of pages that have already been cleaned

● CleanableRowsAdded returns the number of rows that need to be cleaned

● CleanableRowsCleaned returns the number of rows that have already been cleaned

The difference between the values of CleanablePagesAdded and CleanablePagesCleaned indicates how
many database pages still require cleaning.

You can use the sa_clean_database system procedure to configure the database cleaner to run until all the
pages in a database are cleaned, or to specify a maximum duration for the database cleaner to run.

To further customize the behavior of the database cleaner, you can set up an event that starts the database
cleaner if the number of pages or rows that need to be cleaned exceed a specified threshold.

Permissions
DBA authority

Side effects
None

See also
● “CREATE EVENT statement” on page 526
● “CleanablePagesAdded database property” [SQL Anywhere Server - Database Administration]
● “CleanablePagesCleaned database property” [SQL Anywhere Server - Database Administration]
● “CleanableRowsAdded database property” [SQL Anywhere Server - Database Administration]
● “CleanableRowsCleaned database property” [SQL Anywhere Server - Database Administration]

Example
The following example sets the duration of the database cleaner to 10 seconds:
CALL sa_clean_database( 10 );

The following example creates a scheduled event that runs daily to allow the database cleaner to run until
all pages in the database are cleaned:
CREATE EVENT DailyDatabaseCleanup
SCHEDULE
START TIME '6:00 pm'
ON ( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' )
HANDLER
BEGIN
CALL sa_clean_database( );
END;

The following example forces the database cleaner to run when 20% or more of the pages in the database
need to be cleaned:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1013


System procedures

CREATE EVENT PERIODIC_CLEANER


SCHEDULE
BETWEEN '9:00 am' and '5:00 pm'
EVERY 1 HOURS
HANDLER
BEGIN
DECLARE @num_db_pages INTEGER;
DECLARE @num_dirty_pages INTEGER;

-- Get the number of database pages


SELECT (SUM( DB_EXTENDED_PROPERTY( 'FileSize', t.dbspace_id ) -
DB_EXTENDED_PROPERTY( 'FreePages', t.dbspace_id ) ))
INTO @num_db_pages
FROM (SELECT dbspace_id FROM SYSDBSPACE) AS t;

-- Get the number of dirty pages to be cleaned


SELECT (DB_PROPERTY( 'CleanablePagesAdded' ) -
DB_PROPERTY( 'CleanablePagesCleaned' ))
INTO @num_dirty_pages;

-- Check whether the number of dirty pages exceeds 20% of


-- the size of the database
IF @num_dirty_pages > @num_db_pages * 0.20 THEN
-- Start cleaning the database for a maximum of 60 seconds
CALL sa_clean_database( 60 );
END IF;
END;

sa_column_stats system procedure


Returns various statistics about the specified column(s). These statistics are not related to the column
statistics maintained for use by the optimizer.

Syntax
sa_column_stats (
[ tab_name ]
[, col_name ]
[, tab_owner ]
[, max_rows ]
)

Arguments
● tab_name This optional CHAR(128) parameter specifies the name of the table. If this parameter is
not specified, statistics are calculated for all columns in all table(s).

● col_name This optional CHAR(128) parameter specifies the columns for which to calculate
statistics. If this parameter is not specified, statistics are calculated for all columns in the specified
table(s).

● tab_owner This optional CHAR(128) parameter specifies the owner of the table. If this parameter
is not specified, the database server uses the owner of the first table that matches the tab_name
specified.

1014 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● max_rows This optional INTEGER parameter specifies the number of rows to use for the
calculations. If this parameter is not specified, 1000 rows are used by default. Specifying 0 instructs
the database server to calculate the ratio based on all the rows in the table.

Result set
With the exception of table_owner, table_name, and column_name, all values in the result set are NULL
for non-string columns. Also, for empty tables, num_rows_processed and num_values_compressed are 0,
while all other values are NULL.

Column name Data type Description

table_owner CHAR(128) The owner of the table.

table_name CHAR(128) The table name.

column_name CHAR(128) The column name.

num_rows_processed INTEGER The total number of rows read to calculate the statistics.

num_values_com- INTEGER The number of values in the column that are compressed. If
pressed the column is not compressed, the value is 0.

avg_compression_ratio DOUBLE The average compression ratio, expressed as a percentage re-


duction in size, for compressed values in the column. If the
column is not compressed, the value is NULL.

avg_length DOUBLE The average length of all non-NULL strings in the column.

stddev_length DOUBLE The standard deviation of the lengths of all non-NULL


strings in the column.

min_length INTEGER The minimum length of non-NULL strings in the column.

max_length INTEGER The maximum length of strings in the column.

avg_uncom- DOUBLE The average length of all uncompressed, non-NULL strings


pressed_length in the column.

stddev_uncom- DOUBLE The standard deviation of the lengths of all uncompressed,


pressed_length non-NULL strings in the column.

min_uncom- INTEGER The minimum length of all uncompressed, non-NULL strings


pressed_length in the column.

max_uncom- INTEGER The maximum length of all uncompressed, non-NULL


pressed_length strings in the column.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1015


System procedures

Remarks
The database server determines the columns that match the owner, table, and column names specified, and
then for each one, calculates statistics for the data in each specified column. By default, the database
server only uses the first 1000 rows of data.

For avg_compression_ratio, values cannot be greater than, or equal to 100, however, they can be less than
0 if highly incompressible data (for example, data that is already compressed) is inserted into a
compressed column. Higher values indicate better compression. For example, if the number returned is
80, then the size of the compressed data is 80% less than the size of the uncompressed data.

Permissions
DBA authority

Side effects
None

See also
● “Column compression considerations” [SQL Anywhere Server - Database Administration]

Example
In this example, you use the sa_column_stats system procedure in a SELECT statement to determine
which columns in the database are benefitting most from column compression:
SELECT * FROM sa_column_stats()
WHERE num_values_compressed > 0
ORDER BY avg_compression_ratio desc;

In this example, you narrow your selection from the previous example to tables owned by bsmith:
SELECT * FROM sa_column_stats( tab_owner='bsmith' )
WHERE num_values_compressed > 0
ORDER BY avg_compression_ratio desc;

sa_conn_activity system procedure


Returns the most recently-prepared SQL statement for each connection to the specified database on the
server.

Syntax
sa_conn_activity( [ connidparm ] )

Arguments
● connidparm Use this optional INTEGER parameter to specify the connection ID number.

1016 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Result set
Column name Data type Description

Number INT Returns the ID number of the connection.

Name VARCHAR(255) Returns the name of the current connection.

Temporary connection names have INT: prepended to the con-


nection name

Userid VARCHAR(255) Returns the user ID for the connection.

DBNumber INT Returns the ID number of the database.

LastReqTime VARCHAR(255) Returns the time at which the last request for the specified con-
nection started. This property can return an empty string for in-
ternal connections, such as events.

LastStatement LONG VAR- Returns the most recently prepared SQL statement for the current
CHAR connection.

Remarks
The sa_conn_activity system procedure returns a result set consisting of the most recently-prepared SQL
statement for each connection, if the server has been told to collect the information. Recording of
statements must be enabled for the database server before calling sa_conn_activity. To do this, specify the
-zl option when starting the database server, or execute the following:
CALL sa_server_option('RememberLastStatement','ON');

This procedure is useful when the database server is busy and you want to obtain information about the
last SQL statement prepared for each connection. This feature can be used as an alternative to request
logging.

If connidparm is not specified, then information is returned for all connections to all databases running on
the database server. If connidparm is less than zero, option values for the current connection are returned.

Cloud note: Because of tenant database isolation rules, when this system procedure is run in the
cloud it returns only information about the current tenant database.

Permissions
None

Side effects
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1017


System procedures

See also
● “-zl dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “sa_server_option system procedure” on page 1120
● “Name connection property” [SQL Anywhere Server - Database Administration]
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]

sa_conn_compression_info system procedure


Summarizes communication compression rates.

Syntax
sa_conn_compression_info( [ connidparm ] )

Arguments
● connidparm Use this optional INTEGER parameter to specify the connection ID number.

Result set
Column name Data type Description

Type VAR- Returns a string identifying whether the compression statistics that
CHAR(20) follow represent either one connection (Connection), or all con-
nections to the server (Server).

ConnNumber INTEGER Returns an INTEGER representing a connection ID number. Re-


turns NULL if the Type is Server.

Compression VAR- Returns On or Off to indicate whether communication compres-


CHAR(10) sion is enabled on the connection.

Returns NULL if the Type is Server, or ON/OFF if the Type is


Connection.

TotalBytes INTEGER Returns an INTEGER representing the total number of actual


bytes both sent and received.

TotalBytesUn- INTEGER Returns an INTEGER representing the number of bytes that would
Comp have been sent and received if compression were disabled.

CompRate NUMER- Returns a NUMERIC (5,2) value representing the overall com-
IC(5,2) pression rate. For example, a value of 0 indicates that no compres-
sion occurred. A value of 75 indicates that the data was com-
pressed by 75%, or down to one quarter of its original size.

CompRateSent NUMER- Returns a NUMERIC (5,2) value representing the compression


IC(5,2) rate for data sent to the client.

1018 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Column name Data type Description

CompRateRe- NUMER- Returns a NUMERIC (5,2) value representing the compression


ceived IC(5,2) rate for data received from the client.

TotalPackets INTEGER Returns an INTEGER representing the total number of actual


packets both sent and received.

TotalPacket- INTEGER Returns an INTEGER representing the total number of packets


sUnComp that would have been sent and received if compression was disa-
bled.

CompPktRate NUMER- Returns a NUMERIC (5,2) value representing the overall com-
IC(5,2) pression rate of packets.

CompPktRate- NUMER- Returns a NUMERIC (5,2) value representing the compression


Sent IC(5,2) rate of packets sent to the client.

CompPktRa- NUMER- Returns a NUMERIC (5,2) value representing the compression


teReceived IC(5,2) rate of packets received from the client.

Remarks
If you specify the connection ID number, the sa_conn_compression_info system procedure returns a
result set consisting of compression properties for the supplied connection. If connidparm is not supplied,
this system procedure returns information for all current connections to databases on the server.

Cloud note: Because of tenant database isolation rules, when this system procedure is run in the
cloud it returns only information about the current tenant database.

Permissions
None

Side effects
None

See also
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]

Example
The following example uses the sa_conn_compression_info system procedure to return a result set
summarizing compression properties for all connections to the server.
CALL sa_conn_compression_info( );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1019


System procedures

Type ConnNumber Compression TotalBytes ...

Connection 79 Off 7841 ...

Server (NULL) (NULL) 2737761 ...

... ... ... ... ...

sa_conn_info system procedure


Reports connection property information.

Syntax
sa_conn_info( [ connidparm ] )

Arguments
● connidparm This optional INTEGER parameter specifies the connection ID number.

Result set
Column Data type Description
name

Number INTEGER Returns the ID number of the connection.

Name VAR- Returns the ID number of the connection.


CHAR(255)
Temporary connection names have INT: prepended to the connec-
tion name.

Userid VAR- Returns the user ID for the connection.


CHAR(255)

DBNumber INTEGER Returns the ID number of the database.

LastReq- VAR- Returns the time at which the last request for the specified connec-
Time CHAR(255) tion started. This property can return an empty string for internal
connections, such as events.

ReqType VAR- Returns the type of the last request. If a connection has been cached
CHAR(255) by connection pooling, its ReqType value is CON-
NECT_POOL_CACHE.

CommLink VAR- Returns the communication link for the connection. This is one of the
CHAR(255) network protocols supported by SQL Anywhere, or local for a same-
computer connection.

1020 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Column Data type Description


name

NodeAddr VAR- Returns the address of the client in a client/server connection.


CHAR(255)

ClientPort INTEGER Returns the client's TCP/IP port number or 0 if the connection isn't a
TCP/IP connection.

ServerPort INTEGER Returns the database server's TCP/IP port number or 0.

BlockedOn INTEGER Returns zero if the current connection isn't blocked, or if it is


blocked, the connection number on which the connection is blocked
because of a locking conflict.

LockRowID UNSIGNED Returns the identifier of the locked row.


BIGINT
LockRowID is NULL if the connection is not waiting on a lock asso-
ciated with a row (that is, it is not waiting on a lock, or it is waiting
on a lock that has no associated row).

LockIndex- INTEGER Returns the identifier of the locked index.


ID
LockIndexID is -1 if the lock is associated with all indexes on the ta-
ble in LockTable. LockIndexID is NULL if the connection is not
waiting on a lock associated with an index (that is, it is not waiting
on a lock, or it is waiting on a lock that has no associated index).

LockTable VAR- Returns the name of the table associated with a lock if the connection
CHAR(255) is currently waiting for a lock. Otherwise, LockTable returns an emp-
ty string.

Uncommi- INTEGER Returns the number of uncommitted operations.


tOps

ParentCon- INTEGER Returns the connection ID of the connection that created a temporary
nection connection to perform a database operation (such as performing a
backup or creating a database). For other types of connections, this
property returns NULL.

Remarks
If you specify the connection ID number, the sa_conn_info system procedure returns a result set
consisting of connection properties for the supplied connection. If no connidparm is supplied, this system
procedure returns information for all current connections to databases on the server. If connidparm is less
than zero, option values for the current connection are returned.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1021


System procedures

In a block 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 system procedure can be used to display the locks
held by the blocking connection.

For more information based on any of these properties, you can execute something similar to the
following:
SELECT *, DB_NAME( DBNumber ),
CONNECTION_PROPERTY( 'LastStatement', Number )
FROM sa_conn_info( );

The value of LockRowID can be used to look up a lock in the output of the sa_locks procedure.

The value in LockIndexID can be used to look up a lock in the output of the sa_locks procedure. Also, the
value in LockIndexID corresponds to the primary key of the ISYSIDX system table, which can be viewed
using the SYSIDX system view.

Every lock has an associated table, so the value of LockTable can be used to unambiguously determine
whether a connection is waiting on a lock.

Cloud note: Because of tenant database isolation rules, when this system procedure is run in the
cloud it returns only information about the current tenant database.

Permissions
None

Side effects
None

See also
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “Name connection property” [SQL Anywhere Server - Database Administration]
● “sa_locks system procedure” on page 1071
● “SYSIDX system view” on page 1211

Examples
The following example uses the sa_conn_info system procedure to return a result set summarizing
connection properties for all connections to the server.
CALL sa_conn_info( );

Number Name Userid DBNumber ...

79 DBA 0 ...

46 Sybase Central 1 DBA 0 ...

... ... ... ... ...

1022 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

The following example uses the sa_conn_info system procedure to return a result set showing which
connection created a temporary connection.

SELECT Number, Name, ParentConnection FROM sa_conn_info();

Connection 8 created the temporary connection that executed a CREATE DATABASE statement.

Number Name ParentConnection


------------------------------------------------
1000000048 INT: CreateDB 8
9 SQL_DBC_14675af8 (NULL)
8 SQL_DBA_152d5ac0 (NULL)

sa_conn_list system procedure


Returns a result set containing connection IDs.

Syntax
sa_conn_list(
[ connidparm ]
[, dbidparm ]
)

Arguments
● connidparm Use this optional INTEGER parameter to specify the connection ID number.

● dbidparm Use this optional INTEGER parameter to specify the database ID number.

Result set
Column name Data type Description

Number INTEGER Returns the ID number of the connection.

Remarks
If you do not specify any parameters, or if both parameters are NULL, the connection IDs for all
connections to all databases running on the database server are returned. If connidparm is less than 0, only
the connection ID for the current connection is returned. If connidparm is NULL and dbidparm is less
than 0, the connection IDs for just the current database are returned. If connidparm is NULL, and
dbidparm is not NULL and its value is greater than or equal to 0, the connection IDs for only that
database are returned.

Cloud note: Because of tenant database isolation rules, when this system procedure is run in the
cloud it returns only information about the current tenant database.

Permissions
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1023


System procedures

Side effects
None

See also
● “sa_db_list system procedure” on page 1031
● “sa_conn_options system procedure” on page 1024

sa_conn_options system procedure


Returns property information for connection properties that correspond to database options.

Syntax
sa_conn_options( [ connidparm ] )

Arguments
● connidparm Use this optional INTEGER parameter to specify the connection ID number.

Result set
Column name Data type Description

Number INTEGER Returns the ID number of the connection.

PropNum INTEGER Returns the connection property number.

OptionName VARCHAR(255) Returns the option name.

OptionDescription VARCHAR(255) Returns the option description.

Value LONG VARCHAR Returns the option value.

Remarks
Returns the connection ID as Number, and the PropNum, OptionName, OptionDescription, and Value for
each available connection property that corresponds to a database option.

If you do not specify connidparm, then option values for all connections to the current database are
returned. If connidparm is less than zero, option values for the current connection are returned.

Cloud note: Because of tenant database isolation rules, when this system procedure is run in the
cloud it returns only information about the current tenant database.

Permissions
None

1024 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Side effects
None

See also
● “sa_db_list system procedure” on page 1031
● “sa_conn_list system procedure” on page 1023
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “Database options” [SQL Anywhere Server - Database Administration]

sa_conn_properties system procedure


Reports connection property information.

Syntax
sa_conn_properties( [ connidparm ] )

Arguments
● connidparm Use this optional INTEGER parameter to specify the connection ID number.

Result set
Column name Data type Description

Number INTEGER Returns the ID number of the connection.

PropNum INTEGER Returns the connection property number.

PropName VARCHAR(255) Returns the connection property name.

PropDescription VARCHAR(255) Returns the connection property description.

Value LONG VARCHAR Returns the connection property value.

Remarks
Returns the connection ID as Number, and the PropNum, PropName, PropDescription, and Value for each
available connection property. Values are returned for all connection properties, database option settings
related to connections, and statistics related to connections. Valid properties with NULL values are also
returned.

If no connidparm is supplied, properties for all connections to the current database are returned. If
connidparm is less than zero, property values for the current connection are returned.

Cloud note: Because of tenant database isolation rules, when this system procedure is run in the
cloud it returns only information about the current tenant database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1025


System procedures

Permissions
None

Side effects
None

See also
● “sa_conn_list system procedure” on page 1023
● “sa_conn_options system procedure” on page 1024
● “System functions” on page 144
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]

Examples
The following example uses the sa_conn_properties system procedure to return a result set summarizing
connection property information for all connections.
CALL sa_conn_properties( );

Number PropNum PropName ...

79 37 CacheHits ...

79 38 CacheRead ...

... ... ... ...

This example uses the sa_conn_properties system procedure to return a list of all connections, in
decreasing order by CPU time*:
SELECT Number AS connection_number,
CONNECTION_PROPERTY ( 'Name', Number ) AS connection_name,
CONNECTION_PROPERTY ( 'Userid', Number ) AS user_id,
CAST ( Value AS NUMERIC ( 30, 2 ) ) AS approx_cpu_time
FROM sa_conn_properties()
WHERE PropName = 'ApproximateCPUTime'
ORDER BY approx_cpu_time DESC;

*Example courtesy of Breck Carter, RisingRoad Professional Services (http://www.risingroad.com).

sa_convert_ml_progress_to_timestamp system procedure


For MobiLink scripted uploads only. This converts the progress value for scripted upload from an
UNSIGNED BIGINT to a TIMESTAMP.

Syntax
sa_convert_ml_progress_to_timestamp( progress )

1026 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Arguments
● progress The function takes one parameter which is an UNSIGNED BIGINT.

Remarks
The function returns the TIMESTAMP that is represented by the value passed in. This procedure is the
inverse of sa_convert_timestamp_to_ml_progress.

Permissions
None

Side effects
None

See also
● “sa_convert_timestamp_to_ml_progress system procedure” on page 1027
● “Scripted upload” [MobiLink - Client Administration]

Example
SELECT sa_convert_ml_progress_to_timestamp( 3465034611199 );

sa_convert_timestamp_to_ml_progress system procedure


For MobiLink scripted uploads only. This converts the progress value for scripted upload from a
TIMESTAMP to an UNSIGNED BIGINT.

Syntax
sa_convert_timestamp_to_ml_progress( t1 )

Arguments
● t1 Use this TIMESTAMP parameter to specify the progress value to convert to an UNSIGNED
BIGINT.

Remarks
The function returns an UNSIGNED BIGINT that represents the timestamp passed in as a parameter. This
procedure is the inverse of sa_convert_ml_progress_to_timestamp.

Permissions
None

Side effects
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1027


System procedures

See also
● “sa_convert_ml_progress_to_timestamp system procedure” on page 1026
● “Scripted upload” [MobiLink - Client Administration]

Examples
SELECT sa_convert_timestamp_to_ml_progress( CURRENT TIMESTAMP );

SELECT sa_convert_timestamp_to_ml_progress( '1900/01/01 1:00' );

sa_copy_cursor_to_temp_table system procedure


Creates a temporary table and copies the result set of an open cursor to it.

Syntax
sa_copy_cursor_to_temp_table(
cursor_name,
table_name
[ , first_row [, max_rows ] ]
)

Arguments
● cursor_name The name of the open cursor to describe.

● table_name The name of the temporary table to create.

● first_row The number of the first row to copy to the temporary table. The defaults is 1.

● max_rows The maximum number of rows to copy to the temporary table. The default is
9223372036854775807 (all rows).

Remarks
Suppose you have a cursor of several integer columns. sa_copy_cursor_to_temp_table creates a
temporary table using a statement in this form:
BEGIN
CREATE LOCAL TEMPORARY TABLE TempTab (
col1 INT,
col2 INT,
...
rownum bigint primary key )
END;

sa_copy_cursor_to_temp_table names the columns col1,col2, and so on to avoid duplication of names or


difficulty if cursor columns do not have a well defined name (for example, if they are a complex
expression).

Once the temporary table is created, the contents of the open cursor are inserted by moving to the row
number indicated by first_row, and inserting the number of rows indicated by max_rows. After the
contents have been inserted into the temporary table, the cursor is re-positioned at its original location.

1028 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Permissions
None

Side effects
Copying from the cursor fetches the rows using the cursor's isolation settings. This may acquire locks on
rows and have other effects equivalent to fetching from the cursor.

If concurrent changes are made outside of the current connection and the cursor is not protected from
these by materialization or isolation settings, then it is possible that the cursor will be positioned on a
different row after the procedure completes. For example, if the previous current row of the cursor was
deleted, the cursor could be repositioned on the row after the original position.

If an error occurs while copying from the cursor, the cursor enters an invalid state, and further operations
on the cursor fail with an error.

See also
● “sa_list_cursors system procedure” on page 1069
● “sa_describe_cursor system procedure” on page 1035

Example
The following batch creates a cursor named myCursor and loads it with data from the Products table. The
cursor is then opened (OPEN statement). A DROP statement drops myTempTable, if it already exists.
Calling sa_copy_cursor_to_temp_table creates a temporary table called myTempTable and copies the
contents of myCursor into it. Finally, a SELECT statement returns the data that was copied into the
temporary table from the cursor:
begin
DECLARE myCursor CURSOR FOR
SELECT Id, Name, Description, Color, Quantity FROM Products;
OPEN myCursor;
DROP TABLE IF EXISTS myTempTable;
CALL sa_copy_cursor_to_temp_table( 'myCursor','myTempTable' );
CLOSE myCursor;
SELECT * FROM myTempTable;
end

sa_db_info system procedure


Reports database property information.

Syntax
sa_db_info( [ dbidparm ] )

Arguments
● dbidparm Use this optional INTEGER parameter to specify the database ID number.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1029


System procedures

Result set
Column Data type Description
name

Number INTEGER Returns the ID number of the connection.

Alias VARCHAR(255) Returns the database name.

File VARCHAR(255) Returns the file name of the database root file, including path.

ConnCount INTEGER Returns the number of connections to the database. The property
value does not include connections used for internal operations,
but it does include connections used for events and external envi-
ronment support.

PageSize INTEGER Returns the page size of the database, in bytes.

LogName VARCHAR(255) Returns the file name of the transaction log, including path.

Remarks
If you specify a database ID, sa_db_info returns a single row containing the Number, Alias, File,
ConnCount, PageSize, and LogName for the specified database.

If dbidparm is not supplied, properties for all databases are returned.

Cloud note: Because of tenant database isolation rules, when this system procedure is run in the
cloud it returns only information about the current tenant database.

Permissions
None

Side effects
None

See also
● “sa_db_properties system procedure” on page 1032
● “Accessing database property values” [SQL Anywhere Server - Database Administration]

Example
The following statement returns a row for each database that is running on the server:

CALL sa_db_info( );

Property Value

Number 0

1030 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Property Value

Alias demo

File C:\Documents and Settings\All Users\Documents\SQL Anywhere 12\Samples\demo.db

ConnCount 1

PageSize 4096

LogName C:\Documents and Settings\All Users\Documents\SQL Anywhere 12\Samples\demo.log

sa_db_list system procedure


Returns a database ID.

Syntax
sa_db_list( [ dbidparm ] )

Arguments
● dbidparm Use this optional INTEGER parameter to specify the database ID number.

Result set
Column name Data type Description

Number INTEGER The database ID number.

Remarks
If you do not specify dbidparm, or if dbidparm is NULL, the IDs for all databases running on the database
server are returned. If dbidparm is less than 0, then only the ID for the current database is returned.

Cloud note: Because of tenant database isolation rules, when this system procedure is run in the
cloud it returns only information about the current tenant database.

Permissions
None

Side effects
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1031


System procedures

See also
● “sa_conn_list system procedure” on page 1023
● “sa_conn_options system procedure” on page 1024
● “DB_NAME function [System]” on page 201

Example
The following example returns the number of databases running on a database server.

SELECT * FROM sa_db_list();

The following example uses the system procedure sa_db_list and the function DB_Name to return a list of
the databases running on a database server.

SELECT DB_NAME(Number) FROM sa_db_list();

sa_db_properties system procedure


Reports database property information.

Syntax
sa_db_properties( [ dbidparm ] )

Arguments
● dbidparm Use this optional INTEGER parameter to specify the database ID number.

Result set
Column name Data type Description

Number INTEGER The database ID number.

PropNum INTEGER The database property number.

PropName VARCHAR(255) The database property name.

PropDescription VARCHAR(255) The database property description.

Value LONG VARCHAR The database property value.

Remarks
If you specify a database ID, the sa_db_properties system procedure returns the database ID number and
the PropNum, PropName, PropDescription, and Value for each available database property. Values are
returned for all database properties and statistics related to databases. Valid properties with NULL values
are also returned.

If dbidparm is not specified, properties for all databases are returned.

1032 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Cloud note: Because of tenant database isolation rules, when this system procedure is run in the
cloud it returns only information about the current tenant database.

Permissions
None

Side effects
None

See also
● “sa_db_info system procedure” on page 1029
● “Accessing database property values” [SQL Anywhere Server - Database Administration]

Example
The following example uses the sa_db_properties system procedure to return a result set summarizing
database property information for all databases.
CALL sa_db_properties( );

Number PropNum PropName ...

0 0 ConnCount ...

0 1 IdleCheck ...

0 2 IdleWrite ...

... ... ... ...

sa_dependent_views system procedure


Returns the list of all dependent views for a given table or view.

Syntax
sa_dependent_views( 'tbl_name ' [, ' owner_name ] ' )

Arguments
● tbl_name Use this CHARACTER parameter to specify the name of the table or view.

● owner_name Use this optional CHARACTER parameter to specify the owner for tbl_name.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1033


System procedures

Result set
Column name Data type Description

table_id UNSIGNED INTEGER The object ID of the table or view.

dep_view_id UNSIGNED INTEGER The object ID of the dependent views.

Remarks
Use this procedure to obtain the list of IDs of dependent views. Alternatively, you can use the procedure
in a statement that returns more information about the views, such as their names.

No errors are generated if no existing tables satisfy the specified criteria for table and owner names. Also:

● tbl_name is optional and has a default value of NULL.

● If both owner and tbl_name are null, information is returned on all tables that have dependent views.

● If tbl_name is null but owner is specified, information is returned on all tables owned by the specified
owner.

● If tbl_name is specified but owner is null, information is returned on any one of the tables with the
specified name.

By default, execution of the procedure does not require any permissions and assumes that PUBLIC has
access to the catalog. DBAs can control access as needed on the view and/or the catalog.

Permissions
None

Side effects
None

See also
● “SYSDEPENDENCY system view” on page 1203
● “View dependencies” [SQL Anywhere Server - SQL Usage]

Examples
In this example, the sa_dependent_views system procedure is used to obtain the list of IDs for the views
that are dependent on the SalesOrders table. The procedure returns the table_id for SalesOrders, and the
dep_view_id for the dependent view, ViewSalesOrders.

CALL sa_dependent_views( 'SalesOrders' );

In this example, the sa_dependent_views system procedure is used in a SELECT statement to obtain the
list of names of views dependent on the SalesOrders table. The procedure returns the ViewSalesOrders
view.

1034 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

SELECT t.table_name FROM SYSTAB t,


sa_dependent_views( 'SalesOrders' ) v
WHERE t.table_id = v.dep_view_id;

sa_describe_cursor system procedure


Describes the name and type information for the columns of a cursor.

Syntax
sa_describe_cursor( cursor_name )

Arguments
● cursor_name This VARCHAR(256) value identifies the open cursor to describe.

Result set
Column name Data type Description

column_number INTEGER The ordinal position of the column described by this


row, starting at 1.

name VAR- The name of the column.


CHAR(128)

domain_id SMALLINT The data type of the column.

domain_name VAR- The data type name of the column.


CHAR(128)

domain_name_with_size VAR- The data type name, including size and precision (as
CHAR(160) used in CREATE TABLE or CAST functions).

width INTEGER The length of a string parameter, the precision of a nu-


meric parameter, or the number of bytes of storage for
any other data type.

scale INTEGER The number of digits after the decimal point for numer-
ic data type columns, and zero for all other data types.

declared_width INTEGER The length of a string parameter, the precision of a nu-


meric parameter, or the number of bytes of storage for
any other data type.

user_type_id SMALLINT The user-defined data type if applicable, otherwise


NULL.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1035


System procedures

Column name Data type Description

user_type_name VAR- The user-defined data type if applicable, otherwise


CHAR(128) NULL.

correlation_name VAR- The correlation name associated with the expression if


CHAR(128) applicable, otherwise NULL.

base_table_id UNSIGNED IN- The table_id if the expression is a column, otherwise


TEGER NULL.

base_column_id UNSIGNED IN- The column_id if the expression is a column, otherwise


TEGER NULL.

base_owner_name VAR- The owner name if the expression is a column, other-


CHAR(128) wise NULL.

base_table_name VAR- The table name if the expression is a column, otherwise


CHAR(128) NULL.

base_column_name VAR- The column name if the expression is a column, other-


CHAR(128) wise NULL.

nulls_allowed BIT The indicator whether the expression can be NULL (1).

is_autoincrement BIT An indicator whether the expression is an AUTO-


INCREMENT column (1).

is_key_column BIT An indicator whether the expression is part of a key for


the result set (1). For more information, see the Re-
marks section below.

is_added_key_column BIT An indicator whether the expression is an added key


column (1). For more information, see the Remarks
section below.

Remarks
The sa_describe_cursor system procedure provides an API-independent mechanism for retrieving the
description of the columns returned by the cursor. The system procedure can be useful when writing
stored procedures that work with dynamic SQL.

The sa_describe_cursor system procedure can be used in a CALL statement or in the FROM clause of a
SELECT statement.

cursor_name must refer to an open cursor in the current connection. Use the sa_list_cursors system
procedure to get the list of open cursors for the connection.

1036 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Permissions
None

Side effects
None

See also
● “sa_list_cursors system procedure” on page 1069
● “sa_copy_cursor_to_temp_table system procedure” on page 1028
● “SYSDOMAIN system view” on page 1203
● “SYSUSER system view” on page 1254
● “SYSTABCOL system view” on page 1244
● “SYSUSERTYPE system view” on page 1256
● “SYSDOMAIN system view” on page 1203

sa_describe_query system procedure


Describes the result set for a query with one row describing each output column of the query.

Syntax
sa_describe_query(
query
[, add_keys ]
)

Arguments
● query Use this LONG VARCHAR parameter to specify the text of the SQL statement being
described.

● add_keys Use this optional BIT parameter to specify whether to determine a set of columns that
uniquely identify rows in the result set for the query being described. The default is 0; the database
server does not attempt to identify the columns. See the Remarks section below for a full explanation
of this parameter.

Result set
Column name Data type Description

column_number INTEGER The ordinal position of the column described by this


row, starting at 1.

name VAR- The name of the column.


CHAR(128)

domain_id SMALLINT The data type of the column.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1037


System procedures

Column name Data type Description

domain_name VAR- The data type name.


CHAR(128)

domain_name_with_size VAR- The data type name, including size and precision (as
CHAR(160) used in CREATE TABLE or CAST functions).

width INTEGER The length of a string parameter, the precision of a nu-


meric parameter, or the number of bytes of storage for
any other data type.

scale INTEGER The number of digits after the decimal point for numer-
ic data type columns, and zero for all other data types.

declared_width INTEGER The length of a string parameter, the precision of a nu-


meric parameter, or the number of bytes of storage for
any other data type.

user_type_id SMALLINT The type_id of the user-defined data type if there is one,
otherwise NULL.

user_type_name VAR- The name of the user-defined data type if there is one,
CHAR(128) otherwise NULL.

correlation_name VAR- The correlation name associated with the expression if


CHAR(128) one is available, otherwise NULL.

base_table_id UNSIGNED IN- The table_id if the expression is a column, otherwise


TEGER NULL.

base_column_id UNSIGNED IN- The column_id if the expression is a column, otherwise


TEGER NULL.

base_owner_name VAR- The owner name if the expression is a column, other-


CHAR(128) wise NULL.

base_table_name VAR- The table name if the expression is a column, otherwise


CHAR(128) NULL.

base_column_name VAR- The column name if the expression is a column, other-


CHAR(128) wise NULL.

nulls_allowed BIT An indicator that is 1 if the expression can be NULL,


otherwise 0.

is_autoincrement BIT An indicator that is 1 if the expression is a column de-


clared to be AUTOINCREMENT, otherwise 0.

1038 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Column name Data type Description

is_key_column BIT An indicator that is 1 if the expression is part of a key


for the result set, otherwise 0. For more information,
see the Remarks section below.

is_added_key_column BIT An indicator that is 1 if the expression is an added key


column, otherwise 0. For more information, see the Re-
marks section below.

Remarks
The sa_describe_query procedure provides an API-independent mechanism to describe the name and type
information for the expressions in the result set of a query.

When 1 is specified for add_keys, the sa_describe_query procedure attempts to find a set of columns from
the objects being queried that, when combined, can be used as a key to uniquely identify rows in result set
of the query being described. The key takes the form of one or more columns from the objects being
queried, and may include columns that are not explicitly referenced in the query. If the optimizer finds a
key, the column or columns used in the key are identified in the results by an is_key_column value of 1. If
no key is found, an error is returned.

For any column that is included in the key but that is not explicitly referenced in the query, the
is_added_key_column value is set to 1 to indicate that the column has been added to the results for the
procedure; otherwise, the value of is_added_key_column is 0.

If you do not specify add_keys, or you specify a value of 0, the optimizer does not attempt to find a key
for the result set, and the is_key_column and is_added_key_column columns contain NULL.

The declared_width and width values both describe the size of a column. The declared_width describes
the size of the column as defined by the CREATE TABLE statement or by the query, while the width
value gives the size of the column when fetched to the client. The client representation of a type may be
different from the database server. For example, date and time types are converted to strings if the
return_date_time_as_string option is on. For strings, columns declared with character-length semantics
have a declared_width value that matches the CREATE TABLE size, while the width value gives the
maximum number of bytes needed to store the returned string. For example:

Declaration width declared_width

CHAR(10) 10 10

CHAR(10 CHAR) 40 10

TIMESTAMP depends on the length of the timestamp format string 8

NUMERIC(10, 3) 10 (precision) 10 (precision)

Permissions
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1039


System procedures

Side effects
None

See also
● “EXPRTYPE function [Miscellaneous]” on page 222
● “Character data types” on page 81
● “return_date_time_as_string option” [SQL Anywhere Server - Database Administration]
● “SYSDOMAIN system view” on page 1203
● “SYSDOMAIN system view” on page 1203
● “SYSUSERTYPE system view” on page 1256
● “SYSTAB system view” on page 1241
● “SYSUSER system view” on page 1254

Examples
The following example describes the information returned when querying all columns in the Departments
table:
SELECT *
FROM sa_describe_query( 'SELECT * FROM Departments DEPT' );

The results show the values of the is_key_column and is_added_key_column as NULL because the
add_keys parameter was not specified.

The following example describes the information returned by querying the DepartmentName and
Surname columns of the Employees table, joined with the Departments table:
SELECT *
FROM sa_describe_query( 'SELECT DepartmentName, Surname
FROM Employees E JOIN Departments D ON E.EmployeeID = D.DepartmentHeadId',
add_keys = 1 );

The results shows a 1 in rows 3 and 4 of the result set, indicating that the columns needed to uniquely
identify rows in the result set for the query are Employees.EmployeeID and Departments.DepartmentID.
Also, a 1 is present in the is_added_key_column for rows 3 and 4 because Employees.EmployeeID and
Departments.DepartmentID were not explicitly referenced in the query being described.

sa_describe_shapefile system procedure


Describes the names and types of columns contained in a ESRI shapefile. This system feature is for use
with the spatial data features.

Syntax
sa_describe_shapefile( shp_filename
, srid
[, encoding ]
)

1040 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Arguments
● shp_filename A VARCHAR(512) parameter that identifies the location of the ESRI shapefile.
The file name must have the extension .shp and must have an associated .dbf file with the same base
name located in the same directory. The path is relative to the database server, not the client
application.

● srid An INTEGER parameter that identifies the SRID for the geometries in the shapefile. Specify
NULL to indicate the column can store multiple SRIDs. Specifying NULL limits the operations that
can be performed on the geometry values.

● encoding A VARCHAR(50) parameter that identifies the encoding to use when reading the
shapefile. The default encoding is ISO-8859-1.

Result set
Column name Data type Description

column_number INTEGER The ordinal position of the column described by this


row, starting at 1.

name VARCHAR(128) The name of the column.

domain_name_with_size VARCHAR(160) The data type name, including size and precision (as
used in CREATE TABLE or CAST functions).

Remarks
The sa_describe_shapefile system procedure is used to describe the name and type of columns in an ESRI
shapefile. This information can be used to create a table to load data from a shapefile using the LOAD
TABLE or INPUT statements. Alternately, this system procedure can be used to read a shapefile by
specifying the WITH clause for OPENSTRING...FORMAT SHAPEFILE.

Permissions
If the -gl database option has been set to all, all users can execute this system procedure. Otherwise, DBA
or READFILE authority is required.

See also
● “LOAD TABLE statement” on page 792
● “INPUT statement [Interactive SQL]” on page 773
● “Support for ESRI shapefiles” [SQL Anywhere Server - Spatial Data Support]

Example
The following example returns a string that can be used to create a table for storing shapefile data:

SELECT 'create table esri_load( record_number int primary key, ' ||


(SELECT list( name || ' ' || domain_name_with_size, ', '
ORDER BY column_number )
FROM sa_describe_shapefile( 'c:\\esri\\shapefile.shp', 1000004326 )
WHERE column_number > 1 ) || ' )';

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1041


System procedures

Once the table has been created, you could load the shapefile data into it using the following statement:
LOAD TABLE esri_load USING FILE 'c:\\esri\\shapefile.shp' FORMAT SHAPEFILE;

sa_disable_auditing_type system procedure


Disables auditing of specific events.

Syntax
sa_disable_auditing_type(' types ')

Arguments
● types Use this VARCHAR(128) parameter to specify a comma-delimited string containing one or
more of the following values:

○ all disables all types of auditing.

○ connect disables auditing of both successful and failed connection attempts.

○ connectFailed disables auditing of failed connection attempts.

○ DDL disables auditing of DDL statements.

○ options disables auditing of public options.

○ permission disables auditing of permission checks, user checks, and SETUSER statements.

○ permissionDenied disables auditing of failed permission and user checks.

○ triggers disables auditing in response to trigger events.

Remarks
You can use the sa_disable_auditing_type system procedure to disable auditing of one or more categories
of information.

Setting this option to all disables all auditing. You can also disable auditing by setting the
PUBLIC.auditing option to Off.

Permissions
DBA authority

Side effects
None

1042 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

See also
● “sa_enable_auditing_type system procedure” on page 1044
● “Database activity audits” [SQL Anywhere Server - Database Administration]
● “auditing option” [SQL Anywhere Server - Database Administration]

Example
To disable all auditing:
CALL sa_disable_auditing_type( 'all' );

sa_disk_free_space system procedure


Reports information about space available for a dbspace, transaction log, transaction log mirror, and/or
temporary file.

Syntax
sa_disk_free_space( [ p_dbspace_name ] )

Arguments
● p_dbspace_name Use this VARCHAR(128) parameter to specify the name of a dbspace,
transaction log file, transaction log mirror file, or temporary file.

If there is a dbspace called log, mirror, or temp, you can prefix the keyword with an underscore. For
example, use _log to get information about the log file if a dbspace called log exists.

Specify SYSTEM to get information about the main database file, TEMPORARY or TEMP to get
information about the temporary file, TRANSLOG to get information about the transaction log, or
TRANSLOGMIRROR to get information about the transaction log mirror.

Result set
Column name Data type Description

dbspace_name VARCHAR(128) This is the dbspace name, transaction log file, transaction log
mirror file, or temporary file.

free_space UNSIGNED BIGINT The number of free bytes on the volume.

total_space UNSIGNED BIGINT The total amount of disk space available on the drive where
the dbspace resides.

Remarks
If the p_dbspace_name parameter is not specified or is NULL, then the result set contains one row for
each dbspace, plus one row for each of the transaction log, transaction log mirror, and temporary file, if
they exist. If p_dbspace_name is specified, then exactly one or zero rows are returned (zero if no such
dbspace exists, or if log or mirror is specified and there is no log or mirror file).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1043


System procedures

Permissions
DBA authority

Side effects
None

Example
The following example uses the sa_disk_free_space system procedure to return a result set containing
information about available space.
CALL sa_disk_free_space( );

dbspace_name free_space total_space

system 10952101888 21410402304

translog 10952101888 21410402304

temporary 10952101888 21410402304

See also
● “Predefined dbspaces” [SQL Anywhere Server - Database Administration]

sa_enable_auditing_type system procedure


Enables auditing and specifies which events to audit.

Syntax
sa_enable_auditing_type( 'types' )

Arguments
● types Use this VARCHAR(128) parameter to specify a comma-delimited string containing one or
more of the following values:

○ all enables all types of auditing.

○ connect enables auditing of both successful and failed connection attempts.

○ connectFailed enables auditing of failed connection attempts.

○ DDL enables auditing of DDL statements.

○ options enables auditing of public options.

○ permission enables auditing of permission checks, user checks, and SETUSER statements.

○ permissionDenied enables auditing of failed permission and user checks.

1044 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

○ triggers enables auditing after a trigger event.

Remarks
sa_enable_auditing_type works in conjunction with the PUBLIC.auditing option to enable auditing of
specific types of information.

If you set the PUBLIC.auditing option to On, and do not specify which type of information to audit, the
default setting (all) takes effect. In this case, all types of auditing information are recorded.

If you set the PUBLIC.auditing option to On, and disable all types of auditing using
sa_disable_auditing_type, no auditing information is recorded. To re-establish auditing, you must use
sa_enable_auditing_type to specify which type of information you want to audit.

If you set the PUBLIC.auditing option to Off, then no auditing information is recorded, regardless of the
sa_enable_auditing_type setting.

Permissions
DBA authority

Side effects
None

See also
● “sa_disable_auditing_type system procedure” on page 1042
● “Database activity audits” [SQL Anywhere Server - Database Administration]
● “auditing option” [SQL Anywhere Server - Database Administration]

Example
To enable only option auditing:
CALL sa_enable_auditing_type( 'options' );

sa_eng_properties system procedure


Reports database server property information.

Syntax
sa_eng_properties( )

Result set
Column name Data type Description

PropNum INTEGER The database server property number.

PropName VARCHAR(255) The database server property name.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1045


System procedures

Column name Data type Description

PropDescription VARCHAR(255) The database server property description.

Value LONG VARCHAR The database server property value.

Remarks
Returns the PropNum, PropName, PropDescription, and Value for each available server property. Values
are returned for all database server properties and statistics related to database servers.

Permissions
None

Side effects
None

See also
● “Accessing database server property values” [SQL Anywhere Server - Database Administration]
● “System functions” on page 144

Example
The following statement returns a set of available server properties
CALL sa_eng_properties( );

PropNum PropName ...

1 IdleWrite ...

2 IdleChkPt ...

... ... ...

sa_external_library_unload system procedure


Unloads an external library.

Syntax
sa_external_library_unload( [ 'lib_name' ] )

Arguments
● lib_name Optionally use this LONG VARCHAR parameter to specify the name of a library to be
unloaded. If no library is specified, all external libraries that are not in use are unloaded.

1046 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Remarks
If an external library is specified, but is in use or is not loaded, an error is returned. If no parameter is
specified, an error is returned if no loaded external libraries are found.

Permissions
DBA authority

Side effects
None

See also
● “SQL Anywhere external call interface” [SQL Anywhere Server - Programming]

Example
The following example unloads an external library called myextlib.dll:
CALL sa_external_library_unload( 'myextlib.dll' );

The following example unloads all libraries that are not currently in use:
CALL sa_external_library_unload();

sa_flush_cache system procedure


Empties all pages for the current database in the database server cache.

Syntax
sa_flush_cache( )

Remarks
Database administrators can use this procedure to empty the contents of the database server cache for the
current database. This is useful in performance measurement to ensure repeatable results.

Permissions
DBA authority

Side effects
None

sa_flush_statistics system procedure


Saves all cost model statistics in the database server cache.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1047


System procedures

Syntax
sa_flush_statistics( )

Remarks
Use this procedure to flush current cost model statistics in the database, currently cached, to disk. You can
then retrieve the statistics using the sa_get_histogram system procedure, or the Histogram utility (dbhist).
When this system procedure runs, the ISYSCOLSTAT system table is updated. Under normal operation it
should not be necessary to execute this procedure because the server automatically writes out statistics to
disk on a periodic basis.

Permissions
DBA authority

Side effects
None

See also
● “sa_get_histogram system procedure” on page 1051
● “SYSCOLSTAT system view” on page 1199
● “Histogram utility (dbhist)” [SQL Anywhere Server - Database Administration]

sa_get_bits system procedure


Takes a bit string and returns a row for each bit in the string. By default, only rows with a bit value of 1
are returned.

Syntax
sa_get_bits( bit_string [ , only_on_bits ] )

Arguments
● bit_string Use this LONG VARBIT parameter to specify the bit string from which to get the bits.
If the bit_string parameter is NULL, no rows are returned.

● only_on_bits Use this optional BIT to specify whether to return only rows with on bits (bits with
the value of 1). Specify 1 (the default) to return only rows with on bits; specify 0 to return rows for all
bits in the bit string.

Result set
Column Data type Description

bitnum UNSIGNED The position of the bit described by this row. For example, the first bit in
INT the bit string has bitnum of 1.

1048 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Column Data type Description

bit_val BIT The value of the bit at position bitnum. If only_on_bits is set to 1, this val-
ue is always 1.

Remarks
The sa_get_bits system procedure decodes a bit string, returning one row for each bit in the bit string,
indicating the value of the bit. If only_on_bits is set to 1 (the default) or NULL, then only rows
corresponding to on bits are returned. An optimization allows this case to be processed efficiently for long
bit strings that have few on bits. If only_on_bits is set to 0, then a row is returned for each bit in the bit
string.

For example, the statement CALL sa_get_bits( '1010' ) returns the following result set,
indicating on bits in positions 1 and 3 of the bit string.

bitnum bit_val

1 1

3 1

The sa_get_bits system procedure can be used to convert a bit string into a relation. This can be used to
join a bit string with a table, or to retrieve a bit string as a result set instead of as a single binary value. It
can be more efficient to retrieve a bit string as a result set if there are a large number of 0 bits, as these do
not need to be retrieved.

Permissions
None

Side effects
None

See also
● “sa_split_list system procedure” on page 1142
● “SET_BIT function [Bit array]” on page 333
● “SET_BITS function [Aggregate]” on page 334
● “GET_BIT function [Bit array]” on page 226

Examples
The following example shows how to use the sa_get_bits system procedure to encode a set of integers as a
bit string, and then decode it for use in a join:
CREATE VARIABLE @s_depts LONG VARBIT;

SELECT SET_BITS( DepartmentID )


INTO @s_depts
FROM Departments
WHERE DepartmentName like 'S%';

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1049


System procedures

SELECT *
FROM sa_get_bits( @s_depts ) B
JOIN Departments D ON B.bitnum = D.DepartmentID;

sa_get_dtt system procedure


Reports the current value of the Disk Transfer Time (DTT) model, which is part of the cost model.

Syntax
sa_get_dtt( file_id )

Arguments
● file_id Use this UNSIGNED SMALLINT parameter to specify the database file ID.

Remarks
You can obtain the file_id from the SYSDBSPACE system view.

This procedure, intended for internal diagnostic purposes, retrieves data from the ISYSOPTSTAT system
table.

Result set
Column name Data type Description

BandSize UNSIGNED INTEGER Size, in pages, of disk over which random access takes
place.

ReadTime UNSIGNED INTEGER Amortized cost, in microseconds, of reading one page.

WriteTime UNSIGNED INTEGER Amortized cost, in microseconds, of writing one page.

Permissions
None

Side effects
None

See also
● “SYSDBSPACE system view” on page 1202
● “SYSOPTSTAT system view” on page 1221
● “sa_get_dtt_groupreads system procedure” on page 1051

1050 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

sa_get_dtt_groupreads system procedure


Estimates and reports the cost of issuing group reads on the database server.

Syntax
sa_get_dtt_groupreads( file_id )

Arguments
● file_id Use this UNSIGNED SMALLINT parameter to specify the database file ID.

Remarks
You can obtain the file_id from the SYSDBSPACE system view. The estimates returned by the
sa_get_dtt_groupreads system procedure are part of the cost model, and are used to select group reads of
appropriate sizes during operations such as sorting.

This procedure, intended for internal diagnostic purposes, retrieves data from the ISYSOPTSTAT system
table. Rows are not returned if the specified dbspace does not have any estimates recorded in
SYSOPTSTAT. To tailor estimates for specific hardware devices, execute the following statement:
ALTER DATABASE CALIBRATE GROUP READ;

Result set
Column name Data type Description

GroupSize UNSIGNED INTE- Size, in pages, of disk over which random access takes
GER place.

ReadTime FLOAT Amortized cost, in microseconds, of reading one page.

Permissions
None

Side effects
None

See also
● “SYSDBSPACE system view” on page 1202
● “SYSOPTSTAT system view” on page 1221
● “ALTER DATABASE statement” on page 400
● “sa_get_dtt system procedure” on page 1050

sa_get_histogram system procedure


Retrieves the histogram for a column.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1051


System procedures

Syntax
sa_get_histogram(
col_name,
tbl_name
[, owner_name ]
)

Arguments
● col_name Use this CHAR(128) parameter to specify the column for which to retrieve the
histogram.

● tbl_name Use this CHAR(128) parameter to specify the table in which col_name is found.

● owner_name Use this optional CHAR(128) parameter to specify the owner of tbl_name.

Result set
Column name Data type Description

StepNumber SMALLINT Histogram bucket number. The frequency of the first bucket ( Step-
Number = 0) indicates the selectivity of NULLs.

Low CHAR(128) Lowest (inclusive) column value in the bucket.

High CHAR(128) Highest (exclusive) column value in the bucket.

Frequency DOUBLE Selectivity of values in the bucket.

Remarks
This procedure, intended for internal diagnostic purposes, retrieves column statistics from the database
server for the specified columns. Note that while these statistics are permanently stored in the
ISYSCOLSTAT system table, they are maintained in memory while the server is running, and written to
ISYSCOLSTAT periodically. As such, the statistics returned by the sa_get_histogram system procedure
may differ from those obtained by selecting from ISYSCOLSTAT at any given point of time.

You can manually update ISYSCOLSTAT with the latest statistics held in memory using the
sa_flush_statistics system procedure, however, this is not recommended in a production environment, and
should be reserved for diagnostic purposes.

A singleton bucket is indicated by a Low value in the result set being equal to the corresponding High
value.

It is recommended that you use the Histogram utility to view histograms.

To determine the selectivity of a predicate over a string column, use the ESTIMATE or
ESTIMATE_SOURCE functions. For string columns, both sa_get_histogram and the Histogram utility
retrieve nothing from the ISYSCOLSTAT system table. Attempting to retrieve string data generates an
error.

1052 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Statistics (including histograms) may not be present for a table or materialized view, for example, if
statistics were recently dropped. In this case, the result set for the sa_get_histogram system procedure is
empty. To create statistics for a table or materialized view, execute a CREATE STATISTICS statement.

Permissions
DBA authority

Side effects
None

See also
● “Optimizer estimates and statistics” [SQL Anywhere Server - SQL Usage]
● “Histogram utility (dbhist)” [SQL Anywhere Server - Database Administration]
● “SYSCOLSTAT system view” on page 1199
● “CREATE STATISTICS statement” on page 625
● “sa_flush_statistics system procedure” on page 1047
● “ESTIMATE_SOURCE function [Miscellaneous]” on page 213
● “ESTIMATE function [Miscellaneous]” on page 212
● “Histogram utility (dbhist)” [SQL Anywhere Server - Database Administration]

Example
For example, the following statement retrieves the histogram for the ProductID column of the
SalesOrderItems table:
CALL sa_get_histogram( 'ProductID', 'SalesOrderItems' );

sa_get_request_profile system procedure


Analyzes the request log to determine the execution times of similar statements.

Syntax
sa_get_request_profile(
[ filename
[, conn_id
[, first_file
[, num_files ] ] ] ]
)

Arguments
● filename Use this optional LONG VARCHAR parameter to specify the request logging file name.

● conn_id Use this optional UNSIGNED INTEGER parameter to specify the connection ID number.

● first_file Use this optional INTEGER parameter to specify the first request log file to analyze.

● num_files Use this optional INTEGER parameter to specify the number of request log files to
analyze.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1053


System procedures

Remarks
This procedure calls sa_get_request_times to process a request log file, and then summarizes the results
into the global temporary table satmp_request_profile. This table contains the statements from the log
along with how many times each was executed, and their total, average, and maximum execution times.
The table can be sorted in various ways to identify targets for performance optimization efforts.

If you do not specify a log file (filename), the default is the current log file that is specified with the -zo
database server option, or that has been specified by
sa_server_option( 'RequestLogFile', filename )

If a connection ID is specified, it is used to filter information from the log so that only requests for that
connection are retrieved.

This system procedure is not supported in cloud databases.

Permissions
DBA authority

Side effects
Automatic commit

Example
The following command obtains the request times for the requests in the files req.out.3, req.out.4, and
req.out.5.
CALL sa_get_request_profile('req.out',0,3,3);

See also
● “sa_get_request_times system procedure” on page 1054
● “sa_statement_text system procedure” on page 1145
● “sa_server_option system procedure” on page 1120
● “-zo dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]

sa_get_request_times system procedure


Analyzes the request log to determine statement execution times.

Syntax
sa_get_request_times( filename
[, conn_id
[, first_file
[, num_files ] ] ]
)

Arguments
● filename Use this optional LONG VARCHAR parameter to specify the request logging file name.

1054 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● conn_id Use this optional UNSIGNED INTEGER parameter to specify the connection ID number.

● first_file Use this optional INTEGER parameter to specify the first file to analyze.

● num_files Use this optional INTEGER parameter to specify the number of request log files to
analyze.

Remarks
This procedure reads the specified request log and populates the global temporary table
satmp_request_time with the statements from the log and their execution times.

For statements such as inserts and updates, the execution time is straightforward. For queries, the time is
calculated from preparing the statement to dropping it, including describing it, opening a cursor, fetching
rows, and closing the cursor. For most queries, this is an accurate reflection of the amount of time taken.
When the cursor is left open while other events take place, such as operator interaction or client
processing, the time appears as a large value but is not a true indication that the query is costly.

This procedure recognizes host variables in the request log and populates the global temporary table
satmp_request_hostvar with their values. For older databases where this temporary table does not exist,
host variable values are ignored.

If you do not specify a log file, the default is the current log file that is specified in the command with -zo,
or that has been specified by

sa_server_option( 'RequestLogFile', filename )

If a connection ID is specified, it is used to filter information from the log so that only requests for that
connection are retrieved.

This system procedure is not supported in cloud databases.

Permissions
DBA authority

Side effects
Automatic commit

Example
The following command obtains the execution times for the requests in the files req.out.3, req.out.4, and
req.out.5.

CALL sa_get_request_times('req.out',0,3,3);

See also
● “sa_get_request_profile system procedure” on page 1053
● “sa_statement_text system procedure” on page 1145
● “sa_server_option system procedure” on page 1120

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1055


System procedures

sa_get_server_messages system procedure [deprecated]


Allows you to return constants from the database server messages window as a result set.

This system procedure is deprecated. Use sa_server_messages instead.

Syntax
sa_get_server_messages( first_line )

Arguments
● first_line Use this INTEGER parameter to specify the line number from which to start displaying
server messages.

Result set
Column name Data type Description

line_num INTEGER The line number of a server message.

message_text VARCHAR(255) The server message text.

message_time TIMESTAMP The time of the message.

Remarks
This procedure takes an INTEGER parameter that specifies the starting line number to display, and
returns a row for that line and for all subsequent lines. If the starting line is negative, the result set starts at
the first available line. The result set includes the line number, message text, and message time.

Permissions
None

Side effects
None

Example
The following example uses the sa_get_server_messages system procedure to return a result set
containing the content of the database server messages window, starting from line 16.
CALL sa_get_server_messages( 16 );

line_num message_text ...

16 Running on Windows XP Build 2195... ...

17 2132K of memory used for caching ...

1056 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

line_num message_text ...

... ... ...

sa_get_table_definition system procedure


Returns a LONG VARCHAR string containing the SQL statements required to create the specified table
and its indexes, foreign keys, triggers, and granted permissions.

Syntax
sa_get_table_definition( owner, tabname )

Arguments
● owner Use this CHAR(128) parameter to specify the owner of tabname.

● tabname Use this CHAR(128) parameter to specify the name of the table.

Remarks
To create a new table with the same definition, use the string returned by the sa_get_table_definition
system procedure with the EXECUTE IMMEDIATE statement and the LOCATE, SUBSTRING, and
REPLACE functions.

Permissions
DBA authority

Side effects
None

See also
● “sa_split_list system procedure” on page 1142
● “EXECUTE IMMEDIATE statement [SP]” on page 719
● “LOCATE function [String]” on page 264
● “SUBSTRING function [String]” on page 353
● “REPLACE function [String]” on page 321

Example
The following statement uses the sa_get_table_definition system procedure to display the string
containing the SQL statements required to create the Departments table.
SELECT sa_get_table_definition( 'GROUPO', 'Departments');

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1057


System procedures

sa_get_user_status system procedure


Allows you to determine the current status of users.

Syntax
sa_get_user_status( )

Arguments
None

Result set
Column name Data type Description

user_id UNSIGNED INT A unique number identifying the user.

user_name CHAR(128) The name of the user.

connections INT The current number of connections by this user.

failed_logins UNSIGNED INT The number of failed login attempts made by the user.

last_login_time TIMESTAMP The time the user last logged in.

locked TINYINT Indicates if the user account is locked.

reason_locked LONG VARCHAR The reason the account is locked.

Remarks
This procedure returns a result set that shows the current status of users. In addition to basic user
information, the procedure includes a column indicating if the user has been locked out and a column with
a reason for the lockout. Users can be locked out for the following reasons: locked due to policy,
password expiry, or too many failed attempts.

A user without DBA authority can obtain user information by creating and executing a cover procedure
owned by a DBA.

Permissions
DBA authority is required to view information about all users. Users without DBA authority can view
their own information. In addition, users without DBA authority can view information about other users
by executing a cover procedure owned by a DBA.

Side effects
None

1058 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

See also
● “Login policies” [SQL Anywhere Server - Database Administration]
● “Creating a new login policy” [SQL Anywhere Server - Database Administration]
● “Creating a user and assigning a login policy” [SQL Anywhere Server - Database Administration]
● “Assigning a login policy to an existing user” [SQL Anywhere Server - Database Administration]
● “Altering a login policy” [SQL Anywhere Server - Database Administration]
● “Dropping a login policy” [SQL Anywhere Server - Database Administration]

Example
The following example uses the sa_get_user_status system procedure to return the status of database
users.
CALL sa_get_user_status;

sa_http_header_info system procedure


Returns HTTP request header names and values.

Syntax
sa_http_header_info( [header_parm] )

Arguments
● header_parm Use this optional VARCHAR(255) parameter to specify an HTTP header name.

Result set
Column name Data type Description

Name VARCHAR(255) The HTTP header name.

Value LONG VARCHAR The HTTP header value.

Remarks
The sa_http_header_info system procedure returns header names and values. If you do not specify the
header name using the optional parameter, the result set contains values for all headers.

This procedure returns a non-empty result set if it is called while processing an HTTP request within a
web service.

Permissions
None

Side effects
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1059


System procedures

See also
● “NEXT_HTTP_HEADER function [Web service]” on page 282
● “HTTP_HEADER function [Web service]” on page 242
● “Web services functions” on page 141
● “Web services system procedures” on page 996

sa_http_php_page system procedure


Returns the result of passing the PHP code that is to be interpreted through a PHP interpreter using the
current HTTP request for context information such as headers, GET/POST data, protocol version, request
URL, method, and so on.

Syntax
sa_http_php_page( php_page )

Arguments
● php_page This LONG VARCHAR parameter contains the entire PHP code that is to be
interpreted, including the starting and ending markers (<?php and ?>).

Remarks
To use this system procedure, the PHP external environment must already be installed.

The owner of this system procedure is DBO. However, for improved security, the sa_http_php_page
system procedure is executed as the invoker.

Permissions
None

Side effects
None

See also
● “sa_http_php_page_interpreted system procedure” on page 1060
● “Web services functions” on page 141
● “Web services system procedures” on page 996

sa_http_php_page_interpreted system procedure


Returns the result of passing the PHP code that is to be interpreted through a PHP interpreter using the
specified parameters for context information such as headers, GET/POST data, protocol version, request
URL, method, and so on.

1060 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Syntax
sa_http_php_page_interpreted(
php_page,
method,
url,
version,
headers,
request_body
)

Arguments
● php_page This LONG VARCHAR parameter contains the entire PHP code that is to be
interpreted, including the starting and ending markers (<?php and ?>).

● method This LONG VARCHAR parameter contains the HTTP request method (for example,
GET, POST, PUT, or one of the other standard request methods). The value for method can be
determined using the value of @HttpMethod in the current HTTP request.

● url This LONG VARCHAR parameter contains the full HTTP request URL, including the query
string, if present. The value for url can be determined using the value of @HttpURI in the current
HTTP request.

● version This LONG VARCHAR parameter contains the HTTP request protocol version (for
example, HTTP/1.1). The value for version can be determined using the value of @HttpVersion in the
current HTTP request.

● headers This LONG BINARY parameter contains the HTTP request headers in the standard
HTTP header format: Field-Name: Value\r\n. The value for headers can be retrieved from the
current HTTP request using the following SELECT statement:

SELECT LIST( name || ': ' || value, CHAR(13) || CHAR(10) )


FROM sa_http_header_info();

● request_body This LONG BINARY parameter contains the HTTP request body in binary form.
The value for request_body can be retrieved from the current HTTP request using the HTTP_BODY
function.

Remarks
To use this system procedure, the PHP external environment must already be installed.

To use this system procedure outside web services requests, you must provide request information. Any
headers set within the PHP code are lost.

The owner of this system procedure is DBO. However, for improved security, the
sa_http_php_page_interpreted system procedure is executed as the invoker.

Permissions
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1061


System procedures

Side effects
None

See also
● “HTTP_BODY function [Web service]” on page 239
● “The PHP external environment” [SQL Anywhere Server - Programming]
● “sa_http_php_page system procedure” on page 1060
● “sa_http_header_info system procedure” on page 1059
● “Web services functions” on page 141
● “Web services system procedures” on page 996

sa_http_variable_info system procedure


Returns HTTP variable names and values.

Syntax
sa_http_variable_info( [variable_parm] )

Arguments
● variable_parm Use this optional VARCHAR(255) parameter to specify an HTTP variable name.

Result set
Column name Data type Description

Name VARCHAR(255) The HTTP variable name.

Value LONG VARCHAR The HTTP variable value.

Remarks
The sa_http_variable_info system procedure returns variable names and values. If you do not specify the
variable name using the optional parameter, the result set contains values for all variables.

This procedure returns a non-empty result set if it is called while processing an HTTP request within a
web service.

Permissions
None

Side effects
None

1062 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

See also
● “NEXT_HTTP_VARIABLE function [Web service]” on page 285
● “HTTP_VARIABLE function [Web service]” on page 245
● “sa_http_header_info system procedure” on page 1059
● “Web services functions” on page 141
● “Web services system procedures” on page 996

sa_index_density system procedure


Reports information about the amount of fragmentation and skew within indexes.

Syntax
sa_index_density(
[ tbl_name
[, owner_name ] ]
)

Arguments
● tbl_name Use this optional CHAR(128) parameter to specify the table name.

● owner_name Use this optional CHAR(128) parameter to specify the owner name.

Result set
Column Data type Description
name

TableName CHAR(128) The name of a table.

TableId UNSIGNED IN- The table ID.


TEGER

IndexName CHAR(128) The name of an index.

IndexId UNSIGNED IN- The index ID. This column contains one of the following values:
TEGER
● 0 for primary keys

● SYSFKEY.foreign_key_id for foreign keys

● SYSIDX.index_id for all other indexes

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1063


System procedures

Column Data type Description


name

IndexType CHAR(4) The index type. This column contains one of the following val-
ues:

● PKEY for primary keys

● FKEY for foreign keys

● UI for unique indexes

● UC for unique constraints

● NUI for non-unique indexes

LeafPages UNSIGNED IN- The number of leaf pages.


TEGER

Density DOUBLE A fraction between 0 and 1 that provides an indication of how full
each index page is (on average).

Skew DOUBLE A number that provides an indication of the level of unbalance in


an index. A value of 1 indicates a perfectly balanced index. Larg-
er values indicate a higher degree of skew.

Remarks
Use the sa_index_density system procedure to obtain information about the degree of fragmentation and
skew in indexes. For indexes with a high number of leaf pages, higher density values and lower skew
values are desirable.

Index density reflects the average fullness of the index pages, as a percentage. A density of 0.7 indicates
that index pages are, on average, 70% full with index data. Index skew reflects the typical deviation from
the average density. The amount of skew is important to the optimizer when making selectivity estimates.

When the number of leaf pages is low, you do not need to be concerned about density and skew values.
Density and skew values become important only when the number of leaf pages are high. When the
number of leaf pages is high, a low density value can indicate fragmentation, and a high skew value can
indicate that indexes are not well balanced. Both of these can be factors in poor performance. Executing a
REORGANIZE TABLE statement addresses both of these issues.

If you do not specify a table when calling this procedure, the information for all indexes on all tables in
the database is returned.

You can also use the Application Profiling Wizard to determine whether index density and skew are at
acceptable levels.

Permissions
DBA authority

1064 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Side effects
None

See also
● “Reduce index fragmentation and skew” [SQL Anywhere Server - SQL Usage]
● “REORGANIZE TABLE statement” on page 852
● “Using the Application Profiling Wizard” [SQL Anywhere Server - SQL Usage]

Example
The following example uses the sa_index_density system procedure to return a result set summarizing the
amount of fragmentation and skew within all the indexes in the database.
CALL sa_index_density( );

sa_index_levels system procedure


Assists in performance tuning by reporting the number of levels in an index.

Syntax
sa_index_levels(
[ tbl_name
[, owner_name ] ]
)

Arguments
● tbl_name Use this optional CHAR(128) parameter to specify the table name.

● owner_name Use this optional CHAR(128) parameter to specify the owner name.

Result set
Column name Data type Description

TableName CHAR(128) The name of a table.

TableId UNSIGNED IN- The table ID.


TEGER

IndexName CHAR(128) The name of an index.

IndexId UNSIGNED IN- The index ID. This column contains one of the following:
TEGER
● 0 for primary keys

● SYSFKEY.foreign_key_id for foreign keys

● SYSIDX.index_id for all other indexes

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1065


System procedures

Column name Data type Description

IndexType CHAR(4) The index type. This column contains one of the following val-
ues:

● PKEY for primary keys

● FKEY for foreign keys

● UI for unique indexes

● UC for unique constraints

● NUI for non-unique indexes

Levels INTEGER The number of levels in the index.

Remarks
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 few levels are more efficient than indexes with a large number of levels.

The procedure returns a result set containing the table name, the table ID, the index name, the index ID,
the index type, and the number of levels in the index.

If no arguments are supplied, levels are returned for all indexes in the database. If only tbl_name is
supplied, levels for all indexes on that table are supplied. If tbl_name is NULL and an owner_name is
given, only levels for indexes on tables owned by that user are returned.

Permissions
DBA authority

Side effects
None

See also
● “CREATE INDEX statement” on page 553
● “Proper selection of indexes can make a large performance difference” [SQL Anywhere Server - SQL
Usage]

Example
The following example uses the sa_index_levels system procedure to return the number of levels in the
Products index.
CALL sa_index_levels( );

1066 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

TableName TableId IndexName ... Levels

Products 436 Products ... 1

... ... ... ... ...

sa_install_feature system procedure


Installs additional spatial features.

Syntax
sa_install_feature( ' feat_name ' )

Arguments
● feat_name A LONG VARCHAR parameter that identifies the feature to install. The supported
feature names are:

Value Description

st_geometry_prede- Installs predefined units of measure that are not installed by default in new
fined_uom databases.

st_geometry_prede- Installs predefined spatial reference systems and units of measure that are
fined_srs not installed by default in new databases.

st_geometry_com- Installs a set of spatial compatibility functions. These functions can be used
pat_func as an alternative to the spatial methods.

Feature name definitions are provided in the st_geometry_config.tgz file located in the %SQLANY12%
\scripts directory. If the file is removed and you attempt to install features that are dependent on the
file, an error is returned.

Remarks
You can query the feat_name value to see what will be installed. For example, the following query returns
the units of measure that would be installed for st_geometry_predefined_uom.
SELECT * FROM dbo.st_geometry_predefined_uom('CREATE');

The previous example also shows you parameter names so you can query for specific values using a
WHERE clause. For example, the following statement queries the unit_name parameter for the chain unit
of measure:
SELECT * FROM dbo.st_geometry_predefined_uom('CREATE') WHERE
unit_name='chain';

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1067


System procedures

unit_name unit_type conversion_factor ...

chain LINEAR 20.1168 ...

The following returns all units of measure that are based on foot:

SELECT * FROM dbo.st_geometry_predefined_uom() WHERE unit_name LIKE '%foot%';

Use the following query to find the spatial reference systems that would be installed:

SELECT * FROM dbo.st_geometry_predefined_srs();

The following statement queries for a spatial reference system by organization and
organization_coordsys_id:

SELECT * FROM dbo.st_geometry_predefined_srs() WHERE organization='EPSG' AND


organization_coordsys_id=2295;

Permissions
DBA or be a member of the SYS_SPATIAL_ADMIN_ROLE group

See also
● “Spatial reference systems (SRS) and Spatial reference identifiers (SRID)” [SQL Anywhere Server -
Spatial Data Support]
● “Units of measure” [SQL Anywhere Server - Spatial Data Support]
● “Spatial compatibility functions” [SQL Anywhere Server - Spatial Data Support]

Example
The following statement installs all of the predefined units of measure that are not installed by default in a
new database:

CALL sa_install_feature('st_geometry_predefined_uom');

sa_java_loaded_classes system procedure


Lists the classes currently loaded by the database server into a Java VM.

Syntax
sa_java_loaded_classes( )

Result set
Column name Data type Description

class_name VARCHAR(512) The name of a class currently loaded by the database server into a
Java VM.

1068 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Remarks
Returns a result set containing all the names of the Java classes currently loaded by the database server
into a Java VM.

The procedure can be useful to diagnose missing classes. It can also be used to identify which classes
from a particular jar are used by a given application.

Permissions
DBA authority

Side effects
None

See also
● “Installing Java classes into a database” [SQL Anywhere Server - Programming]

sa_list_cursors system procedure


Returns the list of cursors in use by the current connection.

Syntax
sa_list_cursors( )

Result set
Column name Data type Description

handle UNSIGNED INT A unique handle identifying the cursor.

scope INTEGER The scope of the call stack where the cursor is open.

cursor_name VARCHAR(128) The cursor name.

is_open BIT The indicator of whether the cursor is currently open (1).

is_pinned BIT The indicator of whether the cursor is currently pinned in


memory (1) in anticipation of reuse.

fetch_count UNSIGNED BIGINT The number of rows that have been fetched from the cursor.

Remarks
The sa_list_cursors system procedure can be used in a CALL statement or in the FROM clause of a
SELECT statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1069


System procedures

Permissions
None

Side effects
None

See also
● “sa_copy_cursor_to_temp_table system procedure” on page 1028
● “sa_describe_cursor system procedure” on page 1035

Example
The following example returns the list of open cursors for the connection:
CALL sa_list_cursors();

sa_load_cost_model system procedure


Replaces the current cost model with the cost model stored in the specified file.

Syntax
sa_load_cost_model ( file_name )

Arguments
● file_name Use this CHAR(1024) parameter to specify the name of the cost model file to load.

Remarks
The optimizer uses cost models to determine optimal access plans for queries. The database server
maintains a cost model for each database. The cost model for a database can be recalibrated at any time
using the CALIBRATE SERVER clause of the ALTER DATABASE statement. For example, you might
decide to recalibrate the cost model if you move the database onto non-standard hardware.

The sa_load_cost_model system procedure allows you to load a cost model that has been saved to file
(file_name). Loading a cost model replaces the current cost model for the database.

Note
The sa_unload_cost_model system procedure does not include CALIBRATE PARALLEL READ
information in the file that sa_load_cost_model loads.

Using the sa_load_cost_model system procedure can eliminate repetitive, time-consuming recalibration
activities when there is a large number of identical hardware installations.

Exclusive use of the database is required when loading the new cost model.

When loading a cost model, consider whether it was generated for a database that is located on similar
hardware. Loading a cost model from a database that is stored on significantly different hardware may
cause poor performance due to inefficient access plans.

1070 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Cost models are saved to file using the sa_unload_cost_model system procedure.

Permissions
DBA authority

Side effects
The database server performs a COMMIT after loading the new cost model.

See also
● “ALTER DATABASE statement” on page 400
● “sa_unload_cost_model system procedure” on page 1154
● “Advanced: Query optimization” [SQL Anywhere Server - SQL Usage]

Example
The following example loads the cost model from a file called costmodel8:
CALL sa_load_cost_model( 'costmodel8' );

sa_locks system procedure


Displays all locks in the database.

Syntax
sa_locks(
[ connection
[ , creator
[ , table_name
[ , max_locks ] ] ] ]
)

Arguments
● connection Use this INTEGER parameter to specify a connection ID number. The procedure
returns lock information only about the specified connection. The default value is 0 (or NULL), in
which case information is returned about all connections.

● creator Use this CHAR(128) parameter to specify a user ID. The procedure returns information
only about the tables owned by the specified user. The default value for the creator parameter is
NULL. When this parameter is set to NULL, sa_locks returns the following information:

○ if the table_name parameter is unspecified, locking information is returned for all tables in the
database

○ if the table_name parameter is specified, locking information is returned for tables with the
specified name that were created by the current user

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1071


System procedures

● table_name Use this CHAR(128) parameter to specify 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.

● max_locks Use this INTEGER parameter to specify the maximum number of locks for which to
return information. The default value is 1000. The value -1 means return all lock information.

Result set
Column name Data type Description

conn_name VARCHAR(128) The name of the current connection.

conn_id INTEGER The connection ID number.

user_id CHAR(128) The user ID for the connection.

table_type CHAR(6) The type of table. This type is either BASE for a table,
GLBTMP for global temporary table, or MVIEW for a materi-
alized view.

creator VARCHAR(128) The owner of the table.

table_name VARCHAR(128) The table on which the lock is held.

index_id INTEGER The index ID or NULL.

lock_class CHAR(8) The lock class. One of Schema, Row, Table, or Position.

lock_duration CHAR(11) The duration of the lock. One of Transaction, Position, or


Connection.

lock_type CHAR(9) The lock type (this is dependent on the lock class).

row_identifier UNSIGNED BI- The identifier for the row. This is either an 8-byte row identifi-
GINT er or NULL.

Remarks
The sa_locks procedure returns a result set containing information about all the locks in the database.

The value in the lock_type column depends on the lock classification in the lock_class column. The
following values can be returned:

1072 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Lock Lock types Comments


class

Sche- Shared (shared schema For schema locks, the row_identifier and index ID values are
ma lock) NULL.

Exclusive (exclusive
schema lock)

Row Read (read lock) Row read locks can be short-term locks (scans at isolation level
1) or can be long-term locks at higher isolation levels. The
Intent (intent lock) lock_duration column indicates whether the read lock is of short
duration because of cursor stability (Position) or long duration,
ReadPK (read lock) held until COMMIT/ROLLBACK (Transaction). Row locks are
always held on a specific row, whose 8-byte row identifier is re-
Write (write lock)
ported as a 64-bit integer value in the row_identifier column. A
WriteNoPK (write lock) surrogate lock is a special case of a row lock. Surrogate locks are
held on surrogate entries, which are created when referential in-
Surrogate (surrogate tegrity checking is delayed.
lock)
There is not a unique surrogate lock for every surrogate entry
created in a table. Rather, a surrogate lock corresponds to the set
of surrogate entries created for a given table by a given connec-
tion. The row_identifier value is unique for the table and connec-
tion associated with the surrogate lock.

If required, key and non-key portions of a row can be locked in-


dependently. A connection can obtain a read lock on the key por-
tion of a row for shared (read) access so that other connections
can still obtain write locks on other non-key columns of a row.
Updating non-key columns of a row does not interfere with the
insertion and deletion of foreign rows referencing that row.

Table Shared (shared table See “Table locks” [SQL Anywhere Server - SQL Usage].
lock)

Intent (intent to update


table lock)

Exclusive (exclusive ta-


ble lock)

Posi- Phantom (phantom lock) Usually a position lock is also held on a specific row, and that
tion row's 64-bit row identifier appears in the row_identifier column
Insert (insert lock) in the result set. However, Position locks can be held on entire
scans (index or sequential), in which case the row_identifier col-
umn is NULL.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1073


System procedures

A position lock can be associated with a sequential table scan, or an index scan. The index_id column
indicates whether the position lock is associated with a sequential scan. If the position lock is held
because of a sequential scan, the index_id column is NULL. If the position lock is held as the result of a
specific index scan, the index identifier of that index is listed in the index_id column. The index identifier
corresponds to the primary key of the ISYSIDX system table, which can be viewed using the SYSIDX
view. If the position lock is held for scans over all indexes, the index ID value is -1.

Permissions
DBA authority

Side effects
None

See also
● “How locking works” [SQL Anywhere Server - SQL Usage]
● “SYSIDX system view” on page 1211
● “Objects that can be locked” [SQL Anywhere Server - SQL Usage]
● “Schema locks” [SQL Anywhere Server - SQL Usage]
● “Locks during inserts” [SQL Anywhere Server - SQL Usage]
● “Row locks” [SQL Anywhere Server - SQL Usage]
● “Position locks” [SQL Anywhere Server - SQL Usage]

Example
For an example of this system procedure, and tips to augment the amount of information you can return,
see “How to obtain information about locks” [SQL Anywhere Server - SQL Usage].

sa_make_object system procedure


Ensures that a skeletal instance of an object exists before executing an ALTER statement.

Syntax
sa_make_object(
objtype,
objname
[, owner
[, tabname ] ]
)

objtype:
'procedure'
| 'function'
| 'view'
| 'trigger'
| 'service'
| 'event'

1074 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Arguments
● objtype Use this CHAR(30) parameter to specify the type of object being created. If objtype is
'trigger', this argument specifies the owner of the table on which the trigger is to be created.

● objname Use this CHAR(128) parameter to specify the name of the object to be created.

● owner Use this optional CHAR(128) parameter to specify the owner of the object to be created.
The default value is CURRENT USER.

● tabname This CHAR(128) parameter is required only if objtype is 'trigger', in which case you use
it to specify the name of the table on which the trigger is to be created.

Remarks
This procedure is useful in scripts that are run repeatedly to create or modify a database schema. A
common problem in such scripts is that the first time they are run, a CREATE statement must be
executed, but subsequent times an ALTER statement must be executed. This procedure avoids the
necessity of querying the system views to find out whether the object exists.

To use the procedure, follow it by an ALTER statement that contains the entire object definition.

Permissions
Resource authority is required to create or modify database objects

Side effects
Automatic commit

See also
● “ALTER EVENT statement” on page 408
● “ALTER FUNCTION statement” on page 412
● “ALTER PROCEDURE statement” on page 423
● “ALTER TRIGGER statement” on page 469
● “ALTER VIEW statement” on page 472
● “ALTER SERVICE statement [HTTP web service]” on page 431
● “ALTER SERVICE statement [SOAP web service]” on page 436

Examples
The following statements ensure that a skeleton procedure definition is created, define the procedure, and
grant permissions on it. A script file containing these instructions could be run repeatedly against a
database without error.
CALL sa_make_object( 'procedure','myproc' );
ALTER PROCEDURE myproc( in p1 INT, in p2 CHAR(30) )
BEGIN
// ...
END;
GRANT EXECUTE ON myproc TO public;

The following example uses the sa_make_object system procedure to add a skeleton web service.
CALL sa_make_object( 'service','my_web_service' );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1075


System procedures

sa_materialized_view_can_be_immediate system
procedure
Returns whether the specified materialized view can be defined as immediate.

Syntax
sa_materialized_view_can_be_immediate(
view_name
, owner_name
)

Arguments
● view_name Use this CHAR(128) parameter to specify the name of the materialized view. If
view_name is NULL, an error is returned.

● owner_name Use this CHAR(128) parameter to specify the owner of the materialized view. If
owner_name is NULL, an error is returned.

Remarks
There are restrictions on whether the specified manual view can be changed to an immediate view. Use
this system procedure to determine whether the change is permitted.

The sa_materialized_view_can_be_immediate system procedure returns the following information for the
specified materialized view.

Column name Data type Description

SQLStateVal CHAR(6) The SQLSTATE returned.

ErrorMessage LONG VARCHAR The error message corresponding to the SQLSTATE.

Each row in the result set corresponds to a single SQLSTATE returned for a view. So, if the materialized
view definition violates more than one restriction, the results include multiple rows for the view.

You can combine the output of this system procedure with the output of the sa_materialized_view_info
system procedure to get information about the status of views and whether they can be made immediate.

Permissions
DBA authority, or execute permissions on DBO owned procedures.

See also
● “Advanced: Changing refresh type for a materialized view” [SQL Anywhere Server - SQL Usage]
● “Restrictions when changing a materialized view from manual to immediate” [SQL Anywhere Server -
SQL Usage]
● “sa_materialized_view_info system procedure” on page 1077

1076 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Side effects
All metadata for the specified materialized view, and all dependencies, are loaded into the server cache.

Example
Execute the following statements to create a manual view, view10, and refresh it:

CREATE MATERIALIZED VIEW view10


AS (SELECT C.ID, C.Surname, sum(P.UnitPrice) as revenue, C.CompanyName,
SO.OrderDate
FROM Customers C, SalesOrders SO, SalesOrderItems SOI, Products P
WHERE C.ID = SO.CustomerID
AND SO.ID = SOI.ID
AND P.ID = SOI.ProductID
GROUP BY C.ID, C.Surname, C.CompanyName, SO.OrderDate);
REFRESH MATERIALIZED VIEW view10;

Use the following query to find the reasons why view10 cannot be changed to an immediate view:

SELECT SQLStateVal AS "SQLstate", ErrorMessage AS Description


FROM sa_materialized_view_can_be_immediate( 'view10', 'DBA' )
ORDER BY SQLSTATE;

SQLstate Description

42WC3 See “The materialized view %1 cannot be changed to immediate because it has already
been initialized” [Error Messages].

42WCA See “The materialized view %1 cannot be changed to immediate because it does not have
a unique index on non-nullable columns” [Error Messages].

42WC6 See “The materialized view cannot be changed to immediate because COUNT(*) must be
part of the SELECT list” [Error Messages].

42WC7 See “The materialized view cannot be changed to immediate because it does not have a
unique index on non-aggregate, non-nullable columns” [Error Messages].

sa_materialized_view_info system procedure


Returns information about the specified materialized views.

Syntax
sa_materialized_view_info(
[ view_name
[, owner_name ] ]
)

Arguments
● view_name Use this optional CHAR(128) parameter to specify the name of the materialized view
for which to return information.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1077


System procedures

● owner_name Use this optional CHAR(128) parameter to specify the owner of the materialized
view.

Remarks
If neither view_name nor owner_name are specified, information about all materialized views in the
database is returned.

If owner_name is not specified, information about all materialized views named view_name is returned.

The sa_materialized_view_info system procedure returns the following information for a materialized
view:

Column Data type Description


name

OwnerName CHAR(128) The owner of the view.

ViewName CHAR(128) The name of the view.

Status CHAR(1) Status information about the view. Possible values are:

● D disabled

● E enabled

DataStatus CHAR(1) Status information about data in the view. Possible values are:

● E An error occurred during the last refresh attempt. The view is


enabled, but uninitialized.

● F The underlying tables have not changed since the last refresh,
and the view is considered fresh. The view is enabled and initial-
ized.

● N The view is uninitialized. This occurs when one of the follow-


ing is true:

○ the view has not been refreshed since it was created

○ the data has been truncated from the view

○ the view is disabled

● S An underlying table has changed since the last refresh, and the
view is considered stale. The view is enabled and initialized.

ViewLas- TIME- The time when the view was last refreshed. If the value of ViewLas-
tRefreshed STAMP tRefreshed is NULL, the view is uninitialized.

1078 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Column Data type Description


name

DataLast- TIME- For a stale view, the last time that underlying data was modified.
Modified STAMP
The value is NULL for views that are not initialized, or for views that
are not considered stale.

AvailFor- CHAR(1) Information about the availability of the view for use by the optimizer.
Optimiza- Possible values are:
tion
● D Use by the optimizer is disabled. The owner of the view
doesn't allow the view to be used by the optimizer.

● I The view cannot be used by the optimizer for some internal rea-
son, for example its definition doesn't meet the conditions required.
However, the owner has not explicitly disallowed its use by the op-
timizer.

● N The view contains no data because a refresh has not been done
or has failed. The view can be used by the optimizer by the owner
of the view, but it is not initialized.

● O There is an incompatible option value for current connection.


The view can be used by the optimizer and its definition meets all
the required conditions, but the current option settings are not com-
patible with the options settings used to create the view.

● Y The view can be used by the optimizer. The owner of the view
allows the view to be used by the optimizer and the view definition
meets all the conditions needed to be used by the optimizer.

Refresh- CHAR(1) The refresh type for the view. Possible values are:
Type
● I The view is an immediate view. Immediate views are refreshed
immediately when changes to the data in an underlying table im-
pact the data in the materialized view.

● M The view is a manual view. Manual views are refreshed man-


ually, for example using the REFRESH MATERIALIZED VIEW
statement, or the sa_refresh_materialized_views system procedure.

This procedure can be useful for determining the list of materialized views that will never be considered
by the optimizer because of a problem with the view definition. The AvailForOptimization value is I for
these materialized views.

The following table shows how the AvailForOptimization property is determined. Starting from the left
column, you read across the row to see the conditions that must be in place to result in the value found in
the AvailForOptimization column.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1079


System procedures

User allows view The view The connection The view is AvailForOptimization
to be used in definition options match initialized? value
optimization? satisfies all the those required
conditions for use of the
required for view?
use?

Yes Yes Yes Yes Y

No N/A N/A N/A D

Yes No N/A Yes I

Yes N/A N/A No N

Yes Yes No Yes O

An initialized materialized view can be empty. This occurs when there is no data in the underlying tables
that meets the materialized view definition. An empty view is not considered the same as an uninitialized
materialized view, which also has no data in it. The value of the ViewLastRefreshed property allows you
to distinguish between whether the view is uninitialized (NULL), or empty because of data in the
underlying tables (non-NULL).

Permissions
DBA authority, or execute permissions on DBO owned procedures.

Side effects
All metadata for the specified materialized views, and all dependencies, are loaded into the database
server cache.

See also
● “Materialized views” [SQL Anywhere Server - SQL Usage]
● “Advanced: Changing refresh type for a materialized view” [SQL Anywhere Server - SQL Usage]
● “Restrictions when changing a materialized view from manual to immediate” [SQL Anywhere Server -
SQL Usage]
● “sa_materialized_view_can_be_immediate system procedure” on page 1076
● “Determining which materialized views were considered by the optimizer” [SQL Anywhere Server -
SQL Usage]
● “Materialized views restrictions” [SQL Anywhere Server - SQL Usage]`
● “Whether to set refresh type to manual or immediate” [SQL Anywhere Server - SQL Usage]

Example
The following statement returns information about all materialized views in the database:

SELECT *
FROM sa_materialized_view_info();

1080 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

The results of the sa_materialized_view_info system procedure can be combined with the results of the
sa_materialized_view_can_be_immediate system procedure to return status information, and whether the
view is eligible for being an immediate view. Execute the following statements to create materialized
views that are examined for this example:
CREATE MATERIALIZED VIEW view0 AS (
SELECT ID, Name, Description, Size
FROM Products
WHERE Quantity > 0 );
CREATE UNIQUE INDEX u_view0
ON view0( ID );
ALTER MATERIALIZED VIEW view0
IMMEDIATE REFRESH;
CREATE MATERIALIZED VIEW view00 AS (
SELECT ID, Name, Description, Size
FROM Products
WHERE Quantity <= 0 );
CREATE UNIQUE INDEX u_view00
ON view00( ID );
CREATE MATERIALIZED VIEW view1 AS (
SELECT ID, Name, Description, Size
FROM Products
WHERE Quantity = 0 );
ALTER MATERIALIZED VIEW view1
DISABLE;
CREATE MATERIALIZED VIEW view100
AS (SELECT C.ID, C.Surname, sum(P.UnitPrice) as revenue, C.CompanyName,
SO.OrderDate
FROM Customers C, SalesOrders SO, SalesOrderItems SOI, Products P
WHERE C.ID = SO.CustomerID
AND SO.ID = SOI.ID
AND P.ID = SOI.ProductID
GROUP BY C.ID, C.Surname, C.CompanyName, SO.OrderDate);
REFRESH MATERIALIZED VIEW view100;

Execute the following statement to return the status and eligibility information for the views you just
created:
SELECT ViewName, Status, ViewLastRefreshed, AvailForOptimization,
RefreshType, CanBeImmediate
FROM sa_materialized_view_info() AS V,
LATERAL( SELECT LIST( ErrorMessage, '' )
FROM sa_materialized_view_can_be_immediate( V.ViewName,
V.OwnerName ) ) AS I( CanBeImmediate );;

ViewName Status ViewLastRefreshed AvailForOptimization RefreshType CanBeImmediate

view0 E (NULL) N I

view00 E (NULL) N M

view1 D (NULL) N M Cannot use


view 'view1'
because it
has been
disabled

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1081


System procedures

ViewName Status ViewLastRefreshed AvailForOptimization RefreshType CanBeImmediate

view100 E 2008-02-12 Y M The materi-


16:47:00.000 alized view
view100 can-
not be
changed to
immediate
because it
has already
been ini-
tialized.
The materi-
alized view
view100 can-
not be
changed to
immediate
because it
does not
have a
unique index
on non-nul-
lable col-
umns. The
materialized
view cannot
be changed
to immediate
because
COUNT(*) is
required to
be part of
the SELECT
list. The
materialized
view cannot
be changed
to immediate
because it
does not
have a
unique index
on non-ag-
gregate non-
nullable
columns.

1082 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

From the results you can see that:

● view0 was never refreshed and is an immediate view.

● view00 was never refreshed and is a manual view.

● view1 is disabled

● view100 is a manual view that was last refreshed at 2008-02-12 16:47:00.000.

● view00 can be changed to an immediate view because there are no error messages in the
CanBeImmediate column.

● view1 and view100 cannot be changed to immediate views for the reasons listed in the
CanBeImmediate column.

sa_migrate system procedure


Migrates a set of remote tables to a SQL Anywhere database.

Syntax
sa_migrate(
base_table_owner,
server_name
[, table_name ]
[, owner_name ]
[, database_name ]
[, migrate_data ]
[, drop_proxy_tables ]
[, migrate_fkeys ]
)

Arguments
● base_table_owner Use this VARCHAR(128) parameter to specify the user on the target SQL
Anywhere database who owns the migrated tables. Use the GRANT CONNECT statement to create
this user. A value is required for this parameter.

● server_name Use this VARCHAR(128) parameter to specify the name of the remote server that is
being used to connect to the remote database. Use the CREATE SERVER statement to create this
server. A value is required for this parameter.

● table_name If you are migrating a single table, use this VARCHAR(128) parameter to specify the
table name. Otherwise, you should specify NULL (the default) for this parameter. Do not specify
NULL for both the table_name and owner_name parameters.

● owner_name If you are migrating only tables that belong to one owner, use this VARCHAR(128)
parameter to specify the owner's name. Otherwise, you should enter NULL (the default) for this
parameter. Do not specify NULL for both the table_name and owner_name parameters.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1083


System procedures

● database_name Use this VARCHAR(128) parameter to specify the name of the remote database.
You must specify the database name if you want to migrate tables from only one database on the
remote server. Otherwise, enter NULL (the default) for this parameter.

● migrate_data Use this optional BIT parameter to specify whether the data in the remote tables is
migrated. This parameter can be 0 (do not migrate data) or 1 (migrate data). By default, data is
migrated. (1)

● drop_proxy_tables Use this optional BIT parameter to specify whether the proxy tables created
for the migration process are dropped once the migration is complete. This parameter can be 0 (proxy
tables are not dropped) or 1 (proxy tables are dropped). By default, the proxy tables are dropped (1).

● migrate_fkeys Use this optional BIT parameter to specify whether the foreign key mappings are
migrated. This parameter can be 0 (do not migrate foreign key mappings) or 1 (migrate foreign key
mappings). By default, the foreign key mappings are migrated (1).

Remarks
You can use this procedure to migrate tables to SQL Anywhere from a remote Oracle, IBM DB2,
Microsoft SQL Server, Adaptive Server Enterprise, or SQL Anywhere database. This procedure allows
you to migrate in one step a set of remote tables, including their foreign key mappings, from the specified
server. The sa_migrate system procedure calls the following system procedures:

● sa_migrate_create_remote_table_list
● sa_migrate_create_tables
● sa_migrate_data
● sa_migrate_create_remote_fks_list
● sa_migrate_create_fks
● sa_migrate_drop_proxy_tables

You might want to use these system procedures instead of sa_migrate if you need more flexibility. For
example, if you are migrating tables with foreign key relationships that are owned by different users, you
cannot retain the foreign key relationships if you use sa_migrate.

Before you can migrate any tables, you must first create a remote server to connect to the remote database
using the CREATE SERVER statement. You may also need to create an external login to the remote
database using the CREATE EXTERNLOGIN statement.

You can migrate all the tables from the remote database to a SQL Anywhere database by specifying only
the base_table_owner and server_name parameters. However, if you specify only these two parameters,
all the tables that are migrated will belong to one owner in the target SQL Anywhere database. If tables
have different owners on the remote database and you want them to have different owners on the SQL
Anywhere database, then you must migrate the tables for each owner separately, specifying the
base_table_owner and owner_name parameters each time you call the sa_migrate procedure.

1084 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Caution
Do not specify NULL for both the table_name and owner_name parameters. Supplying NULL for both
the table_name and owner_name parameters migrates all the tables in the database, including system
tables. As well, tables that have the same name, but different owners in the remote database all belong to
one owner in the target database. It is recommended that you migrate tables associated with one owner at
a time.

Permissions
None

Side effects
None

See also
● “Database migration to SQL Anywhere” [SQL Anywhere Server - SQL Usage]
● “CREATE EXTERNLOGIN statement” on page 534
● “CREATE SERVER statement” on page 601
● “GRANT statement” on page 760
● “sa_migrate_create_remote_table_list system procedure” on page 1088
● “sa_migrate_create_tables system procedure” on page 1089
● “sa_migrate_data system procedure” on page 1090
● “sa_migrate_create_remote_fks_list system procedure” on page 1087
● “sa_migrate_create_fks system procedure” on page 1085
● “sa_migrate_drop_proxy_tables system procedure” on page 1091

Examples
The following statement migrates all the tables belonging to user p_chin from the remote database,
including foreign key mappings; migrates the data in the remote tables; and drops the proxy tables when
migration is complete. In this example, all the tables that are migrated belong to local_user in the target
SQL Anywhere database.

CALL sa_migrate( 'local_user', 'server_a', NULL, 'p_chin', NULL, 1, 1, 1 );

The following statement migrates only the tables that belong to user remote_a from the remote database.
In the target SQL Anywhere database, these tables belong to the user local_a. Proxy tables created during
the migration are not dropped at completion.

CALL sa_migrate( 'local_a', 'server_a', NULL, 'remote_a', NULL, 1, 0, 1 );

sa_migrate_create_fks system procedure


Creates foreign keys for each table listed in the dbo.migrate_remote_fks_list table.

Syntax
sa_migrate_create_fks( i_table_owner )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1085


System procedures

Arguments
● i_table_owner Use this VARCHAR(128) parameter to specify the user on the target SQL
Anywhere database who owns the migrated foreign keys. If you want to migrate tables that belong to
different user, you must execute this procedure for each user whose tables you want to migrate. The
i_table_owner is created using the GRANT CONNECT statement. A value is required for this
parameter.

Remarks
This procedure creates foreign keys for each table that is listed in the dbo.migrate_remote_fks_list table.
The user specified by the i_table_owner argument owns the foreign keys in the target database.

If the tables in the target SQL Anywhere database do not all have the same owner, you must execute this
procedure for each user who owns tables for which you need to migrate foreign keys.

Note
This system procedure is used in conjunction with several other migration system procedures, which must
be executed in sequence as listed below:

1. sa_migrate_create_remote_table_list

2. sa_migrate_create_tables

3. sa_migrate_data

4. sa_migrate_create_remote_fks_list

5. sa_migrate_create_fks

6. sa_migrate_drop_proxy_tables

As an alternative, you can migrate all tables in one step using the sa_migrate system procedure.

Permissions
None

Side effects
None

See also
● “Database migration to SQL Anywhere” [SQL Anywhere Server - SQL Usage]
● “GRANT statement” on page 760
● “sa_migrate system procedure” on page 1083
● “sa_migrate_create_remote_table_list system procedure” on page 1088
● “sa_migrate_create_tables system procedure” on page 1089
● “sa_migrate_data system procedure” on page 1090
● “sa_migrate_create_remote_fks_list system procedure” on page 1087
● “sa_migrate_drop_proxy_tables system procedure” on page 1091

1086 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Example
The following statement creates foreign keys based on the dbo.migrate_remote_fks_list table. The foreign
keys belong to the user local_a on the local SQL Anywhere database.
CALL sa_migrate_create_fks( 'local_a' );

sa_migrate_create_remote_fks_list system procedure


Populates the dbo.migrate_remote_fks_list table.

Syntax
sa_migrate_create_remote_fks_list( server_name )

Arguments
● server_name Use this VARCHAR(128) parameter to specify the name of the remote server that is
being used to connect to the remote database. The remote server is created with the CREATE
SERVER statement. A value is required for this parameter.

Remarks
This procedure populates the dbo.migrate_remote_fks_list table with a list of foreign keys that can be
migrated from the remote database. You can delete rows from this table for foreign keys that you do not
want to migrate.

As an alternative, you can migrate all tables in one step using the sa_migrate system procedure.

This system procedure is used in conjunction with several other migration system procedures. The note in
the Remarks section of the sa_migrate_create_fks system procedure contains the list of migrate
procedures, and the order in which you must execute them.

Permissions
None

Side effects
None

See also
● “CREATE SERVER statement” on page 601
● “Database migration to SQL Anywhere” [SQL Anywhere Server - SQL Usage]
● “sa_migrate system procedure” on page 1083
● “sa_migrate_create_remote_table_list system procedure” on page 1088
● “sa_migrate_create_tables system procedure” on page 1089
● “sa_migrate_data system procedure” on page 1090
● “sa_migrate_create_fks system procedure” on page 1085
● “sa_migrate_drop_proxy_tables system procedure” on page 1091

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1087


System procedures

Example
The following statement creates a list of foreign keys that are in the remote database.
CALL sa_migrate_create_remote_fks_list( 'server_a' );

sa_migrate_create_remote_table_list system procedure


Populates the dbo.migrate_remote_table_list table.

Syntax
sa_migrate_create_remote_table_list(
i_server_name
[, i_table_name
[, i_owner_name
[, i_database_name ] ] ]
)

Arguments
● i_server_name Use this VARCHAR(128) parameter to specify the name of the remote server that
is being used to connect to the remote database. The remote server is created with the CREATE
SERVER statement. A value is required for this parameter.

● i_table_name Use this optional VARCHAR(128) parameter to specify the name(s) of the tables
that you want to migrate, or NULL to migrate all the tables. The default is NULL. Do not specify
NULL for both the i_table_name and i_owner_name parameters.

● i_owner_name Use this optional VARCHAR(128) parameter to specify the user who owns the
tables on the remote database that you want to migrate, or NULL to migrate all the tables. The default
is NULL. Do not specify NULL for both the i_table_name and i_owner_name parameters

● i_database_name Use this optional VARCHAR(128) parameter to specify the name of the remote
database from which you want to migrate tables. This parameter is NULL by default. When migrating
tables from Adaptive Server Enterprise and Microsoft SQL Server databases, you must specify the
database name.

Remarks
This procedure populates the dbo.migrate_remote_table_list table with a list of tables that can be migrated
from the remote database. You can delete rows from this table for remote tables that you do not want to
migrate.

If you do not want all the migrated tables to have the same owner on the target SQL Anywhere database,
you must execute this procedure for each user whose tables you want to migrate.

As an alternative, you can migrate all tables in one step using the sa_migrate system procedure.

1088 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Caution
Do not specify NULL for both the i_table_name and i_owner_name parameters. Supplying NULL for
both the i_table_name and i_owner_name parameters migrates all the tables in the database, including
system tables. As well, tables that have the same name, but different owners in the remote database all
belong to one owner in the target database. It is recommended that you migrate tables associated with one
owner at a time.

This system procedure is used in conjunction with several other migration system procedures. The note in
the Remarks section of the sa_migrate_create_fks system procedure contains the list of migrate
procedures, and the order in which you must execute them.

Permissions
None

Side effects
None

See also
● “CREATE SERVER statement” on page 601
● “Database migration to SQL Anywhere” [SQL Anywhere Server - SQL Usage]
● “sa_migrate system procedure” on page 1083
● “sa_migrate_create_tables system procedure” on page 1089
● “sa_migrate_data system procedure” on page 1090
● “sa_migrate_create_remote_fks_list system procedure” on page 1087
● “sa_migrate_create_fks system procedure” on page 1085
● “sa_migrate_drop_proxy_tables system procedure” on page 1091

Example
The following statement creates a list of tables that belong to the user remote_a on the remote database.
CALL sa_migrate_create_remote_table_list( 'server_a', NULL, 'remote_a',
NULL );

sa_migrate_create_tables system procedure


Creates a proxy table and base table for each table listed in the dbo.migrate_remote_table_list table.

Syntax
sa_migrate_create_tables( i_table_owner )

Arguments
● i_table_owner Use this VARCHAR(128) parameter to specify the user on the target SQL
Anywhere database who owns the migrated tables. This user is created using the GRANT CONNECT
statement. A value is required for this parameter.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1089


System procedures

Remarks
This procedure creates a base table and proxy table for each table listed in the
dbo.migrate_remote_table_list table (created using the sa_migrate_create_remote_table_list procedure).
These proxy tables and base tables are owned by the user specified by the i_table_owner argument. This
procedure also creates the same primary key indexes and other indexes for the new table that the remote
table has in the remote database.

If you do not want all the migrated tables to have the same owner on the target SQL Anywhere database,
you must execute the sa_migrate_create_remote_table_list procedure and the sa_migrate_create_tables
procedure for each user who will own migrated tables.

As an alternative, you can migrate all tables in one step using the sa_migrate system procedure.

This system procedure is used in conjunction with several other migration system procedures. The note in
the Remarks section of the sa_migrate_create_fks system procedure contains the list of migrate
procedures, and the order in which you must execute them.

Permissions
None

Side effects
None

See also
● “Database migration to SQL Anywhere” [SQL Anywhere Server - SQL Usage]
● “sa_migrate system procedure” on page 1083
● “sa_migrate_create_remote_table_list system procedure” on page 1088
● “sa_migrate_data system procedure” on page 1090
● “sa_migrate_create_remote_fks_list system procedure” on page 1087
● “sa_migrate_create_fks system procedure” on page 1085
● “sa_migrate_drop_proxy_tables system procedure” on page 1091

Example
The following statement creates base tables and proxy tables on the target SQL Anywhere database.
These tables belong to the user local_a.
CALL sa_migrate_create_tables( 'local_a' );

sa_migrate_data system procedure


Migrates data from the remote database tables to the target SQL Anywhere database.

Syntax
sa_migrate_data( i_table_owner )

1090 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Arguments
● i_table_owner Use this VARCHAR(128) parameter to specify the user on the target SQL
Anywhere database who owns the migrated tables. This user is created using the GRANT CONNECT
statement. A value is required for this parameter.

Remarks
This procedure migrates the data from the remote database to the SQL Anywhere database for tables
belonging to the user specified by the i_table_owner argument.

When the tables on the target SQL Anywhere database do not all have the same owner, you must execute
this procedure for each user whose tables have data that you want to migrate.

As an alternative, you can migrate all tables in one step using the sa_migrate system procedure.

This system procedure is used in conjunction with several other migration system procedures.

Permissions
None

Side effects
None

See also
● “Database migration to SQL Anywhere” [SQL Anywhere Server - SQL Usage]
● “sa_migrate system procedure” on page 1083
● “sa_migrate_create_remote_table_list system procedure” on page 1088
● “sa_migrate_create_tables system procedure” on page 1089
● “sa_migrate_create_remote_fks_list system procedure” on page 1087
● “sa_migrate_create_fks system procedure” on page 1085
● “sa_migrate_drop_proxy_tables system procedure” on page 1091

Example
The following statement migrates data to the target SQL Anywhere database for tables that belong to the
user local_a.
CALL sa_migrate_data( 'local_a' );

sa_migrate_drop_proxy_tables system procedure


Drops the proxy tables that were created for migration purposes.

Syntax
sa_migrate_drop_proxy_tables( i_table_owner )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1091


System procedures

Arguments
● i_table_owner Use this VARCHAR(128) parameter to specify the user on the target SQL
Anywhere database who owns the proxy tables. This user is created using the GRANT CONNECT
statement. A value is required for this parameter.

Remarks
This procedure drops the proxy tables that were created for the migration. The user who owns these proxy
tables is specified by the i_table_owner argument.

If the migrated tables are not all owned by the same user on the target SQL Anywhere database, you must
call this procedure for each user to drop all the proxy tables.

As an alternative, you can migrate all tables in one step using the sa_migrate system procedure.

This system procedure is used in conjunction with several other migration system procedures. The note in
the Remarks section of the sa_migrate_create_fks system procedure contains the list of migrate
procedures, and the order in which you must execute them.

Permissions
None

Side effects
None

See also
● “Database migration to SQL Anywhere” [SQL Anywhere Server - SQL Usage]
● “sa_migrate system procedure” on page 1083
● “sa_migrate_create_remote_table_list system procedure” on page 1088
● “sa_migrate_create_tables system procedure” on page 1089
● “sa_migrate_data system procedure” on page 1090
● “sa_migrate_create_remote_fks_list system procedure” on page 1087
● “sa_migrate_create_fks system procedure” on page 1085

Example
The following statement drops the proxy tables on the target SQL Anywhere database that belong to the
user local_a.
CALL sa_migrate_drop_proxy_tables( 'local_a' );

sa_mirror_server_status system procedure


Returns the connection status of the current servers and all the servers that are directly or indirectly
receiving log pages from the current server. On primary servers, the procedure returns the status of all
connected servers.

1092 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Syntax
sa_mirror_server_status( )

Result set
Column name Data type Description

server_name CHAR(128) The name of the server.

state CHAR(20) The connection status of the server. It can be one of the fol-
lowing values:

● connected
● disconnected

last_updated TIMESTAMP The time the server status was last updated.
WITH TIME
ZONE

load_current DOUBLE The amount of work that the database server is currently
performing.

load_last_1_min DOUBLE The amount of work that the database server has performed
in the previous minute.

load_last_5_mins DOUBLE The amount of work that the database server has performed
in the previous 5 minutes.

load_last_10_mins DOUBLE The amount of work that the database server has performed
in the previous 10 minutes.

num_connections UNSIGNED INT The number of connections to the database server.

num_processors UNSIGNED INT The number of database server processors.

log_written UNSIGNED BI- The latest transaction log position written to disk based on
GINT the last update received from the server.

log_applied UNSIGNED BI- The last operation from the transaction log that has been ap-
GINT plied based on the last update received from the server.
This value is the same as the value of the CurrentRedoPos
property

Remarks
Each server updates its status and that of its copy nodes every 5 seconds. On mirror servers, the procedure
returns the status of any copy nodes that are receiving log pages from the mirror server, but does not
return the status of the primary server. The columns with the prefix load represent a computed load on the
database server. The value returned represents the database server load, and not the load from other
processes. Higher load values indicate that the database server has more work to perform.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1093


System procedures

When the NodeType connection parameter is specified, the database server uses load information to
redirect connections. The database server selects the mirror server with the lowest load; if all servers have
the same load, the server with the fewest connections is used.

Note
For database servers running in the cloud, the NodeType connection parameter does not use load
information to redirect connections.

Permissions
None

Side effects
None

See also
● “CurrentRedoPos database property” [SQL Anywhere Server - Database Administration]
● “NodeType (NODE) connection parameter” [SQL Anywhere Server - Database Administration]
● “Database mirroring” [SQL Anywhere Server - Database Administration]
● “CREATE MIRROR SERVER statement” on page 564
● “ALTER MIRROR SERVER statement” on page 420
● “DROP MIRROR SERVER statement” on page 699

sa_nchar_terms system procedure


Breaks an NCHAR string into terms and returns each term as a row along with its position.

Syntax
sa_nchar_terms( 'text' [, 'config_name' [, 'owner' ] ]
)

Arguments
● text The NCHAR string you are parsing.

● config_name The text configuration object to apply when processing the string. The default is
'default_nchar'.

● owner The owner of the specified text configuration object. The default value is NULL, and the
current user is assumed if the owner is not specified or if NULL is specified.

Remarks
You can use this system procedure to find out how a string is interpreted when the settings for a text
configuration object are applied. This can be helpful when you want to know what terms would be
dropped during indexing or from a query string.

1094 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Permissions
None

Side effects
None

See also
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Text configuration object concepts and reference” [SQL Anywhere Server - SQL Usage]
● “sa_char_terms system procedure” on page 1009

Example
The following statement returns the terms in the NCHAR string, It's a work-at-home day!, using the
default NCHAR text configuration object, default_nchar:
CALL sa_nchar_terms (N'It''s a work-at-home day!', 'default_nchar', 'sys');

term position

It 1

s 2

a 3

work 4

at 5

home 6

day 7

sa_performance_diagnostics system procedure


Returns a summary of request timing information for all connections when the database server has request
timing logging enabled.

Syntax
sa_performance_diagnostics( )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1095


System procedures

Result set
Column Data type Description
name

Number INT Returns the ID number of the connection.

Name VAR- Returns the name of the current connection.


CHAR(255)
You can specify a connection name using the ConnectionName (CON)
connection parameter. See “ConnectionName (CON) connection pa-
rameter” [SQL Anywhere Server - Database Administration].

The following names are used for temporary connections created by


the database server:

● INT:ApplyRecovery
● INT:BackupDB
● INT:Checkpoint
● INT:Cleaner
● INT:CloseDB
● INT:CreateDB
● INT:CreateMirror
● INT:DelayedCommit
● INT:DiagRcvr
● INT:DropDB
● INT:EncryptDB
● INT:Exchange
● INT:FlushMirrorLog
● INT:FlushStats
● INT:HTTPReq
● INT:PromoteMirror
● INT:PurgeSnapshot
● INT:ReconnectMirror
● INT:RecoverMirror
● INT:RedoCheckpoint
● INT:RefreshIndex
● INT:ReloadTrigger
● INT:RenameMirror
● INT:RestoreDB
● INT:StartDB
● INT:VSS

See “Temporary connections” [SQL Anywhere Server - Database Ad-


ministration].

Userid VAR- Returns the user ID for the connection.


CHAR(255)

1096 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Column Data type Description


name

DBNumber INT Returns the ID number of the database.

LoginTime TIME- Returns the date and time the connection was established.
STAMP

Transaction- TIME- Returns a string containing the time the database was first modified af-
StartTime STAMP ter a COMMIT or ROLLBACK, or an empty string if no modifications
have been made to the database since the last COMMIT or ROLL-
BACK.

LastReq- TIME- Returns the time at which the last request for the specified connection
Time STAMP started. This property can return an empty string for internal connec-
tions, such as events.

ReqType VAR- Returns the type of the last request. If a connection has been cached by
CHAR(255) connection pooling, its ReqType value is CONNECT_POOL_CACHE.

ReqStatus VAR- Returns the status of the request. It can be one of the following values:
CHAR(255)
● Idle The connection is not currently processing a request.

● Unscheduled* The connection has work to do and is waiting for


an available database server worker.

● BlockedIO* The connection is blocked waiting for an I/O.

● BlockedContention* The connection is blocked waiting for ac-


cess to shared database server data structures.

● BlockedLock The connection is blocked waiting for a locked


object.

● Executing The connection is executing a request.

The values marked with an asterisk (*) are only returned when logging
of request timing information has been turned on for the database serv-
er using the -zt server option. If request timing information is not being
logged (the default), the values are reported as Executing.

See “-zt dbeng12/dbsrv12 server option” [SQL Anywhere Server - Da-


tabase Administration].

ReqTi- DOUBLE Returns the amount of unscheduled time, or NULL if the -zt option was
meUnsched- not specified. See “-zt dbeng12/dbsrv12 server option” [SQL Anywhere
uled Server - Database Administration].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1097


System procedures

Column Data type Description


name

ReqTi- DOUBLE Returns the amount of time spent processing requests, or NULL if the -
meActive zt option was not specified. See “-zt dbeng12/dbsrv12 server option”
[SQL Anywhere Server - Database Administration].

ReqTime- DOUBLE Returns the amount of time spent waiting for I/O to complete, or
BlockIO NULL if the -zt option was not specified. See “-zt dbeng12/dbsrv12
server option” [SQL Anywhere Server - Database Administration].

ReqTime- DOUBLE Returns the amount of time spent waiting for a lock, or NULL if the -zt
BlockLock option was not specified. See “-zt dbeng12/dbsrv12 server option”
[SQL Anywhere Server - Database Administration].

ReqTime- DOUBLE Returns the amount of time spent waiting for atomic access, or NULL
BlockCon- if the RequestTiming server property is set to Off. See “-zt dbeng12/
tention dbsrv12 server option” [SQL Anywhere Server - Database Administra-
tion].

ReqCoun- INT Returns the number of times the connection waited for scheduling, or
tUnschedul- NULL if the -zt option was not specified. See “-zt dbeng12/dbsrv12
ed server option” [SQL Anywhere Server - Database Administration].

ReqCoun- INT Returns the number of requests processed, or NULL if the Reques-
tActive tTiming server property is set to Off. See “-zt dbeng12/dbsrv12 server
option” [SQL Anywhere Server - Database Administration].

ReqCount- INT Returns the number of times the connection waited for I/O to complete,
BlockIO or NULL if the -zt option was not specified. See “-zt dbeng12/dbsrv12
server option” [SQL Anywhere Server - Database Administration].

ReqCount- INT Returns the number of times the connection waited for a lock, or
BlockLock NULL if the -zt option was not specified. See “-zt dbeng12/dbsrv12
server option” [SQL Anywhere Server - Database Administration].

ReqCount- INT Returns the number of times the connection waited for atomic access,
BlockCon- or NULL if the -zt option was not specified. See “-zt dbeng12/dbsrv12
tention server option” [SQL Anywhere Server - Database Administration].

LastIdle INT Returns the number of ticks between requests.

BlockedOn INT Returns zero if the current connection isn't blocked, or if it is blocked,
the connection number on which the connection is blocked because of
a locking conflict.

Uncommi- INT Returns the number of uncommitted operations.


tOp

1098 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Column Data type Description


name

CurrentPro- VAR- Returns the name of the procedure that a connection is currently exe-
cedure CHAR(255) cuting. If the connection is executing nested procedure calls, the name
is the name of the current procedure. If there is no procedure executing,
an empty string is returned.

EventName VAR- Returns the name of the associated event if the connection is running
CHAR(255) an event handler. Otherwise, an empty string is returned.

CurrentLi- INT Returns the current line number of the procedure or compound state-
neNumber ment a connection is executing. The procedure can be identified using
the CurrentProcedure property. If the line is part of a compound state-
ment from the client, an empty string is returned.

LastState- LONG VAR- Returns the most recently prepared SQL statement for the current con-
ment CHAR nection.

The LastStatement value is set when a statement is prepared, and is


cleared when a statement is dropped. Only one statement string is re-
membered for each connection.

If sa_conn_activity reports a non-empty value for a connection, it is


most likely the statement that the connection is currently executing. If
the statement had completed, it would likely have been dropped and
the property value would have been cleared. If an application prepares
multiple statements and retains their statement handles, then the Last-
Statement value does not reflect what a connection is currently doing.

When client statement caching is enabled, and a cached statement is


reused, this property returns an empty string.

LastPlan- LONG VAR- Returns the long text plan of the last query executed on the connection.
Text CHAR You control the remembering of the last plan by setting the Remember-
LastPlan option of the sa_server_option system procedure, or using the
-zp server option. See “-zp dbeng12/dbsrv12 server option” [SQL Any-
where Server - Database Administration].

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1099


System procedures

Column Data type Description


name

AppInfo LONG VAR- Returns information about the client that made the connection. For
CHAR HTTP connections, this includes information about the browser. For
connections using older versions of jConnect or Sybase Open Client,
the information may be incomplete.

The API value can be DBLIB, ODBC, OLEDB, ADO.NET, iAny-


whereJDBC, PHP, PerlDBD, or DBEXPRESS.

For more information about the values returned for other types of con-
nections, see “AppInfo (APP) connection parameter” [SQL Anywhere
Server - Database Administration].

LockCount INT Returns the number of locks held by the connection.

Snapshot- INT Returns the number of snapshots associated with the connection.
Count

Remarks
The sa_performance_diagnostics system procedure returns a result set consisting of a set of request timing
properties and statistics if the server has been told to collect the information. Recording of request timing
information must be turned on the database server before calling sa_performance_diagnostics. To do this,
specify the -zt option when starting the database server or execute the following:
CALL sa_server_option( 'RequestTiming','ON' );

Permissions
DBA authority

Side effects
None

See also
● “-zt dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “sa_performance_statistics system procedure” on page 1101
● “sa_server_option system procedure” on page 1120

Examples
You can execute the following query to identify connections that have spent a long time waiting for
database server requests to complete.
SELECT Number, Name,
CAST( DATEDIFF( second, LoginTime, CURRENT TIMESTAMP ) AS DOUBLE ) AS
T,
ReqTimeActive / T AS PercentActive
FROM dbo.sa_performance_diagnostics()

1100 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

WHERE PercentActive > 10.0


ORDER BY PercentActive DESC;

Find all requests that are currently executing, and have been executing for more than 60 seconds:
SELECT Number, Name,
CAST( DATEDIFF( second, LastReqTime, CURRENT TIMESTAMP ) AS DOUBLE )
AS ReqTime
FROM dbo.sa_performance_diagnostics()
WHERE ReqStatus <> 'IDLE' AND ReqTime > 60.0
ORDER BY ReqTime DESC;

sa_performance_statistics system procedure


Returns a summary of memory diagnostic statistics for all connections when the database server has
request timing logging enabled.

Syntax
sa_performance_statistics( )

Result set
Column name Data type Description

DBNumber INT Returns the ID number of the database.

ConnNumber INT Returns the ID number of the connection.

Returns NULL if the Type is Server.

PropNum INT Returns the connection property number.

PropName VARCHAR(255) Returns the connection property name.

Value INT Returns the connection property value.

Remarks
The sa_performance_statistics system procedure returns a result set consisting of a set of memory
diagnostic statistics if the server has been told to collect the information. Recording of memory diagnostic
statistics must be turned on the database server before calling sa_performance_statistics. To do this,
specify the -zt option when starting the database server or execute the following:
CALL sa_server_option( 'RequestTiming','ON' );

Permissions
DBA authority

Side effects
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1101


System procedures

See also
● “-zt dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “sa_performance_diagnostics system procedure” on page 1095
● “sa_server_option system procedure” on page 1120

Example
The following example unloads all performance statistics to a text file named dump_stats.txt:
UNLOAD
SELECT CURRENT TIMESTAMP, *
FROM sa_performance_statistics()
TO 'dump_stats.txt'
APPEND ON;

sa_post_login_procedure system procedure


Determines whether a user's password is about to expire.

Syntax
sa_post_login_procedure( )

Arguments
None

Result set
The sa_post_login_procedure system procedure returns the following:

Column name Data type Description

message_text VARCHAR(255) If message_action is 1, message_text returns the message to dis-


play. If message_action is 0, message_text is NULL.

message_action INTEGER Whether the password is about to expire (1=yes, 0=no).

Remarks
The sa_post_login_procedure system procedure is the default setting for the post_login_procedure
database option.

sa_post_login_procedure uses the user's password_life_time and password_grace_time login policy


option values, and the current date and time, to determine whether a user's password is about to expire. If
it is, the message to display to the user is returned in the result set.

Permissions
DBA authority

1102 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Side effects
None

See also
● “post_login_procedure option” [SQL Anywhere Server - Database Administration]
● “Login policies” [SQL Anywhere Server - Database Administration]

sa_procedure_profile system procedure


Reports information about the execution time for each line within procedures, functions, events, or
triggers that have been executed in a database.

Syntax
sa_procedure_profile(
[ filename
[, save_to_file ] ]
)

Arguments
● filename Use this optional LONG VARCHAR parameter to specify the file to which the profiling
information should be saved, or from which file it should be loaded. See the Remarks section below
for more about saving and loading the profiling information.

● save_to_file Use this optional INTEGER parameter to specify whether to save the profiling
information to a file, or load it from a previously stored file.

Result set
Column name Data type Description

object_type CHAR(1) The type of object. See the Remarks section below for a list of
possible object types.

object_name CHAR(128) The name of the stored procedure, function, event, or trigger.
If the object_type is C or D, then this is the name of the for-
eign key for which the system trigger was defined.

owner_name CHAR(128) The object's owner.

table_name CHAR(128) The table associated with a trigger (the value is NULL for oth-
er object types).

line_num UNSIGNED INTE- The line number within the procedure.


GER

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1103


System procedures

Column name Data type Description

executions UNSIGNED INTE- The number of times the line has been executed.
GER

millisecs UNSIGNED INTE- The time to execute the line, in milliseconds.


GER

percentage DOUBLE The percentage of the total execution time required for the spe-
cific line.

foreign_owner CHAR(128) The database user who owns the foreign table for a system
trigger.

foreign_table CHAR(128) The name of the foreign table for a system trigger.

Remarks
This procedure provides the same information as the Profile tab in Sybase Central.

You can use this procedure to:

● Return detailed procedure profiling information To do this, you can simply call the procedure
without specifying any arguments.

● Save detailed procedure profiling information to file To do this, you must include the
filename argument and specify 1 for the save_to_file argument.

● Load detailed procedure profiling information from a previously saved file To do this, you
must include the filename argument and specify 0 for the save_to_file argument (or leave it off, since
the default is 0). When using the procedure in this way, the loaded file must have been created by the
same database as the one from which you are running the procedure; otherwise, the results may be
unusable.

Since the result set includes information about the execution times for individual lines within procedures,
triggers, functions, and events, and what percentage of the total procedure execution time those lines use,
you can use this profiling information to fine-tune slower procedures that may decrease performance.

Before you can profile your database, you must enable profiling.

The object_type column of the result set can be:

● P stored procedure

● F function

● E event

● T trigger

● C ON UPDATE system trigger

1104 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● D ON DELETE system trigger

If you want summary information instead of line by line details for each execution, use the
sa_procedure_profile_summary procedure instead.

Permissions
DBA authority

Side effects
None

See also
● “sa_server_option system procedure” on page 1120
● “sa_procedure_profile_summary system procedure” on page 1105
● “Enabling procedure profiling” [SQL Anywhere Server - SQL Usage]

Example
The following statement returns the execution time for each line of every procedure, function, event, or
trigger that has been executed in the database:
CALL sa_procedure_profile( );

The following statement returns the same detailed procedure profiling information as the example above,
and saves it to a file called detailedinfo.txt:
CALL sa_procedure_profile( "detailedinfo.txt", 1 );

Either of the following statements can be used to load detailed procedure profiling information from a file
called detailedinfoOLD.txt:
CALL sa_procedure_profile( "detailedinfoOLD.txt", 0 );

CALL sa_procedure_profile( "detailedinfoOLD.txt" );

sa_procedure_profile_summary system procedure


Reports summary information about the execution times for all procedures, functions, events, or triggers
that have been executed in a database. This procedure provides the same information for these objects as
the Profile tab in Sybase Central.

Syntax
sa_procedure_profile_summary(
[ filename
[, save_to_file ] ]
)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1105


System procedures

Arguments
● filename Use this optional LONG VARCHAR parameter to specify the file to which the profiling
information is saved, or from which file it should be loaded. See the Remarks section below for more
about saving and loading the profiling information.

● save_to_file Use this optional INTEGER parameter to specify whether to save the summary
information to a file, or to load it from a previously saved file.

Result set
Column name Data type Description

object_type CHAR(1) The type of object. See the Remarks section below for a list of
possible object types.

object_name CHAR(128) The name of the stored procedure, function, event, or trigger.

owner_name CHAR(128) The object's owner.

table_name CHAR(128) The table associated with a trigger (the value is NULL for oth-
er object types).

executions UNSIGNED INTE- The number of times each procedure has been executed.
GER

millisecs UNSIGNED INTE- The time to execute the procedure, in milliseconds.


GER

foreign_owner CHAR(128) The database user who owns the foreign table for a system
trigger.

foreign_table CHAR(128) The name of the foreign table for a system trigger.

Remarks
You can use this procedure to:

● Return current summary information To do this, you can simply call the procedure without
specifying any arguments.

● Save current summary information to file To do this, you must include the filename argument
and specify 1 for the save_to_file argument.

● Load stored summary information from a file To do this, you must include the filename
argument and specify 0 for the save_to_file argument (or leave it off, since the default is 0). When
using the procedure in this way, the loaded file must have been created by the same database as the
one from which you are running the procedure; otherwise, the results may be unusable.

Since the procedure returns information about the usage frequency and efficiency of stored procedures,
functions, events, and triggers, you can use this information to fine-tune slower procedures to improve
database performance.

1106 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Before you can profile your database, you must enable profiling.

The object_type column of the result set can be:

● P stored procedure

● F function

● E event

● T trigger

● S system trigger

● C ON UPDATE system trigger

● D ON DELETE system trigger

If you want line by line details for each execution instead of summary information, use the
sa_procedure_profile procedure instead.

Permissions
DBA authority

Side effects
None

See also
● “Enabling procedure profiling” [SQL Anywhere Server - SQL Usage]
● “sa_server_option system procedure” on page 1120
● “sa_procedure_profile system procedure” on page 1103

Example
The following statement returns the execution time for any procedure, function, event, or trigger that has
been executed in the database:
CALL sa_procedure_profile_summary( );

The following statement returns the same summary information as the previous example, and saves it to a
file called summaryinfo.txt:
CALL sa_procedure_profile_summary( "summaryinfo.txt", 1 );

Either of the following statements can be used to load stored summary information from a file called
summaryinfoOLD.txt:
CALL sa_procedure_profile_summary( "summaryinfoOLD".txt, 0 );

CALL sa_procedure_profile_summary( "summaryinfoOLD.txt" );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1107


System procedures

sa_recompile_views system procedure


Locates view definitions stored in the catalog that do not have column definitions and causes the column
definitions to be created.

Syntax
sa_recompile_views( [ ignore_errors ] )

Arguments
● ignore_errors Use this optional INTEGER parameter to specify whether to return errors during
the recompilation. If you specify 0, an error is returned for each view for which column definition
failed. If you specify 1, or any value other than 0, no errors are returned. If no value is specified, 0 is
used by default.

Remarks
This procedure is used to locate views in the catalog that do not have column definitions and execute an
ALTER VIEW statement with the RECOMPILE clause to create the column definitions. The procedure
does this for each view that does not have a column definition until there are none left that require
compilation or until any remaining column definitions cannot be created. If the procedure is unable to
recompile any views, an error is reported. Errors can be suppressed by specifying a non-zero parameter to
this procedure.

Caution
The sa_recompile_views system procedure should only be called from within a reload.sql script. This
procedure is used by the Unload utility (dbunload) and should not be used explicitly.

The sa_recompile_views system procedure does not attempt to recompile materialized views or any view
marked DISABLED.

Permissions
DBA authority

Side effects
For each regular view that does not have a VALID status, an ALTER VIEW owner.viewname
ENABLE statement is executed, causing an automatic commit.

See also
● “Statuses for regular views” [SQL Anywhere Server - SQL Usage]
● “force_view_creation option” [SQL Anywhere Server - Database Administration]
● “ALTER VIEW statement” on page 472

sa_refresh_materialized_views system procedure


Initializes all materialized views that are in an uninitialized state.

1108 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Syntax
sa_refresh_materialized_views( [ ignore_errors ] )

Arguments
● ignore_errors Use this optional INTEGER parameter to specify whether to return errors during
the recompilation. If you specify 0, an error is returned for each view for which column definition
failed. If you specify 1, or any value other than 0, no errors are returned. If no value is specified, 0 is
used by default.

Remarks
A materialized view may be in an uninitialized state because it has just been created, has just been re-
enabled, or the last attempt to initialize or refresh it failed due to an error. The
sa_refresh_materialized_views system procedure scans the database for all such materialized views and
attempts to initialize them. If the procedure encounters an error initializing a materialized view, it
continues on attempting to process the remaining uninitialized views.

You can also use the REFRESH MATERIALIZED VIEW statement to initialize a materialized view.

Permissions
DBA authority

Side effects
None

See also
● “REFRESH MATERIALIZED VIEW statement” on page 843
● “Refreshing a manual materialized view” [SQL Anywhere Server - SQL Usage]

sa_refresh_text_indexes system procedure


Refreshes all text indexes defined as MANUAL REFRESH or AUTO REFRESH.

Syntax
sa_refresh_text_indexes( )

Remarks
The sa_refresh_text_indexes system procedure refreshes all text indexes defined as MANUAL REFRESH
or AUTO REFRESH. It does not refresh text indexes defined as IMMEDIATE REFRESH (the default)
because changes to those indexes are made when data is changed in the underlying table.

Permissions
DBA authority

Side effects
Automatic commit

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1109


System procedures

See also
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Text configuration object concepts and reference” [SQL Anywhere Server - SQL Usage]
● “DROP TEXT INDEX statement” on page 713
● “REFRESH TEXT INDEX statement” on page 846
● “TRUNCATE statement” on page 933
● “SYSTEXTIDX system view” on page 1249
● “sa_text_index_stats system procedure” on page 1149
● “sa_text_index_vocab system procedure” on page 1150

Example
The following statement refreshes all MANUAL and AUTO REFRESH text indexes in the database:
CALL sa_refresh_text_indexes( );

sa_remove_tracing_data system procedure


Permanently deletes from the diagnostic tracing tables all records pertaining to the specified logging
(tracing) session ID.

Syntax
sa_remove_tracing_data( log_session_id )

Arguments
● log_session_id Use this INTEGER parameter to specify the ID of the logging session for which
to remove the data.

Remarks
If there are no records for the specified log_session_id, the procedure has no effect. The procedure has no
return values.

Permissions
DBA authority

Side effects
Causes a commit upon completion, even if no records were found for the specified log_session_id.

See also
● “Diagnostic tracing tables” on page 980

sa_report_deadlocks system procedure


Retrieves information about deadlocks from an internal buffer created by the database server.

1110 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Syntax
sa_report_deadlocks( )

Result set
Column name Data type Description

snapshotId BIGINT The deadlock instance (all rows pertaining to a particular dead-
lock have the same ID).

snapshotAt TIMESTAMP The time when the deadlock occurred.

waiter INT The connection handle of the waiting connection.

who VARCHAR(128) The user ID associated with the connection that is waiting.

what LONG VAR- The command being executed by the waiting connection.
CHAR
This information is only available if you have turned on captur-
ing of the most recently-prepared SQL statement by specifying
the -zl option on the database server command line or have
turned this feature on using the sa_server_option system proce-
dure.

object_id UNSIGNED BI- The object ID of the table containing the row.
GINT

record_id BIGINT The row ID of the associated row.

owner INT The connection handle of the connection owning the lock being
waited on.

is_victim BIT Identifies the rolled back transaction.

rollback_opera- UNSIGNED INT The number of uncommitted operations that may be lost if the
tion_count transaction rolls back.

Remarks
When the log_deadlocks option is set to On, the database server logs information about deadlocks in an
internal buffer. You can view the information in the log using the sa_report_deadlocks system procedure.

Permissions
DBA authority

Side effects
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1111


System procedures

See also
● “System events” [SQL Anywhere Server - Database Administration]
● “log_deadlocks option” [SQL Anywhere Server - Database Administration]
● “sa_server_option system procedure” on page 1120
● “Determining who is blocked” [SQL Anywhere Server - SQL Usage]
● “-zl dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “sa_server_option system procedure” on page 1120

sa_reserved_words system procedure


Returns a list of reserved words. Many, but not all, the keywords that appear in SQL statements are
reserved words.

Syntax
sa_reserved_words( )

Remarks
The procedure takes no parameters and returns one word per row. The list of reserved words is based on
the version of the database server that executes the query, not the version of the software used to create
the database file.

Permissions
None

Side effects
None

See also
● “Reserved words” on page 1

Example
The following statement returns a list of reserved words:
SELECT *
FROM dbo.sa_reserved_words();

sa_reset_identity system procedure


Allows the next identity value to be set for a table. Use this procedure to change the AUTOINCREMENT
value for the next row that will be inserted.

Syntax
sa_reset_identity(
tbl_name,

1112 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

owner_name,
new_identity
)

Arguments
● tbl_name Use this CHAR(128) parameter to specify the table for which you want to reset the
identity value. If the owner of the table is not specified, tbl_name must uniquely identify a table in the
database.

● owner_name Use this CHAR(128) parameter to specify the owner of the table for which you want
to reset the identity value. If owner_name is not specified or is NULL, then the third argument must
be named. For example: CALL sa_reset_identity ( 'Employees', new_identity
= 100 );

● new_identity Use this BIGINT parameter to specify the value from which you want the
autoincrementing to start.

Remarks
The next identity value generated for a row inserted into the table is new_identity + 1.

No checking occurs to see whether new_identity + 1 conflicts with existing rows in the table. For
example, if you specify new_identity as 100, the next row inserted gets an identity value of 101. However,
if 101 already exists in the table, the row insertion fails.

The sa_reset_identity system procedure cannot be used on a table having no columns with a default of
either AUTOINCREMENT or GLOBAL AUTOINCREMENT.

Permissions
DBA authority

Side effects
Causes a checkpoint to occur after the value has been updated

See also
● “The AUTOINCREMENT default” [SQL Anywhere Server - SQL Usage]
● “The GLOBAL AUTOINCREMENT default” [SQL Anywhere Server - SQL Usage]

Example
The following statement resets the next identity value to 101:

CALL sa_reset_identity( 'Employees', 'GROUPO', 100 );

sa_rowgenerator system procedure


Returns a result set with rows between a specified start and end value.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1113


System procedures

Syntax
sa_rowgenerator(
[ rstart
[, rend
[, rstep ] ] ]
)

Arguments
● rstart Use this optional INTEGER parameter to specify the starting value. The default value is 0.

● rend Use this optional INTEGER parameter to specify the ending value that is greater than or equal
to rstart. The default value is 100.

● rstep Use this optional INTEGER parameter to specify the increment by which the sequence
values are increased. The default value is 1.

Result set
Column name Data type Description

row_num INTEGER Sequence number.

Remarks
The sa_rowgenerator procedure can be used in the FROM clause of a query to generate a sequence of
numbers. This procedure is an alternative to using the RowGenerator system table. You can use
sa_rowgenerator for such tasks as:

● generating test data for a known number of rows in a result set.

● generating a result set with rows for values in every range. For example, you can generate a row for
every day of the month, or you can generate ranges of zip codes.

● generating a query that has a specified number of rows in the result set. This may be useful for testing
the performance of queries.

No rows are returned if you do not specify correct start and end values and a positive non-zero step value.

You can emulate the behavior of the RowGenerator table with the following statement:
SELECT row_num FROM sa_rowgenerator( 1, 255 );

Permissions
None

Side effects
None

See also
● “RowGenerator table (dbo)” on page 993
● “Null value eliminated in aggregate function” [Error Messages]

1114 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Example
The following query returns a result set containing one row for each day of the current month.

SELECT DATEADD( day, row_num-1,


YMD( DATEPART( year, CURRENT DATE ),
DATEPART( month, CURRENT DATE ), 1 ) )
AS day_of_month
FROM sa_rowgenerator( 1, 31, 1 )
WHERE DATEPART( month, day_of_month ) =
DATEPART( month, CURRENT DATE )
ORDER BY row_num;

The following query shows how many employees live in zip code ranges (0-9999), (10000-19999), ...,
(90000-99999). Some of these ranges have no employees, which causes a warning.

The sa_rowgenerator procedure can be used to generate these ranges, even though no employees have a
zip code in the range.

SELECT row_num AS r1, row_num+9999


AS r2, COUNT( PostalCode ) AS zips_in_range
FROM sa_rowgenerator( 0, 99999, 10000 ) D LEFT JOIN Employees
ON PostalCode BETWEEN r1 AND r2
GROUP BY r1, r2
ORDER BY 1;

The following example generates 10 rows of data and inserts them into the NewEmployees table:

INSERT INTO NewEmployees ( ID, Salary, Name )


SELECT row_num,
CAST( RAND() * 1000 AS INTEGER ),
'Mary'
FROM sa_rowgenerator( 1, 10 );

The following example uses the sa_rowgenerator system procedure to create a view containing all
integers. The value 2147483647 in this example represents the maximum signed integer that is supported.

CREATE VIEW Integers AS


SELECT row_num AS n
FROM sa_rowgenerator( 0, 2147483647, 1 );

This example uses the sa_rowgenerator system procedure to create a view containing dates from
0001-01-01 to 9999-12-31. The value 3652058 in this example represents the number of days between
0001-01-01 and 9999-12-31, the earliest and latest dates that are supported.

CREATE VIEW Dates AS


SELECT DATEADD( day, row_num, '0001-01-01' ) AS d
FROM sa_rowgenerator( 0, 3652058, 1 );

The following query returns all years between 1900 and 2058 that have 54 weeks.

SELECT DATEADD ( day, row_num, '1900-01-01' ) AS d, DATEPART ( week, d ) w


FROM sa_rowgenerator ( 0, 63919, 1 )
WHERE w = 54;

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1115


System procedures

sa_save_trace_data system procedure


Saves tracing data to base tables.

Syntax
sa_save_trace_data( )

Remarks
While a tracing session is running, diagnostic data is stored in temporary versions of the diagnostic
tracing tables. When you stop a tracing session, you specify whether you want to permanently store the
tracing data in the base tables for diagnostic tracing. If you do not choose to save the data, you can still
save the data after the session is stopped by using the sa_save_trace_data system procedure.

The sa_save_trace_data system procedure returns an error if tracing is still in progress; you must stop
tracing to use this system procedure.

The sa_save_trace_data system procedure can be used even if the user specified WITHOUT SAVING
when stopping tracing. Also, the procedure must be called from the tracing database.

Permissions
DBA authority

Side effects
Automatic commit.

See also
● “Creating a diagnostic tracing session (Sybase Central)” [SQL Anywhere Server - SQL Usage]
● “Diagnostic tracing tables” on page 980

sa_send_udp system procedure


Sends a UDP packet to the specified address.

Syntax
sa_send_udp(
destAddress,
destPort,
msg
)

Arguments
● destAddress Use this CHAR(254) to specify either the host name or IP number.

● destPort Use this UNSIGNED SMALLINT parameter to specify the port number to use.

1116 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● msg Use this LONG BINARY parameter to specify the message to send to the specified address. If
this value is a string, it must be enclosed in single quotes.

Remarks
This procedure sends a single UDP packet to the specified address. The procedure returns 0 if the message
is sent successfully, and returns an error code if an error occurs. The error code is one of the following:

● -1 if the message is too large to send over a UDP socket (as determined by the operating system) or if
there is a problem with the destination address

● the Winsock/Posix error code that is returned by the operating system

If the msg parameter contains binary data or is more complex than a string, you may want to use a
variable. For example:
CREATE VARIABLE v LONG BINARY;
SET v='This is a UDP message';
SELECT dbo.sa_send_udp( '10.25.99.124', 1234, v );
DROP VARIABLE v;

This procedure can be used with MobiLink server-initiated synchronization to wake up the MobiLink
Listener utility (dblsn.exe). If you use the sa_send_udp system procedure as a way to notify the MobiLink
Listener, you should append a 1 to your UDP packet. This number is a server-initiated synchronization
protocol number. In future versions of MobiLink, new protocol versions may cause the MobiLink
Listener to behave differently.

Permissions
DBA authority

Side effects
None

See also
● “Sending a push notification using the sa_send_udp system procedure” [MobiLink - Server-Initiated
Synchronization]

Example
The following example sends the message "This is a test" to IP address 10.25.99.196 on port 2345:
CALL sa_send_udp( '10.25.99.196', 2345', 'This is a test' );

sa_server_messages system procedure


Allows you to return messages from the database server messages window as a result set.

Syntax
sa_server_messages( [ first_msg ] [, num_msgs ] )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1117


System procedures

Arguments
● first_msg Use this optional UNSIGNED BIGINT parameter to specify the ID of the first or last
message to be returned, depending on the sign of the num_msgs parameter. The default is NULL,
which means that the search starts at the beginning of the list if num_msgs is NULL or non-negative;
the search starts past the end of the list if num_msgs is negative.

● num_msgs Use this optional BIGINT parameter to specify the number of messages to be returned.
The sign indicates whether the request is for messages starting at first_msg or ending at first_msg. The
default is NULL, which means that all messages starting at first_msg to the end of the list are
returned.

Result set
Column Data type Description
name

msg_id UNSIGNED BI- Unique message ID. Message IDs start at 0.


GINT

msg_text LONG VAR- Message text.


CHAR

msg_time TIMESTAMP Time when the message was issued.

msg_severi- VAR- Message severity. This column contains one of the following val-
ty CHAR(255) ues:

● INFO Informational message.

● WARN Warning.

● ERR Error.

1118 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Column Data type Description


name

msg_catego- VAR- Message category. This column contains one of the following val-
ry CHAR(255) ues:

● STARTUP/SHUTDOWN Messages related to database server


or database startup or shutdown.

● CHKPT Messages related to checkpoints.

● MSG Messages generated using the MESSAGE or PRINT


statements.

● DBA_MSG Messages generated using the MESSAGE state-


ment that would have required DBA permissions, such as mes-
sages sent to the event log.

● CONN Messages about database server connectivity.

● OTHER All other types of messages.

msg_data- VAR- Database name associated with the message if it applies to one spe-
base CHAR(255) cific database. Otherwise, NULL.

Remarks
When new messages are sent to the console, old messages with the same category or severity are deleted
if the number of messages exceeds the value of the MessageCategoryLimit property. As a result, there
may be gaps in the result set, and two consecutive rows may not have consecutive message IDs.

The STARTUP/SHUTDOWN message category does not show shutdown messages for servers.
Shutdown messages are shown only if multiple databases are running on a server and one or more are shut
down.

Permissions
None

Side effects
None

See also
● “MessageCategoryLimit server property” [SQL Anywhere Server - Database Administration]

Example
The following command requests 100 messages starting at the message whose ID is 3:
CALL sa_server_messages( 3, 100 );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1119


System procedures

The following command requests 500 messages up to, and including, message 4032:

CALL sa_server_messages( 4032, -500 );

The following commands request all messages starting with message 3:

CALL sa_server_messages( 3, NULL );

CALL sa_server_messages( 3 );

The following command requests the first 100 messages in the list:

CALL sa_server_messages( NULL, 100 );

The following command requests the last 100 messages in the list:

CALL sa_server_messages( NULL, -100 );

The following commands request all the messages in the list:

CALL sa_server_messages( NULL, NULL );

CALL sa_server_messages( );

sa_server_option system procedure


Overrides a server option while the server is running.

Syntax
sa_server_option(
opt,
val
)

Arguments
● opt Use this CHAR(128) parameter to specify a server option name.

● val Use this CHAR(128) parameter to specify the new value for the server option.

Remarks
Database administrators can use this procedure to override some database server options temporarily,
without restarting the database server.

The option values that are changed using this procedure are reset to their default values when the server
shuts down. If you want to change an option value every time the server is started, you can specify the
corresponding database server option when the database server is started if one exists (these are listed in
the rightmost column in the table below).

The following option settings can be changed:

1120 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Option name Values Default Server option See also

AutoMultiProg- YES, NO YES “-gna dbsrv12 “Database server con-


rammingLevel server option” figuration of the mul-
[SQL Anywhere tiprogramming level”
Server - Data- [SQL Anywhere Serv-
base Administra- er - Database Admin-
tion] istration]

AutoMultiProg- YES, NO NO “-gns dbsrv12 “AutoMultiProgram-


rammingLevel- server option” mingLevelStatistics
Statistics [SQL Anywhere server property” [SQL
Server - Data- Anywhere Server -
base Administra- Database Administra-
tion] tion]

CacheSizingSta- YES, NO NO “-cs dbeng12/ “CacheSizingStatistics


tistics dbsrv12 server server property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

CollectStatistics YES, NO YES “-k dbeng12/ “CollectStatistics


dbsrv12 server server property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

ConnsDisabled YES, NO NO “ConnsDisabled serv-


er property” [SQL
Anywhere Server -
Database Administra-
tion]

ConnsDisabled- YES, NO NO
ForDB

ConsoleLogFile filename “-o dbeng12/ “ConsoleLogFile


dbsrv12 server server property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1121


System procedures

Option name Values Default Server option See also

ConsoleLog- file-size, in bytes “-on dbeng12/ “ConsoleLogMaxSize


MaxSize dbsrv12 server server property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

CurrentMulti- Integer 20 “-gn dbsrv12 “Database server con-


ProgrammingLe- server option” figuration of the mul-
vel [SQL Anywhere tiprogramming level”
Server - Data- [SQL Anywhere Serv-
base Administra- er - Database Admin-
tion] istration]

DatabaseCleaner ON, OFF ON “DatabaseCleaner da-


tabase property” [SQL
Anywhere Server -
Database Administra-
tion]

DeadlockLog- ON, OFF, RE- OFF “log_deadlocks


ging SET, CLEAR option” [SQL
Anywhere Server
- Database Ad-
ministration]

DebuggingInfor- YES, NO NO “-z dbeng12/ “DebuggingInforma-


mation dbsrv12 server tion server property”
option” [SQL [SQL Anywhere Serv-
Anywhere Server er - Database Admin-
- Database Ad- istration]
ministration]

DropBadStatis- YES, NO YES


tics

DropUnusedSta- YES, NO YES


tistics

IdleTimeout Integer, in mi- 240 “-ti dbeng12/ “IdleTimeout server


nutes dbsrv12 server property” [SQL Any-
option” [SQL where Server - Data-
Anywhere Server base Administration]
- Database Ad-
ministration]

1122 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Option name Values Default Server option See also

IPAddressMoni- Integer, in sec- 120 for portable “-xm dbeng12/ “IPAddressMonitor-


torPeriod onds devices, 0 other- dbsrv12 server Period server proper-
wise option” [SQL ty” [SQL Anywhere
Anywhere Server Server - Database Ad-
- Database Ad- ministration]
ministration]

LivenessTimeout Integer, in sec- 120 “-tl dbeng12/ “LivenessTimeout


onds dbsrv12 server server property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

MaxMultiProg- Integer Four times the “-gnh dbsrv12 “Database server con-
rammingLevel CurrentMulti- server option” figuration of the mul-
ProgrammingLe- [SQL Anywhere tiprogramming level”
vel value Server - Data- [SQL Anywhere Serv-
base Administra- er - Database Admin-
tion] istration]

MessageCategor- Integer 400 “MessageCategoryLi-


yLimit mit server property”
[SQL Anywhere Serv-
er - Database Admin-
istration]

MinMultiProg- Integer The minimum of “-gnl dbsrv12 “Database server con-


rammingLevel the value of the - server option” figuration of the mul-
gtc server option [SQL Anywhere tiprogramming level”
and the number Server - Data- [SQL Anywhere Serv-
of logical CPUs base Administra- er - Database Admin-
on the computer tion] istration]

OptionWatchAc- MESSAGE, ER- MESSAGE ● “Monitoring op-


tion ROR tion settings”
[SQL Anywhere
Server - Database
Administration]
● “OptionWatchAc-
tion database
property” [SQL
Anywhere Server -
Database Admin-
istration]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1123


System procedures

Option name Values Default Server option See also

OptionWatchList comma-separated ● “Monitoring op-


list of database tion settings”
options [SQL Anywhere
Server - Database
Administration]
● “OptionWatchList
database property”
[SQL Anywhere
Server - Database
Administration]

ProcedureProfil- YES, NO, RE- NO “ProcedureProfiling


ing SET, CLEAR database property”
[SQL Anywhere Serv-
er - Database Admin-
istration]

ProfileFilter- connection-id “ProfileFilterConn


Conn server property” [SQL
Anywhere Server -
Database Administra-
tion]

ProfileFilterUser user-id “ProfileFilterUser


server property” [SQL
Anywhere Server -
Database Administra-
tion]

QuittingTime valid date and “-tq dbeng12/ “QuittingTime server


time dbsrv12 server property” [SQL Any-
option” [SQL where Server - Data-
Anywhere Server base Administration]
- Database Ad-
ministration]

RememberLast- YES, NO NO “-zp dbeng12/ “RememberLastPlan


Plan dbsrv12 server server property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

1124 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Option name Values Default Server option See also

RememberLast- YES, NO NO “-zl dbeng12/ “RememberLastState-


Statement dbsrv12 server ment server property”
option” [SQL [SQL Anywhere Serv-
Anywhere Server er - Database Admin-
- Database Ad- istration]
ministration]

RequestFilter- connection-id, -1 “RequestFilterConn


Conn server property” [SQL
Anywhere Server -
Database Administra-
tion]

RequestFilterDB database-id, -1 “RequestFilterDB


server property” [SQL
Anywhere Server -
Database Administra-
tion]

RequestLogFile filename “-zo dbeng12/ “RequestLogFile serv-


dbsrv12 server er property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

RequestLogging SQL, HOST- NONE “-zr dbeng12/ “RequestLogging


VARS, PLAN, dbsrv12 server server property” [SQL
PROCEDURES, option” [SQL Anywhere Server -
TRIGGERS, Anywhere Server Database Administra-
OTHER, - Database Ad- tion]
BLOCKS, RE- ministration]
PLACE, ALL,
YES, NONE,
NO

RequestLogMax- file-size, in bytes “-zs dbeng12/ “RequestLogMaxSize


Size dbsrv12 server server property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1125


System procedures

Option name Values Default Server option See also

RequestLog- Integer “-zn dbeng12/ “RequestLogNum-


NumFiles dbsrv12 server Files server property”
option” [SQL [SQL Anywhere Serv-
Anywhere Server er - Database Admin-
- Database Ad- istration]
ministration]

RequestTiming YES, NO NO “-zt dbeng12/ “RequestTiming serv-


dbsrv12 server er property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

SecureFeatures feature-list “-sf dbeng12/ “Secured features”


dbsrv12 server [SQL Anywhere Serv-
option” [SQL er - Database Admin-
Anywhere Server istration]
- Database Ad-
ministration]

StatisticsCleaner ON, OFF ON

WebClientLog- filename “-zoc dbeng12/ “WebClientLogFile


File dbsrv12 server server property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

WebClientLog- ON, OFF OFF “-zoc dbeng12/ “WebClientLogging


ging dbsrv12 server server property” [SQL
option” [SQL Anywhere Server -
Anywhere Server Database Administra-
- Database Ad- tion]
ministration]

● AutoMultiProgrammingLevel When set to YES, the database server automatically adjusts its
multiprogramming level, which controls the maximum number of tasks that can be active at a time. If
you choose to control the multiprogramming level manually by setting this option to NO, you can still
set the initial, minimum, and maximum values for the multiprogramming level.

● AutoMultiProgrammingLevelStatistics When set to YES, statistics for automatic


multiprogramming level adjustments appear in the database server message log.

1126 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● CacheSizingStatistics When set to YES, display cache information in the database server
messages window whenever the cache size changes.

● CollectStatistics When set to YES, the database server collects Performance Monitor statistics.

● ConnsDisabled When set to YES, no other connections are allowed to any databases on the
database server.

● ConnsDisabledForDB When set to YES, no other connections are allowed to the current
database.

● ConsoleLogFile The name of the file used to record database server message log information.
Specifying an empty string stops logging to the file. Any backslash characters in the path must be
doubled because this is a SQL string.

● ConsoleLogMaxSize The maximum size, in bytes, of the file used to record database server
message log information. When the database server message log file reaches the size specified by
either this property or the -on server option, the file is renamed with the extension .old appended
(replacing an existing file with the same name if one exists). The database server message log file is
then restarted.

● CurrentMultiProgrammingLevel Sets the multiprogramming level of the database server.

● DatabaseCleaner Do not change the setting of this option except on the recommendation of
iAnywhere Technical Support.

● DeadlockLogging Controls deadlock logging. The value deadlock_logging is also supported.


Deadlock logging options can also be configured in the Database Properties window in Sybase
Central. The following values are supported:

○ ON Enables deadlock logging.

○ OFF Disables deadlock logging and leaves the deadlock data available for viewing.

○ RESET Clears the logged deadlock data, if any exists, and then enables deadlock logging.

○ CLEAR Clears the logged deadlock data, if any exists, and then disables deadlock logging.

Once deadlock logging is enabled, you can use the sa_report_deadlocks system procedure to retrieve
deadlock information from the database.

● DebuggingInformation Displays diagnostic messages and other messages for troubleshooting


purposes. The messages appear in the database server messages window.

● DropBadStatistics Allows automatic statistics management to drop statistics that return bad
estimates from the database.

● DropUnusedStatistics Allows automatic statistics management to drop statistics that have not
been used for 90 consecutive days from the database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1127


System procedures

● IdleTimeout Disconnects TCP/IP connections that have not submitted a request for the specified
number of minutes. This prevents inactive connections from holding locks indefinitely.

● IPAddressMonitorPeriod Sets the time to check for new IP addresses in seconds. The minimum
value is 10 and the default is 0. For portable devices, the default value is 120 seconds.

● LivenessTimeout A liveness packet is sent periodically across a client/server TCP/IP network to


confirm that a connection is intact. If the network server runs for a LivenessTimeout period without
detecting a liveness packet, the communication is severed.

● MaxMultiProgrammingLevel Sets the maximum database server multiprogramming level.

● MessageCategoryLimit Sets the minimum number of messages of each severity and category that
can be retrieved using the sa_server_messages system procedure.

● MinMultiProgrammingLevel Sets the minimum database server multiprogramming level.

● OptionWatchAction Specifies the action the database server should take when an attempt is made
to set an option in the list. The supported values are MESSAGE and ERROR. When
OptionWatchAction is set to MESSAGE, and an option specified by OptionWatchList is set, a
message appears in the database server messages window indicating that the option being set is on the
options watch list.

When OptionWatchAction is set to ERROR, an error is returned indicating that the option cannot be
set because it is on the options watch list.

You can view the current setting for this property by executing the following query:
SELECT DB_PROPERTY( 'OptionWatchAction' );

● OptionWatchList Specifies a comma-separated list of database options that you want to be


notified about, or have the database server return an error for, when they are set. The string length is
limited to 128 bytes. By default, it is an empty string. For example, the following command adds the
automatic_timestamp, float_as_double, and tsql_hex_constant option to the list of options being
watched:
CALL sa_server_option( 'OptionWatchList','automatic_timestamp,
float_as_double,tsql_hex_constant' )

You can view the current setting for this property by executing the following query:
SELECT DB_PROPERTY( 'OptionWatchList' );

● ProcedureProfiling Controls procedure profiling for stored procedures, functions, events, and
triggers. Procedure profiling shows you how long it takes your stored procedures, functions, events,
and triggers to execute. You can also set procedure profiling options on the Database Properties
window in Sybase Central

○ YES enables procedure profiling for the database you are currently connected to.

○ NO disables procedure profiling and leaves the profiling data available for viewing.

○ RESET returns the profiling counters to zero, without changing the YES or NO setting.

1128 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

○ CLEAR returns the profiling counters to zero and disables procedure profiling.

Once profiling is enabled, you can use the sa_procedure_profile_summary and


sa_procedure_profile system procedures to retrieve profiling information from the database.

● ProfileFilterConn Instructs the database server to capture profiling information for a specific
connection ID, without preventing other connections from using the database. When connection
filtering is enabled, the value returned for SELECT PROPERTY( 'ProfileFilterConn' ) is
the connection ID of the connection being monitored. If no ID has been specified, or if connection
filtering is disabled, the value returned is -1.

● ProfileFilterUser Instructs the database server to capture profiling information for a specific user
ID.

● QuittingTime Instructs the database server to shut down at the specified time.

● RememberLastPlan Instructs the database server to capture the long text plan of the last query
executed on the connection. This setting is also controlled by the -zp server option.

When RememberLastPlan is turned on, you can obtain the textual representation of the plan of the last
query executed on the connection by querying the value of the LastPlanText connection property:
SELECT CONNECTION_PROPERTY( 'LastPlanText' );

● RememberLastStatement Instructs the database server to capture the most recently prepared
SQL statement for each database running on the server. For stored procedure calls, only the outermost
procedure call appears, not the statements within the procedure.

When RememberLastStatement is turned on, you can obtain the current value of the LastStatement for
a connection by querying the value of the LastStatement connection property:
SELECT CONNECTION_PROPERTY( 'LastStatement' );

When client statement caching is enabled, and a cached statement is reused, this property returns an
empty string.

When RememberLastStatement is turned on, the following statement returns the most recently-
prepared statement for the specified connection:
SELECT CONNECTION_PROPERTY( 'LastStatement', connection-id );

The sa_conn_activity system procedure returns this same information for all connections.

Caution
When -zl is specified, or when the RememberLastStatement server setting is turned on, any user can
call the sa_conn_activity system procedure or obtain the value of the LastStatement connection
property to find out the most recently-prepared SQL statement for any other user. This option should
be used with caution and turned off when it is not required.

● RequestFilterConn Filter the request logging information so that only information for a particular
connection is logged. This can help reduce the size of the request log file when monitoring a database

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1129


System procedures

server with many active connections or multiple databases. You can obtain the connection ID by
executing the following:
CALL sa_conn_info( );

To specify a specific connection to be logged once you have obtained the connection ID, execute the
following:
CALL sa_server_option( 'RequestFilterConn', connection-id );

Filtering remains in effect until it is explicitly reset, or until the database server is shut down. To reset
filtering, use the following statement:
CALL sa_server_option( 'RequestFilterConn', -1 );

● RequestFilterDB Filter the request logging information so that only information for a particular
database is logged. This can help reduce the size of the request log file when monitoring a server with
multiple databases. You can obtain the database ID by executing the following statement when you
are connected to the desired database:
SELECT CONNECTION_PROPERTY( 'DBNumber' );

To specify that only information for a particular database is to be logged, execute the following:
CALL sa_server_option( 'RequestFilterDB', database-id );

Filtering remains in effect until it is explicitly reset, or until the database server is shut down. To reset
filtering, use the following statement:
CALL sa_server_option( 'RequestFilterDB', -1 );

● RequestLogFile The name of the file used to record request information. Specifying an empty
string stops logging to the request log file. If request logging is enabled, but the request log file was
not specified or has been set to an empty string, the server logs requests to the database server
messages window. Any backslash characters in the path must be doubled as this is a SQL string.

When client statement caching is enabled, the max_client_statements_cached option should be set to 0
to disable client statement caching while the request log is captured, if the log will be analyzed using
the tracetime.pl Perl script.

● RequestLogging This call turns on logging of individual SQL statements sent to the database
server for use in troubleshooting, in conjunction with the database server -zr and -zo options. Values
can be combinations of the following, separated by either a plus sign (+), or a comma:

○ PLAN enables logging of execution plans (short form). Execution plans for procedures are also
recorded if logging of procedures (PROCEDURES) is enabled.

○ HOSTVARS enables logging of host variable values. If you specify HOSTVARS, the
information listed for SQL is also logged.

○ PROCEDURES enables logging of statements executed from within procedures.

○ TRIGGERS enables logging of statements executed from within triggers.

1130 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

○ OTHER enables logging of additional request types not included by SQL, such as FETCH and
PREFETCH. However, if you specify OTHER but do not specify SQL, it is the equivalent of
specifying SQL+OTHER. Including OTHER can cause the log file to grow rapidly and could
negatively impact server performance.

○ BLOCKS enables logging of details showing when a connection is blocked and unblocked on
another connection.

○ REPLACE at the start of logging, the existing request log is replaced with a new (empty) one of
the same name. Otherwise, the existing request log is opened and new entries are appended to the
end of the file.

○ ALL logs all supported information. This is equivalent to specifying SQL+PLAN+HOSTVARS


+PROCEDURES+TRIGGERS+OTHER+BLOCKS. This setting can cause the log file to grow
rapidly and could negatively impact server performance.

○ NO or NONE turns off logging to the request log.

You can view the current setting for this property by executing the following query:
SELECT PROPERTY( 'RequestLogging' );

For more information, see “Accessing database server property values” [SQL Anywhere Server -
Database Administration].

● RequestLogMaxSize The maximum size of the file used to record request logging information, in
bytes. If you specify 0, then there is no maximum size for the request logging file, and the file is never
renamed. This is the default value.

When the request log file reaches the size specified by either the sa_server_option system procedure
or the -zs server option, the file is renamed with the extension .old appended (replacing an existing file
with the same name if one exists). The request log file is then restarted.

● RequestLogNumFiles The number of request log file copies to retain.

If request logging is enabled over a long period of time, the request log file can become large. The -zn
option allows you to specify the number of request log file copies to retain.

● RequestTiming Instructs the database server to maintain timing information for each connection.
This feature is turned off by default. When it is turned on, the database server maintains cumulative
timers for each connection that indicate how much time the connection spent in the server in each of
several states. You can use the sa_performance_diagnostics system procedure to obtain a summary of

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1131


System procedures

this timing information, or you can retrieve individual values by inspecting the following connection
properties:

○ ReqCountUnscheduled
○ ReqTimeUnscheduled
○ ReqCountActive
○ ReqTimeActive
○ ReqCountBlockIO
○ ReqTimeBlockIO
○ ReqCountBlockLock
○ ReqTimeBlockLock
○ ReqCountBlockContention
○ ReqTimeBlockContention

When the RequestTiming server property is on, there is a small overhead for each request to maintain
the additional counters.

● SecureFeatures Allows you to enable or disable secure features of a database server that is
already running. The feature-list is a comma-separated list of feature names or feature sets. By adding
a feature to the list, you limit its availability. To remove items from the list of secure features, specify
a minus sign (-) before the secure feature name.

Any changes you make to enable or disable features take effect immediately for the connection. The
settings do not affect the connection that executes the sa_server_option system procedure; you must
disconnect and reconnect to see the change.

Note
To use the sa_server_option system procedure to enable or disable features, you must have specified a
key with the -sk option when starting the database server, and set the value of the secure_feature_key
database option to the key you specified for -sk (for example, SET TEMPORARY OPTION
secure_feature_key = 'j978kls12'). Setting the secure_feature_key database option to
the -sk value allows you to change the setting for secure features.

For example, to disable two features and enable a third, you would use this syntax:

CALL sa_server_option('SecureFeatures', 'CONSOLE_LOG,WEBCLIENT_LOG,-


REQUEST_LOG' );

After executing this statement, CONSOLE_LOG, and WEBCLIENT_LOG are added to the list of
secure features, and REQUEST_LOG is removed from the list.

● StatisticsCleaner The statistics cleaner fixes statistics that give bad estimates by performing scans
on tables. By default the statistics cleaner runs in the background and has a minimal impact on
performance.

Turning off the statistics cleaner does not disable the statistic governor, but when the statistics cleaner
is turned off, statistics are only created or fixed when a query is run.

1132 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● WebClientLogFile The name of the web service client log file. The web service client log file is
truncated each time you use the -zoc server option or the WebClientLogFile property to set or reset
the file name. Any backslash characters in the path must be doubled because this is a string.

● WebClientLogging This option enables and disables logging of web service clients. The
information that is logged includes HTTP requests and response data. Specify ON to start logging to
the web service client log file, and specify OFF to stop logging to the file.

Permissions
The following options, which are related to application profiling or request logging, require either DBA or
PROFILE authority:

● ProcedureProfiling
● ProfileFilterConn
● ProfileFilterUser
● RequestFilterConn
● RequestFilterDB
● RequestLogFile
● RequestLogging
● RequestLogMaxSize
● RequestLogNumFiles

All other options require DBA authority.

Side effects
None

See also
● “Procedure profiling using system procedures” [SQL Anywhere Server - SQL Usage]
● “Update column statistics” [SQL Anywhere Server - SQL Usage]
● “sa_performance_diagnostics system procedure” on page 1095
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “log_deadlocks option” [SQL Anywhere Server - Database Administration]
● “secure_feature_key” [SQL Anywhere Server - Database Administration]
● “-sk dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]
● “-sf dbeng12/dbsrv12 server option” [SQL Anywhere Server - Database Administration]

Example
The following statement disallows new connections to the database server:
CALL sa_server_option( 'ConnsDisabled', 'YES' );

The following statement disallows new connections to the current database:


CALL sa_server_option( 'ConnsDisabledForDB', 'YES' );

The following statement enables logging of all SQL statements, procedure calls, plans, blocking and
unblocking events, and specifies that a new request log be started:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1133


System procedures

CALL sa_server_option( 'RequestLogging', 'SQL+PROCEDURES+BLOCKS+PLAN


+REPLACE' );

sa_set_http_header system procedure


Permits a web service to set an HTTP response header.

Syntax
sa_set_http_header(
fldname,
val
)

Arguments
● fldname Use this CHAR(128) parameter to specify a string containing the name of one of the
HTTP header fields.

● val Use this LONG VARCHAR parameter to specify the value to which the named parameter
should be set. Setting a response header to NULL, effectively removes it.

Remarks
Setting the special header field @HttpStatus sets the status code returned with the request. The status code
is also known as the response code. For example, the following script sets the status code to 404 Not
Found:

CALL sa_set_http_header( '@HttpStatus', '404' );

You can create a user-defined status message by specifying a three digit status code with an optional
colon-delimited text message. For example, the following script outputs a status code with the message
"999 User Code":

CALL sa_set_http_header( '@HttpStatus', '999:User Code' );

Note
A user defined status text message is not translated into a database character-set when logged using the
LogOptions protocol option.

The body of the error message is inserted automatically. Only valid HTTP error codes can be used.
Setting the status to an invalid code causes a SQL error.

The sa_set_http_header procedure always overwrites the existing header value of the header field when
called.

Response headers generated automatically by the database server can be removed. For example, the
following command removes the Expires response header:

CALL sa_set_http_header( 'Expires', NULL );

1134 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Permissions
None

Side effects
None

See also
● “NEXT_HTTP_RESPONSE_HEADER function [Web service]” on page 284
● “HTTP_RESPONSE_HEADER function [Web service]” on page 244
● “Web services functions” on page 141
● “Web services system procedures” on page 996
● “LogOptions (LOPT) protocol option” [SQL Anywhere Server - Database Administration]

Example
The following example sets the Content-Type header field to text/html.
CALL sa_set_http_header( 'Content-Type', 'text/html' );

sa_set_http_option system procedure


Permits a web service to set an HTTP option for process control.

Syntax
sa_set_http_option(
optname,
val
)

Arguments
● optname Use this CHAR(128) parameter to specify a string containing the name of one of the
HTTP options.

The supported options are:

○ CharsetConversion Use this option to control whether the result set is to be automatically
converted from the character set encoding of the database to the character set encoding of the
client. The only permitted values are ON and OFF. The default value is ON.

○ AcceptCharset Use this option to specify the web server's preferences for a response character
set encoding. One or more character set encodings may be specified in order of preference. The
syntax for this option conforms to the syntax used for the HTTP Accept-Charset request-header
field specification in RFC2616 Hypertext Transfer Protocol.

An HTTP client such as a web browser may provide an Accept-Charset request header which
specifies a list of character set encodings ordered by preference. Optionally, each encoding may be
given an associated quality value (q=qvalue) which represents the client's preference for that
encoding. By default, the quality value is 1 (q=1). Here is an example:

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1135


System procedures

Accept-Charset: iso-8859-5, utf-8;q=0.8

A plus sign (+) in the AcceptCharset HTTP option value may be used as a shortcut to represent the
current database character set encoding. The plus sign also indicates that the database character set
encoding should take precedence if the client also specifies the encoding in its list, regardless of
the quality value assigned by the client.

An asterisk (*) in the AcceptCharset HTTP option may be used to indicate that the web service
should use a character set encoding preferred by the client, as long as it is also supported by the
server, when client and server do not have an intersecting list.

When sending the response, the first character set encoding preferred by both client and web
service is used. The client's order of preference takes precedence. If no mutual encoding
preference exists, then the web service's most preferred encoding is used, unless an asterisk (*)
appears in the web service list in which case the client's most preferred encoding is used.

If the AcceptCharset HTTP option is not used, the most preferred character set encoding specified
by the client and supported by the server is used. If none of the encodings specified by the client
are supported (or the client does not send an Accept-Charset request header) then the database
character set encoding is used.

If a client does not send an Accept-Charset header then one of the following actions are taken:

● If the AcceptCharset HTTP option has not been specified then the web server will use the
database character set encoding.

● If the AcceptCharset HTTP option has been specified then the web server will use its most
preferred character set encoding.

If a client does send an Accept-Charset header then one of the following actions are taken:

● If the AcceptCharset HTTP option has not been specified then the web server will attempt to
use one of the client's preferred character set encodings, starting with the most preferred
encoding. If the web server does not support any of the client's preferred encodings, it will use
the database character set encoding.

● If the AcceptCharset HTTP option has been specified then the web server will attempt to use the
first preferred character set encoding common to both lists, starting with the client's most
preferred encoding. For example, if the client sends an Accept-Charset header listing, in order
of preference, encodings iso-a, iso-b, and iso-c and the web server prefers iso-b, then iso-a, and
finally iso-c, then iso-a will be selected.
Web client: iso-a, iso-b, iso-c
Web server: iso-b, iso-a, iso-c

If the intersection of the two lists is empty, then the web server's first preferred character set is
used. From the following example, encoding iso-d will be used.
Web client: iso-a, iso-b, iso-c
Web server: iso-d, iso-e, iso-f

1136 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

If an asterisk ('*') was included in the AcceptCharset HTTP option, then emphasis would be
placed on the client's choice of encodings, resulting in iso-a being used. Essentially, the use of
an asterisk guarantees that the intersection of the two lists will not be empty.

The ideal situation occurs when both client and web service use the database character set
encoding since this eliminates the need for character set translation and improves the response
time of the web server.

Note that if the CharsetConversion option has been set to OFF, then AcceptCharset processing is
not performed.

○ SessionID Use this option to create, delete or rename an HTTP session. The database
connection is persisted when a web service sets this option to create an HTTP session but sessions
are not persisted across server restarts. If already within a session context, this call will rename the
session to the new session ID. When called with a NULL value, the session will be deleted when
the web service terminates.

The generated session keys are limited to 128 characters in length and unique across databases if
multiple databases are loaded.

○ SessionTimeout Use this option to specify the amount of time, in minutes, that the HTTP
session persists during inactivity. This time-out period is reset whenever an HTTP request uses the
given session. The session is automatically deleted when the SessionTimeout is exceeded.

● val Use this LONG VARCHAR parameter to specify the value to which the named option should
be set.

Remarks
Use this procedure within statements or procedures that handle web services to set options.

When sa_set_http_option is called from within a procedure invoked through a web service, and either the
option or option value is invalid, an error is returned.

Permissions
None

Side effects
None

See also
● “Character set conversion considerations” [SQL Anywhere Server - Programming]
● “HTTP session management on an HTTP server” [SQL Anywhere Server - Programming]
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Examples
The following example illustrates the use of sa_set_http_option to indicate the web service's preference
for database character set encoding. The UTF-8 encoding is specified as a second choice. The asterisk (*)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1137


System procedures

indicates that the web service is willing to use the character set encoding most preferred by the client,
provided that it is supported by the web server.

CALL sa_set_http_option( 'AcceptCharset', '+,UTF-8,*');

The following example illustrates the use of sa_set_http_option to correctly identify the character
encoding in use by the web service. In this example, the web server is connected to a 1251CYR database
and is prepared to serve HTML documents containing the Cyrillic alphabet to any web browser.

CREATE PROCEDURE cyrillic_html()


RESULT (html_doc XML)
BEGIN
DECLARE pos INT;
DECLARE charset VARCHAR(30);
CALL sa_set_http_option( 'AcceptCharset', 'iso-8859-5, utf-8' );
SET charset = CONNECTION_PROPERTY( 'CharSet' );
-- Change any IANA labels like ISO_8859-5:1988
-- to ISO_8859-5 for Firefox.
SET pos = LOCATE( charset, ':' );
IF pos > 0 THEN
SET charset = LEFT( charset, pos - 1 );
END IF;
CALL sa_set_http_header( 'Content-Type', 'text/html; charset=' ||
charset );
SELECT '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">' ||
XMLCONCAT(
XMLELEMENT('HTML',
XMLELEMENT('HEAD',
XMLELEMENT('TITLE', 'Cyrillic characters')
),
XMLELEMENT('BODY',
XMLELEMENT('H1', 'First 5 lowercase Russian letters'),
XMLELEMENT('P', UNISTR('\u0430\u0431\u0432\u0433\u0434'))
)
)
);
END;
CREATE SERVICE cyrillic
TYPE 'RAW'
AUTHORIZATION OFF
USER DBA
AS CALL cyrillic_html();

To illustrate the process of establishing the correct character set encoding to use, consider the following
Accept-Charset header delivered by a web browser such as Firefox to the web service. It indicates that the
browser prefers ISO-8859-1 and UTF-8 encodings but is willing to accept others.

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7

The web service will not accept the ISO-8859-1 character set encoding since the web page to be
transmitted contains Cyrillic characters. The web service prefers ISO-8859-5 or UTF-8 encodings as
indicated by the call to sa_set_http_option. In this example, the UTF-8 encoding will be chosen since it is
agreeable to both parties. The database connection property 'CharSet' indicates which encoding has been
selected by the web service. The sa_set_http_header procedure is used to indicate the HTML document's
encoding to the web browser.

Content-Type: text/html; charset=UTF-8

1138 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

If the web browser does not specify an Accept-Charset, then the web service defaults to its first
preference, ISO-8859-5. The sa_set_http_header procedure is used to indicate the HTML document's
encoding.

Content-Type: text/html; charset=ISO_8859-5

The following example sets a unique HTTP session identifier:

DECLARE sessionid VARCHAR(30);


DECLARE tm TIMESTAMP;
SET tm = NOW(*);
SET sessionid = 'MySessions_' ||
CONVERT( VARCHAR, SECONDS(tm)*1000 + DATEPART(millisecond,tm));
CALL sa_set_http_option('SessionID', sessionid);

The following example sets the time-out for an HTTP session to 5 minutes:

CALL sa_set_http_option('SessionTimeout', '5');

sa_set_soap_header system procedure


Permits the setting of SOAP headers for SOAP responses. This procedure is used within stored
procedures called from SOAP web services.

Syntax
sa_set_soap_header(
fldname,
val
)

Arguments
● fldname Use this VARCHAR parameter to specify the header key, a unique string used to
reference the given header entry (it need not be identical to the localname of the val).

● val Use this VARCHAR parameter to specify the raw XML of a top level header entry and its
children within the scope of a SOAP Header element.

Remarks
All SOAP header entries set with this procedure are serialized within the SOAP Header element when the
SOAP response message is sent. A val of NULL is not serialized. If no header entries exist for a SOAP
response, then an enclosing Header element, within the SOAP envelope, is not created.

Permissions
None

Side effects
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1139


System procedures

See also
● “Tutorial: Using SQL Anywhere to access a SOAP/DISH service” [SQL Anywhere Server -
Programming]
● “Web services functions” on page 141
● “Web services system procedures” on page 996

Example
The following example sets the SOAP header welcome to Hello:
CALL sa_set_soap_header( 'welcome', '<welcome>Hello</welcome>' )

sa_set_tracing_level system procedure


Initializes the level of tracing information to be stored in the diagnostic tracing tables.

Syntax
sa_set_tracing_level(
level
[, specified_scope
, specified_name ]
[, do_commit ]
)

Arguments
● level Use this INTEGER parameter to specify the level of diagnostic tracing to perform. Possible
values include:

○ 0 Do not generate any tracing data. This level keeps the tracing session open, but does not send
any tracing data to the diagnostic tracing tables.

○ 1 Sets a basic level of tracing.

○ 2 Sets a medium level of tracing.

○ 3 Sets a high level of tracing.

● specified_scope Use this optional LONG VARCHAR parameter to specify the tracing scope; for
example, USER, DATABASE, CONNECTION_NAME, TRIGGER, and so on.

● specified_name Use this optional LONG VARCHAR parameter to specify the identifier for the
object indicated in specified_scope.

● do_commit Use this optional TINYINT parameter to specify whether to commit, automatically,
rows inserted by this procedure. Specify 1 (the default) to commit the rows automatically
(recommended), and 0 to not commit them automatically.

1140 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Remarks
This procedure replaces the rows in the sa_diagnostic_tracing_level table, changing the tracing level and
scope to the settings specified when the procedure is called.

Setting the level 0 does not stop the tracing session. Instead, the tracing session remains attached to the
tracing database, but no tracing data is sent. The tracing session is still active when the level is 0.

This system procedure must be called from the database being profiled.

Permissions
DBA authority

Side effects
None

See also
● “Customized diagnostic tracing levels” [SQL Anywhere Server - SQL Usage]
● “Diagnostic tracing scopes” [SQL Anywhere Server - SQL Usage]
● “sa_diagnostic_tracing_level table” on page 991
● “Diagnostic tracing” [SQL Anywhere Server - SQL Usage]

Examples
The following example sets the tracing level to 1. This means that the entire database is profiled for
performance counter data, and some samples of executed statements:

CALL sa_set_tracing_level( 1 );

The following example sets the tracing level to 3, and specifies the user AG84756. This means that only
activities associated with AG84756 are traced:

CALL sa_set_tracing_level( 3, 'user', 'AG84756' );

sa_snapshots system procedure


Returns a list of snapshots that are currently active.

Syntax
sa_snapshots( )

Result set
Column name Data type Description

connection_num INT The connection ID for the connection on which the snapshot is
running.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1141


System procedures

Column name Data type Description

start_sequence_num UNSIGNED A unique number that identifies the snapshot.


BIGINT

statement_level BIT True if the snapshot was created with statement-snapshot or re-
adonly-statement-snapshot. Otherwise, false.

Remarks
Several statement snapshots can exist on one connection. For nested or interleaved statements running
under statement snapshot isolation levels, each one begins a different statement snapshot with its first read
or update.

Usually there is only one transaction snapshot per connection (one entry per connection in sa_snapshots
with statement_level=0). However, a snapshot associated with a cursor never changes after the cursor's
first fetch and a cursor opened WITH HOLD stays open through a commit or rollback. If the cursor has an
associated snapshot, then the snapshot also persists. Therefore, it is possible for multiple transaction
snapshots to exist for the same connection_num: one for the current transaction snapshot and one or more
for old transaction snapshots that persist because of WITH HOLD cursors.

Permissions
DBA authority

Side effects
None

See also
● “sa_transactions system procedure” on page 1153
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]

sa_split_list system procedure


Takes a string of values, separated by a delimiter, and returns a set of rows—one row for each value.

Syntax
sa_split_list(
str
[, delim ]
[, maxlen ]
)

Arguments
● str Use this LONG VARCHAR parameter to specify the string containing the values to be split,
separated by delim.

1142 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● delim Use this optional CHAR(10) parameter to specify the delimiter used in str to separate values.
The delimiter can be a string of any characters, up to 10 bytes. If delim is not specified, a comma is
used by default.

● maxlen Use this optional INTEGER parameter to specify the maximum length of the returned
values. For example, if maxlen is set to 3, the values in the result set are truncated to a length of 3
characters. If you specify 0 (the default), values can be any length.

Result set
Column name Data type Description

line_num INTEGER Sequential number for the row.

row_value LONG VARCHAR Value from the string, truncated to maxlen if required.

Remarks
The sa_split_list procedure accepts a string with a delimited list of values, and returns a result set with one
value per row. This is the opposite of the action performed by the LIST function [Aggregate]. An empty
string is returned for row_value if the string:

● begins with delim


● contains two successive instances of delim in the middle of the string
● ends with delim

White space within the input string is significant. If the delimiter is a space character, extra spaces in the
input string result in extra rows in the result set. If the delimiter is not a space character, spaces in the
input string are not trimmed from the values in the result set.

Permissions
None

Side effects
None

See also
● “LIST function [Aggregate]” on page 261

Examples
The following query returns a list of black colored products.
SELECT list( Name )
FROM Products
WHERE Color = 'Black';

list (Products.Name)

Tee Shirt,Baseball Cap,Visor,Shorts

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1143


System procedures

In the following example, the sa_split_list procedure is used to return the original result set from the
aggregated list.
SELECT *
FROM sa_split_list( 'Tee Shirt,Baseball Cap,Visor,Shorts' );

line_num row_value

1 Tee Shirt

2 Baseball Cap

3 Visor

4 Shorts

The following example returns a row for each word. To avoid returning rows where row_value is an
empty string, the WHERE clause must be specified.
SELECT *
FROM sa_split_list( 'one||three|four||six|', '|' )
WHERE row_value <> '';

line_num row_value

1 one

3 three

4 four

6 six

In the following example, a procedure called ProductsWithColor is created. When called, the
ProductsWithColor procedure uses sa_split_list to parse the color values specified by the user, looks in
the Color column of the Products table, and returns the name, description, size, and color for each product
that matches one of the user-specified colors.

The result of the procedure call below is the name, description, size, and color of all products that are
either white or black.
CREATE PROCEDURE ProductsWithColor( IN color_list LONG VARCHAR )
BEGIN
SELECT Name, Description, Size, Color
FROM Products
WHERE Color IN ( SELECT row_value FROM sa_split_list( color_list ) )
END;
go

SELECT * from ProductsWithColor( 'white,black' );

1144 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

sa_statement_text system procedure


Formats a SELECT statement so that individual items appear on separate lines. This is useful when
viewing long statements from the request log, in which all newline characters are removed.

Syntax
sa_statement_text( txt )

Arguments
● txt Use this LONG VARCHAR parameter to specify a SELECT statement.

Remarks
The txt that is entered must be a string (in single quotes) or a string expression.

Permissions
None

Side effects
None

See also
● “sa_get_request_times system procedure” on page 1054
● “sa_get_request_profile system procedure” on page 1053

Example
The following call formats a SELECT statement so that individual items appear on separate lines.

CALL sa_statement_text( 'SELECT * FROM car WHERE name=''Audi''' );

stmt_text

1 SELECT *

2 FROM car

3 WHERE name = 'Audi'

sa_table_fragmentation system procedure


Reports information about the fragmentation of database tables.

Syntax
sa_table_fragmentation(
[ tbl_name

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1145


System procedures

[, owner_name ] ]
)

Arguments
● tbl_name Use this optional CHAR(128) parameter to specify the name of the table to check for
fragmentation.

● owner_name Use this optional CHAR(128) parameter to specify the owner of tbl_name.

Result set
Column name Data type Description

TableName CHAR(128) Name of the table.

rows UNSIGNED INTEGER Number of rows in the table.

row_segments UNSIGNED BIGINT Number of row segments in the table.

segs_per_row DOUBLE Number of segments per row.

Remarks
Database administrators can use this procedure to obtain information about the fragmentation in a
database's tables. If no arguments are supplied, results are returned for all tables in the database.

When database tables become excessively fragmented, you can run REORGANIZE TABLE or rebuild
the database to reduce table fragmentation and improve performance.

Permissions
DBA authority

Side effects
None

See also
● “Reduce table fragmentation” [SQL Anywhere Server - SQL Usage]
● “Database rebuilds” [SQL Anywhere Server - SQL Usage]
● “REORGANIZE TABLE statement” on page 852

Example
CALL sa_table_fragmentation( 'Products','GROUPO' );

sa_table_page_usage system procedure


Reports information about the page usage of database tables.

1146 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Syntax
sa_table_page_usage( )

Result set
Column name Data type Description

TableId UNSIGNED INTEGER The table ID.

TablePages INTEGER The number of table pages used by the table.

PctUsedT INTEGER The percentage of used table page space.

IndexPages INTEGER The number of index pages used by the table.

PctUsedI INTEGER The percentage of used index page space.

PctOfFile INTEGER The percentage of the total database file the table occupies.

TableName CHAR(128) The table name.

Remarks
The results include the same information provided by the Information utility. When the
progress_messages database option is set to Raw or Formatted, progress messages are sent from the
database server to the client while the sa_table_page_usage system procedure is running.

Permissions
DBA authority

Side effects
None

See also
● “Information utility (dbinfo)” [SQL Anywhere Server - Database Administration]
● “progress_messages option” [SQL Anywhere Server - Database Administration]

sa_table_stats system procedure


Reports information about how many pages have been read from each table.

Syntax
sa_table_stats( )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1147


System procedures

Result set
Column name Data type Description

table_id INT The table ID.

creator CHAR(128) The user name of the table's creator.

table_name CHAR(128) The table name.

count UNSIGNED BIGINT The estimated number of rows in the table, taken from
SYSTAB.

table_page_count UNSIGNED BIGINT The number of main pages used by the table.

table_page_cached UNSIGNED BIGINT The number of tables pages currently stored in the cache.

table_page_reads UNSIGNED BIGINT The number of page reads performed for pages in the
main table.

ext_page_count UNSIGNED BIGINT The estimated number of pages in the table

ext_page_cached UNSIGNED BIGINT Reserved for future use.

ext_page_reads UNSIGNED BIGINT Reserved for future use.

Remarks
Each row returned by the sa_table_stats procedure describes a table for which the optimizer is
maintaining page statistics. The sa_table_stats procedure can be used to find which tables are using cache
memory and how many disk reads are being performed for each table. For example, you can use the
sa_table_stats procedure to find the table that is generating the most disk reads. The results of the
procedure represent estimates and should be used only for diagnostic purposes.

The table_page_cached column indicates how many pages of the table are currently stored in the cache,
and the table_page_reads column indicates how many table pages have been read from disk since the
optimizer started maintaining counts for the table. These statistics are not stored persistently within the
database; they represent the activity on tables after they are loaded into memory for the first time.

Permissions
DBA authority

Side effects
None

See also
● “SYSTAB system view” on page 1241

1148 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

sa_text_index_stats system procedure


Returns statistical information about the text indexes in the database.

Syntax
sa_text_index_stats( )

Remarks
Use the sa_text_index_stats system procedure to view statistical information for each text index in the
database. The following table describes the information returned by sa_text_index_stats.

Column name Type Description

owner_id UNSIGNED INT ID of the owner of the table

table_id UNSIGNED INT ID of the table

index_id UNSIGNED INT ID of the text index

text_config_id UNSIGNED BIGINT ID of the text configuration object referenced by the index

owner_name CHAR(128) Name of the owner

table_name CHAR(128) Name of the table

index_name CHAR(128) Name of the text index

text_config_name CHAR(128) Name of the text configuration object

doc_count UNSIGNED BIGINT Total number of indexed column values in the text index

doc_length UNSIGNED BIGINT Total length of data in the text index

pending_length UNSIGNED BIGINT Total length of the pending changes

deleted_length UNSIGNED BIGINT Total length of the pending deletions

last_refresh TIMESTAMP Date and time of the last refresh

The pending_length, deleted_length, and last_refresh values are 0 for IMMEDIATE REFRESH text
indexes.

For MANUAL REFRESH text indexes, you can use doc_length, pending_length, and deleted_length to
decide whether to refresh the text index, and the type of refresh to perform (rebuild vs. incremental).

Permissions
DBA authority

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1149


System procedures

Side effects
None

See also
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Text index concepts and reference” [SQL Anywhere Server - SQL Usage]
● “DROP TEXT INDEX statement” on page 713
● “REFRESH TEXT INDEX statement” on page 846
● “TRUNCATE TEXT INDEX statement” on page 935
● “sa_refresh_text_indexes system procedure” on page 1109
● “sa_text_index_vocab system procedure” on page 1150
● “SYSTEXTIDX system view” on page 1249

Example
The following statement returns statistical information for each text index in the database:
CALL sa_text_index_stats( );

sa_text_index_vocab system procedure


Lists all terms that appear in a CHAR text index, and the total number of indexed values that each term
appears in.

Syntax
sa_text_index_vocab(
'indexname',
'tabname',
[ 'tabowner' ]
)

Arguments
● indexname Use this CHAR(128) parameter to specify the name of the text index.

● tabname Use this CHAR(128) parameter to specify the name of the table on which the text index
is built.

● tabowner Use this optional CHAR(128) parameter to specify the owner of the table.

Result set
Column name Data type Description

term VARCHAR(60) A term in the text index.

freq BIGINT The number of indexed values the term appears in.

1150 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Remarks
The sa_text_index_vocab system procedure returns all terms that appear in a text index, and the total
number of indexed values that each term appears in (which is less than the total number of occurrences if
the term appears multiple times in some indexed values).

Permissions
DBA authority, or SELECT permission on the indexed table is required.

Side effects
None

See also
● “sa_text_index_vocab_nchar system procedure” on page 1152
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Term and phrase search” [SQL Anywhere Server - SQL Usage]
● “DROP TEXT INDEX statement” on page 713
● “REFRESH TEXT INDEX statement” on page 846
● “TRUNCATE TEXT INDEX statement” on page 935
● “sa_refresh_text_indexes system procedure” on page 1109
● “SYSTEXTIDX system view” on page 1249

Example
The following example builds a text index called VocabTxtIdx on the Products.Description column in the
sample database. The next statement executes the sa_text_index_vocab system procedure to return all the
terms that appear in the text index.
CREATE TEXT INDEX VocabTxtIdx2 ON Products( Description );
SELECT *
FROM sa_text_index_vocab( 'VocabTxtIdx2', 'Products', 'GROUPO' );

term freq

Cap 2

Cloth 1

Cotton 2

Crew 1

Hooded 1

neck 2

... ...

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1151


System procedures

sa_text_index_vocab_nchar system procedure


Lists all terms that appear in an NCHAR text index, and the total number of indexed values that each term
appears in.

Syntax
sa_text_index_vocab(
'indexname',
'tabname',
[ 'tabowner' ]
)

Arguments
● indexname Use this CHAR(128) parameter to specify the name of the text index.

● tabname Use this CHAR(128) parameter to specify the name of the table on which the text index
is built.

● tabowner Use this optional CHAR(128) parameter to specify the owner of the table.

Result set
Column name Data type Description

term NCHAR(60) A term in the text index.

freq BIGINT The number of indexed values the term appears in.

Remarks
The sa_text_index_vocab_nchar system procedure returns all terms that appear in a text index, and the
total number of indexed values that each term appears in (which is less than the total number of
occurrences if the term appears multiple times in some indexed values).

Permissions
DBA authority, or SELECT permission on the indexed table is required.

Side effects
None

1152 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

See also
● “sa_text_index_vocab system procedure” on page 1150
● “Full text search” [SQL Anywhere Server - SQL Usage]
● “Term and phrase search” [SQL Anywhere Server - SQL Usage]
● “DROP TEXT INDEX statement” on page 713
● “REFRESH TEXT INDEX statement” on page 846
● “TRUNCATE TEXT INDEX statement” on page 935
● “sa_refresh_text_indexes system procedure” on page 1109
● “SYSTEXTIDX system view” on page 1249

sa_transactions system procedure


Returns a list of transactions that are currently active.

Syntax
sa_transactions( )

Result set
Column name Data type Description

connection_num INT The connection ID for the connection the transaction is running
on.

transaction_id INT The ID that uniquely identifies the transaction as long as the da-
tabase server keeps track of it. IDs are reused as old transaction
information is discarded.

start_time TIMESTAMP The TIMESTAMP for when the transaction started.

start_se- UNSIGNED The start sequence number for the transaction.


quence_num BIGINT

end_se- UNSIGNED Then end sequence number for the transaction if it has been
quence_num BIGINT committed or rolled back, otherwise, NULL.

committed bit The state of the transaction: true if the transaction ended with a
COMMIT, false if it ended with a ROLLBACK, and NULL if
the transaction is still active.

version_entries unsigned INT The count of the number of row versions the transaction has
saved.

Remarks
This procedure provides information about the transactions that are currently running against the database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1153


System procedures

Permissions
DBA authority

Side effects
None

See also
● “sa_snapshots system procedure” on page 1141
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]

sa_unload_cost_model system procedure


Unloads the current cost model to the specified file.

Syntax
sa_unload_cost_model ( file_name )

Arguments
● file_name Use this CHAR(256) parameter to specify the name of the file in which to unload the
data. Because it is the database server that executes the system procedure, file_name specifies a file on
the database server computer, and a relative file_name specifies a file relative to the database server's
starting directory.

Remarks
The optimizer uses cost models to determine optimal access plans for queries. The database server
maintains a cost model for each database. The cost model for a database can be recalibrated at any time
using the CALIBRATE SERVER clause of the ALTER DATABASE statement. For example, you might
decide to recalibrate the cost model if you move the database onto non-standard hardware.

The sa_unload_cost_model system procedure allows you save a cost model to an ASCII file (file_name).
You can then log into another database and use the sa_load_cost_model system procedure to load the cost
model from the first database into the second one. This avoids having to recalibrate the second database.

Note
The sa_unload_cost_model system procedure does not include CALIBRATE PARALLEL READ
information in the file.

Using the sa_unload_cost_model system procedure eliminates repetitive, time-consuming recalibration


activities when there is a large number of similar hardware installations.

Permissions
DBA authority

You must have write permissions where the file is created.

1154 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Side effects
None

See also
● “ALTER DATABASE statement” on page 400
● “sa_load_cost_model system procedure” on page 1070
● “Advanced: Query optimization” [SQL Anywhere Server - SQL Usage]

Example
The following example unloads the cost model to a file called costmodel8:
CALL sa_unload_cost_model( 'costmodel8' );

sa_user_defined_counter_add system procedure


Adjusts the value of a user-defined counter by a specified amount.

Syntax
sa_user_defined_counter_add ( counter_name
[, delta
[, apply_to_con
[, appy_to_db
[, apply_to_server ] ] ] ]
)

Arguments
● counter_name Use this VARCHAR(128) parameter to specify the name of the user-defined
counter whose value you want to change. Examples of user-defined counter names are
UserDefinedCounterRate01 and UserDefinedCounterRaw01.

● delta The amount that the user-defined counter is incremented or decremented by. The default is 1.

● apply_to_con Use this INT parameter to specify whether to adjust the counter value for the
current connection. 0 means do not adjust the value, and 1 means adjust the value. The default is 1.

● apply_to_db Use this INT parameter to specify whether to adjust the counter value for the
database. 0 means do not adjust the value, and 1 means adjust the value. The default is 1.

● apply_to_server Use this INT parameter to specify whether to adjust the counter value for the
database server. 0 means do not adjust the value, and 1 means adjust the value. The default is 1.

Remarks
This procedure returns 1 if delta is defined, and 0 otherwise. The procedure returns 0 when delta is not
defined, and returns an error code if an error occurs. Examples of errors include:

● an invalid counter name


● an invalid value for the apply_to_server, apply_to_db, or apply_to_con parameter.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1155


System procedures

Concurrent access to counters is applied atomically, so a counter value can be incremented from multiple,
concurrent requests.

Permissions
DBA authority

Side effects
None

See also
● “sa_user_defined_counter_set system procedure” on page 1156
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “Accessing database property values” [SQL Anywhere Server - Database Administration]
● “Accessing database server property values” [SQL Anywhere Server - Database Administration]
● “User-defined statistics” [SQL Anywhere Server - SQL Usage]
● “User-defined properties” [SQL Anywhere Server - Database Administration]

Example
The following statement changes the value of UserDefinedCounterRate01 to 0 for the current connection,
database, and database server:
SELECT dbo.sa_user_defined_counter_set( 'UserDefinedCounterRate01', 0, 1, 1,
1 );

sa_user_defined_counter_set system procedure


Sets a user-defined counter to a specified value.

Syntax
sa_user_defined_counter_set ( counter_name
[, value
[, apply_to_con
[, appy_to_db
[, apply_to_server ] ] ] ]
)

Arguments
● counter_name Use this VARCHAR(128) parameter to specify the name of the user-defined
counter whose value you want to change. Examples of user-defined counter names are
UserDefinedCounterRate01 and UserDefinedCounterRaw01.

● value The amount that the user-defined counter is changed to. The default is 1.

● apply_to_con Use this INT parameter to specify whether to adjust the counter value for the
current connection. 0 means do not adjust the value, and 1 means adjust the value. The default is 1.

1156 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● apply_to_db Use this INT parameter to specify whether to adjust the counter value for the
database. 0 means do not adjust the value, and 1 means adjust the value. The default is 1.

● apply_to_server Use this INT parameter to specify whether to adjust the counter value for the
database server. 0 means do not adjust the value, and 1 means adjust the value. The default is 1.

Remarks
The procedure returns 1 if value is defined, and 0 otherwise. The procedure returns 0 when value is not
defined, and returns an error code if an error occurs. Example of errors include:

● an invalid counter name


● an invalid value for the apply_to_server, apply_to_db, or apply_to_con parameter.

Concurrent access to counters is applied atomically, so a counter value can be reset from multiple,
concurrent requests.

Permissions
DBA authority

Side effects
None

See also
● “sa_user_defined_counter_add system procedure” on page 1155
● “Accessing connection property values” [SQL Anywhere Server - Database Administration]
● “Accessing database property values” [SQL Anywhere Server - Database Administration]
● “Accessing database server property values” [SQL Anywhere Server - Database Administration]
● “User-defined properties” [SQL Anywhere Server - Database Administration]
● “User-defined statistics” [SQL Anywhere Server - SQL Usage]

Example
The following statement sets the value of UserDefinedCounterRate01 to 0 for the current connection,
database, and database server:

SELECT dbo.sa_user_defined_counter_set( 'UserDefinedCounterRate01', 0, 1, 1,


1 );

sa_validate system procedure


Validates all, or parts, of a database.

Syntax
sa_validate(
[ tbl_name [, owner_name ] ]
)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1157


System procedures

Arguments
● tbl_name Use this optional VARCHAR(128) parameter to specify the name of a table or
materialized view to validate.

● owner_name Use this optional VARCHAR(128) parameter to specify an owner. When specified
by itself, all tables and materialized views owned by the owner are validated.

Permissions
DBA authority

Side effects
None

Remarks
Argument Type of validation
specified

None All tables, materialized views, and indexes in the database are validated. The data-
base itself is also validated, including checksum validation.

owner_name All tables, materialized views, and indexes owned by the specified user are valida-
ted.

tbl_name The specified table, or materialized view, and all of its indexes, that are owned by
the current user are validated.

owner_name The specified table, or materialized view, and all of its indexes, that are owned by
and tbl_name the specified user are validated.

The values for tbl_name and owner_name are strings and must be enclosed in quotes.

The procedure returns a single column named Messages. Errors returned during validation appear in the
column. If validation succeeds without error, the column contains No error detected.

Caution
Validating a table or an entire database should be performed while no connections are making changes to
the database; otherwise, errors may be reported indicating some form of database corruption even though
no corruption actually exists.

Example
The following statement performs a validation of tables and materialized views owned by DBA:
CALL sa_validate( owner_name = 'DBA' );

1158 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

sa_verify_password system procedure


Validates the password of the current user.

Syntax
sa_verify_password( curr_pswd )

Arguments
● curr_pwsd Use this CHAR(128) parameter to specify the password of the current database user.

Remarks
This procedure is used by sp_password. If the password matches, it is accepted. If the password does not
match, an error is returned.

Permissions
None

Side effects
None

See also
● “Adaptive Server Enterprise system procedures” on page 999

sp_forward_to_remote_server system procedure


Syntax
sp_forward_to_remote_server (
server_name,
sql
)

Arguments
● server_name Use this CHAR(128) parameter to specify the name of the remote server the SQL
statement is executed on.

● sql Use this LONG VARCHAR parameter to specify the SQL statement to execute on the remote
server.

Remarks
This procedure allows an application to execute a SQL statement on a remote server and retrieve any
result sets generated by that statement. The SQL statement is sent verbatim to the remote server and
therefore SQL Anywhere does not need to able to parse the statement.

To use this system procedure, you must define the remote server with the CREATE SERVER statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1159


System procedures

Unlike the FORWARD TO statement, sp_forward_to_remote_server can be used within procedures.


However, this stored procedure cannot be used within the FROM clause of a SELECT statement since the
schema of the remote result sets is arbitrary. You can fetch remote result sets by declaring a cursor on a
stored procedure that is called in the sp_forward_to_remote_server procedure.

Note
If the SQL statement returns multiple result sets, the sp_forward_to_remote_server stored procedure
returns each remote result set in turn.

Permissions
None

Side effects
There are no local side effects to executing this stored procedure; however, since the SQL statement that
is executed on the remote server is arbitrary, there may be side effects on the remote server.

See also
● “FORWARD TO statement” on page 736
● “CREATE SERVER statement” on page 601

Example
The following example uses the sp_forward_to_remote_server stored procedure and a local function to
determine the number of tables that a remote SQL Anywhere 12 database has.

1. Run the following command to create two databases named testdb1 and testdb2:
dbinit testdb1
dbinit testdb2

2. Start both databases with the same SQL Anywhere server.


dbeng12 -n mytest testdb1 testdb2

3. Connect to testdb1 from Interactive SQL.


dbisql -c "uid=DBA;pwd=sql;server=mytest;dbn=testdb1;links=SharedMemory"

4. Create a remote data access server on testdb2.


CREATE SERVER rem CLASS 'saodbc' USING 'driver=SQL Anywhere 12 ;
eng = mytest ; dbn = testdb2 ; links = SharedMemory'

5. Assume that external logins are not needed. Create the local function that calls
sp_forward_to_remote_server.
CREATE FUNCTION fetch_num_remote_tables ( IN server char(128) ) RETURNS
int
BEGIN
DECLARE num_tables int;
DECLARE curs CURSOR FOR CALL sp_forward_to_remote_server
( server, 'SELECT COUNT(*) FROM sys.systable' );
OPEN curs;

1160 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

FETCH next curs INTO num_tables;


CLOSE curs;
RETURN num_tables;
END

6. Fetch the number of tables from the remote server.

SELECT fetch_num_remote_tables( 'rem' )

sp_get_last_synchronize_result system procedure


Returns information about the last synchronization initiated by the SYNCHRONIZE statement.

Syntax
sp_get_last_synchronize_result (
conn_id,
complete_only
)

Arguments
● conn_id Use this INTEGER parameter to specify the connection ID number for a connection on
which the SYNCHRONIZE statement was executed. If no value is specified, then the connection ID
of the current connection is used.

● complete_only Set this BIT parameter to 1 to have the stored procedure return information about
completed synchronizations. Set the parameter to 0 to return information about synchronizations that
are currently active.

Result set
Column Data type Description
name

row_id BIGINT The primary key of the table used to determine the order in which
rows were inserted into the table.

conn_id UNSIGNED INT The connection id number of the connection that executed the
SYNCHRONIZE statement that generated this event.

result_time TIMESTAMP The time the event was added to the synchronize_results table.

result_type CHAR(128) The type of event.

parm_id INTEGER Each event can have zero or more parameters associated with it.
The parm_id column orders the parameters associated with each
event.

parm_result long varchar The message text associated with the event parameter.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1161


System procedures

Remarks
To view details of past or current synchronizations, you can use the sp_get_last_synchronize_result stored
procedure as an alternative to directly querying the synchronize_results and synchronize_parameters
global shared temporary table. The stored procedure only returns the results of the last synchronization for
the specified connection ID number. If you do not specify any parameters, the last completed
synchronization on the current connection is returned.

You can also use this stored procedure to monitor the progress of a synchronization on a connection that
is different from your current connection. To monitor the progress of a synchronization on a different
connection:

1. Execute a SELECT CONNECTION_PROPERTY statement to determine the connection ID of your


current connection.

2. Execute a SYNCHRONIZE statement using the connection ID returned by the SELECT


CONNECTION_PROPERTY statement.

3. On a different connection, execute a SELECT CONNECTION_PROPERTY statement and set the


complete_only parameter to 0. Information about the last synchronization for the specified connection
is returned, even if the synchronization is incomplete.

Following is a list of events and their associated parm_id values from the synchronize_parameters table:

Event parm_id Description


value

DBSC_EVENTTYPE_ER- 0 The text of the error message.


ROR_MSG

1 The message id associated with the message.

DBSC_EVEN- 0 The text of the warning message.


TTYPE_WARNING_MSG

1 The message id associated with the message.

DBSC_EVENTTYPE_IN- 0 The text of the information message.


FO_MSG

1 The message id associated with the message.

DBSC_EVENTTYPE_PRO- 0 The new progress index value.


GRESS_INDEX

DBSC_EVENTTYPE_PRO- 0 The new progress text.


GRESS_TEXT

DBSC_EVENTTYPE_TITLE 0 The new window title.

1162 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Event parm_id Description


value

DBSC_EVEN- 0 The exit code from the synchronization. 0 indicates


TTYPE_SYNC_DONE success.

DBSC_EVEN- 0 The communications protocol being used.


TTYPE_ML_CONNECT

1 The network protocol options being used.

DBSC_EVEN- 0 The number of insert/update operations committed.


TTYPE_DOWNLOAD_COM-
MITTED

1 The number of delete operations committed.

DBSC_EVENTTYPE_UP- 0 The number of insert operations uploaded.


LOAD_SENT

1 The number of update operations uploaded.

2 The number of delete operations uploaded.

Permissions
DBA

Side effects
None

See also
● “SYNCHRONIZE statement [MobiLink]” on page 925
● “DBSC_Event structure [Dbmlsync .NET]” [MobiLink - Client Administration]

Example
The following example returns information about the last synchronization that completed on the current
connection.
CALL sp_get_last_synchronize_result();

The following example uses named parameters when calling the sp_get_last_synchronize_result system
procedure, and returns information about the last completed synchronization that was initiated from
connection ID 25.
CALL sp_get_last_synchronize_result(
@conn_id=25,
@complete_only=1);

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1163


System procedures

sp_login_environment system procedure


Sets connection options when users log in.

Syntax
sp_login_environment( )

Remarks
sp_login_environment is the default procedure called by the login_procedure database option.

It is recommended that you do 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;

Permissions
None

Side effects
None

See also
● “login_procedure option” [SQL Anywhere Server - Database Administration]

sp_remote_columns system procedure


Produces a list of the columns in 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(
server_name,
table_name
[, table_owner
[, table_qualifier] ]
)

Arguments
● server_name Use this CHAR(128) parameter to specify a string containing the server name as
specified by the CREATE SERVER statement.

1164 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● table_name Use this CHAR(128) parameter to specify the name of the remote table.

● table_owner Use this optional CHAR(128) parameter to specify the owner of table_name.

● table_qualifier Use this optional CHAR(128) parameter to specify the name of the database in
which table_name is located.

Result set
Column name Data type Description

database CHAR(128) The database name.

owner CHAR(128) The database owner name.

table_name CHAR(128) The table name.

column_name CHAR(128) The name of a column.

domain_id SMALLINT An INTEGER which indicates the data type of the column.

width INTEGER The meaning of this column depends on the data type. For character
types width represents the number of characters.

scale SMALLINT The meaning of this column depends on the data type. For NUMER-
IC data types scale is the number of digits after the decimal point.

nullable SMALLINT If NULL column values are allowed, the value is 1. Otherwise the
value is 0.

base_type_str CHAR(4096) The annotated type string representing the physical type of the col-
umn.

Remarks
If you are entering a CREATE EXISTING TABLE statement and you are specifying 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. If you specify a database, you
must either specify an owner or provide the value NULL.

Standards and compatibility


● Sybase Supported by Open Client/Open Server.

Permissions
None

Side effects
None

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1165


System procedures

See also
● “Remote data access” [SQL Anywhere Server - SQL Usage]
● “Server classes for remote data access” [SQL Anywhere Server - SQL Usage]
● “CREATE SERVER statement” on page 601

Example
The following example returns columns from the SYSOBJECTS table in the production database on an
Adaptive Server Enterprise server named asetest. The owner is unspecified.
CALL sp_remote_columns( 'asetest', 'sysobjects', null, 'production' );

sp_remote_exported_keys system procedure


Provides information about tables with foreign keys on a specified primary table.

The server must be defined with the CREATE SERVER statement to use this system procedure.

Syntax
sp_remote_exported_keys(
server_name
, sp_name
[, sp_owner
[, sp_qualifier ] ]
)

Arguments
● server_name Use this CHAR(128) parameter to specify the server the primary table is located on.

● sp_name Use this CHAR(128) parameter to specify the table containing the primary key.

● sp_owner Use this optional CHAR(128) parameter to specify the primary table's owner.

● sp_qualifier Use this optional CHAR(128) parameter to specify the database containing the
primary table.

Result set
Column name Data type Description

pk_database CHAR(128) The database containing the primary key table.

pk_owner CHAR(128) The owner of the primary key table.

pk_table CHAR(128) The primary key table.

pk_column CHAR(128) The name of the primary key column.

fk_database CHAR(128) The database containing the foreign key table.

1166 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Column name Data type Description

fk_owner CHAR(128) The foreign key table's owner.

fk_table CHAR(128) The foreign key table.

fk_column CHAR(128) The name of the foreign key column.

key_seq SMALLINT The key sequence number.

fk_name CHAR(128) The foreign key name.

pk_name CHAR(128) The primary key name.

Remarks
This procedure provides information about the remote tables that have a foreign key on a particular
primary table. The result set for the sp_remote_exported_keys system procedure includes the database,
owner, table, column, and name for both the primary and the foreign key, and the foreign key sequence
for the foreign key columns. The result set may vary because of the underlying ODBC and JDBC calls,
but information about the table and column for a foreign key is always returned.

Permissions
None

Side effects
None

See also
● “CREATE SERVER statement” on page 601
● “Foreign keys” [SQL Anywhere Server - SQL Usage]

Example
This example uses named parameters when calling the system procedure, and returns information about
the remote tables with foreign keys on the SYSOBJECTS table, in the production database, on a server
named asetest:

CALL sp_remote_exported_keys(
@server_name='asetest',
@sp_name='sysobjects',
@sp_qualifier='production' );

sp_remote_imported_keys system procedure


Provides information about remote tables with primary keys that correspond to a specified foreign key.

The server must be defined with the CREATE SERVER statement to use this system procedure.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1167


System procedures

Syntax
sp_remote_imported_keys(
server_name
, sp_name
[, sp_owner
[, sp_qualifier ] ]
)

Arguments
● server_name Use this optional CHAR(128) parameter to specify the server the foreign key table is
located on. A value is required for this parameter.

● sp_name Use this optional CHAR(128) parameter to specify the table containing the foreign key.
A value is required for this parameter.

● sp_owner Use this optional CHAR(128) parameter to specify the foreign key table's owner.

● sp_qualifier Use this optional CHAR(128) parameter to specify the database containing the
foreign key table.

Result set
Column name Data type Description

pk_database CHAR(128) The database containing the primary key table.

pk_owner CHAR(128) The owner of the primary key table.

pk_table CHAR(128) The primary key table.

pk_column CHAR(128) The name of the primary key column.

fk_database CHAR(128) The database containing the foreign key table.

fk_owner CHAR(128) The foreign key table's owner.

fk_table CHAR(128) The foreign key table.

fk_column CHAR(128) The name of the foreign key column.

key_seq SMALLINT The key sequence number.

fk_name CHAR(128) The foreign key name.

pk_name CHAR(128) The primary key name.

Remarks
Foreign keys reference a row in a separate table that contains the corresponding primary key. This
procedure allows you to obtain a list of the remote tables with primary keys that correspond to a particular
foreign table. The sp_remote_imported_keys result set includes the database, owner, table, column, and

1168 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

name for both the primary and the foreign key, and the foreign key sequence for the foreign key columns.
The result set may vary because of the underlying ODBC and JDBC calls, but information about the table
and column for a primary key is always returned.

Permissions
None

Side effects
None

See also
● “CREATE SERVER statement” on page 601
● “Foreign keys” [SQL Anywhere Server - SQL Usage]

Example
The following example uses named parameters when calling the procedure, and returns the tables with
primary keys that correspond to a foreign key on the SYSOBJECTS table in the asetest server:
CALL sp_remote_imported_keys(
@server_name='asetest',
@sp_name='sysobjects',
@sp_qualifier='production' );

sp_remote_primary_keys system procedure


Provides primary key information about remote tables using remote data access.

Syntax
sp_remote_primary_keys(
server_name
, table_name
[, table_owner
[, table_qualifier ] ]
)

Arguments
● server_name Use this CHAR(128) parameter to specify the server the remote table is located on.

● table_name Use this CHAR(128) parameter to specify the remote table.

● table_owner Use this optional CHAR(128) parameter to specify the owner of the remote table.

● table_qualifier Use this optional CHAR(128) parameter to specify the name of the remote
database.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1169


System procedures

Result set
Column name Data type Description

database CHAR(128) The name of the remote database.

owner CHAR(128) The owner of the remote table.

table-name CHAR(128) The remote table.

column-name CHAR(128) The column name.

key-seq SMALLINT The primary key sequence number.

pk_name CHAR(128) The primary key name.

Remarks
This system procedure provides primary key information about remote tables using remote data access.

Because of differences in the underlying ODBC/JDBC calls, the information returned differs slightly
from the catalog/database value depending upon the remote data access class that is specified for the
server.

Standards and compatibility


● Sybase Supported by Open Client/Open Server.

Permissions
None

Side effects
None

sp_remote_tables system procedure


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(
server_name
[, table_name
[, table_owner
[, table_qualifier
[, with_table_type ] ] ] ]
)

1170 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Arguments
● server_name Use this CHAR(128) parameter to specify the server the remote table is located on.

● table_name Use this optional CHAR(128) parameter to specify the remote table.

● table_owner Use this optional CHAR(128) parameter to specify the owner of the remote table.

● table_qualifier Use this optional CHAR(128) parameter to specify the database in which
table_name is located.

● with_table_type Use this optional BIT parameter to specify the type of remote table. This
argument is a bit type and accepts two values, 0 (the default) and 1. You must enter the value 1 if you
want the result set to include a column that lists table types.

Result set
Column name Data type Description

database CHAR(128) The name of the remote database.

owner CHAR(128) The name of the remote database owner.

table-name CHAR(128) The remote table.

table-type CHAR(128) Specifies the table type. The value depends on the type of remote serv-
er. For example, TABLE, VIEW, SYS, and GBL TEMP are possible
values.

Remarks
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.

The procedure accepts five parameters. If a table, owner, or database name is given, the list of tables will
be limited to only those that match the arguments.

Standards and compatibility


● Sybase Supported by Open Client/Open Server.

Permissions
None

Side effects
None

See also
● “Remote data access” [SQL Anywhere Server - SQL Usage]
● “Server classes for remote data access” [SQL Anywhere Server - SQL Usage]
● “CREATE SERVER statement” on page 601

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1171


System procedures

Examples
To get a list of all the Microsoft Excel worksheets available from an ODBC data source referenced by a
server named excel:

CALL sp_remote_tables( 'excel' );

To get a list of all the tables owned by fred in the production database in an Adaptive Server Enterprise
server named asetest:

CALL sp_remote_tables( 'asetest', null, 'fred', 'production' );

sp_servercaps system procedure


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( sname )

Arguments
● sname Use this CHAR(64) parameter to specify a server defined with the CREATE SERVER
statement. sname must be the same server name used in the CREATE SERVER statement.

Remarks
This procedure displays information about a remote server's capabilities. The capability information is
used to determine how much of a SQL statement can be forwarded to a remote server. The
ISYSCAPABILITY system table, which lists the server capabilities, is not populated until a connection is
made to the first remote server.

Standards and compatibility


● Sybase Supported by Open Client/Open Server.

Permissions
None

Side effects
None

See also
● “SYSCAPABILITY system view” on page 1197
● “SYSCAPABILITYNAME system view” on page 1197
● “Remote data access” [SQL Anywhere Server - SQL Usage]
● “Server classes for remote data access” [SQL Anywhere Server - SQL Usage]
● “CREATE SERVER statement” on page 601

1172 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Example
To display information about the remote server testasa:
CALL sp_servercaps( 'testasa' );

sp_tsql_environment system procedure


Sets connection options when users connect from jConnect or Open Client applications.

Syntax
sp_tsql_environment( )

Remarks
The sp_login_environment procedure is the default procedure specified by the login_procedure database
option. For each new connection, the procedure specified by login_procedure is called. 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 Adaptive Server Enterprise
behavior.

If you want 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.

Permissions
None

Side effects
None

See also
● “sp_login_environment system procedure” on page 1164
● “login_procedure option” [SQL Anywhere Server - Database Administration]

Example
Here is the text of the sp_tsql_environment procedure:
CREATE PROCEDURE dbo.sp_tsql_environment()
BEGIN
IF db_property( 'IQStore' ) = 'Off' THEN
-- SQL Anywhere datastore
SET TEMPORARY OPTION close_on_endtrans='OFF';
END IF;
SET TEMPORARY OPTION ansinull='OFF';
SET TEMPORARY OPTION tsql_variables='ON';
SET TEMPORARY OPTION ansi_blanks='ON';
SET TEMPORARY OPTION chained='OFF';
SET TEMPORARY OPTION quoted_identifier='OFF';
SET TEMPORARY OPTION allow_nulls_by_default='OFF';

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1173


System procedures

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

st_geometry_dump system procedure


Disassembles a geometry into its lowest level component geometries.

Syntax
st_geometry_dump ( geometry [, options ] )

Arguments
● geometry The geometry value to be disassembled.

● options A VARCHAR(255) string of parameters and values, separated by semicolons, you can use
to configure the output of the procedure.

The following table lists the parameters that can be specified:

Parameter Default Allowed Description


value values

Format Original Original, The format to return the geometry in. Specifying Original
Internal, or returns the geometry in its original format. Specifying In-
Mixed ternal returns the geometry in its normalized format. Spec-
ifying Mixed returns whatever stored formats are availa-
ble, one row per format.

Expand- Yes Yes, No By default, when disassembling a geometry containing


Points points (such as ST_LineString or ST_MultiPoint), the
st_geometry_dump system procedure outputs the constitu-
ent points to separate rows. Set ExpandPoints to No if you
do not want these extra rows to be generated.

MaxDepth -1 -1, any By default, st_geometry_dump system procedure contin-


number ues to disassembles an object hierarchy until it reaches the
greater or leaf objects. The MaxDepth parameter can be set to limit
equal to the number of levels in the hierarchy the geometry is disas-
zero sembled. With a value of 0, only the root geometry is re-
turned. With a value of 1, the geometry and its immediate
children are returned, and so on.

1174 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Parameter Default Allowed Description


value values

SetGeom Yes Yes, No The st_geometry_dump system procedure returns a col-


umn that is the ST_Geometry associated with an object in
the original type hierarchy. If this column is not needed,
the parameter SetGeom can be set to No to reduce the run-
ning time and output size of the procedure.

Validate Basic None, Ba- By default, the st_geometry_dump system procedure ap-
sic, Full plies the validation rules that the database server uses
when loading geometries, and sets the Valid column of the
result set to 1 if the object in the row matches these rules.
The Validate parameter can be set to None to disable this
checking, or it can be set to Full to also apply the addition-
al checks performed by the ST_IsValid method. Full
checking takes longer to perform.

Returns
The following table describes the results returned by the st_geometry_dump procedure:

Column Data type Description

id UNSIGNED BI- A unique ID for this row in the results.


GINT

parent_id UNSIGNED BI- The ID of the immediate parent of this object.


GINT

depth INT The depth from the root object to the object associated with this
row.

format VARCHAR(128) Whether the geometry is the original representation (Original) or


the normalized representation (Internal).

valid BIT Whether the geometry is valid (1) according to the checking level
specified by the Validate option.

geom_type VARCHAR(128) The geometry type, as returned by the ST_GeometryType.

geom ST_Geometry The geometry specification. If SetGeom parameter is set to No, the
geometry specification is not returned in the result set.

xmin DOUBLE The minimum x value for the geometry.

xmax DOUBLE The maximum x value for the geometry.

ymin DOUBLE The minimum y value for the geometry.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1175


System procedures

Column Data type Description

ymax DOUBLE The maximum y value for the geometry.

zmin DOUBLE The minimum z value for the geometry.

zmax DOUBLE The maximum z value for the geometry.

mmin DOUBLE The minimum m value for the geometry.

mmax DOUBLE The maximum m value for the geometry.

details LONG VARCHAR Any extra details about the geometry, including additional infor-
mation about why the object is not valid.

Remarks
The st_geometry_dump system procedure disassembles a geometry hierarchy with one row for each of the
objects in the hierarchy (including the root object). Each geometry in the hierarchy can be validated to
find out if it is valid, and if not, why.

Some of the functionality of the st_geometry_dump system procedure can be matched by using type-
specific methods such as ST_GeometryN or ST_PointN.

The st_geometry_dump system procedure can be used to correct invalid geometries.

Permissions
None

Side effects
None

See also
● “ST_IsValid method for type ST_Geometry” [SQL Anywhere Server - Spatial Data Support]
● “CREATE SPATIAL REFERENCE SYSTEM statement” on page 616
● “st_geometry_on_invalid option” [SQL Anywhere Server - Database Administration]
● “STORAGE FORMAT clause, CREATE SPATIAL REFERENCE SYSTEM statement” on page 622

Example
The following example disassembles the polygon, 'Polygon ((0 0, 3 0, 3 3, 0 3, 0
0))', into its component geometries:
SELECT * FROM st_geometry_dump( 'Polygon ((0 0, 3 0, 3 3, 0 3, 0 0))',
'SetGeom=No' );

1176 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

id parent_id depth format valid geom_type geom xmin xmax ymin ymax ...

1 1 0 Inter- 1 ST_Poly- Poly- 0 3 0 3 ...


nal gon gon
((0 0,
3 0, 3
3, 0
3, 0
0))

2 1 1 Inter- 1 ST_Line- Line- 0 3 0 3 ...


nal String String
(0 0,
3 0, 3
3, 0
3, 0
0)

3 2 2 Inter- 1 ST_Point Point 0 0 0 0 ...


nal (0 0)

4 2 2 Inter- 1 ST_Point Point 3 3 0 0 ...


nal (3 0)

5 2 2 Inter- 1 ST_Point Point 3 3 3 3 ...


nal (3 3)

6 2 2 Inter- 1 ST_Point Point 0 0 3 3 ...


nal (0 3)

7 2 2 Inter- 1 ST_Point Point 0 0 0 0 ...


nal (0 0)

The following example shows how the st_geometry_dump system procedure can be used to find the
invalid points within a geometry. In this example, the linestring contains a point with longitude 1200.
Because of this, the point and the linestring are both reported as invalid (valid=0) in the results.
SET TEMPORARY OPTION st_geometry_on_invalid='Ignore';
CREATE OR REPLACE VARIABLE @geo ST_Geometry;
SET @geo = new ST_LineString( 'LineString(1200 2, 80 10)', 4326 );
SELECT * FROM dbo.st_geometry_dump( @geo, 'SetGeom=No' );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1177


System procedures

id parent_id depth format valid geom_type geom xmin xmax ymin ymax ... details

1 1 0 Origi- 0 ST_Line- (NULL) 80 1,200 2 10 ... Value


nal String 1200.000000
out of range
for coordi-
nate longi-
tude (SRS
allows
-180.000000
to
180.000000).

2 1 1 Origi- 0 ST_Line- (NULL) 1,200 1,200 2 2 ... Value


nal String 1200.000000
out of range
for coordi-
nate longi-
tude (SRS
allows
-180.000000
to
180.000000).

3 1 1 Origi- 1 ST_Point (NULL) 80 80 10 10 ...


nal

Once invalid data has been identified, the st_geometry_dump system procedure can be used with other
spatial methods to correct the invalid elements to assemble a valid geometry. The following example
shows how an invalid point with longitude 1200 can be corrected to have longitude 120.0:
SELECT ST_LineString::ST_LineStringAggr(
new ST_Point( IF xmax = 1200 then 120.0 ELSE xmax ENDIF,
ymax, 4326 ) ORDER BY id )
FROM dbo.st_geometry_dump( @geo )
WHERE geom_type='ST_Point';

st_geometry_load_shapefile system procedure


Creates a table and loads an ESRI shapefile into it.

Syntax
st_geometry_load_shapefile ( shp_filename
, srid
, table_name
[, table_owner ]
[, shp_encoding ] )

1178 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Arguments
● shp_filename Use this VARCHAR(512) parameter to specify the location of the ESRI shapefile.
The file name must have the extension .shp and must have associated .shx and .dbf files with the same
base name located in the same directory. The path is relative to the database server, not the client
application.

● srid Use this INTEGER parameter to specify the SRID to associate with the data from the
shapefile. For the geometries to be meaningful, the SRID you specify should be appropriate for the
geometries, even if it isn't identical to the SRID used in the shapefile.

● table_name Use this VARCHAR(128) column to specify the name of the table to create to hold
the shapefile data.

● table_owner Use this optional VARCHAR(128) column to specify the owner for the new table
that is created. The default owner is the current user.

● shp_encoding Use this optional VARCHAR(50) parameter to specify the encoding to use when
reading the shapefile. The default encoding is ISO-8859-1.

Remarks
The st_geometry_load_shapefile system procedure first creates the table "table_owner"."table_name"
using the column information (names and types) found in the ESRI shapefile. st_geometry_load_shapefile
then loads the data from the shapefile into the new table.

This procedures makes use of the sa_describe_shapefile system procedure, and the LOAD
TABLE...FORMAT SHAPEFILE statement.

Permissions
RESOURCE authority is required.

If the -gl option has been set to DBA, DBA authority is required.

If the -gl option has been set to NONE, loading the data fails.

Side effects
If loading fails, the created table remains.

See also
● “sa_describe_shapefile system procedure” on page 1040
● “Lesson 3: Load the ESRI shapefile data” [SQL Anywhere Server - Spatial Data Support]
● “LOAD TABLE statement” on page 792
● “Support for ESRI shapefiles” [SQL Anywhere Server - Spatial Data Support]

Example
The following statement creates the esri_load table and loads the data from a fictitious shapefile, c:\esri
\shapefile.shp, into it, associating the data with SRID 1000004326:
CALL st_geometry_load_shapefile( 'c:\\esri\\shapefile.shp', 1000004326,
'esri_load' );

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1179


System procedures

xp_cmdshell system procedure


Carries out an operating system command from a procedure.

Syntax
xp_cmdshell(
command
[ , redir_output | 'no_output' ] )

Arguments
● command Use this CHAR(8000) parameter to specify a system command.

● redir_output Use this optional CHAR(254) parameter to specify whether to display output in a
command window. The default behavior is to display output in a command window. If you specify
'no_output', output is not displayed in a command window.

Remarks
xp_cmdshell executes a system command and then returns control to the calling environment. The value
returned by xp_cmdshell is the exit code from the executed shell process. The return value is 2 if an error
occurs when the child process is started.

The second parameter affects only command line applications on Windows operating systems. For Unix,
no command window appears, regardless of the setting for the second parameter.

For Windows Mobile, any commands executed are visible in the database server message log, regardless
of the setting for the second parameter. The console shell \\windows\cmd.exe is needed to run the
procedure.

Permissions
DBA authority

See also
● “CALL statement” on page 491
● “Security tips” [SQL Anywhere Server - Database Administration]

Example
The following statement lists the files in the current directory in the file c:\temp.txt:
CALL xp_cmdshell( 'dir > c:\\temp.txt' );

The following statement carries out the same operation, but does so without displaying a Command
window.
CALL xp_cmdshell( 'dir > c:\\temp.txt', 'no_output' );

1180 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

xp_msver system procedure


Retrieves version and name information about the database server.

Syntax
xp_msver( the_option )

Arguments
● the_option The string must be one of the following, enclosed in string delimiters.

Argument Description

ProductName The name of the product (SQL Anywhere).

ProductVersion The version number, followed by the build number. The format is as follows:
12.0.1.3600

CompanyName Returns the following string:


iAnywhere Solutions, Inc.

FileDescription Returns the name of the product, followed by the name of the operating sys-
tem.

LegalCopyright Returns a copyright string for the software.

LegalTrademarks Returns trademark information for the software.

Remarks
xp_msver returns product, company, version, and other information.

Permissions
None

See also
● “System functions” on page 144

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. The value for Version will likely be different on your system.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1181


System procedures

Version Description

12.0.1.3600 SQL Anywhere Windows XP

xp_read_file system procedure


Reads a file and returns the contents of the file as a LONG BINARY variable.

Syntax
xp_read_file( filename [, lazy ] )

Arguments
● filename Use this LONG VARCHAR parameter to specify the name of the file for which to return
the contents.

● lazy When you specify this optional INTEGER parameter and its value is not zero, the contents of
the file are not read until they are requested. Reads only occur when the LONG BINARY value is
accessed and only on the portion of the file that is requested. The default is zero, or non-lazy.

Remarks
The function reads the contents of the named file, and returns the result as a LONG BINARY value.

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.

If the data file is in a different character set, you can use the CSCONVERT function to convert it.

You can also use the CSCONVERT function to address character set conversion requirements you have
when using the xp_read_file system procedure.

Permissions
DBA authority

See also
● “CSCONVERT function [String]” on page 183
● “xp_write_file system procedure” on page 1192
● “CALL statement” on page 491
● “Using openxml with xp_read_file” [SQL Anywhere Server - SQL Usage]

Example
The following statement inserts an image into a column named picture of the table t1 (assuming all other
columns can accept NULL):

1182 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

INSERT INTO t1 ( picture )


SELECT xp_read_file( 'portrait.gif' );

xp_scanf system procedure


Extracts substrings from an input string and a format string.

Syntax
xp_scanf(
input_buffer,
format,
parm [, parm2, ... ]
)

Arguments
● input_buffer Use this CHAR(254) parameter to specify the input string.

● format Use this CHAR(254) parameter to specify the format of the input string, using placeholders
(%s) for each parm argument. There can be up to fifty placeholders in the format argument, and there
must be the same number of placeholders as parm arguments.

● parm Use one or more of these CHAR(254) parameters to specify the substrings extracted from
input_buffer. There can be up to 50 of these parameters.

Remarks
The xp_scanf system procedure extracts substrings from an input string using the specified format, and
puts the results in the specified parm values.

Permissions
None

See also
● “CALL statement” on page 491

Example
The following statements extract the substrings Hello and World! from the input buffer Hello World!, and
put them into variables string1 and string2, and then selects them:
CREATE VARIABLE string1 CHAR(254);
CREATE VARIABLE string2 CHAR(254);
CALL xp_scanf( 'Hello World!', '%s %s', string1, string2 );
SELECT string1, string2;

xp_sendmail system procedure


Sends an email message.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1183


System procedures

Syntax
xp_sendmail(
recipient = mail-address
[, subject = subject ]
[, cc_recipient = mail-address ]
[, bcc_recipient = mail-address ]
[, query = sql-query ]
[, "message" = message-body ]
[, attachname = attach-name ]
[, attach_result = attach-result ]
[, echo_error = echo-error ]
[, include_file = filename ]
[, no_column_header = no-column-header ]
[, no_output = no-output ]
[, width = width ]
[, separator = separator-char ]
[, dbuser = user-name ]
[, dbname = db-name ]
[, type = type ]
[, include_query = include-query ]
[, content_type = content-type ]
)

Arguments
Some arguments supply fixed values and are available for use to ensure Transact-SQL compatibility, as
noted below.

● recipient This LONG VARCHAR parameter specifies the recipient mail address. When specifying
multiple recipients, each mail address must be separated by a semicolon.

● subject This LONG VARCHAR parameter specifies the subject field of the message. The default
is NULL.

● cc_recipient This LONG VARCHAR parameter specifies the cc recipient mail address. When
specifying multiple cc recipients, each mail address must be separated by a semicolon. The default is
NULL.

● bcc_recipient This LONG VARCHAR parameter specifies the bcc recipient mail address. When
specifying multiple bcc recipients, each mail address must be separated by a semicolon. The default is
NULL.

● query This LONG VARCHAR is provided for Transact-SQL compatibility. It is not used by SQL
Anywhere. The default is NULL.

● "message" This LONG VARCHAR parameter specifies the message contents. The default is
NULL. The "message" parameter name requires double quotes around it because MESSAGE is a
reserved word.

● attachname This LONG VARCHAR parameter is provided for Transact-SQL compatibility. It is


not used by SQL Anywhere. The default is NULL.

● attach_result This INT parameter is provided for Transact-SQL compatibility. It is not used by
SQL Anywhere. The default is 0.

1184 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

● echo_error This INT parameter is provided for Transact-SQL compatibility. It is not used by SQL
Anywhere. The default is 1.

● include_file This LONG VARCHAR parameter specifies an attachment file. The default is NULL.

● no_column_header This INT parameter is provided for Transact-SQL compatibility. It is not


used by SQL Anywhere. The default is 0.

● no_output This INT parameter is provided for Transact-SQL compatibility. It is not used by SQL
Anywhere. The default is 0.

● width This INT parameter is provided for Transact-SQL compatibility. It is not used by SQL
Anywhere. The default is 80.

● separator This CHAR(1) parameter is provided for Transact-SQL compatibility. It is not used by
SQL Anywhere. The default is CHAR(9).

● dbuser This LONG VARCHAR parameter is provided for Transact-SQL compatibility. It is not
used by SQL Anywhere. The default is guest.

● dbname This LONG VARCHAR parameter is provided for Transact-SQL compatibility. It is not
used by SQL Anywhere. The default is master.

● type This LONG VARCHAR parameter is provided for Transact-SQL compatibility. It is not used
by SQL Anywhere. The default is NULL.

● include_query This INT parameter is provided for Transact-SQL compatibility. It is not used by
SQL Anywhere. The default is 0.

● content_type This LONG VARCHAR parameter specifies the content type for the "message"
parameter (for example, text/html, ASIS, and so on). The default is NULL. The value of content_type
is not validated; setting an invalid content type results in an invalid or incomprehensible email being
sent.

If you want to set headers manually, you can set content_type parameter to ASIS. When you do this,
the xp_sendmail procedure assumes that the data passed to the message parameter is a properly
formed email with headers, and does not add any additional headers. When specifying ASIS, you
must set all the headers manually in the message parameter, even headers that would normally be
filled in by passing data to the other parameters.

Permissions
DBA authority

Must have executed xp_startmail to start an email session using MAPI, or xp_startsmtp to start an email
session using SMTP.

If you are sending mail using MAPI, the content_type parameter is not supported.

Remarks
xp_sendmail is a system procedure that sends an email message to the specified recipients once a session
has been started with xp_startmail or xp_startsmtp. The procedure accepts messages of any length. The

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1185


System procedures

argument values for xp_sendmail are strings. The length of each argument is limited to the amount of
available memory on your system.

The content_type argument is intended for users who understand the requirements of MIME email.
xp_sendmail accepts ASIS as a content_type. When content_type is set to ASIS, xp_sendmail assumes
that the message body ("message") is a properly formed email with headers, and does not add any
additional headers. Specify ASIS to send multipart messages containing more than one content type. For
more information about MIME, see RFCs 2045-2049 (http://www.ietf.org/).

Any attachment specified by the include_file parameter is sent as application/octet-stream MIME type,
with base64 encoding, and must be present on the database server.

In SQL Anywhere 10.0.0 and later, email sent with an SMTP email system is encoded if the subject line
contains characters that are not 7-bit ASCII. Also, email sent to an SMS-capable device may not be
decoded properly if the subject line contains characters that are not 7-bit ASCII.

Return codes
See “Return codes for MAPI and SMTP system procedures” on page 997.

See also
● “MAPI and SMTP procedures” on page 996
● “xp_startmail system procedure” on page 1188
● “xp_startsmtp system procedure” on page 1189
● “xp_stopmail system procedure” on page 1191
● “xp_stopsmtp system procedure” on page 1192
● “CALL statement” on page 491
● “Reserved words” on page 1

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' );

The following sample program shows various uses of the xp_sendmail system procedure, as described in
the example itself:
BEGIN
DECLARE to_list LONG VARCHAR;
DECLARE email_subject CHAR(256);
DECLARE content LONG VARCHAR;
DECLARE uid CHAR(20);
SET to_list='[email protected]';
SET email_subject='This is a test';
SET uid='[email protected]';

// Call xp_startsmtp to start an SMTP email session


CALL xp_startsmtp( uid, 'mymailserver.mytestdomain.com' );

// Basic email example

1186 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

SET content='This text is the body of my email.\n';


CALL xp_sendmail( recipient=to_list,
subject=email_subject,
"message"=content );

// Send email containing HTML using the content_type parameter,


// as well as including an attachment with the include_file
// parameter
SET content='Plain text.<BR><BR><B>Bold text.</B><BR><BR><a
href="www.iAnywhere.com">iAnywhere
Home Page</a></B><BR><BR>';
CALL xp_sendmail( recipient=to_list,
subject=email_subject,
"message"=content,
content_type = 'text/html',
include_file = 'test.zip' );

// Send email "ASIS". Here the content-type has been specified


// by the user as part of email body. Note the attachment can
// also be done separately
SET content='Content-Type: text/html;\nContent-Disposition: inline; \n\nThis
text
is not bold<BR><BR><B>This text is bold</B><BR><BR><a
href="www.iAnywhere.com">iAnywhere Home
Page</a></B><BR><BR>';
CALL xp_sendmail( recipient=to_list,
subject=email_subject,
"message"=content,
content_type = 'ASIS',
include_file = 'test.zip' );

// Send email "ASIS" along with an include file. Note that


// "message" contains the information for another attachment
SET content = 'Content-Type: multipart/mixed; boundary="xxxxx";\n';
SET content = content || 'This part of the email should not be shown. If
this is shown
then the email client is not MIME compatible\n\n';
SET content = content || '--xxxxx\n';
SET content = content || 'Content-Type: text/html;\n';
SET content = content || 'Content-Disposition: inline;\n\n';
SET content = content || 'This text is not bold<BR><BR><B>This text is bold</
B><BR>
<BR><a href="www.iAnywhere.com">iAnywhere Home Page</a></B><BR><BR>\n\n';
SET content = content || '--xxxxx\n';
SET content = content || 'Content-Type: application/zip; name="test.zip"\n';
SET content = content || 'Content-Transfer-Encoding: base64\n';
SET content = content || 'Content-Disposition: attachment;
filename="test.zip"\n\n';
// Encode the attachment instead of adding this one in
// the include_file parameter
SET content = content || base64_encode( xp_read_file( 'othertest.zip' ) ) ||
'\n\n';
SET content = content || '--xxxxx--\n';
CALL xp_sendmail( recipient=to_list,
subject=email_subject,
"message"=content,
content_type = 'ASIS',
include_file = 'othertest.zip' );

// End the SMTP session


CALL xp_stopsmtp();
END

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1187


System procedures

xp_sprintf system procedure


Builds a result string from a set of input strings.

Syntax
xp_sprintf(
output_buffer,
format,
parm [, parm2, ... ]
)

Arguments
● output_buffer Use this CHAR(254) parameter to specify the output buffer containing the result
string.

● format Use this CHAR(254) parameter to specify how to format the result string, using
placeholders (%s) for each parm argument. There can be up to fifty placeholders in the format
argument, and there should be the same number of placeholders as parm arguments.

● parm These are the input strings that are used in the result string. You can specify up to 50 of these
CHAR(254) arguments.

Remarks
The xp_sprintf system procedure builds up a string using the format argument and the parm argument(s),
and puts the results in output_buffer.

Permissions
None

See also
● “CALL statement” on page 491

Example
The following statements put the string Hello World! into the result variable.
CREATE VARIABLE result CHAR(254);
Call xp_sprintf( result, '%s %s', 'Hello', 'World!' );

xp_startmail system procedure


Starts an email session under MAPI.

Syntax
xp_startmail(
[ mail_user = mail-login-name ]
[, mail_password = mail-password ] )

1188 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Arguments
● mail_user Use this LONG VARCHAR parameter to specify the MAPI login name.

● mail_password Use this LONG VARCHAR parameter to specify the MAPI password.

Permissions
DBA authority

Not supported on Unix.

Remarks
xp_startmail is a system procedure that starts an email 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
See “Return codes for MAPI and SMTP system procedures” on page 997.

See also
● “MAPI and SMTP procedures” on page 996
● “xp_stopmail system procedure” on page 1191
● “xp_sendmail system procedure” on page 1183
● “xp_startsmtp system procedure” on page 1189
● “xp_stopsmtp system procedure” on page 1192
● “CALL statement” on page 491
● “Security tips” [SQL Anywhere Server - Database Administration]

xp_startsmtp system procedure


Starts an email session under SMTP.

Syntax
xp_startsmtp(
smtp_sender = email-address
, smtp_server = smtp-server
[, smtp_port = port-number ]
[, timeout = timeout ]
[, smtp_sender_name = username ]
[, smtp_auth_username = auth-username ]
[, smtp_auth_password = auth-password ]
[, trusted_certificates = public-certificate ]
[, certificate_company = organization ]
[, certificate_unit = organization-unit ]
[, certificate_name = common-name ]
)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1189


System procedures

Arguments
● smtp_sender This LONG VARCHAR parameter specifies the email address of the sender.

● smtp_server This LONG VARCHAR parameter specifies which SMTP server to use, and is the
server name or IP address.

● smtp_port This optional INTEGER parameter specifies the port number to connect to on the
SMTP server. The default is 25.

● timeout This optional INTEGER parameter specifies how long to wait, in seconds, for a response
from the database server before aborting the current call to xp_sendmail. The default is 60 seconds.

● smtp_sender_name This optional LONG VARCHAR parameter specifies an alias for the
sender's email address. For example, 'JSmith' instead of 'email-address'.

● smtp_auth_username This optional LONG VARCHAR parameter specifies the user name to
provide to SMTP servers requiring authentication.

● smtp_auth_password This optional LONG VARCHAR parameter specifies the password to


provide to SMTP servers requiring authentication.

● trusted_certificates This optional LONG VARCHAR parameter specifies the path and file name
of a file that contains one or more trusted certificates. The default is NULL. When this parameter is
NULL, a standard SMTP connection is made.

The trusted certificate can be a server's self-signed certificate, a public enterprise root certificate, or a
certificate belonging to a commercial Certificate Authority. You must generate your certificates using
RSA.

● certificate_company This optional LONG VARCHAR parameter specifies that the client accepts
server certificates only when the Organization field of the certificate matches this value. This
parameter is ignored when the trusted_certificates value is NULL.

● certificate_unit This optional LONG VARCHAR parameter specifies that the client accepts server
certificates only when the Organization Unit field of the certificate matches this value. This parameter
is ignored when the trusted_certificates value is NULL.

● certificate_name This optional LONG VARCHAR parameter specifies that the client accepts
server certificates only when the Common Name field on the certificate matches this value. This
parameter is ignored when the trusted_certificates value is NULL.

Permissions
DBA authority

Remarks
xp_startsmtp is a system procedure that starts a mail session for a specified email address by connecting
to an SMTP server. This connection can time out. Therefore, it is recommended that you call xp_startsmtp
just before executing xp_sendmail.

1190 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

If you specify smtp_auth_username and smtp_auth_password, and the server does not support the SMTP
authentication capability, error code 104 is returned.

Virus scanners can affect xp_startsmtp, causing it to return error code 100. For McAfee VirusScan
version 8.0.0 and later, settings for preventing mass mailing of email worms also prevent xp_sendmail
from executing properly. If your virus scanning software allows you to specify processes that can bypass
the mass mailing protections, specify dbeng12.exe and dbsrv12.exe. For example, with McAfee
VirusScan you can prevent mass mailing by adding these two processes to the list of Excluded Processes
in the Properties area.

Return codes
See “Return codes for MAPI and SMTP system procedures” on page 997.

See also
● “MAPI and SMTP procedures” on page 996
● “xp_startmail system procedure” on page 1188
● “xp_stopmail system procedure” on page 1191
● “xp_sendmail system procedure” on page 1183
● “xp_stopsmtp system procedure” on page 1192
● “CALL statement” on page 491
● “Security tips” [SQL Anywhere Server - Database Administration]

xp_stopmail system procedure


Closes a MAPI email session.

Syntax
xp_stopmail( )

Permissions
DBA authority

Not supported on Unix.

Remarks
xp_stopmail is a system procedure that ends an email session.

Return codes
See “Return codes for MAPI and SMTP system procedures” on page 997.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1191


System procedures

See also
● “MAPI and SMTP procedures” on page 996
● “xp_startmail system procedure” on page 1188
● “xp_sendmail system procedure” on page 1183
● “xp_startsmtp system procedure” on page 1189
● “xp_stopsmtp system procedure” on page 1192
● “CALL statement” on page 491
● “Security tips” [SQL Anywhere Server - Database Administration]

xp_stopsmtp system procedure


Closes an SMTP email session.

Syntax
xp_stopsmtp( )

Permissions
DBA authority

Remarks
xp_stopsmtp is a system procedure that ends an email session.

Return codes
See “Return codes for MAPI and SMTP system procedures” on page 997.

See also
● “MAPI and SMTP procedures” on page 996
● “xp_startmail system procedure” on page 1188
● “xp_stopmail system procedure” on page 1191
● “xp_sendmail system procedure” on page 1183
● “xp_startsmtp system procedure” on page 1189
● “CALL statement” on page 491
● “Security tips” [SQL Anywhere Server - Database Administration]

xp_write_file system procedure


Writes data to a file from a SQL statement.

Syntax
xp_write_file(
filename,
file_contents
)

1192 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Alphabetical list of system procedures

Arguments
● filename Use this LONG VARCHAR parameter to specify the file name.

● file_contents Use this LONG BINARY parameter to specify the contents to write to the file.

Remarks
The function writes file_contents to the file filename. It returns 0 if successful, and non-zero if it fails.

The filename value can be prefixed by either an absolute or a relative path. If filename is prefixed by a
relative path, then the file name 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.

You can also use the CSCONVERT function to address character set conversion requirements you have
when using the xp_write_file system procedure.

Permissions
DBA authority

See also
● “CSCONVERT function [String]” on page 183
● “xp_read_file system procedure” on page 1182
● “CALL statement” on page 491

Examples
This example uses xp_write_file to create a file accountnum.txt containing the data 123456:
CALL xp_write_file( 'accountnum.txt', '123456' );

This example queries the Contacts table of the sample database, and then creates a text file for each
contact living in New Jersey. Each text file is named using a concatenation of the contact's first name
(GivenName), last name (Surname), and then the string .txt (for example, Reeves_Scott.txt), and contains
the contact's street address (Street), city (City), and state (State), on separate lines.
SELECT xp_write_file(
Surname || '_' || GivenName || '.txt',
Street || '\n' || City || '\n' || State )
FROM Contacts WHERE State = 'NJ';

This example uses xp_write_file to create an image file (JPG) for every product in the Products table.
Each value of the ID column becomes a file name for a file with the contents of the corresponding value
of the Photo column:
SELECT xp_write_file( ID || '.jpg' , Photo ) FROM Products;

In the example above, ID is a row with a UNIQUE constraint. This is important to ensure that a file isn't
overwritten with the contents of subsequent row. Also, you must specify the file extension applicable to
the data stored in the column. In this case, the Products.Photo stores image data (JPGs).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1193


1194 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1
Views

System views
The catalog contains system tables that link together by keys and indexes. In SQL Anywhere, the system
tables are hidden. However, there is a system view for each table. A system view may also include
columns from more than one system table to satisfy a commonly needed join.

To ensure compatibility with future versions of the SQL Anywhere catalog, make sure your applications
make use of system views and not the underlying system tables, which may change.

Viewing detailed system information for views and


definitions
Database administrators can access information about system views, including their definitions, from
Sybase Central.

Prerequisites

DBA authority.

Context and remarks

Many.

View detailed system information for views and definitions (Sybase Central)

1. Use the SQL Anywhere 12 plug-in to connect to the database as a user with DBA authority.

2. Right-click the database, and then click Configure Owner Filter.

3. Click SYS, and then click OK.

4. In the left pane, double-click Views.

5. In the left pane click a view, and in the right pane click the SQL tab.

6. Click the Data tab.

Results

The view definition appears on the Data tab.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1195


Views

Next

None.

SYSARTICLE system view


Each row of the SYSARTICLE system view describes an article in a publication. The underlying system
table for this view is ISYSARTICLE.

Column name Data type Description

publication_id UNSIGNED INT The publication of which the article is a part.

table_id UNSIGNED INT Each article consists of columns and rows from a single ta-
ble. This column contains the table ID for this table.

where_expr LONG VAR- For articles that contain a subset of rows defined by a
CHAR WHERE clause, this column contains the search condition.

subscribe_by_expr LONG VAR- For articles that contain a subset of rows defined by a
CHAR SUBSCRIBE BY expression, this column contains the ex-
pression.

query CHAR(1) Indicates information about the article type to the database
server.

alias VARCHAR(256) The alias for the article.

schema_change_ac- BIT 1 if the table and publication are part of a synchronization


tive schema change.

Constraints on underlying system table


PRIMARY KEY (publication_id, table_id)

FOREIGN KEY (publication_id) references SYS.ISYSPUBLICATION (publication_id)

FOREIGN KEY (table_id) references SYS.ISYSTAB (table_id)

SYSARTICLECOL system view


Each row of the SYSARTICLECOL system view identifies a column in an article. The underlying system
table for this view is ISYSARTICLECOL.

1196 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

publication_id UNSIGNED INT A unique identifier for the publication of which the column is a
part.

table_id UNSIGNED INT The table to which the column belongs.

column_id UNSIGNED INT The column identifier, from the SYSTABCOL system view.

Constraints on underlying system table


PRIMARY KEY (publication_id, table_id, column_id)

FOREIGN KEY (publication_id, table_id) references SYS.ISYSARTICLE


(publication_id, table_id)

FOREIGN KEY (table_id, column_id) references SYS.ISYSTABCOL (table_id,


column_id)

SYSCAPABILITY system view


Each row of the SYSCAPABILITY system view specifies the status of a capability on a remote database
server. The underlying system table for this view is ISYSCAPABILITY.

Column name Data type Description

capid INTEGER The ID of the capability, as listed in the SYSCAPABILITY-


NAME system view.

srvid UNSIGNED INT The server to which the capability applies, as listed in the SYS-
SERVER system view.

capvalue CHAR(128) The value of the capability.

Constraints on underlying system table


PRIMARY KEY (capid, srvid)

FOREIGN KEY (srvid) references SYS.ISYSSERVER (srvid)

See also
● “SYSCAPABILITYNAME system view” on page 1197

SYSCAPABILITYNAME system view


Each row in the SYSCAPABILITYNAME system view provides a name for each capability ID in the
SYSCAPABILITY system view.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1197


Views

Column name Data type Description

capid INTEGER A number uniquely identifying the capability.

capname VARCHAR(32000) The name of the capability.

Remarks
The SYSCAPABILITYNAME system view is defined using a combination of sa_rowgenerator and the
following server properties:

● RemoteCapability
● MaxRemoteCapability

See also
● “Accessing database server property values” [SQL Anywhere Server - Database Administration]
● “SYSCAPABILITY system view” on page 1197

SYSCHECK system view


Each row in the SYSCHECK system view provides the definition for a named check constraint in a table.
The underlying system table for this view is ISYSCHECK.

Column name Data type Description

check_id UNSIGNED INT A number that uniquely identifies the constraint in the data-
base.

check_defn LONG VARCHAR The CHECK expression.

Constraints on underlying system table


PRIMARY KEY (check_id)

FOREIGN KEY (check_id) references SYS.ISYSCONSTRAINT (constraint_id)

SYSCOLPERM system view


The GRANT statement can give UPDATE, SELECT, or REFERENCES permission to individual
columns in a table. Each column with UPDATE, SELECT, or REFERENCES permission is recorded in
one row of the SYSCOLPERM system view. The underlying system table for this view is
ISYSCOLPERM.

1198 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

table_id UNSIGNED The table number for the table containing the column.
INT

grantee UNSIGNED The user number of the user ID that is given permission on the
INT column. If the grantee is the user number for the special PUBLIC
user ID, the permission is given to all user IDs.

grantor UNSIGNED The user number of the user ID that grants the permission.
INT

column_id UNSIGNED This column number, together with the table_id, identifies the
INT column for which permission has been granted.

privilege_type SMALLINT The number in this column indicates the kind of column permis-
sion (16=REFERENCES, 1=SELECT, or 8=UPDATE).

is_grantable CHAR(1) Indicates if the permission on the column was granted WITH
GRANT OPTION.

Constraints on underlying system table


PRIMARY KEY (table_id, grantee, grantor, column_id, privilege_type)

FOREIGN KEY (table_id, column_id) references SYS.ISYSTABCOL (table_id,


column_id)

FOREIGN KEY (grantor) references SYS.ISYSUSER (user_id)

FOREIGN KEY (grantee) references SYS.ISYSUSER (user_id)

SYSCOLSTAT system view


The SYSCOLSTAT system view contains the column statistics, including histograms, that are used by the
optimizer. The contents of this view are best retrieved using the sa_get_histogram stored procedure or the
Histogram utility. The underlying system table for this view is ISYSCOLSTAT.

Column name Data type Description

table_id UNSIGNED INT A number that uniquely identifies the table or materialized view
to which the column belongs.

column_id UNSIGNED INT A number that, together with table_id, uniquely identifies the col-
umn.

format_id SMALLINT For system use only.

update_time TIMESTAMP The time of the last update of the column statistics.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1199


Views

Column name Data type Description

density FLOAT An estimate of the average selectivity of a single value for the
column, not counting the large single value selectivities stored in
the row.

max_steps SMALLINT For system use only.

actual_steps SMALLINT For system use only.

step_values LONG BINARY For system use only.

frequencies LONG BINARY For system use only.

Note
For databases created using SQL Anywhere 12 or later, the underlying system table for this view is
always encrypted to protect the data from unauthorized access.

Constraints on underlying system table


PRIMARY KEY (table_id, column_id)
FOREIGN KEY (table_id, column_id) references SYS.ISYSTABCOL (table_id,
column_id)

SYSCONSTRAINT system view


Each row in the SYSCONSTRAINT system view describes a named constraint in the database. The
underlying system table for this view is ISYSCONSTRAINT.

Column name Data type Description

constraint_id UNSIGNED INT The unique ID for the con-


straint.

constraint_type CHAR(1) The type of constraint:

● C column check con-


straint

● T table constraint

● P primary key

● F foreign key

● U unique constraint

1200 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

ref_object_id UNSIGNED BIGINT The object ID of the column, ta-


ble, or index to which the con-
straint applies.

table_object_id UNSIGNED BIGINT The object ID of the table to


which the constraint applies.

constraint_name CHAR(128) The name of the constraint.

Constraints on underlying system table


PRIMARY KEY (constraint_id)

FOREIGN KEY (ref_object_id) references SYS.ISYSOBJECT (object_id)

FOREIGN KEY (table_object_id) references SYS.ISYSOBJECT (object_id)

UNIQUE Constraint (table_object_id, constraint_name)

SYSDBFILE system view


Each row in the SYSDBFILE system view describes a dbspace file. The underlying system table for this
view is ISYSDBFILE.

Column name Data type Description

dbfile_id SMALLINT For internal use only.

dbspace_id SMALLINT Each dbspace file in a database is assigned a unique number.


The system dbspace contains all system objects and has a
dbspace_id of 0.

dbfile_name CHAR(128) The file name for the dbspace. For dbspaces other than system
and TEMPORARY, the file name can be changed using the fol-
lowing statement:
ALTER DBSPACE dbspace RENAME 'new-filename';

file_name LONG VAR- A unique name for the dbspace. It is used in the CREATE TA-
CHAR BLE command.

lob_map LONG VARBIT For internal use only.

Constraints on underlying system table


PRIMARY KEY (dbfile_id)

FOREIGN KEY (dbspace_id) references SYS.ISYSDBSPACE (dbspace_id)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1201


Views

UNIQUE Index (file_name)

SYSDBSPACE system view


Each row in the SYSDBSPACE system view describes a dbspace file. The underlying system table for
this view is ISYSDBSPACE.

Column name Data type Description

dbspace_id SMALLINT Unique number identifying the dbspace. The system dbspace
contains all system objects and has a dbspace_id of 0.

object_id UNSIGNED BIGINT The object ID of the dbspace.

dbspace_name CHAR(128) A unique name for the dbspace. It is used in the CREATE
TABLE command.

store_type TINYINT For internal use only.

Constraints on underlying system table


PRIMARY KEY (dbspace_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

SYSDBSPACEPERM system view


Each row in the SYSDBSPACEPERM system view describes a permission on a dbspace file. The
underlying system table for this view is ISYSDBSPACEPERM.

Column name Data type Description

dbspace_id SMALLINT Unique number identifying the dbspace. The system dbspace con-
tains all system objects and has a dbspace_id of 0.

grantee UNSIGNED The user ID of the user getting the permission.


INT

privilege_type SMALLINT The permission that is granted to the grantee. For example, CRE-
ATE gives the grantee permission to create objects on the
dbspace.

Constraints on underlying system table


FOREIGN KEY (dbspace_id) references SYS.ISYSDBSPACE (dbspace_id)

FOREIGN KEY (grantee) references SYS.ISYSUSER (user_id)

1202 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

See also
● “GRANT statement” on page 760
● “User IDs, authorities, and permissions” [SQL Anywhere Server - Database Administration]

SYSDEPENDENCY system view


Each row in the SYSDEPENDENCY system view describes a dependency between two database objects.
The underlying system table for this view is ISYSDEPENDENCY.

A dependency exists between two database objects when one object references another object in its
definition. For example, if the query specification for a view references a table, the view is said to be
dependent on the table. The database server tracks dependencies of views on tables, views, materialized
views, and columns.

Column name Data type Description

ref_object_id UNSIGNED BIGINT The object ID of the referenced object.

dep_object_id UNSIGNED BIGINT The ID of the referencing object.

Constraints on underlying system table


PRIMARY KEY (ref_object_id, dep_object_id)

FOREIGN KEY (ref_object_id) references SYS.ISYSOBJECT (object_id)

FOREIGN KEY (dep_object_id) references SYS.ISYSOBJECT (object_id)

See also
● “sa_dependent_views system procedure” on page 1033
● “View dependencies” [SQL Anywhere Server - SQL Usage]

SYSDOMAIN system view


The SYSDOMAIN system view records information about built-in data types (also called domains). The
contents of this view does not change during normal operation. The underlying system table for this view
is ISYSDOMAIN.

Column name Data type Description

domain_id SMALLINT The unique number assigned to each data type. These numbers cannot
be changed.

domain_name CHAR(128) The name of the data type normally found in the CREATE TABLE
command, such as CHAR or INTEGER.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1203


Views

Column name Data type Description

type_id SMALLINT The ODBC data type. This value corresponds to the value for da-
ta_type in the Transact-SQL-compatibility dbo.SYSTYPES table.

"precision" SMALLINT The number of significant digits that can be stored using this data
type. The column value is NULL for non-numeric data types.

Constraints on underlying system table


PRIMARY KEY (domain_id)

SYSEVENT system view


Each row in the SYSEVENT system view describes an event created with CREATE EVENT. The
underlying system table for this view is ISYSEVENT.

Column name Data type Description

event_id UNSIGNED INT The unique number assigned to each event.

object_id UNSIGNED BIGINT The internal ID for the event, uniquely identifying it in the
database.

creator UNSIGNED INT The user number of the owner of the event. The name of the
user can be found by looking in the SYSUSER system view.

event_name VARCHAR(128) The name of the event.

enabled CHAR(1) Indicates whether the event is allowed to fire.

location CHAR(1) The location where the event is to fire:

● C = consolidated
● R = remote
● A = all

event_type_id UNSIGNED INT For system events, the event type as listed in the SYSE-
VENTTYPE system view.

action LONG VARCHAR The event handler definition. An obfuscated value indicates
a hidden event.

external_action LONG VARCHAR For system use only.

condition LONG VARCHAR The condition used to control firing of the event handler.

1204 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

remarks LONG VARCHAR Remarks for the event; this column comes from ISYSRE-
MARK.

source LONG VARCHAR The original source for the event; this column comes from
ISYSSOURCE.

Constraints on underlying system table


PRIMARY KEY (event_id)

FOREIGN KEY (creator) references SYS.ISYSUSER (user_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

UNIQUE Index (event_name)

See also
● “SYSEVENTTYPE system view” on page 1205

SYSEVENTTYPE system view


The SYSEVENTTYPE system view defines the system event types that can be referenced by CREATE
EVENT.

Column name Data type Description

event_type_id INT The unique number assigned to each event type.

name VARCHAR(32000) The name of the system event type.

description LONG VARCHAR A description of the system event type.

Remarks
The SYSEVENTTYPE system view is defined using a combination of sa_rowgenerator and the following
server properties:

● EventTypeName
● EventTypeDesc
● MaxEventType

See also
● “Accessing database server property values” [SQL Anywhere Server - Database Administration]
● “SYSEVENT system view” on page 1204

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1205


Views

SYSEXTERNENV system view


Many external runtime environments are supported, including embedded SQL and ODBC applications
written in C/C++, and applications written in Java, Perl, PHP, or languages such as C# and Visual Basic
that are based on the Microsoft .NET Framework Common Language Runtime (CLR).

Each row in the SYSEXTERNENV system view describes the information needed to identify and launch
each of the external environments. The underlying system table for this view is ISYSEXTERNENV.

Column name Data type Description

object_id unsigned bigint A unique identifier for the external environment.

name char(128) The name of the external environment or language.

scope char(1) Identifies if the external environment is launched as one-per-con-


nection (C), or one-per-database (D).

support_re- char(1) Identifies the external environments that can return result sets to the
sult_sets user.

location long varchar Identifies the location where the main executable for the environ-
ment can be found.

options long varchar Identifies the options required on the command line to launch the
external environment.

user_id unsigned int For internal use only.

Constraints on underlying system table


PRIMARY KEY (object_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (user_id) references SYS.ISYSUSER (user_id)

UNIQUE Index (name)

SYSEXTERNENVOBJECT system view


Many external runtime environments are supported, including embedded SQL and ODBC applications
written in C/C++, and applications written in Java, Perl, PHP, or languages such as C# and Visual Basic
that are based on the Microsoft .NET Framework Common Language Runtime (CLR).

Each row in the SYSEXTERNENVOBJECT system view describes an installed external object. The
underlying system table for this view is ISYSEXTERNENVOBJECT.

1206 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

object_id unsigned bigint A unique identifier for the external object.

extenv_id unsigned bigint The unique identifier for the external environment (SYSEXTER-
NENV.object_id).

owner unsigned int Identifies the creator/owner of the external object.

name long varchar Identifies the name of the external object as specified in the IN-
STALL statement.

contents long binary The contents of the external object.

update_time timestamp Identifies the last time the object was modified (or installed).

Constraints on underlying system table


PRIMARY KEY (object_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (extenv_id) references SYS.ISYSEXTERNENV (object_id)

FOREIGN KEY (owner) references SYS.ISYSUSER (user_id)

UNIQUE Index (name)

SYSEXTERNLOGIN system view


Each row in the SYSEXTERNLOGIN system view describes an external login for remote data access.
The underlying system table for this view is ISYSEXTERNLOGIN.

Note
Previous versions of the catalog contained a SYSEXTERNLOGINS system table. That table has been
renamed to be ISYSEXTERNLOGIN (without an 'S'), and is the underlying table for this view.

Column name Data type Description

user_id UNSIGNED INT The user ID on the local database.

srvid UNSIGNED INT The remote server, as listed in the SYSSERVER system
view.

remote_login VARCHAR(128) The login name for the user, for the remote server.

remote_password VARBINARY(128) The password for the user, for the remote server.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1207


Views

Note
For databases created using SQL Anywhere 12 or later, the underlying system table for this view is
always encrypted to protect the data from unauthorized access.

Constraints on underlying system table


PRIMARY KEY (user_id, srvid)

FOREIGN KEY (user_id) references SYS.ISYSUSER (user_id)

FOREIGN KEY (srvid) references SYS.ISYSSERVER (srvid)

SYSFKEY system view


Each row in the SYSFKEY system view describes a foreign key constraint in the system. The underlying
system table for this view is ISYSFKEY.

Column name Data type Description

foreign_table_id UNSIGNED The table number of the foreign table.


INT

foreign_index_id UNSIGNED The index number for the foreign key.


INT

primary_table_id UNSIGNED The table number of the primary table.


INT

primary_index_id UNSIGNED The index number of the primary key.


INT

match_type TINYINT The matching type for the constraint. Matching types include:

● 0 Use the default matching

● 1 SIMPLE

● 2 FULL

● 129 SIMPLE UNIQUE

● 130 FULL UNIQUE

For more information about match types, see the MATCH


clause of the “CREATE TABLE statement” on page 633.

check_on_commit CHAR(1) Indicates whether INSERT and UPDATE statements should


wait until the COMMIT to check if foreign keys are still valid.

1208 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

nulls CHAR(1) 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.

Constraints on underlying system table


PRIMARY KEY (foreign_table_id, foreign_index_id)

FOREIGN KEY (foreign_table_id, foreign_index_id) references SYS.ISYSIDX


(table_id, index_id)

FOREIGN KEY (primary_table_id, primary_index_id) references SYS.ISYSIDX


(table_id, index_id)

SYSGROUP system view


There is one row in the SYSGROUP system view for each member of each group. This view describes
the many-to-many relationship between groups and members. A group may have many members, and a
user may be a member of many groups. The underlying system table for this view is ISYSGROUP.

Column name Data type Description

group_id UNSIGNED INT The user number of the group.

group_member UNSIGNED INT The user number of a member.

Constraints on underlying system table


PRIMARY KEY (group_id, group_member)

FOREIGN KEY group_id (group_id) references SYS.ISYSUSER (user_id)

FOREIGN KEY group_member (group_member) references SYS.ISYSUSER (user_id)

SYSHISTORY system view


Each row in the SYSHISTORY system view records a system operation on the database, such as a
database start, a database calibration, and so on. The underlying system table for this view is
ISYSHISTORY.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1209


Views

Column Data type Description


name

operation CHAR(128) The type of operation performed on the database file. The operation
must be one of the following values:

● INIT Information about when the database was created.

● UPGRADE Information about when the database was upgraded.

● START Information about when the database was started using a


specific version of the database server on a particular operating sys-
tem.

● LAST_START Information about the most recent time the data-


base server was started. A LAST_START operation is converted to
a START operation when the database is started with a different
version of the database server and/or on a different operating sys-
tem than those values currently stored in the LAST_START row.

● DTT Information about the second to last Disk Transfer Time


(DTT) calibration operation performed on the dbspace. That is, in-
formation about the second to last execution of either an ALTER
DATABASE CALIBRATE or ALTER DATABASE RESTORE
DEFAULT CALIBRATION statement.

● LAST_DTT Information about the most recent DTT calibration


operation performed on the dbspace. That is, information about the
most recent execution of either an ALTER DATABASE CALI-
BRATE or ALTER DATABASE RESTORE DEFAULT CALI-
BRATION statement.

● LAST_BACKUP Information about the last backup, including


date and time of the backup, the backup type, the files that were
backed up, and the version of database server that performed the
backup.

object_id UNSIGNED For any operation other than DTT and LAST_DTT, the value in this
INT column will be 0. For DTT and LAST_DTT operations, this is the
dbspace_id of the dbspace as defined in the SYSDBSPACE system
view.

1210 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column Data type Description


name

sub_opera- CHAR(128) For any operation other than DTT and LAST_DTT, the value in this
tion column will be a set of empty single quotes ("). For DTT and
LAST_DTT operations, this column contains the type of sub-operation
performed on the dbspace. Values include:

● DTT_SET The dbspace calibration has been set.

● DTT_UNSET The dbspace calibration has been restored to the


default setting.

version CHAR(128) The version and build number of the database server used to perform
the operation.

platform CHAR(128) The operating system on which the operation was carried out.

first_time TIMESTAMP The date and time the database was first started on a particular operat-
ing system with a particular version of the software.

last_time TIMESTAMP The most recent date and time the database was started on a particular
operating system with a particular version of the software.

details LONG VAR- This column stores information such as command line options used to
CHAR start the database server or the capability bits enabled for the database.
This information is for use by technical support.

Constraints on underlying system table


PRIMARY KEY (operation, object_id, version, platform)

See also
● “SYSDBSPACE system view” on page 1202

SYSIDX system view


Each row in the SYSIDX system view defines a logical index in the database. The underlying system
table for this view is ISYSIDX.

Column name Data type Description

table_id UNSIGNED INT Uniquely identifies the table to which this index applies.

index_id UNSIGNED INT A unique number identifying the index within its table.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1211


Views

Column name Data type Description

object_id UNSIGNED BI- The internal ID for the index, uniquely identifying it in the data-
GINT base.

phys_index_id UNSIGNED INT Identifies the underlying physical index used to implement the
logical index. This value is NULL for indexes on temporary ta-
bles or remote tables. Otherwise, the value corresponds to the ob-
ject_id of a physical index in the SYSPHYSIDX system view.

dbspace_id SMALLINT The ID of the file in which the index is contained. This value cor-
responds to an entry in the SYSDBSPACE system view.

file_id SMALLINT DEPRECATED. This column is present in SYSVIEW, but not in


the underlying system table ISYSIDX. The contents of this col-
umn is the same as dbspace_id and is provided for compatibility.
Use dbspace_id instead.

index_catego- TINYINT The type of index. Values include:


ry
● 1 Primary key

● 2 Foreign key

● 3 Secondary index (includes unique constraints)

● 4 Text indexes

"unique" TINYINT Indicates whether the index is a unique index (1), a non-unique
index (4), or a unique constraint (2). A unique index prevents two
rows in the indexed table from having the same values in the in-
dex columns.

index_name CHAR(128) The name of the index.

not_enforced CHAR(1) For system use only.

file_id SMALLINT For system use only.

Constraints on underlying system table


PRIMARY KEY (table_id, index_id)

FOREIGN KEY (table_id) references SYS.ISYSTAB (table_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (table_id, phys_index_id) references SYS.ISYSPHYSIDX (table_id,


phys_index_id)

UNIQUE Index (index_name, table_id, index_category)

1212 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

See also
● “SYSIDXCOL system view” on page 1213
● “SYSPHYSIDX system view” on page 1222
● “SYSDBSPACE system view” on page 1202

SYSIDXCOL system view


Each row in the SYSIDXCOL system view describes one column of an index described in the SYSIDX
system view. The underlying system table for this view is ISYSIDXCOL.

Column Data type Description


name

table_id UNSIGNED Identifies the table to which the index applies.


INT

index_id UNSIGNED Identifies the index to which the column applies. Together, table_id
INT and index_id identify one index described in the SYSIDX system
view.

sequence SMALLINT 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 UNSIGNED Identifies which column of the table is indexed. Together, table_id
INT and column_id identify one column described in the SYSCOLUMN
system view.

"order" CHAR(1) Indicates whether the column in the index is kept in ascending(A) or
descending(D) order. This value is NULL for text indexes.

primary_col- UNSIGNED The ID of the primary key column that corresponds to this foreign
umn_id INT key column. The value is NULL for non foreign key columns.

Constraints on underlying system table


PRIMARY KEY (table_id, index_id, column_id)

FOREIGN KEY (table_id, index_id) references SYS.ISYSIDX (table_id, index_id)

FOREIGN KEY (table_id, column_id) references SYS.ISYSTABCOL (table_id,


column_id)

See also
● “SYSIDX system view” on page 1211

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1213


Views

SYSJAR system view


Each row in the SYSJAR system view defines a JAR file stored in the database. The underlying system
table for this view is ISYSJAR.

Column name Data type Description

jar_id INTEGER A unique number identifying the JAR file.

object_id UNSIGNED BIGINT The internal ID for the JAR file, uniquely identifying it in the
database.

creator UNSIGNED INT The user number of the creator of the JAR file.

jar_name LONG VARCHAR The name of the JAR file.

jar_file LONG VARCHAR The external file name of the JAR file within the database.

update_time TIMESTAMP The time the JAR file was last updated.

Constraints on underlying system table


PRIMARY KEY (jar_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

UNIQUE Index (jar_name)

See also
● “SYSJARCOMPONENT system view” on page 1214

SYSJARCOMPONENT system view


Each row in the SYSJAR system view defines a JAR file component. The underlying system table for this
view is ISYSJARCOMPONENT.

Column name Data type Description

component_id INTEGER The primary key containing the id of the component.

jar_id INTEGER A field containing the ID number of the JAR.

component_name LONG VARCHAR The name of the component.

component_type CHAR(1) The type of the component.

contents LONG BINARY The byte code of the JAR file.

1214 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Constraints on underlying system table


PRIMARY KEY (component_id)

FOREIGN KEY (jar_id) references SYS.ISYSJAR (jar_id)

See also
● “SYSJAR system view” on page 1214

SYSJAVACLASS system view


Each row in the SYSJAVACLASS system view describes one Java class stored in the database. The
underlying system table for this view is ISYSJAVACLASS.

Column name Data type Description

class_id INTEGER The unique number for the Java class. Also the primary key
for the table.

object_id UNSIGNED BI- The internal ID for the Java class, uniquely identifying it in
GINT the database.

creator UNSIGNED INT The user number of the creator of the class.

jar_id INTEGER The id of the JAR file from which the class came.

class_name LONG VARCHAR The name of the Java class.

public CHAR(1) Indicates whether the class is public (Y) or private (N).

component_id INTEGER The id of the component in the SYSJARCOMPONENT sys-


tem view.

update_time TIMESTAMP The last update time of the class.

Constraints on underlying system table


PRIMARY KEY (class_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (creator) references SYS.ISYSUSER (user_id)

FOREIGN KEY (component_id) references SYS.ISYSJARCOMPONENT (component_id)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1215


Views

SYSLOGINMAP system view


The SYSLOGINMAP system view contains one row for each user that can connect to the database using
either an integrated login, or Kerberos login. As a security measure, only users with DBA authority can
view the contents of this view. The underlying system table for this view is ISYSLOGINMAP.

Column name Data type Description

login_mode TINYINT The type of login: 1 for integrated logins, 2 for Kerberos log-
ins.

login_id VARCHAR(1024) Either the integrated login user profile name, or the Kerberos
principal that maps to database_uid.

object_id UNSIGNED BIGINT A unique identifier, one for each mapping between user ID
and database user ID.

database_uid UNSIGNED INT The database user ID to which the login ID is mapped.

Constraints on underlying system table


PRIMARY KEY (login_mode, login_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (database_uid) references SYS.ISYSUSER (user_id)

SYSLOGINPOLICY system view


The underlying system table for this view is ISYSLOGINPOLICY.

Column name Data type Description

login_policy_id UNSIGNED BIGINT A unique identifier for the login policy.

login_policy_name CHAR(128) The name of the login policy.

Constraints on underlying system table


PRIMARY KEY (login_policy_id)

FOREIGN KEY (login_policy_id) references SYS.ISYSOBJECT (object_id)

UNIQUE Index (login_policy_name)

See also
● “SYSLOGINPOLICYOPTION system view” on page 1217
● “SYSUSER system view” on page 1254

1216 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

SYSLOGINPOLICYOPTION system view


The underlying system table for this view is ISYSLOGINPOLICYOPTION.

Column name Data type Description

login_policy_id UNSIGNED BIGINT A unique identifier for the login policy.

login_option_name CHAR(128) The name of the login policy.

login_option_value LONG VARCHAR The value of the login policy at the time it was created.

Constraints on underlying system table


PRIMARY KEY (login_policy_id, login_option_name)

FOREIGN KEY (login_policy_id) references SYS.ISYSLOGINPOLICY


(login_policy_id)

See also
● “SYSLOGINPOLICY system view” on page 1216
● “SYSUSER system view” on page 1254

SYSMIRROROPTION system view


The underlying system table for this view is ISYSMIRROROPTION.

Column name Data type Description

option_name CHAR(128) The name of the option.

option_value LONG VARCHAR The value of the option when the mirror was created.

Constraints on underlying system table


PRIMARY KEY (option_name)

See also
● “SYSMIRRORSERVER system view” on page 1217
● “SYSMIRRORSERVEROPTION system view” on page 1218

SYSMIRRORSERVER system view


The underlying system table for this view is ISYSMIRRORSERVER.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1217


Views

Column Data type Description


name

object_id UNSIGNED BI- A unique identifier for the mirror server.


GINT

server_name CHAR(128) The name of the server.

server_type CHAR(20) The type of server. The value can be one of PRIMARY, MIR-
ROR, ARBITER, PARTNER, or COPY.

parent UNSIGNED BI- The parent server. If the value is NULL, then the server is the
GINT primary or mirror server in a database mirroring system.

If there is a value in this column, it is the ID of the server that is


the parent of the current server.

alternate_pa- UNSIGNED BI- The ID of the server that is used as an alternate parent if the cur-
rent GINT rent parent becomes unavailable.

Constraints on underlying system table


PRIMARY KEY (object_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id)

UNIQUE Index (server_name)

See also
● “SYSMIRROROPTION system view” on page 1217
● “SYSMIRRORSERVEROPTION system view” on page 1218
● “Copy node parent determination” [SQL Anywhere Server - Database Administration]
● “CREATE MIRROR SERVER statement” on page 564

SYSMIRRORSERVEROPTION system view


The underlying system table for this view is ISYSMIRRORSERVEROPTION.

Column name Data type Description

server_id UNSIGNED BIGINT A unique identifier for the mirror server.

option_name CHAR(128) The name of the option.

option_value LONG VARCHAR The value of the option when the mirror was created.

Constraints on underlying system table


PRIMARY KEY (server_id, option_name)

1218 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

FOREIGN KEY (server_id) references SYS.ISYSMIRRORSERVER (object_id)

See also
● “SYSMIRROROPTION system view” on page 1217
● “SYSMIRRORSERVER system view” on page 1217

SYSMVOPTION system view


Each row in the SYSMVOPTION system view describes the setting of one option value for a materialized
view or text index at the time of its creation. The name of the option can be found in the
SYSMVOPTIONNAME system view. The underlying system table for this view is ISYSMVOPTION.

Column name Data type Description

view_object_id UNSIGNED BI- The object ID of the materialized view.


GINT

option_id UNSIGNED INT A unique number identifying the option in the database. To see
the option name, see the SYSMVOPTIONNAME system view.

option_value LONG VAR- The value of the option when the materialized view was created.
CHAR

Constraints on underlying system table


PRIMARY KEY (view_object_id, option_id)

FOREIGN KEY (view_object_id) references SYS.ISYSOBJECT (object_id)

FOREIGN KEY (option_id) references SYS.ISYSMVOPTIONNAME (option_id)

See also
● “SYSMVOPTIONNAME system view” on page 1219
● “Viewing information about a text index in the database (Sybase Central)” [SQL Anywhere Server -
SQL Usage]
● “Advanced: Viewing materialized view information in the catalog” [SQL Anywhere Server - SQL
Usage]

SYSMVOPTIONNAME system view


Each row in the SYSMVOPTION system view gives the name option value for a materialized view or
text index at the time of its creation. The value for the option can be found in the SYSMVOPTION
system view. The underlying system table for this view is ISYSMVOPTIONNAME.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1219


Views

Column name Data type Description

option_id UNSIGNED INT A number uniquely identifying the option in the database.

option_name CHAR(128) The name of the option.

Constraints on underlying system table


PRIMARY KEY (option_id)

UNIQUE Index (option_name)

See also
● “SYSMVOPTION system view” on page 1219
● “Viewing information about a text index in the database (Sybase Central)” [SQL Anywhere Server -
SQL Usage]
● “Advanced: Viewing materialized view information in the catalog” [SQL Anywhere Server - SQL
Usage]

SYSOBJECT system view


Each row in the SYSOBJECT system view describes a database object. The underlying system table for
this view is ISYSOBJECT.

Column name Data type Description

object_id UNSIGNED The internal ID for the object, uniquely identifying it in the database.
BIGINT

status TINYINT The status of the object. Values include:

● 1 (valid) The object is available for use by the database server.


This status is synonymous with ENABLED. That is, if you ENA-
BLE an object, the status changes to VALID.

● 2 (invalid) An attempt to recompile the object after an internal


operation has failed, for example, after a schema-altering modifi-
cation to an object on which it depends. The database server con-
tinues to try to recompile the object whenever it is referenced in a
statement.

● 4 (disabled) The object has been explicitly disabled by the


user, for example using an ALTER TABLE...DISABLE VIEW
DEPENDENCIES statement.

object_type TINYINT Type of object.

1220 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

creation_time TIME- The date and time when the object was created.
STAMP

object_type_str CHAR (128) Type of object.

Constraints on underlying system table


PRIMARY KEY (object_id)

SYSOPTION system view


The SYSOPTION system view contains the options one row for each option setting stored in the
database. Each user can have their own setting for a given option. In addition, settings for the PUBLIC
user ID define the default settings to be used for users that do not have their own setting. The underlying
system table for this view is ISYSOPTION.

Column name Data type Description

user_id UNSIGNED INT The user number to whom the option setting applies.

"option" CHAR(128) The name of the option.

"setting" LONG VARCHAR The current setting for the option.

Constraints on underlying system table


PRIMARY KEY (user_id, "option")

FOREIGN KEY (user_id) references SYS.ISYSUSER (user_id)

SYSOPTSTAT system view


The SYSOPTSTAT system view stores the cost model calibration information as computed by the
ALTER DATABASE CALIBRATE statement. The contents of this view are for internal use only and are
best accessed via the sa_get_dtt system procedure. The underlying system table for this view is
ISYSOPTSTAT.

Column name Data type Description

stat_id UNSIGNED INT For system use only.

group_id UNSIGNED INT For system use only.

format_id SMALLINT For system use only.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1221


Views

Column name Data type Description

data LONG BINARY For system use only.

Constraints on underlying system table


PRIMARY KEY (stat_id, group_id, format_id)

SYSPHYSIDX system view


Each row in the SYSPHYSIDX system view defines a physical index in the database. The underlying
system table for this view is ISYSPHYSIDX.

Column name Data type Description

table_id UNSIGNED INT The object ID of the table to which the index corre-
sponds.

phys_index_id UNSIGNED INT The unique number of the physical index within its
table.

root INTEGER Identifies the location of the root page of the physical
index in the database file.

key_value_count UNSIGNED INT The number of distinct key values in the index.

leaf_page_count UNSIGNED INT The number of leaf index pages.

depth UNSIGNED SMALL- The depth (number of levels) of the physical index.
INT

max_key_distance UNSIGNED INT For system use only.

seq_transitions UNSIGNED INT For system use only.

rand_transitions UNSIGNED INT For system use only.

rand_distance UNSIGNED INT For system use only.

allocation_bitmap LONG VARBIT For system use only.

long_value_bitmap LONG VARBIT For system use only.

Constraints on underlying system table


PRIMARY KEY (table_id, phys_index_id)

1222 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

See also
● “SYSIDX system view” on page 1211
● “SYSIDXCOL system view” on page 1213

SYSPROCEDURE system view


Each row in the SYSPROCEDURE system view describes one procedure in the database. The underlying
system table for this view is ISYSPROCEDURE.

Column name Data type Description

proc_id UNSIGNED INT Each procedure is assigned a unique number (the procedure
number).

creator UNSIGNED INT The owner of the procedure.

object_id UNSIGNED BI- The internal ID for the procedure, uniquely identifying it in the
GINT database.

proc_name CHAR(128) The name of the procedure. One creator cannot have two pro-
cedures with the same name.

proc_defn LONG VAR- The definition of the procedure.


CHAR

remarks LONG VAR- Remarks about the procedure. This value is stored in the ISYS-
CHAR REMARK system table.

replicate CHAR(1) This property is for internal use only.

srvid UNSIGNED INT If the procedure is a proxy for a procedure on a remote data-
base server, indicates the remote server.

source LONG VAR- The preserved source for the procedure. This value is stored in
CHAR the ISYSSOURCE system table.

avg_num_rows FLOAT Information collected for use in query optimization when the
procedure appears in the FROM clause.

avg_cost FLOAT Information collected for use in query optimization when the
procedure appears in the FROM clause.

stats LONG BINARY Information collected for use in query optimization when the
procedure appears in the FROM clause.

Constraints on underlying system table


PRIMARY KEY (proc_id)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1223


Views

FOREIGN KEY (srvid) references SYS.ISYSSERVER (srvid)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (creator) references SYS.ISYSUSER (user_id)

UNIQUE Index (proc_name, creator)

SYSPROCPARM system view


Each row in the SYSPROCPARM system view describes one parameter to a procedure in the database.
The underlying system table for this view is ISYSPROCPARM.

Column name Data type Description

proc_id UNSIGNED INT Uniquely identifies the procedure to which the parameter be-
longs.

parm_id SMALLINT Each procedure starts numbering parameters at 1. The order of


parameter numbers corresponds to the order in which they were
defined. For functions, the first parameter has the name of the
function and represents the return value for the function.

parm_type SMALLINT The type of parameter is one of the following:

● 0 Normal parameter (variable)

● 1 Result variable - used with a procedure that returns re-


sult sets

● 2 SQLSTATE error value

● 3 SQLCODE error value

● 4 Return value from function

parm_mode_in CHAR(1) Indicates whether the parameter supplies a value to the proce-
dure (IN or INOUT parameters).

parm_mode_out CHAR(1) Indicates whether the parameter returns a value from the proce-
dure (OUT or INOUT parameters) or columns in the RESULT
clause.

domain_id SMALLINT Identifies the data type for the parameter, by the data type num-
ber listed in the SYSDOMAIN system view.

1224 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

width BIGINT Contains the length of a string parameter, the precision of a nu-
meric parameter, or the number of bytes of storage for any oth-
er data type.

scale SMALLINT For numeric data types, the number of digits after the decimal
point. For all other data types, the value of this column is 1.

user_type SMALLINT The user type of the parameter, if applicable.

parm_name CHAR(128) The name of the procedure parameter.

"default" LONG VAR- Default value of the parameter. Provided for informational pur-
CHAR poses only.

remarks LONG VAR- Always returns NULL. Provided to allow the use of previous
CHAR versions of ODBC drivers with newer personal database serv-
ers.

base_type_str VAR- The annotated type string representing the physical type of the
CHAR(32767) parameter.

Constraints on underlying system table


PRIMARY KEY (proc_id, parm_id)

FOREIGN KEY (proc_id) references SYS.ISYSPROCEDURE (proc_id)

FOREIGN KEY (domain_id) references SYS.ISYSDOMAIN (domain_id)

FOREIGN KEY (user_type) references SYS.ISYSUSERTYPE (type_id)

SYSPROCPERM system view


Each row of the SYSPROCPERM system view describes a user granted permission to execute a
procedure. Only users who have been granted permission can execute a procedure. The underlying system
table for this view is ISYSPROCPERM.

Column name Data type Description

proc_id UNSIGNED INT The procedure number uniquely identifies the procedure for
which permission has been granted.

grantee UNSIGNED INT The user number of the user receiving the permission.

Constraints on underlying system table


PRIMARY KEY (proc_id, grantee)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1225


Views

FOREIGN KEY (grantee) references SYS.ISYSUSER (user_id)

FOREIGN KEY (proc_id) references SYS.ISYSPROCEDURE (proc_id)

SYSPROXYTAB system view


Each row of the SYSPROXYTAB system view describes the remote parameters of one proxy table. The
underlying system table for this view is ISYSPROXYTAB.

Column name Data type Description

table_object_id UNSIGNED BI- The object ID of the proxy table.


GINT

existing_obj CHAR(1) Indicates whether the proxy table previously existed on the
remote server .

srvid UNSIGNED INT The unique ID for the remote server associated with the
proxy table.

remote_location LONG VARCHAR The location of the proxy table on the remote server.

Constraints on underlying system table


PRIMARY KEY (table_object_id)

FOREIGN KEY (table_object_id) references ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (srvid) references SYS.ISYSSERVER (srvid)

SYSPUBLICATION system view


Each row in the SYSPUBLICATION system view describes a SQL Remote or MobiLink publication.
The underlying system table for this view is ISYSPUBLICATION.

Column Data type Description


name

publication_id UNSIGNED INT A number uniquely identifying the publication.

object_id UNSIGNED BI- The internal ID for the publication, uniquely identifying it in the
GINT database.

creator UNSIGNED INT The owner of the publication.

1226 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column Data type Description


name

publica- CHAR(128) The name of the publication.


tion_name

remarks LONG VAR- Remarks about the publication. This value is stored in the ISYS-
CHAR REMARK system table.

type CHAR(1) This column is deprecated.

sync_type UNSIGNED INT The type of synchronization for the publication. Values include:

● 0 (logscan) This is a regular publication that uses the


transaction log to upload all relevant data that has changed
since the last upload.

● 1 (scripted upload) For this publication, the transaction


log is ignored and the upload is defined by the user using
stored procedures. Information about the stored procedures is
stored in the ISYSSYNCSCRIPT system table.

● 2 (download only) This is a download-only publication;


no data is uploaded.

Constraints on underlying system table


PRIMARY KEY (publication_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (creator) references SYS.ISYSUSER (user_id)

UNIQUE Index (publication_name, creator)

See also
● “Scripted upload” [MobiLink - Client Administration]
● “SYSSYNCSCRIPT system view” on page 1240

SYSREMARK system view


Each row in the SYSREMARK system view describes a remark (or comment) for an object. The
underlying system table for this view is ISYSREMARK.

Column Data type Description

object_id UNSIGNED BIGINT The internal ID for the object that has an associated remark.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1227


Views

Column Data type Description

remarks LONG VARCHAR The remark or comment associated with the object.

Constraints on underlying system table


PRIMARY KEY (object_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

SYSREMOTEOPTION system view


Each row in the SYSREMOTEOPTION system view describes the value of a SQL Remote message link
parameter. The underlying system table for this view is ISYSREMOTEOPTION.

Some columns in this view contain potentially sensitive data. For that reason, access to this view is
restricted to users with DBA authority. The SYSREMOTEOPTION2 view provides public access to the
data in this view except for the potentially sensitive 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.

Constraints on underlying system table


PRIMARY KEY (option_id, user_id)

FOREIGN KEY (option_id) references SYS.ISYSREMOTEOPTIONTYPE (option_id)

FOREIGN KEY (user_id) references SYS.ISYSUSER (user_id)

SYSREMOTEOPTIONTYPE system view


Each row in the SYSREMOTEOPTIONTYPE system view describes one of the SQL Remote message
link parameters. The underlying system table for this view is ISYSREMOTEOPTIONTYPE.

Column Data type Description

option_id UNSIGNED INT An identification number for the message link parameter.

type_id SMALLINT An identification number for the message type that uses the parameter.

1228 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column Data type Description

"option" VARCHAR(128) The name of the message link parameter.

Constraints on underlying system table


PRIMARY KEY (option_id)

FOREIGN KEY (type_id) references SYS.ISYSREMOTETYPE (type_id)

SYSREMOTETYPE system view


The SYSREMOTETYPE system view contains information about SQL Remote. The underlying system
table for this view is ISYSREMOTETYPE.

Column name Data type Description

type_id SMALLINT Identifies which of the message systems supported by SQL


Remote is to be used to send messages to the user.

object_id UNSIGNED BI- The internal ID for the remote type, uniquely identifying it in
GINT the database.

type_name CHAR(128) The name of the message system supported by SQL Remote.

publisher_ad- LONG VARCHAR The address of the remote database publisher.


dress

remarks LONG VARCHAR Remarks about the remote type. This value is stored in the
ISYSREMARK system table.

Constraints on underlying system table


PRIMARY KEY (type_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

UNIQUE Index (type_name)

SYSREMOTEUSER system view


Each row in the SYSREMOTEUSER system view describes a user ID with REMOTE permissions (a
subscriber), together with the status of SQL Remote messages that were sent to and from that user. The
underlying system table for this view is ISYSREMOTEUSER.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1229


Views

Column name Data type Description

user_id UNSIGNED INT The user number of the user with REMOTE permissions.

consolidate CHAR(1) Indicates whether the user was granted CONSOLIDATE per-
missions (Y) or REMOTE permissions (N).

type_id SMALLINT Identifies which of the message systems supported by SQL


Remote is used to send messages to the user.

address LONG VAR- The address to which SQL Remote messages are to be sent.
CHAR The address must be appropriate for the address_type.

frequency CHAR(1) How frequently SQL Remote messages are sent.

send_time TIME The next time messages are to be sent to this user.

log_send UNSIGNED BI- Messages are sent only to subscribers for whom log_send is
GINT greater than log_sent.

time_sent TIMESTAMP The time the most recent message was sent to this subscriber.

log_sent UNSIGNED BI- The log offset for the most recently sent operation.
GINT

confirm_sent UNSIGNED BI- The log offset for the most recently confirmed operation from
GINT this subscriber.

send_count INTEGER How many SQL Remote messages have been sent.

resend_count INTEGER Counter to ensure that messages are applied only once at the
subscriber database.

time_received TIMESTAMP The time when the most recent message was received from
this subscriber.

log_received UNSIGNED BI- The log offset in the database of the subscriber for the opera-
GINT tion that was most recently received at the current database.

confirm_re- UNSIGNED BI- The log offset in the database of the subscriber for the most
ceived GINT recent operation for which a confirmation message has been
sent.

receive_count INTEGER How many messages have been received.

rereceive_count INTEGER Counter to ensure that messages are applied only once at the
current database.

1230 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Constraints on underlying system table


PRIMARY KEY (user_id)

FOREIGN KEY (user_id) references SYS.ISYSUSER (user_id)

FOREIGN KEY (type_id) references SYS.ISYSREMOTETYPE (type_id)

UNIQUE Index (type_id, address)

SYSSCHEDULE system view


Each row in the SYSSCHEDULE system view describes a time at which an event is to fire, as specified
by the SCHEDULE clause of CREATE EVENT. The underlying system table for this view is
ISYSSCHEDULE.

Column name Data type Description

event_id UNSIGNED INT The unique number assigned to each event.

sched_name VARCHAR(128) The name associated with the schedule for the event.

recurring TINYINT Indicates if the schedule is repeating.

start_time TIME The schedule start time.

stop_time TIME The schedule stop time if BETWEEN was used.

start_date DATE The first date on which the event is scheduled to execute.

days_of_week TINYINT A bit mask indicating the days of the week on which the event is
scheduled:

● x01 = Sunday
● x02 = Monday
● x04 = Tuesday
● x08 = Wednesday
● x10 = Thursday
● x20 = Friday
● x40 = Saturday

days_of_month UNSIGNED INT A bit mask indicating the days of the month on which the event
is scheduled. Some examples include:

● x01 = first day


● x02 = second day
● x40000000 = 31st day
● x80000000 = last day of month

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1231


Views

Column name Data type Description

interval_units CHAR(10) The interval unit specified by EVERY:

● HH = hours
● NN = minutes
● SS = seconds

interval_amt INTEGER The period specified by EVERY.

Constraints on underlying system table


PRIMARY KEY (event_id, sched_name)

FOREIGN KEY (event_id) references SYS.ISYSEVENT (event_id)

SYSSEQUENCE system view


The SYSSEQUENCE system view contains one row for each user-defined sequence. The underlying
system table for this view is ISYSSEQUENCE.

Column name Data type Description

object_id UNSIGNED BI- The unique number assigned to each sequence.


GINT

owner UNSIGNED INT The owner of the sequence.

min_value BIGINT The minimum value allowed for the sequence.

max_value BIGINT The maximum value allowed for the sequence.

increment_by BIGINT The increment value for the sequence.

start_with BIGINT The starting value for the sequence.

cache UNSIGNED INT The number of sequence values to preallocate in memory for
faster access. A value of 0 indicates that values are not to be
preallocated

cycle TINYINT Whether values should continue to be generated after the


maximum or minimum value is reached.

resume_at BIGINT The RESTART WITH value specified by the ALTER SE-
QUENCE statement. The value is NULL if no ALTER RE-
START WITH statement has been executed.

sequence_name CHAR(128) The name of the sequence.

1232 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Constraints on underlying system table


PRIMARY KEY (object_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT MATCH UNIQUE FULL

FOREIGN KEY (owner) references SYS.ISYSUSER (user_id)

SYSSEQUENCEPERM system view


The SYSSEQUENCEPERM system view records the privileges that users or groups hold on sequences.
The underlying system table for this view is ISYSSEQUENCEPERM.

Column name Data type Description

sequence_id UNSIGNED BIGINT The unique number assigned to each sequence.

grantee UNSIGNED INT The ID of the user or group with permissions to alter or drop
the sequence.

grantor UNSIGNED INT The ID of the user who granted the permissions for the se-
quence.

privilege_type SMALLINT The type of privileges granted to the user or group on the se-
quence.

Constraints on underlying system table


PRIMARY KEY (sequence_id, grantee, privilege_type)

FOREIGN KEY (sequence_id) references SYS.ISYSSEQUENCE (object_id)

FOREIGN KEY (grantee) references SYS.ISYSUSER (user_id)

FOREIGN KEY (grantor) references SYS.ISYSUSER (user_id)

SYSSERVER system view


Each row in the SYSSERVER system view describes a remote server. The underlying system table for
this view is ISYSSERVER.

Note
Previous versions of the catalog contained a SYSSERVERS system table. That table has been renamed to
be ISYSSERVER (without an 'S'), and is the underlying table for this view.

Column name Data type Description

srvid UNSIGNED INT An identifier for the remote server.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1233


Views

Column name Data type Description

srvname VARCHAR(128) The name of the remote server.

srvclass LONG VARCHAR The server class, as specified in the CREATE SERVER state-
ment.

srvinfo LONG VARCHAR Server information.

srvreadonly CHAR(1) Whether the server is read-only.

Constraints on underlying system table


PRIMARY KEY (srvid)

SYSSOURCE system view


Each row in the SYSSOURCE system view contains the source code, if applicable, for an object listed in
the SYSOBJECT system view. The underlying system table for this view is ISYSSOURCE.

Column Data type Description


name

object_id UNSIGNED The internal ID for the object whose source code is being defined.
BIGINT

source LONG VAR- This column contains the original source code for the object if the
CHAR preserve_source_format database option is On when the object was
created.

Constraints on underlying system table


PRIMARY KEY (object_id)
FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE
FULL

See also
● “preserve_source_format option” [SQL Anywhere Server - Database Administration]

SYSSPATIALREFERENCESYSTEM system view


Each row of the SYSSPATIALREFERENCESYSTEM system view describes an SRS defined in the
database. The underlying system table for this view is ISYSSPATIALREFERENCESYSTEM.

This view offers slightly different amount of information than the


ST_SPATIAL_REFERENCE_SYSTEMS system view.

1234 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

object_id UNSIGNED For system use only.


BIGINT

owner UNSIGNED The owner of the SRS.


INT

srs_name CHAR(128) The name of the SRS.

srs_id INT The numeric identifier (SRID) for the spatial reference sys-
tem.

round_earth CHAR(1) Whether the SRS type is ROUND EARTH (Y) or PLANAR
(N).

axis_order CHAR(12) Describes how the database server interprets points with re-
gards to latitude and longitude (for example when using the
ST_Lat and ST_Long methods). For non-geographic spatial
reference systems, the axis order is x/y/z/m. For geographic
spatial reference systems, the default axis order is
long/lat/z/m; lat/long/z/m is also supported.

snap_to_grid DOUBLE Defines the size of the grid SQL Anywhere uses when per-
forming calculations.

tolerance DOUBLE Defines the precision to use when comparing points.

semi_major_axis DOUBLE Distance from center of the ellipsoid to the equator for a
ROUND EARTH SRS.

semi_minor_axis DOUBLE Distance from center of the ellipsoid to the poles for a
ROUND EARTH SRS.

inv_flattening DOUBLE The inverse flattening used for the ellipsoid in a ROUND
EARTH SRS.

Inverse flattening (f) is a mathematical value that defines the


degree of squashing of the pole of a spheroid towards its
equator. The value ranges from no flattening (a perfect cir-
cle) to complete flattening (a straight line). Inverse flatten-
ing is the value of 1/f, as follows:
1/f = (semi_major_axis) / (semi_major_axis -
semi_minor_axis)

min_x DOUBLE The minimum x value allowed in coordinates.

max_x DOUBLE The maximum x value allowed in coordinates.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1235


Views

Column name Data type Description

min_y DOUBLE The minimum y value allowed in coordinates.

max_y DOUBLE The maximum y value allowed in coordinates.

min_z DOUBLE The minimum z value allowed in coordinates.

max_z DOUBLE The maximum z value allowed in coordinates.

min_m DOUBLE The minimum m value allowed in coordinates.

max_m DOUBLE The maximum m value allowed in coordinates.

organization LONG VAR- The name of the organization that created the coordinate
CHAR system used by the spatial reference system.

organization_coord- INT The ID given to the coordinate system by the organization


sys_id that created it.

srs_type CHAR(11) The type of SRS as defined by the SQL/MM standard. Val-
ues can be one of:

● GEOGRAPHIC This is for SRSs based on georefer-


enced coordinate systems with axes of latitude, longi-
tude (and elevation). These SRSs are of type PLANAR
or ROUND EARTH.

● PROJECTED This is for SRSs based on georefer-


enced coordinate systems that do not have axes of lati-
tude and longitude. These SRSs are of type PLANAR.

● ENGINEERING This is for SRSs based on non-geore-


ferenced coordinate systems. These SRSs are of type
PLANAR.

● GEOCENTRIC Unsupported.

● COMPOUND Unsupported.

● VERTICAL Unsupported.

If srs_type is empty, the type is unspecified.

linear_unit_of_meas- UNSIGNED The linear unit of measure used by the spatial reference sys-
ure BIGINT tem.

angu- UNSIGNED The angular unit of measure used by the spatial reference
lar_unit_of_measure BIGINT system.

1236 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

count_in_use UNSIGNED For internal use only.


BIGINT

polygon_format LONG VAR- The orientation of the rings in a polygon. One of Counter-
CHAR Clockwise, ClockWise, or EvenOdd.

storage_format LONG VAR- Whether the data is stored in normalized format (Internal),
CHAR unnormalized format (Original), or both (Mixed).

definition LONG VAR- The WKT definition of the spatial reference system in the
CHAR format defined by the OGC standard.

transform_definition LONG VAR- Transform definition settings for use when transforming da-
CHAR ta from this SRS to another.

Constraints on underlying system table


PRIMARY KEY (object_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id)

FOREIGN KEY (linear_unit_of_measure) references SYS.ISYSUNITOFMEASURE


(object_id)

FOREIGN KEY (angular_unit_of_measure) references SYS.ISYSUNITOFMEASURE


(object_id)

FOREIGN KEY (owner) references SYS.ISYSUSER (user_id)

UNIQUE Constraint (srs_name)

UNIQUE Constraint (srs_id)

See also
● “ST_SPATIAL_REFERENCE_SYSTEMS consolidated view” on page 1261
● “CREATE SPATIAL REFERENCE SYSTEM statement” on page 616

SYSSQLSERVERTYPE system view


The SYSSQLSERVERTYPE system view contains information relating to compatibility with Adaptive
Server Enterprise. The underlying system table for this view is ISYSSQLSERVERTYPE.

Column name Data type Description

ss_user_type SMALLINT The Adaptive Server Enterprise user type.

ss_domain_id SMALLINT The Adaptive Server Enterprise domain ID.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1237


Views

Column name Data type Description

ss_type_name VARCHAR (30) The Adaptive Server Enterprise type name.

primary_sa_domain_id SMALLINT The corresponding SQL Anywhere primary domain ID.

primary_sa_user_type SMALLINT The corresponding SQL Anywhere primary user type.

Constraints on underlying system table


PRIMARY KEY (ss_user_type)

SYSSUBSCRIPTION system view


Each row in the SYSSUBSCRIPTION system view describes a subscription from one user ID (which
must have REMOTE permissions) to one publication. The underlying system table for this view is
ISYSSUBSCRIPTION.

Column name Data type Description

publication_id UNSIGNED INT The identifier for the publication to which the user ID is sub-
scribed.

user_id UNSIGNED INT The ID of the user who is subscribed to the publication.

subscribe_by CHAR(128) The value of the SUBSCRIBE BY expression, if any, for the
subscription.

created UNSIGNED BIGINT The offset in the transaction log at which the subscription
was created.

started UNSIGNED BIGINT The offset in the transaction log at which the subscription
was started.

Constraints on underlying system table


PRIMARY KEY (publication_id, user_id, subscribe_by)

FOREIGN KEY (publication_id) references SYS.ISYSPUBLICATION (publication_id)

FOREIGN KEY (user_id) references SYS.ISYSUSER (user_id)

SYSSYNC system view


The SYSSYNC system view contains information relating to MobiLink synchronization. Some columns
in this view contain potentially sensitive data. For that reason, access to this view is restricted to users

1238 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

with DBA authority. The SYSSYNC2 view provides public access to the data in this view except for the
potentially sensitive columns. The underlying system table for this view is ISYSSYNC.

Column name Data type Description

sync_id UNSIGNED INT A number that uniquely identifies the row.

type CHAR(1) This value is always D.

publication_id UNSIGNED INT A publication_id found in the SYSPUBLICATION sys-


tem view.

progress UNSIGNED BI- The log offset of the last successful upload.
GINT

site_name CHAR(128) A MobiLink user name.

"option" LONG VARCHAR Synchronization options.

server_connect LONG VARCHAR The address or URL of the MobiLink server.

server_conn_type LONG VARCHAR The communication protocol, such as TCP/IP, to use


when synchronizing.

last_down- TIMESTAMP Indicates the last time a download stream was received
load_time from the MobiLink server.

last_upload_time TIMESTAMP Indicates the last time (measured at the MobiLink server)
that information was successfully uploaded. The default
is jan-1-1900.

created UNSIGNED BI- The log offset at which the subscription was created.
GINT

log_sent UNSIGNED BI- The log progress up to which information has been up-
GINT loaded. It is not necessary that an acknowledgement of
the upload be received for the entry in this column to be
updated.

generation_number INTEGER For file-base downloads, the last generation number re-
ceived for this subscription. The default is 0.

extended_state VARCHAR(1024) For internal use only.

script_version CHAR(128) Indicates the script version used by the CREATE and
ALTER SYNCHRONIZATION SUBSCRIPTION state-
ments and the START SYNCHRONIZATION SCHE-
MA CHANGE statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1239


Views

Column name Data type Description

subscription_name CHAR (128) The name of the subscription.

Constraints on underlying system table


PRIMARY KEY (sync_id)

FOREIGN KEY (publication_id) references SYS.ISYSPUBLICATION (publication_id)

UNIQUE Index (publication_id, site_name)

UNIQUE Index (subscription_name)

SYSSYNCPROFILE system view


The SYSSYNCPROFILE system view contains information relating to synchronization profiles for
MobiLink synchronization.

The underlying system table for this view is ISYSSYNCPROFILE.

Column name Data type Description

object_id UNSIGNED BIGINT The object ID of the sync profile.

profile_name CHAR(128) The name of the sync profile.

profile_defn LONG VARCHAR The definition for the syn profile.

Constraints on underlying system table


PRIMARY KEY (object_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id)

UNIQUE Index (profile_name)

SYSSYNCSCRIPT system view


Each row in the SYSSYNCSCRIPT system view identifies a stored procedure for MobiLink scripted
upload. This view is almost identical to the SYSSYNCSCRIPTS view, except that the values in this view
are in their raw format.

The underlying system table for this view is ISYSSYNCSCRIPT.

Column name Data type Description

pub_object_id UNSIGNED BIGINT The object ID of the publication to which the script belongs.

1240 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

table_object_id UNSIGNED BIGINT The object ID of the table to which the script applies.

type UNSIGNED INT The type of upload procedure.

proc_object_id UNSIGNED BIGINT The object ID of the stored procedure to use for the publica-
tion.

Constraints on underlying system table


PRIMARY KEY (pub_object_id, table_object_id, type)

FOREIGN KEY (pub_object_id) references SYS.ISYSOBJECT (object_id)

FOREIGN KEY (table_object_id) references SYS.ISYSOBJECT (object_id)

FOREIGN KEY (proc_object_id) references SYS.ISYSOBJECT (object_id)

See also
● “Scripted upload” [MobiLink - Client Administration]
● “SYSSYNCSCRIPTS consolidated view” on page 1276
● “SYSPROCEDURE system view” on page 1223
● “SYSPUBLICATION system view” on page 1226

SYSTAB system view


Each row of the SYSTAB system view describes one table or view in the database. Additional
information for views can be found in the SYSVIEW system view. The underlying system table for this
view is ISYSTAB.

Column name Data type Description

table_id UNSIGNED Each table is assigned a unique number (the table number).
INT

dbspace_id SMALLINT A value indicating which dbspace contains the table.

count UNSIGNED The number of rows in the table or materialized view. This val-
BIGINT ue is updated during each successful checkpoint. This number
is used to optimize database access. The count is always 0 for a
non-materialized view or remote table.

creator UNSIGNED The user number of the owner of the table or view.
INT

table_page_count INTEGER The total number of main pages used by the underlying table.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1241


Views

Column name Data type Description

ext_page_count INTEGER The total number of extension pages used by the underlying ta-
ble.

commit_action INTEGER For global temporary tables, 0 indicates that the ON COMMIT
PRESERVE ROWS clause was specified when the table was
created, 1 indicates that the ON COMMIT DELETE ROWS
clause was specified when the table was created (the default
behavior for temporary tables), and 3 indicates that the NOT
TRANSACTIONAL clause was specified when the table was
created. For non-temporary tables, commit_action is always 0.

share_type INTEGER For global temporary tables, 4 indicates that the SHARE BY
ALL clause was specified when the table was created, and 5 in-
dicates that the SHARE BY ALL clause was not specified
when the table was created. For non-temporary tables,
share_type is always 5 because the SHARE BY ALL clause
cannot be specified when creating non-temporary tables.

object_id UNSIGNED The object ID of the table.


BIGINT

last_modified_at TIMESTAMP The time at which the data in the table was last modified. This
column is only updated at checkpoint time.

last_modified_tsn UNSIGNED A sequence number assigned to the transaction that modified


BIGINT the table. This column is only updated at checkpoint time.

file_id SMALLINT DEPRECATED. This column is present in SYSVIEW, but not


in the underlying system table ISYSTAB. The contents of this
column is the same as dbspace_id and is provided for compati-
bility. Use dbspace_id instead.

table_name CHAR(128) The name of the table or view. One creator cannot have two ta-
bles or views with the same name.

1242 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

table_type TINYINT The type of table or view. Values include:

● 1 Base table

● 2 Materialized view

● 3 Global temporary table

● 4 Local temporary table

● 5 Text index base table

● 6 Text index global temporary table

● 21 View

replicate CHAR(1) This value is for internal use only.

server_type TINYINT The location of the data for the underlying table. Values in-
clude:

● 1 Local server

● 3 Remote server

tab_page_list LONG VAR- For internal use only. The set of pages that contain information
BIT for the table, expressed as a bitmap.

ext_page_list LONG VAR- For internal use only. The set of pages that contain row exten-
BIT sions and large object (LOB) pages for the table, expressed as a
bitmap.

pct_free UNSIGNED The PCT_FREE specification for the table, if one has been
INT specified; otherwise, NULL.

clustered_in- UNSIGNED The ID of the clustered index for the table. If none of the in-
dex_id INT dexes are clustered, then this field is NULL.

encrypted CHAR(1) Whether the table or materialized view is encrypted.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1243


Views

Column name Data type Description

table_type_str CHAR(9) Readable value for table_type. Values include:

● BASE Base table

● MAT VIEW Materialized view

● GBL TEMP Global temporary table

● VIEW View

Constraints on underlying system table


FOREIGN KEY (dbspace_id) references SYS.ISYSDBSPACE (dbspace_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id)

PRIMARY KEY (table_id)

FOREIGN KEY (creator) references SYS.ISYSUSER (user_id)

UNIQUE Index (table_name, creator)

See also
● “SYSVIEW system view” on page 1257

SYSTABCOL system view


The SYSTABCOL system view contains one row for each column of each table and view in the database.
The underlying system table for this view is ISYSTABCOL.

Column name Data type Description

table_id UNSIGNED INT The object ID of the table or view to which the column belongs.

column_id UNSIGNED INT The ID of the column. For each table, column numbering starts
at 1.

The column_id value determines the order of columns in the re-


sult set when SELECT * is used. It also determines the column
order for an INSERT statement when a list of column names is
not provided.

domain_id SMALLINT The data type for the column, indicated by a data type number
listed in the SYSDOMAIN system view.

nulls CHAR(1) Indicates whether NULL values are allowed in the column.

1244 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

width UNSIGNED INT The length of a string column, the precision of numeric col-
umns, or the number of bytes of storage for any other data type.

scale SMALLINT The number of digits after the decimal point for NUMERIC or
DECIMAL data type columns. For string columns, a value of 1
indicates character-length semantics and 0 indicates byte-length
semantics.

object_id UNSIGNED BI- The object ID of the table column.


GINT

max_identity BIGINT The largest value of the column, if it is an AUTOINCREMENT,


IDENTITY, or GLOBAL AUTOINCREMENT column.

column_name CHAR(128) The name of the column.

"default" LONG VAR- The default value for the column. This value, if specified, is on-
CHAR ly used when an INSERT statement does not specify a value for
the column.

user_type SMALLINT The data type, if the column is defined using a user-defined data
type.

column_type CHAR(1) The type of column (C=computed column, and R=other col-
umns).

compressed TINYINT Whether this column is stored in a compressed format.

collect_stats TINYINT Whether the system automatically collects and updates statistics
on this column.

inline_max SMALLINT The maximum number of bytes of a BLOB to store in a row. A


NULL value indicates that either the default value has been ap-
plied, or that the column is not a character or binary type. A
non-NULL inline_max value corresponds to the INLINE value
specified for the column using the CREATE TABLE or ALTER
TABLE statement.

inline_long SMALLINT The number of duplicate bytes of a BLOB to store in a row if


the BLOB size exceeds the inline_max value. A NULL value in-
dicates that either the default value has been applied, or that the
column is not a character or binary type. A non-NULL in-
line_long value corresponds to the PREFIX value specified for
the column using the CREATE TABLE or ALTER TABLE
statement.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1245


Views

Column name Data type Description

lob_index TINYINT Whether to build indexes on BLOB values in the column that
exceed an internal threshold size (approximately eight database
pages). A NULL value indicates either that the default is ap-
plied, or that the column is not BLOB type. A value of 1 indi-
cates that indexes will be built. A value of 0 indicates that no in-
dexes will be built. A non-NULL lob_index value corresponds
to whether INDEX or NO INDEX was specified for the column
using the CREATE TABLE or ALTER TABLE statement.

base_type_str VAR- The annotated type string representing the physical type of the
CHAR(32,767) column.

Constraints on underlying system table


PRIMARY KEY (table_id, column_id)

FOREIGN KEY (table_id) references SYS.ISYSTAB (table_id)

FOREIGN KEY (domain_id) references SYS.ISYSDOMAIN (domain_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (user_type) references SYS.ISYSUSERTYPE (type_id)

See also
● “CREATE TABLE statement” on page 633

SYSTABLEPERM system view


Permissions given by the GRANT statement are stored in the SYSTABLEPERM system view. Each row
in this view corresponds to one table, one user ID granting the permission (grantor) and one user ID
granted the permission (grantee). The underlying system table for this view is ISYSTABLEPERM.

Column Data type Description


name

stable_id UNSIGNED The table number of the table or view to which the permissions apply.
INT

grantee UNSIGNED The user number of the user ID receiving the permission.
INT

grantor UNSIGNED The user number of the user ID granting the permission.
INT

1246 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column Data type Description


name

selectauth CHAR(1) Indicates whether SELECT permission has been granted. Possible val-
ues are Y, N, or G. See the Remarks area below for more information
about what these values mean.

insertauth CHAR(1) Indicates whether INSERT permission has been granted. Possible val-
ues are Y, N, or G. See the Remarks area below for more information
about what these values mean.

deleteauth CHAR(1) Indicates whether DELETE permission has been granted. Possible val-
ues are Y, N, or G. See the Remarks area below for more information
about what these values mean.

updateauth CHAR(1) Indicates whether UPDATE permission has been granted for all col-
umns in the table. Possible values are Y, N, or G. See the Remarks area
below for more information about what these values mean.

updatecols CHAR(1) Indicates whether UPDATE permission has only been granted for some
of the columns in the underlying table. If updatecols has the value Y,
there will be one or more rows in the SYSCOLPERM system view
granting update permission for the columns.

alterauth CHAR(1) Indicates whether ALTER permission has been granted. Possible values
are Y, N, or G. See the Remarks area below for more information about
what these values mean.

referen- CHAR(1) Indicates whether REFERENCE permission has been granted. Possible
ceauth values are Y, N, or G. See the Remarks area below for more informa-
tion about what these values mean.

Remarks
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.

● G The grantee has been given this permission and can grant the same permission to another user.

Note
The grantee might have been given permission for the same table by another grantor. If so, this
information would be found in a different row of the SYSTABLEPERM system view.

Constraints on underlying system table


PRIMARY KEY (stable_id, grantee, grantor)

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1247


Views

FOREIGN KEY (stable_id) references SYS.ISYSTAB (table_id)

FOREIGN KEY (grantor) references SYS.ISYSUSER (user_id)

FOREIGN KEY (grantee) references SYS.ISYSUSER (user_id)

See also
● “GRANT statement” on page 760

SYSTEXTCONFIG system view


Each row in the SYSTEXTCONFIG system view describes one text configuration object, for use with the
full text search feature. The underlying system table for this view is ISYSTEXTCONFIG.

Column name Data type Description

object_id UNSIGNED The object ID for the text configuration object.


BIGINT

creator UNSIGNED The creator of the text configuration object.


INT

term_breaker TINYINT The algorithm used to separate a string into terms or words.
Values are 0 for GENERIC and 1 for NGRAM. With GE-
NERIC, any string of one or more alphanumeric characters
separated by non-alphanumerics are treated as a term.
NGRAM is for approximate matching or for documents that
do not use a whitespace to separate terms.

stemmer TINYINT For internal use only.

min_term_length TINYINT The minimum length, in characters, allowed for a term.


Terms that are shorter than min_term_length are ignored.

The MINIMUM TERM LENGTH setting is only meaning-


ful for the GENERIC term breaker. For NGRAM text in-
dexes, the setting is ignored.

max_term_length TINYINT For GENERIC text indexes, the maximum length, in charac-
ters, allowed for a term. Terms that are longer than
max_term_length are ignored.

For NGRAM text indexes, this is the length of the n-grams


into which terms are broken.

collation CHAR(128) For internal use only.

text_config_name CHAR(128) The name of the text configuration object.

1248 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

prefilter LONG VAR- The function and library name for an external prefilter li-
CHAR brary.

postfilter LONG VAR- For internal use only.


CHAR

char_stoplist LONG VAR- Terms to ignore when performing a full text search on
CHAR CHAR columns. These terms are also omitted from text in-
dexes. This column is used when the text configuration ob-
ject is created from default_char.

nchar_stoplist LONG Terms to ignore when performing a full text search on


NVARCHAR NCHAR columns. These terms are also omitted from text in-
dexes. This column is used when the text configuration ob-
ject is created from default_nchar.

exter- LONG VAR- The function and library name for an external term breaker
nal_term_breaker CHAR library.

Constraints on underlying system table


PRIMARY KEY (object_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id ) MATCH UNIQUE


FULL

FOREIGN KEY (creator) references SYS.ISYSUSER (user_id)

UNIQUE Index (creator, text_config_name)

See also
● “What to specify when creating or altering text configuration objects” [SQL Anywhere Server - SQL
Usage]
● “Full text search” [SQL Anywhere Server - SQL Usage]

SYSTEXTIDX system view


Each row in the SYSTEXTIDX system view describes one text index. The underlying system table for
this view is ISYSTEXTIDX.

Column name Data type Description

index_id UNSIGNED BIGINT The object ID of the text index in SYSIDX.

sequence UNSIGNED INT For internal use only.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1249


Views

Column name Data type Description

status UNSIGNED INT For internal use only.

text_config UNSIGNED BIGINT The object ID of the text configuration object in SYSTEXT-
CONFIG.

next_handle UNSIGNED INT For internal use only.

last_handle UNSIGNED INT For internal use only.

deleted_length UNSIGNED BIGINT The total size of deleted indexed values in the text index.

pending_length UNSIGNED BIGINT The total size of indexed values that will be added to the
text index at the next refresh.

refresh_type TINYINT The type of refresh. One of:

● 1 MANUAL

● 2 AUTO

● 3 IMMEDIATE

refresh_interval UNSIGNED INT The AUTO REFRESH interval, in minutes.

last_refresh TIMESTAMP The time of the last refresh.

Constraints on underlying system table


PRIMARY KEY (index_id, sequence)

FOREIGN KEY (index_id) references SYS.ISYSOBJECT (object_id)

FOREIGN KEY (text_config) references SYS.ISYSTEXTCONFIG (object_id)

See also
● “Full text search” [SQL Anywhere Server - SQL Usage]

SYSTEXTIDXTAB system view


Each row in the SYSTEXTIDXTAB system view describes a generated table that is part of a text index.
The underlying system table for this view is ISYSTEXTIDXTAB.

Column name Data type Description

index_id UNSIGNED BIGINT For internal use only.

1250 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

sequence UNSIGNED INT For internal use only.

table_type UNSIGNED INT For internal use only.

table_id UNSIGNED INT For internal use only.

Constraints on underlying system table


PRIMARY KEY (index_id, sequence, table_type)

FOREIGN KEY (index_id, sequence) references SYS.ISYSTEXTIDX (index_id,


sequence)

FOREIGN KEY (table_id) references SYS.ISYSTAB (table_id)

See also
● “Full text search” [SQL Anywhere Server - SQL Usage]

SYSTRIGGER system view


Each row in the SYSTRIGGER system view describes one trigger in the database. This view also
contains triggers that are automatically created for foreign key definitions which have a referential
triggered action (such as ON DELETE CASCADE). The underlying system table for this view is
ISYSTRIGGER.

Column name Data type Description

trigger_id UNSIGNED A unique number for the trigger in the SYSTRIGGER view.
INT

table_id UNSIGNED The table ID of the table to which this trigger belongs.
INT

object_id UNSIGNED BI- The object ID for the trigger in the database.
GINT

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1251


Views

Column name Data type Description

event CHAR(1) The operation that causes the trigger to fire.

● A INSERT, DELETE

● B INSERT, UPDATE

● C UPDATE COLUMNS

● D DELETE

● E DELETE, UPDATE

● I INSERT

● M INSERT, DELETE, UPDATE

● U UPDATE

trigger_time CHAR(1) The time when the trigger fires relative to the event.

● A AFTER (row-level trigger)

● B BEFORE (row-level trigger)

● I INSTEAD OF (row-level trigger)

● K INSTEAD OF (statement-level trigger)

● R RESOLVE

● S AFTER (statement-level trigger)

trigger_order SMALLINT The order in which are fired when there are multiple triggers of
the same type (insert, update, or delete) set to fire at the same
time (applies to BEFORE or AFTER triggers only, only).

foreign_ta- UNSIGNED The ID of the table containing a foreign key definition that has a
ble_id INT referential triggered action (such as ON DELETE CASCADE).
The foreign_table_id value reflects the value of ISYSIDX.ta-
ble_id.

foreign_key_id UNSIGNED The ID of the foreign key for the table referenced by foreign_ta-
INT ble_id. The foreign_key_id value reflects the value of ISY-
SIDX.index_id.

1252 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

referential_ac- CHAR(1) The action defined by a foreign key. This single-character value
tion 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 CHAR(128) The name of the trigger. One table cannot have two triggers with
the same name.

trigger_defn LONG VAR- The command that was used to create the trigger.
CHAR

remarks LONG VAR- Remarks about the trigger. This value is stored in the ISYSRE-
CHAR MARK system table.

source LONG VAR- The SQL source for the trigger. This value is stored in the ISYS-
CHAR SOURCE system table.

Constraints on underlying system table


PRIMARY KEY (trigger_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (table_id) references SYS.ISYSTAB (table_id)

FOREIGN KEY fkey_index (foreign_table_id, foreign_key_id) references


SYS.ISYSIDX (table_id, index_id)

UNIQUE Index (table_id, event, trigger_time, trigger_order)

UNIQUE Index (trigger_name, table_id)

UNIQUE Index (table_id, foreign_table_id, foreign_key_id, event)

SYSTYPEMAP system view


The SYSTYPEMAP system view contains the compatibility mapping values for entries in the
SYSSQLSERVERTYPE system view. The underlying system table for this view is ISYSTYPEMAP.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1253


Views

Column name Data type Description

ss_user_type SMALLINT Contains the Adaptive Server Enterprise user type.

sa_domain_id SMALLINT Contains the corresponding SQL Anywhere domain_id.

sa_user_type SMALLINT Contains the corresponding SQL Anywhere user type.

nullable CHAR(1) Whether the type allows NULL values.

Constraints on underlying system table


FOREIGN KEY (sa_domain_id) references SYS.ISYSDOMAIN (domain_id)

SYSUNITOFMEASURE system view


Each row of the SYSUNITOFMEASURE system view describes a unit of measure defined in the
database. The underlying table for the SYSUNITOFMEASURE system view is the
ISYSUNITOFMEASURE system table.

Column name Data type Description

object_id UNSIGNED BIGINT For system use only.

owner UNSIGNED INT The owner of the unit of measure.

unit_name CHAR(128) The name of the unit of measure.

unit_type CHAR(7) Angular or linear.

conversion_factor DOUBLE The conversion factor for the unit of measure.

Constraints on underlying system table


PRIMARY KEY (object_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id)

FOREIGN KEY (owner) references SYS.ISYSUSER (user_id)

UNIQUE constraint (unit_name)

SYSUSER system view


Each row in the SYSUSER system view describes a user in the system. The underlying system table for
this view is ISYSUSER.

1254 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

user_id UNSIGNED INT A unique identifier for the user assigned to the login
policy.

object_id UNSIGNED BIGINT A unique identifier for the user in the database.

user_name CHAR(128) The login name for the user.

password BINARY(128) The password for the user.

login_policy_id UNSIGNED BIGINT A unique identifier for the login policy.

expired_pass- TINYINT Indicates if the password for the user expires at the
word_on_login next login.

password_crea- TIMESTAMP The time the password was created for the user.
tion_time

failed_login_attempts UNSIGNED INT The number of times a user can fail to log in before
the account is locked.

last_login_time TIMESTAMP The time the user last logged in.

Note
For databases created using SQL Anywhere 12 or later, the underlying system table for this view is
always encrypted to protect the data from unauthorized access.

Constraints on underlying system table


PRIMARY KEY (user_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

FOREIGN KEY (login_policy_id) references SYS.ISYSLOGINPOLICY


(login_policy_id)

UNIQUE Index (user_name)

See also
● “SYSLOGINPOLICY system view” on page 1216
● “SYSLOGINPOLICYOPTION system view” on page 1217

SYSUSERAUTHORITY system view


Each row of SYSUSERAUTHORITY system view describes an authority granted to one user ID. The
underlying system table for this view is ISYSUSERAUTHORITY.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1255


Views

Column name Data type Description

user_id UNSIGNED INT The ID of the user to whom the authority belongs.

auth VARCHAR(20) The authority granted to the user.

Constraints on underlying system table


PRIMARY KEY (user_id, auth)

FOREIGN KEY (user_id) references SYS.ISYSUSER (user_id)

SYSUSERMESSAGE system view


Each row in the SYSUSERMESSAGE system view holds a user-defined message for an error condition.
The underlying system table for this view is ISYSUSERMESSAGE.

Note
Previous versions of the catalog contained a SYSUSERMESSAGES system table. That table has been
renamed to be ISYSUSERMESSAGE (without an 'S'), and is the underlying table for this view.

Column name Data type Description

error INTEGER A unique identifying number for the error condition.

uid UNSIGNED INT The user number that defined the message.

description VARCHAR(255) The message corresponding to the error condition.

langid SMALLINT Reserved.

Constraints on underlying system table


FOREIGN KEY (uid) references SYS.ISYSUSER (user_id)

UNIQUE Constraint (error, langid)

SYSUSERTYPE system view


Each row in the SYSUSERTYPE system view holds a description of a user-defined data type. The
underlying system table for this view is ISYSUSERTYPE.

Column name Data type Description

type_id SMALLINT A unique identifying number for the user-defined data type.

1256 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

Column name Data type Description

creator UNSIGNED INT The user number of the owner of the data type.

domain_id SMALLINT The data type on which this user defined data type is based, in-
dicated by a data type number listed in the SYSDOMAIN sys-
tem view.

nulls CHAR(1) Whether the user-defined data type allows nulls. Possible val-
ues are Y, N, or U. A value of U indicates that nullability is
unspecified.

width BIGINT The length of a string column, the precision of a numeric col-
umn, or the number of bytes of storage for any other data type.

scale SMALLINT The number of digits after the decimal point for numeric data
type columns, and zero for all other data types.

type_name CHAR(128) The name for the data type.

"default" LONG VARCHAR The default value for the data type.

"check" LONG VARCHAR The CHECK condition for the data type.

base_type_str VARCHAR(32767) The annotated type string representing the physical type of the
user type.

Constraints on underlying system table


PRIMARY KEY (type_id)

FOREIGN KEY (creator) references SYS.ISYSUSER (user_id)

FOREIGN KEY (domain_id) references SYS.ISYSDOMAIN (domain_id)

UNIQUE Constraint (type_name)

SYSVIEW system view


Each row in the SYSVIEW system view describes a view in the database. Additional information about
views can also be found in the SYSTAB system view. The underlying system table for this view is
ISYSVIEW.

You can also use the sa_materialized_view_info system procedure for a more readable format of the
information for materialized views.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1257


Views

Column name Data type Description

view_object_id UNSIGNED The object ID of the view.


BIGINT

view_def LONG The definition (query specification) of the view.


VARCHAR

mv_build_type TINYINT Currently unused.

mv_refresh_type TINYINT The refresh type defined for the view. Possible values are
IMMEDIATE (1) and MANUAL (2).

mv_use_in_optimiza- TINYINT Whether the materialized view can be used during query op-
tion timization (0=cannot be used in optimization, 1=can be used
in optimization)

mv_last_refreshed_at TIME- Indicates the date and time that the materialized view was
STAMP last refreshed.

mv_known_stale_at TIME- The time at which the materialized view became stale. This
STAMP value corresponds to the time at which one of the underlying
base tables was detected as having changed. A value of 0 in-
dicates that the view is either fresh, or that it has become
stale but the database server has not marked it as such be-
cause the view has not been used since it became stale. Use
the sa_materialized_view_info system procedure to deter-
mine the status of a materialized view.

mv_last_refreshed_tsn UNSIGNED The sequence number assigned to the transaction that re-
BIGINT freshed the materialized view.

Remarks
When a materialized view is refreshed with SNAPSHOT isolation, mv_last_refreshed_at and
mv_last_refreshed_tsn refer to the earliest transaction that modified any row used during the computation
of the materialized view contents.

Constraints on underlying system table


PRIMARY KEY (view_object_id)

FOREIGN KEY (view_object_id) references SYS.ISYSOBJECT (object_id) MATCH


UNIQUE FULL

1258 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


System views

See also
● “Enabling or disabling optimizer use of a materialized view” [SQL Anywhere Server - SQL Usage]
● “Whether to set refresh type to manual or immediate” [SQL Anywhere Server - SQL Usage]
● “sa_materialized_view_info system procedure” on page 1077
● “SYSTAB system view” on page 1241
● “CREATE MATERIALIZED VIEW statement” on page 560
● “REFRESH MATERIALIZED VIEW statement” on page 843
● “CREATE VIEW statement” on page 661

SYSWEBSERVICE system view


Each row in the SYSWEBSERVICE system view holds a description of a web service. The underlying
system table for this view is ISYSWEBSERVICE.

Column name Data type Description

service_id UNSIGNED INT A unique identifying number for the web service.

object_id UNSIGNED BI- The ID of the webservice.


GINT

service_name CHAR(128) The name assigned to the web service.

service_type VARCHAR(40) The type of the service; for example, RAW, HTTP, XML,
SOAP, or DISH.

auth_required CHAR(1) Whether all requests must contain a valid user name and pass-
word.

secure_re- CHAR(1) Whether insecure connections, such as HTTP, are to be accep-


quired ted, or only secure connections, such as HTTPS.

url_path CHAR(1) Controls the interpretation of URLs.

user_id UNSIGNED INT If authentication is enabled, identifies the user, or group of


users, that have permission to use the service. If authentication is
disabled, specifies the account to use when processing requests.

parameter LONG VAR- A prefix that identifies the SOAP services to be included in a
CHAR DISH service.

statement LONG VAR- A SQL statement that is always executed in response to a re-
CHAR quest. If NULL, arbitrary statements contained in each request
are executed instead. Ignored for services of type DISH.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1259


Views

Column name Data type Description

remarks LONG VAR- Remarks about the webservice. This value is stored in the ISYS-
CHAR REMARK system table.

enabled CHAR(1) Indicates whether the web service is currently enabled or disa-
bled (see CREATE SERVICE).

Constraints on underlying system table


PRIMARY KEY (service_id)

FOREIGN KEY (object_id) references SYS.ISYSOBJECT (object_id) MATCH UNIQUE


FULL

UNIQUE Constraint (service_name)

Consolidated views
Consolidated views provide data in a form more frequently required by users. For example, consolidated
views often provide commonly-needed joins. Consolidated views differ from system views in that they
are not just a straight forward view of raw data in a underlying system table(s). For example, many of the
columns in the system views are unintelligible ID values, whereas in the consolidated views, they are
readable names.

ST_GEOMETRY_COLUMNS consolidated view


Each row of the ST_GEOMETRY_COLUMNS system view describes a spatial column defined in the
database.

Column name Data type Description

table_catalog VARCHAR(128) For internal use.

table_schema CHAR(128) The name of the schema to which the table containing
the spatial column belongs. This is equivalent to the table
owner.

table_name CHAR(128) The name of the table containing the spatial column.

column_name CHAR(128) The name of the spatial column.

srs_name CHAR(128) The name of the SRS that is associated with the spatial
column. If an SRS is not associated with the column,
then srs_name is NULL.

1260 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

Column name Data type Description

srs_id INTEGER The SRID for the SRS associated with the spatial col-
umn.

table_id UNSIGNED INT The numeric identifier for the table containing the col-
umn.

column_id UNSIGNED INT The numeric identifier for the column.

geome- VARCHAR(32767) The spatial data type of the geometries contained in the
try_type_name column (for example, ST_Point, ST_Geometry, and so
on.

See also
● “Spatial reference systems (SRS) and Spatial reference identifiers (SRID)” [SQL Anywhere Server -
Spatial Data Support]
● “Supported spatial data types and their hierarchy” [SQL Anywhere Server - Spatial Data Support]

ST_SPATIAL_REFERENCE_SYSTEMS consolidated view


Each row of the ST_SPATIAL_REFERENCE_SYSTEMS system view describes an SRS defined in the
database. This view offers a slightly different amount of information than the
SYSSPATIALREFERENCESYSTEM system view.

Column name Data type Description

object_id UNSIGNED For system use only.


BIGINT

owner UNSIGNED The owner of the SRS.


INT

srs_name CHAR(128) The name of the SRS.

srs_id INT The numeric identifier (SRID) for the spatial reference
system.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1261


Views

Column name Data type Description

srs_type CHAR(11) The type of SRS as defined by the SQL/MM standard.


Values can be one of:

● GEOGRAPHIC This is for SRSs based on georefer-


enced coordinate systems with axes of latitude, longi-
tude (and elevation). These SRSs are of type PLA-
NAR or ROUND EARTH.

● PROJECTED This is for SRSs based on georefer-


enced coordinate systems that do not have axes of lati-
tude and longitude. These SRSs are of type PLANAR.

● ENGINEERING This is for SRSs based on non-


georeferenced coordinate systems. These SRSs are of
type PLANAR.

● GEOCENTRIC Unsupported.

● COMPOUND Unsupported.

● VERTICAL Unsupported.

If srs_type is empty, the type is unspecified.

round_earth CHAR(1) Whether the SRS type is ROUND EARTH (Y) or PLA-
NAR (N).

axis_order CHAR(12) Describes how the database server interprets points with
regards to latitude and longitude (for example when using
the ST_Lat and ST_Long methods). For non-geographic
spatial reference systems, the axis order is x/y/z/m. For
geographic spatial reference systems, the default axis or-
der is long/lat/z/m; lat/long/z/m is also supported.

snap_to_grid DOUBLE Defines the size of the grid SQL Anywhere uses when
performing calculations.

tolerance DOUBLE Defines the precision to use when comparing points.

semi_major_axis DOUBLE Distance from center of the ellipsoid to the equator for a
ROUND EARTH SRS.

semi_minor_axis DOUBLE Distance from center of the ellipsoid to the poles for a
ROUND EARTH SRS.

1262 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

Column name Data type Description

inv_flattening DOUBLE The inverse flattening used for the ellipsoid in a ROUND
EARTH SRS. This is a ratio created by the following
equation:
1/f = (semi-major-axis) / (semi-major-axis
- semi-minor-axis)

min_x DOUBLE The minimum x value allowed in coordinates.

max_x DOUBLE The maximum x value allowed in coordinates.

min_y DOUBLE The minimum y value allowed in coordinates.

max_y DOUBLE The maximum y value allowed in coordinates.

min_z DOUBLE The minimum z value allowed in coordinates.

max_z DOUBLE The maximum z value allowed in coordinates.

min_m DOUBLE The minimum m value allowed in coordinates.

max_m DOUBLE The maximum m value allowed in coordinates.

min_lat DOUBLE The minimum latitude value allowed for coordinates.

max_lat DOUBLE The maximum latitude value allowed for coordinates.

min_long DOUBLE The minimum longitude value allowed in coordinates.

max_long DOUBLE The maximum longitude value allowed in coordinates.

organization LONG VAR- The name of the organization that created the coordinate
CHAR system used by the spatial reference system.

organization_coord- INT The ID given to the coordinate system by the organization


sys_id that created it.

linear_unit_of_meas- CHAR(128) The linear unit of measurement used by the SRS.


ure

angu- CHAR(128) The angular unit of measurement used by the SRS.


lar_unit_of_measure

polygon_format LONG VAR- The orientation of the rings in a polygon. One of Counter-
CHAR Clockwise, ClockWise, or EvenOdd.

storage_format LONG VAR- Whether the data is stored in normalized format (Internal),
CHAR unnormalized format (Original), or both (Mixed).

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1263


Views

Column name Data type Description

definition LONG VAR- Additional definition settings.


CHAR

transform_definition LONG VAR- Transform definition settings for use when transforming
CHAR data from this SRS to another.

description LONG VAR- Description of the SRS.


CHAR

See also
● “SYSSPATIALREFERENCESYSTEM system view” on page 1234
● “CREATE SPATIAL REFERENCE SYSTEM statement” on page 616

ST_UNITS_OF_MEASURE consolidated view


Each row of the ST_UNITS_OF_MEASURE system view describes a unit of measure defined in the
database. This view offers more information than the SYSUNITOFMEASURE system view.

Column name Data type Description

object_id UNSIGNED BIGINT For system use only.

owner UNSIGNED INT The owner of the unit of measure.

unit_name CHAR(128) The name of the unit of measure.

unit_type CHAR(7) Angular or linear.

conversion_factor DOUBLE The conversion factor for the unit of measure.

description LONG VARCHAR Description for the unit of measure.

SYSARTICLECOLS consolidated view


Each row in the SYSARTICLECOLS view identifies a column in an article.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSARTICLECOLS"
as select p.publication_name,t.table_name,c.column_name
from SYS.ISYSARTICLECOL as ac
join SYS.ISYSPUBLICATION as p on p.publication_id = ac.publication_id
join SYS.ISYSTAB as t on t.table_id = ac.table_id

1264 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

join SYS.ISYSTABCOL as c on c.table_id = ac.table_id


and c.column_id = ac.column_id

See also
● “SYSARTICLECOL system view” on page 1196
● “SYSPUBLICATION system view” on page 1226
● “SYSTAB system view” on page 1241
● “SYSTABCOL system view” on page 1244

SYSARTICLES consolidated view


Each row in the SYSARTICLES view describes an article in a publication.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSARTICLES"
as select u1.user_name as publication_owner,p.publication_name,
u2.user_name as table_owner,t.table_name,
a.where_expr,a.subscribe_by_expr,a.alias
from SYS.ISYSARTICLE as a
join SYS.ISYSPUBLICATION as p on(a.publication_id = p.publication_id)
join SYS.ISYSTAB as t on(a.table_id = t.table_id)
join SYS.ISYSUSER as u1 on(p.creator = u1.user_id)
join SYS.ISYSUSER as u2 on(t.creator = u2.user_id)

See also
● “SYSARTICLE system view” on page 1196
● “SYSPUBLICATION system view” on page 1226
● “SYSTAB system view” on page 1241
● “SYSUSER system view” on page 1254

SYSCAPABILITIES consolidated view


Each row in the SYSCAPABILITIES view specifies the status of a capability for a remote database
server. This view gets its data from the ISYSCAPABILITY and ISYSCAPABILITYNAME system
tables.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSCAPABILITIES"
as select
ISYSCAPABILITY.capid,ISYSCAPABILITY.srvid,property('RemoteCapability',ISYSCAP
ABILITY.capid) as capname,ISYSCAPABILITY.capvalue
from SYS.ISYSCAPABILITY

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1265


Views

See also
● “SYSCAPABILITY system view” on page 1197
● “SYSCAPABILITYNAME system view” on page 1197

SYSCATALOG consolidated view


Each row in the SYSCATALOG view describes a system table.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSCATALOG"( creator,
tname,dbspacename,tabletype,ncols,primary_key,"check",
remarks )
as select u.user_name,tab.table_name,dbs.dbspace_name,
if tab.table_type_str = 'BASE' then 'TABLE' else tab.table_type_str
endif,
(select count() from SYS.ISYSTABCOL
where ISYSTABCOL.table_id = tab.table_id),
if ix.index_id is null then 'N' else 'Y' endif,
null,
rmk.remarks
from SYS.SYSTAB as tab
join SYS.ISYSDBSPACE as dbs on(tab.dbspace_id = dbs.dbspace_id)
join SYS.ISYSUSER as u on u.user_id = tab.creator
left outer join SYS.ISYSIDX as ix on(tab.table_id = ix.table_id and
ix.index_id = 0)
left outer join SYS.ISYSREMARK as rmk on(tab.object_id = rmk.object_id)

See also
● “SYSTAB system view” on page 1241
● “SYSTABCOL system view” on page 1244
● “ISYSDBSPACE system table” on page 968
● “SYSUSER system view” on page 1254
● “SYSIDX system view” on page 1211
● “SYSREMARK system view” on page 1227

SYSCOLAUTH consolidated view


Each row in the SYSCOLAUTH view describes the set of privileges (UPDATE, SELECT, or
REFERENCES) granted on a column. The SYSCOLAUTH view provides a user-friendly presentation of
data in the “SYSCOLPERM system view” on page 1198.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSCOLAUTH"( grantor,grantee,creator,tname,colname,
privilege_type,is_grantable )
as select u1.user_name,u2.user_name,u3.user_name,tab.table_name,
col.column_name,cp.privilege_type,cp.is_grantable

1266 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

from SYS.ISYSCOLPERM as cp
join SYS.ISYSUSER as u1 on u1.user_id = cp.grantor
join SYS.ISYSUSER as u2 on u2.user_id = cp.grantee
join SYS.ISYSTAB as tab on tab.table_id = cp.table_id
join SYS.ISYSUSER as u3 on u3.user_id = tab.creator
join SYS.ISYSTABCOL as col on col.table_id = cp.table_id
and col.column_id = cp.column_id

See also
● “SYSCOLPERM system view” on page 1198
● “SYSTABCOL system view” on page 1244
● “SYSUSER system view” on page 1254
● “SYSTAB system view” on page 1241

SYSCOLSTATS consolidated view


The SYSCOLSTATS view contains the column statistics that are stored as histograms and used by the
optimizer.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSCOLSTATS"
as select u.user_name,t.table_name,c.column_name,
s.format_id,s.update_time,s.density,s.max_steps,
s.actual_steps,s.step_values,s.frequencies
from SYS.ISYSCOLSTAT as s
join SYS.ISYSTABCOL as c on(s.table_id = c.table_id
and s.column_id = c.column_id)
join SYS.ISYSTAB as t on(t.table_id = c.table_id)
join SYS.ISYSUSER as u on(u.user_id = t.creator)

See also
● “SYSCOLSTAT system view” on page 1199
● “SYSTABCOL system view” on page 1244
● “SYSTAB system view” on page 1241
● “SYSUSER system view” on page 1254

SYSCOLUMNS consolidated view


Each row in the SYSCOLUMNS view describes one column of each table and view in the catalog.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSCOLUMNS"( creator,cname,tname,coltype,nulls,length,
syslength,in_primary_key,colno,default_value,
column_kind,remarks )
as select u.user_name,col.column_name,tab.table_name,dom.domain_name,
col.nulls,col.width,col.scale,if ixcol.sequence is null then 'N' else

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1267


Views

'Y' endif,col.column_id,
col."default",col.column_type,rmk.remarks
from SYS.SYSTABCOL as col
left outer join SYS.ISYSIDXCOL as ixcol on(col.table_id =
ixcol.table_id and col.column_id = ixcol.column_id and ixcol.index_id = 0)
join SYS.ISYSTAB as tab on(tab.table_id = col.table_id)
join SYS.ISYSDOMAIN as dom on(dom.domain_id = col.domain_id)
join SYS.ISYSUSER as u on u.user_id = tab.creator
left outer join SYS.ISYSREMARK as rmk on(col.object_id = rmk.object_id)

See also
● “SYSTABCOL system view” on page 1244
● “SYSIDXCOL system view” on page 1213
● “SYSTAB system view” on page 1241
● “SYSDOMAIN system view” on page 1203
● “SYSUSER system view” on page 1254
● “SYSREMARK system view” on page 1227

SYSFOREIGNKEYS consolidated view


Each row in the SYSFOREIGNKEYS view describes one foreign key for each table in the catalog.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSFOREIGNKEYS"( foreign_creator,
foreign_tname,
primary_creator,primary_tname,role,columns )
as select fk_up.user_name,fk_tab.table_name,pk_up.user_name,
pk_tab.table_name,ix.index_name,
(select list(string(fk_col.column_name,' IS ',
pk_col.column_name)
order by fkc.table_id,fkc.index_id,fkc."sequence")
from SYS.ISYSIDXCOL as fkc
join SYS.ISYSTABCOL as fk_col on(
fkc.table_id = fk_col.table_id
and fkc.column_id = fk_col.column_id)
,SYS.ISYSTABCOL as pk_col
where fkc.table_id = fk.foreign_table_id
and fkc.index_id = fk.foreign_index_id
and pk_col.table_id = fk.primary_table_id
and pk_col.column_id = fkc.primary_column_id)
from SYS.ISYSFKEY as fk
join SYS.ISYSTAB as fk_tab on fk_tab.table_id = fk.foreign_table_id
join SYS.ISYSUSER as fk_up on fk_up.user_id = fk_tab.creator
join SYS.ISYSTAB as pk_tab on pk_tab.table_id = fk.primary_table_id
join SYS.ISYSUSER as pk_up on pk_up.user_id = pk_tab.creator
join SYS.ISYSIDX as ix on ix.table_id = fk.foreign_table_id and
ix.index_id = fk.foreign_index_id

1268 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

See also
● “SYSTAB system view” on page 1241
● “SYSTABCOL system view” on page 1244
● “ISYSIDX system table” on page 969
● “SYSIDXCOL system view” on page 1213
● “SYSFKEY system view” on page 1208
● “SYSUSER system view” on page 1254
● “SYSDOMAIN system view” on page 1203
● “SYSREMARK system view” on page 1227

SYSGROUPS consolidated view


There is one row in the SYSGROUPS view for each member of each group. This view describes the
many-to-many relationship between groups and members. A group may have many members, and a user
may be a member of many groups.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSGROUPS"( group_name,
member_name )
as select g.user_name,u.user_name
from SYS.ISYSGROUP,SYS.ISYSUSER as g,SYS.ISYSUSER as u
where ISYSGROUP.group_id = g.user_id and ISYSGROUP.group_member =
u.user_id

See also
● “SYSUSER system view” on page 1254
● “SYSGROUP system view” on page 1209

SYSINDEXES consolidated view


Each row in the SYSINDEXES view describes one index in the database. As an alternative to this view,
you could also use the SYSIDX and SYSIDXCOL system views.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSINDEXES"( icreator,
iname,fname,creator,tname,indextype,
colnames,interval,level_num )
as select u.user_name,idx.index_name,dbs.dbspace_name,u.user_name,
tab.table_name,
case idx.index_category
when 1 then 'Primary Key'
when 2 then 'Foreign Key'
when 3 then(
if idx."unique" = 4 then 'Non-unique'
else if idx."unique" = 2 then 'UNIQUE constraint'

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1269


Views

else if idx."unique" = 5 then 'UNIQUE NULLS NOT DISTINCT'


else 'UNIQUE'
endif
endif
endif) when 4 then 'Text Index' end,(select list(string(c.column_name,
if ixc."order" = 'A' then ' ASC' else ' DESC' endif) order by
ixc.table_id asc,ixc.index_id asc,ixc.sequence asc)
from SYS.ISYSIDXCOL as ixc
join SYS.ISYSTABCOL as c on(
c.table_id = ixc.table_id
and c.column_id = ixc.column_id)
where ixc.index_id = idx.index_id
and ixc.table_id = idx.table_id),
0,0
from SYS.ISYSTAB as tab
join SYS.ISYSDBSPACE as dbs on(tab.dbspace_id = dbs.dbspace_id)
join SYS.ISYSIDX as idx on(idx.table_id = tab.table_id)
join SYS.ISYSUSER as u on u.user_id = tab.creator

See also
● “SYSIDX system view” on page 1211
● “SYSTABCOL system view” on page 1244
● “SYSTAB system view” on page 1241
● “SYSDBSPACE system view” on page 1202
● “SYSIDXCOL system view” on page 1213
● “SYSUSER system view” on page 1254

SYSOPTIONS consolidated view


Each row in the SYSOPTIONS view describes one option created using the SET command. Each user can
have their own setting for each option. In addition, settings for the PUBLIC user define the default
settings to be used for users that do not have their own setting.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSOPTIONS"( user_name,"option",setting )


as select u.user_name,opt."option",opt.setting
from SYS.ISYSOPTION as opt
join SYS.ISYSUSER as u on opt.user_id = u.user_id

See also
● “SYSOPTION system view” on page 1221
● “SYSUSER system view” on page 1254

SYSPROCAUTH consolidated view


Each row in the SYSPROCAUTH view describes a set of privileges granted on a procedure. As an
alternative, you can also use the SYSPROCPERM system view.

1270 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSPROCAUTH"( grantee,
creator,procname )
as select u1.user_name,u2.user_name,p.proc_name
from SYS.ISYSPROCEDURE as p
join SYS.ISYSPROCPERM as pp on(p.proc_id = pp.proc_id)
join SYS.ISYSUSER as u1 on u1.user_id = pp.grantee
join SYS.ISYSUSER as u2 on u2.user_id = p.creator

See also
● “SYSPROCEDURE system view” on page 1223
● “SYSPROCPERM system view” on page 1225
● “SYSUSER system view” on page 1254

SYSPROCPARMS consolidated view


Each row in the SYSPROCPARMS view describes a parameter to a procedure in the database.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSPROCPARMS"( creator,
procname,parmname,parm_id,parmtype,parmmode,parmdomain,
length,scale,"default",user_type )
as select up.user_name,p.proc_name,pp.parm_name,pp.parm_id,pp.parm_type,
if pp.parm_mode_in = 'Y' and pp.parm_mode_out = 'N' then 'IN'
else if pp.parm_mode_in = 'N' and pp.parm_mode_out = 'Y' then 'OUT'
else 'INOUT'
endif
endif,dom.domain_name,pp.width,pp.scale,pp."default",ut.type_name
from SYS.SYSPROCPARM as pp
join SYS.ISYSPROCEDURE as p on p.proc_id = pp.proc_id
join SYS.ISYSUSER as up on up.user_id = p.creator
join SYS.ISYSDOMAIN as dom on dom.domain_id = pp.domain_id
left outer join SYS.ISYSUSERTYPE as ut on ut.type_id = pp.user_type

See also
● “SYSPROCPARM system view” on page 1224
● “SYSPROCEDURE system view” on page 1223
● “SYSUSER system view” on page 1254
● “SYSDOMAIN system view” on page 1203
● “SYSUSERTYPE system view” on page 1256

SYSPROCS consolidated view


The SYSPROCS view shows the procedure or function name, the name of its creator and any comments
recorded for the procedure or function.

The tables and columns that make up this view are provided in the ALTER VIEW statement below.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1271


Views

ALTER VIEW "SYS"."SYSPROCS"( creator,


procname,remarks )
as select u.user_name,p.proc_name,r.remarks
from SYS.ISYSPROCEDURE as p
join SYS.ISYSUSER as u on u.user_id = p.creator
left outer join SYS.ISYSREMARK as r on(p.object_id = r.object_id)

See also
● “SYSPROCEDURE system view” on page 1223
● “SYSUSER system view” on page 1254
● “SYSREMARK system view” on page 1227

SYSPUBLICATIONS consolidated view


Each row in the SYSPUBLICATIONS view describes a SQL Remote or MobiLink publication.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSPUBLICATIONS"
as select u.user_name as creator,
p.publication_name,
r.remarks,
p.type,
case p.sync_type
when 0 then 'logscan'
when 1 then 'scripted upload'
when 2 then 'download only'
else 'invalid'
end as sync_type
from SYS.ISYSPUBLICATION as p
join SYS.ISYSUSER as u on u.user_id = p.creator
left outer join SYS.ISYSREMARK as r on(p.object_id = r.object_id)

See also
● “SYSPUBLICATION system view” on page 1226
● “SYSREMARK system view” on page 1227

SYSREMOTEOPTION2 consolidated view


Presents, in a more readable format, the columns from SYSREMOTEOPTION and
SYSREMOTEOPTIONTYPE that do not contain sensitive data.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSREMOTEOPTION2"
as select ISYSREMOTEOPTION.option_id,
ISYSREMOTEOPTION.user_id,
SYS.HIDE_FROM_NON_DBA(ISYSREMOTEOPTION.setting) as setting
from SYS.ISYSREMOTEOPTION

1272 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

See also
● “SYSREMOTEOPTION system view” on page 1228

SYSREMOTEOPTIONS consolidated view


Each row of the SYSREMOTEOPTIONS view describes the values of a SQL Remote message link
parameter. Some columns in this view contain potentially sensitive data. For that reason, access to this
view is restricted to users with DBA authority. The SYSREMOTEOPTION2 view provides public access
to the insensitive data.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSREMOTEOPTIONS"
as select srt.type_name,
sup.user_name,
srot."option",
SYS.HIDE_FROM_NON_DBA(sro.setting) as setting
from SYS.ISYSREMOTETYPE as srt
,SYS.ISYSREMOTEOPTIONTYPE as srot
,SYS.ISYSREMOTEOPTION as sro
,SYS.ISYSUSER as sup
where srt.type_id = srot.type_id
and srot.option_id = sro.option_id
and sro.user_id = sup.user_id

See also
● “SYSREMOTETYPE system view” on page 1229
● “SYSREMOTEOPTIONTYPE system view” on page 1228
● “SYSREMOTEOPTION system view” on page 1228
● “SYSUSER system view” on page 1254

SYSREMOTETYPES consolidated view


Each row of the SYSREMOTETYPES view describes one of the SQL Remote message types, including
the publisher address.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSREMOTETYPES"
as select rt.type_id,rt.type_name,rt.publisher_address,rm.remarks
from SYS.ISYSREMOTETYPE as rt
left outer join SYS.ISYSREMARK as rm on(rt.object_id = rm.object_id)

See also
● “SYSREMOTETYPE system view” on page 1229
● “SYSREMARK system view” on page 1227

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1273


Views

SYSREMOTEUSERS consolidated view


Each row of the SYSREMOTEUSERS view describes a user ID with REMOTE permissions (a
subscriber), together with the status of SQL Remote messages that were sent to and from that user.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSREMOTEUSERS"
as select u.user_name,r.consolidate,t.type_name,r.address,r.frequency,
r.send_time,
(if r.frequency = 'A' then null else if r.frequency = 'P' then
if r.time_sent is null then current timestamp
else(select min(minutes(a.time_sent,60*hour(a.send_time)
+minute(seconds(a.send_time,59))))
from SYS.ISYSREMOTEUSER as a where a.frequency = 'P'
and a.send_time = r.send_time)
endif
else if current date+r.send_time
> coalesce(r.time_sent,current timestamp) then
current date+r.send_time else current date+r.send_time+1 endif
endif endif) as next_send,
r.log_send,r.time_sent,r.log_sent,r.confirm_sent,r.send_count,
r.resend_count,r.time_received,r.log_received,
r.confirm_received,r.receive_count,r.rereceive_count
from SYS.ISYSREMOTEUSER as r
join SYS.ISYSUSER as u on(u.user_id = r.user_id)
join SYS.ISYSREMOTETYPE as t on(t.type_id = r.type_id)

See also
● “SYSREMOTEUSER system view” on page 1229
● “SYSUSER system view” on page 1254
● “SYSREMOTETYPE system view” on page 1229

SYSSUBSCRIPTIONS consolidated view


Each row describes a subscription from one user ID (which must have REMOTE permissions) to one
publication.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSSUBSCRIPTIONS"
as select p.publication_name,u.user_name,s.subscribe_by,s.created,
s.started
from SYS.ISYSSUBSCRIPTION as s
join SYS.ISYSPUBLICATION as p on(p.publication_id = s.publication_id)
join SYS.ISYSUSER as u on u.user_id = s.user_id

See also
● “SYSSUBSCRIPTION system view” on page 1238
● “SYSPUBLICATION system view” on page 1226
● “SYSUSER system view” on page 1254

1274 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

SYSSYNC2 consolidated view


The SYSSYNC2 view provides public access to the data found in the SYSSYNC system view—
information relating to MobiLink synchronization—without exposing potentially sensitive data.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSSYNC2"


as select ISYSSYNC.sync_id,
ISYSSYNC.type,
ISYSSYNC.publication_id,
ISYSSYNC.progress,
ISYSSYNC.site_name,
SYS.HIDE_FROM_NON_DBA(ISYSSYNC."option") as "option",
SYS.HIDE_FROM_NON_DBA(ISYSSYNC.server_connect) as server_connect,
ISYSSYNC.server_conn_type,
ISYSSYNC.last_download_time,
ISYSSYNC.last_upload_time,
ISYSSYNC.created,
ISYSSYNC.log_sent,
ISYSSYNC.generation_number,
ISYSSYNC.extended_state,
ISYSSYNC.script_version,
ISYSSYNC.subscription_name
from SYS.ISYSSYNC

See also
● “SYSSYNC system view” on page 1238

SYSSYNCPUBLICATIONDEFAULTS consolidated view


The SYSSYNCPUBLICATIONDEFAULTS view provides the default synchronization settings
associated with publications involved in MobiLink synchronization.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSSYNCPUBLICATIONDEFAULTS"


as select s.sync_id,
p.publication_name,
SYS.HIDE_FROM_NON_DBA(s."option") as "option",
SYS.HIDE_FROM_NON_DBA(s.server_connect) as server_connect,
s.server_conn_type
from SYS.ISYSSYNC as s join SYS.ISYSPUBLICATION as p on(p.publication_id
= s.publication_id) where
s.site_name is null

See also
● “SYSSYNC system view” on page 1238
● “SYSPUBLICATION system view” on page 1226

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1275


Views

SYSSYNCS consolidated view


The SYSSYNCS view contains information relating to MobiLink synchronization. Some columns in this
view contain potentially sensitive data. For that reason, access to this view is restricted to users with DBA
authority.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSSYNCS"


as select p.publication_name,s.progress,s.site_name,
SYS.HIDE_FROM_NON_DBA(s."option") as "option",
SYS.HIDE_FROM_NON_DBA(s.server_connect) as server_connect,
s.server_conn_type,s.last_download_time,
s.last_upload_time,s.created,s.log_sent,s.generation_number,
s.extended_state
from SYS.ISYSSYNC as s
left outer join SYS.ISYSPUBLICATION as p
on p.publication_id = s.publication_id

See also
● “SYSSYNC system view” on page 1238
● “SYSPUBLICATION system view” on page 1226

SYSSYNCSCRIPTS consolidated view


Each row in the SYSSYNCSCRIPTS view identifies a stored procedure for MobiLink scripted upload.
This view is almost identical to the SYSSYNCSCRIPT system view, except that the values are in human-
readable format, as opposed to raw data.

ALTER VIEW "SYS"."SYSSYNCSCRIPTS"


as select p.publication_name,
t.table_name,
case s.type
when 0 then 'upload insert'
when 1 then 'upload delete'
when 2 then 'upload update'
else 'unknown'
end as type,
c.proc_name
from SYS.ISYSSYNCSCRIPT as s
join SYS.ISYSPUBLICATION as p on p.object_id = s.pub_object_id
join SYS.ISYSTAB as t on t.object_id = s.table_object_id
join SYS.ISYSPROCEDURE as c on c.object_id = s.proc_object_id

See also
● “SYSSYNCSCRIPT system view” on page 1240
● “SYSPUBLICATION system view” on page 1226
● “SYSTAB system view” on page 1241
● “SYSPROCEDURE system view” on page 1223
● “Scripted upload” [MobiLink - Client Administration]

1276 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

SYSSYNCSUBSCRIPTIONS consolidated view


The SYSSYNCSUBSCRIPTIONS view contains the synchronization settings associated with MobiLink
synchronization subscriptions.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSSYNCSUBSCRIPTIONS"


as select s.sync_id,
p.publication_name,
s.progress,
s.site_name,
SYS.HIDE_FROM_NON_DBA(s."option") as "option",
SYS.HIDE_FROM_NON_DBA(s.server_connect) as server_connect,
s.server_conn_type,
s.last_download_time,
s.last_upload_time,
s.created,
s.log_sent,
s.generation_number,
s.extended_state
from SYS.ISYSSYNC as s join SYS.ISYSPUBLICATION as p on(p.publication_id
= s.publication_id)
where s.publication_id is not null and
s.site_name is not null and exists
(select 1 from SYS.SYSSYNCUSERS as u
where s.site_name = u.site_name)

See also
● “SYSSYNC system view” on page 1238
● “SYSPUBLICATION system view” on page 1226
● “SYSSYNCUSERS consolidated view” on page 1277

SYSSYNCUSERS consolidated view


A view of synchronization settings associated with MobiLink synchronization users.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSSYNCUSERS"


as select ISYSSYNC.sync_id,
ISYSSYNC.site_name,
SYS.HIDE_FROM_NON_DBA(ISYSSYNC."option") as "option",
SYS.HIDE_FROM_NON_DBA(ISYSSYNC.server_connect) as server_connect,
ISYSSYNC.server_conn_type
from SYS.ISYSSYNC where
ISYSSYNC.publication_id is null

See also
● “SYSSYNC system view” on page 1238

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1277


Views

SYSTABAUTH consolidated view


The SYSTABAUTH view contains information from the SYSTABLEPERM system view, but in a more
readable format.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSTABAUTH"( grantor,
grantee,screator,stname,tcreator,ttname,
selectauth,insertauth,deleteauth,
updateauth,updatecols,alterauth,referenceauth )
as select u1.user_name,u2.user_name,u3.user_name,tab1.table_name,
u4.user_name,tab2.table_name,tp.selectauth,tp.insertauth,
tp.deleteauth,tp.updateauth,tp.updatecols,tp.alterauth,
tp.referenceauth
from SYS.ISYSTABLEPERM as tp
join SYS.ISYSUSER as u1 on u1.user_id = tp.grantor
join SYS.ISYSUSER as u2 on u2.user_id = tp.grantee
join SYS.ISYSTAB as tab1 on tab1.table_id = tp.stable_id
join SYS.ISYSUSER as u3 on u3.user_id = tab1.creator
join SYS.ISYSTAB as tab2 on tab2.table_id = tp.stable_id
join SYS.ISYSUSER as u4 on u4.user_id = tab2.creator

See also
● “SYSTABLEPERM system view” on page 1246
● “SYSUSER system view” on page 1254
● “SYSTAB system view” on page 1241

SYSTRIGGERS consolidated view


Each row in the SYSTRIGGERS view describes one trigger in the database. This view also contains
triggers that are automatically created for foreign key definitions which have a referential triggered action
(such as ON DELETE CASCADE).

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSTRIGGERS"( owner,
trigname,tname,event,trigtime,trigdefn )
as select u.user_name,trig.trigger_name,tab.table_name,
if trig.event = 'I' then 'INSERT'
else if trig.event = 'U' then 'UPDATE'
else if trig.event = 'C' then 'UPDATE'
else if trig.event = 'D' then 'DELETE'
else if trig.event = 'A' then 'INSERT,DELETE'
else if trig.event = 'B' then 'INSERT,UPDATE'
else if trig.event = 'E' then 'DELETE,UPDATE'
else 'INSERT,DELETE,UPDATE'
endif
endif
endif
endif
endif

1278 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Consolidated views

endif
endif,if trig.trigger_time = 'B' or trig.trigger_time = 'P' then 'BEFORE'
else if trig.trigger_time = 'A' or trig.trigger_time = 'S' then 'AFTER'
else if trig.trigger_time = 'R' then 'RESOLVE'
else 'INSTEAD OF'
endif
endif
endif,trig.trigger_defn
from SYS.ISYSTRIGGER as trig
join SYS.ISYSTAB as tab on(tab.table_id = trig.table_id)
join SYS.ISYSUSER as u on u.user_id = tab.creator where
trig.foreign_table_id is null

See also
● “SYSTRIGGER system view” on page 1251
● “SYSTAB system view” on page 1241
● “SYSUSER system view” on page 1254

SYSUSEROPTIONS consolidated view


The SYSUSEROPTIONS view contains the 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.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSUSEROPTIONS"( user_name,
"option",setting )
as select u.user_name,
o."option",
isnull((select s.setting
from SYS.ISYSOPTION as s
where s.user_id = u.user_id
and s."option" = o."option"),
o.setting)
from SYS.SYSOPTIONS as o,SYS.ISYSUSER as u
where o.user_name = 'PUBLIC'

See also
● “SYSOPTIONS consolidated view” on page 1270
● “SYSUSER system view” on page 1254

SYSVIEWS consolidated view


Each row of the SYSVIEWS view describes one view, including its view definition.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSVIEWS"( vcreator,
viewname,viewtext )

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1279


Views

as select u.user_name,t.table_name,v.view_def
from SYS.ISYSTAB as t
join SYS.ISYSVIEW as v on(t.object_id = v.view_object_id)
join SYS.ISYSUSER as u on(u.user_id = t.creator)

See also
● “SYSTAB system view” on page 1241
● “SYSVIEW system view” on page 1257
● “SYSUSER system view” on page 1254

Compatibility views
Compatibility views are views that are provided for compatibility with versions of SQL Anywhere 10 and
earlier. Where possible you should use system and consolidated views instead, as support may diminish
for some compatibility views in future releases.

SYSCOLLATION compatibility view (deprecated)


The SYSCOLLATION compatibility view contains the collation sequence information for the database. It
is obtainable via built-in functions and is not kept in the catalog. Following is definition for this view:
ALTER VIEW "SYS"."SYSCOLLATION"
as select 1 as collation_id,
DB_PROPERTY('Collation') as collation_label,
DB_EXTENDED_PROPERTY('Collation','Description') as collation_name,
cast(DB_EXTENDED_PROPERTY('Collation','LegacyData') as binary(1280)) as
collation_order

See also
● “Accessing database property values” [SQL Anywhere Server - Database Administration]
● “DB_PROPERTY function [System]” on page 202
● “DB_EXTENDED_PROPERTY function [System]” on page 197

SYSCOLLATIONMAPPINGS compatibility view


(deprecated)
The SYSCOLLATIONMAPPINGS compatibility view contains only one row with the database collation
mapping. It is obtainable via built-in functions and is not kept in the catalog. Following is definition for
this view:
ALTER VIEW "SYS"."SYSCOLLATIONMAPPINGS"
as select DB_PROPERTY('Collation') as collation_label,
DB_EXTENDED_PROPERTY('Collation','Description') as collation_name,
DB_PROPERTY('Charset') as cs_label,
DB_EXTENDED_PROPERTY('Collation','ASESensitiveSortOrder') as
so_case_label,

1280 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Compatibility views

DB_EXTENDED_PROPERTY('Collation','ASEInsensitiveSortOrder') as
so_caseless_label,
DB_EXTENDED_PROPERTY('Charset','java') as jdk_label

See also
● “Accessing database property values” [SQL Anywhere Server - Database Administration]
● “DB_PROPERTY function [System]” on page 202
● “DB_EXTENDED_PROPERTY function [System]” on page 197

SYSCOLUMN compatibility view (deprecated)


The SYSCOLUMN view is provided for compatibility with older versions of the software that offered a
SYSCOLUMN system table. However, the previous SYSCOLUMN table has been replaced by the
ISYSTABCOL system table, and its corresponding SYSTABCOL system view, which you should use
instead.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSCOLUMN"
as select b.table_id,
b.column_id,
if c.sequence is null then 'N' else 'Y' endif as pkey,
b.domain_id,
b.nulls,
b.width,
b.scale,
b.object_id,
b.max_identity,
b.column_name,
r.remarks,
b."default",
b.user_type,
b.column_type
from SYS.SYSTABCOL as b
left outer join SYS.ISYSREMARK as r on(b.object_id = r.object_id)
left outer join SYS.ISYSIDXCOL as c on(b.table_id = c.table_id and
b.column_id = c.column_id and c.index_id = 0)

See also
● “SYSTABCOL system view” on page 1244
● “SYSREMARK system view” on page 1227
● “SYSIDXCOL system view” on page 1213

SYSFILE compatibility view (deprecated)


Each row in the SYSFILE system view describes a dbspace for a database. Every database consists of one
or more dbspaces; each dbspace corresponds to an operating system file.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1281


Views

dbspaces are automatically created for the main database file, temporary file, transaction log file, and
transaction log mirror file. Information about the transaction log, and transaction log mirror dbspaces does
not appear in the SYSFILE system view.
ALTER VIEW "SYS"."SYSFILE"
as select b.dbfile_id as file_id,
if b.dbspace_id = 0 and b.dbfile_id = 0 then
db_property('File')
else
if b.dbspace_id = 15 and b.dbfile_id = 15 then
db_property('TempFileName')
else
b.file_name
endif
endif as file_name,
a.dbspace_name,
a.store_type,
b.lob_map,
b.dbspace_id
from SYS.ISYSDBSPACE as a
join SYS.ISYSDBFILE as b on(a.dbspace_id = b.dbspace_id)

See also
● “Predefined dbspaces” [SQL Anywhere Server - Database Administration]

SYSFKCOL compatibility view (deprecated)


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. This view is deprecated; use the SYSIDX and
SYSIDXCOL system views instead.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSFKCOL"
as select a.table_id as foreign_table_id,
a.index_id as foreign_key_id,
a.column_id as foreign_column_id,
a.primary_column_id
from SYS.ISYSIDXCOL as a
,SYS.ISYSIDX as b
where a.table_id = b.table_id
and a.index_id = b.index_id
and b.index_category = 2

See also
● “SYSIDX system view” on page 1211
● “SYSIDXCOL system view” on page 1213

1282 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Compatibility views

SYSFOREIGNKEY compatibility view (deprecated)


The SYSFOREIGNKEY view is provided for compatibility with older versions of the software that
offered a SYSFOREIGNKEY system table. However, the previous SYSFOREIGNKEY system table has
been replaced by the ISYSFKEY system table, and its corresponding SYSFKEY system view, which you
should use instead.

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.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.

ALTER VIEW "SYS"."SYSFOREIGNKEY"


as select b.foreign_table_id,
b.foreign_index_id as foreign_key_id,
a.object_id,
b.primary_table_id,
p.root,
b.check_on_commit,
b.nulls,
a.index_name as role,
r.remarks,
b.primary_index_id,
a.not_enforced as fk_not_enforced,
10 as hash_limit
from(SYS.ISYSIDX as a left outer join SYS.ISYSPHYSIDX as p on(a.table_id
= p.table_id and a.phys_index_id = p.phys_index_id))
left outer join SYS.ISYSREMARK as r on(a.object_id = r.object_id)
,SYS.ISYSFKEY as b
where a.table_id = b.foreign_table_id
and a.index_id = b.foreign_index_id

See also
● “SYSIDX system view” on page 1211
● “SYSPHYSIDX system view” on page 1222
● “SYSREMARK system view” on page 1227
● “SYSFKEY system view” on page 1208

SYSINDEX compatibility view (deprecated)


The SYSINDEX view is provided for compatibility with older versions of the software that offered a
SYSINDEX system table. However, the SYSINDEX system table has been replaced by the ISYSIDX
system table, and its corresponding SYSIDX system view, which you should use instead.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1283


Views

ALTER VIEW "SYS"."SYSINDEX"


as select b.table_id,
b.index_id,
b.object_id,
p.root,
b.dbspace_id,
case b."unique"
when 1 then 'Y'
when 2 then 'U'
when 3 then 'M'
when 4 then 'N'
when 5 then 'Y'
else 'I'
end as "unique",
t.creator,
b.index_name,
r.remarks,
10 as hash_limit,
b.dbspace_id as file_id
from(SYS.ISYSIDX as b left outer join SYS.ISYSPHYSIDX as p on(b.table_id
= p.table_id and b.phys_index_id = p.phys_index_id))
left outer join SYS.ISYSREMARK as r on(b.object_id = r.object_id)
,SYS.ISYSTAB as t
where t.table_id = b.table_id
and b.index_category = 3

See also
● “SYSIDX system view” on page 1211
● “SYSPHYSIDX system view” on page 1222
● “SYSTABLE compatibility view (deprecated)” on page 1285
● “SYSREMARK system view” on page 1227

SYSINFO compatibility view (deprecated)


The SYSINFO view indicates the database characteristics, as defined when the database was created. It
always contains only one row. This view is obtainable via built-in functions and is not kept in the catalog.
Following is the definition for the SYSINFO view:

ALTER VIEW "SYS"."SYSINFO"( page_size,


encryption,
blank_padding,
case_sensitivity,
default_collation,
database_version )
as select db_property('PageSize'),
if db_property('Encryption') <> 'None' then 'Y' else 'N' endif,
if db_property('BlankPadding') = 'On' then 'Y' else 'N' endif,
if db_property('CaseSensitive') = 'On' then 'Y' else 'N' endif,
db_property('Collation'),
NULL

See also
● “Accessing database property values” [SQL Anywhere Server - Database Administration]
● “DB_PROPERTY function [System]” on page 202
● “DB_EXTENDED_PROPERTY function [System]” on page 197

1284 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Compatibility views

SYSIXCOL compatibility view (deprecated)


The SYSIXCOL view is provided for compatibility with older versions of the software that offered a
SYSIXCOL system table. However, the SYSIXCOL system table has been replaced by the
ISYSIDXCOL system table, and its corresponding SYSIDXCOL system view. You should switch to
using the SYSIDXCOL system view.

Each row of the SYSIXCOL describes a column in an index. The tables and columns that make up this
view are provided in the SQL statement below. To learn more about a particular table or column, use the
links provided beneath the view definition.
ALTER VIEW "SYS"."SYSIXCOL"
as select a.table_id,
a.index_id,
a.sequence,
a.column_id,
a."order"
from SYS.ISYSIDXCOL as a
,SYS.ISYSIDX as b
where a.table_id = b.table_id
and a.index_id = b.index_id
and b.index_category = 3

See also
● “SYSIDX system view” on page 1211
● “SYSIDXCOL system view” on page 1213

SYSTABLE compatibility view (deprecated)


The SYSTABLE view is provided for compatibility with older versions of the software that offered a
SYSTABLE system table. However, the SYSTABLE system table has been replaced by the ISYSTAB
system table, and its corresponding SYSTAB system view, which you should use instead.

Each row of SYSTABLE view describes one table in the database.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSTABLE"
as select b.table_id,
b.file_id,
b.count,
0 as first_page,
b.commit_action as last_page,
COALESCE(ph.root,0) as primary_root,
b.creator,
0 as first_ext_page,
0 as last_ext_page,
b.table_page_count,
b.ext_page_count,
b.object_id,
b.table_name,
b.table_type_str as table_type,

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1285


Views

v.view_def,
r.remarks,
b.replicate,
p.existing_obj,
p.remote_location,
'T' as remote_objtype,
p.srvid,
case b.server_type
when 1 then 'SA'
when 2 then 'IQ'
when 3 then 'OMNI'
else 'INVALID'
end as server_type,
10 as primary_hash_limit,
0 as page_map_start,
s.source,
b."encrypted"
from SYS.SYSTAB as b
left outer join SYS.ISYSREMARK as r on(b.object_id = r.object_id)
left outer join SYS.ISYSSOURCE as s on(b.object_id = s.object_id)
left outer join SYS.ISYSVIEW as v on(b.object_id = v.view_object_id)
left outer join SYS.ISYSPROXYTAB as p on(b.object_id =
p.table_object_id)
left outer join(SYS.ISYSIDX as i left outer join SYS.ISYSPHYSIDX as ph
on(i.table_id = ph.table_id and i.phys_index_id = ph.phys_index_id))
on(b.table_id = i.table_id and i.index_category = 1 and i.index_id
= 0)

See also
● “SYSTAB system view” on page 1241
● “SYSREMARK system view” on page 1227
● “SYSSOURCE system view” on page 1234
● “SYSVIEW system view” on page 1257
● “SYSPROXYTAB system view” on page 1226
● “SYSIDX system view” on page 1211
● “SYSPHYSIDX system view” on page 1222

SYSUSERAUTH compatibility view (deprecated)


The SYSUSERAUTH view is provided for compatibility with older versions of the software. Use the
SYSUSERAUTHORITY system view instead.

Each row of the SYSUSERAUTH view describes a user, without exposing their user_id. Instead, each
user is identified by their user name. Because this view displays passwords, this view does not have
PUBLIC select permission.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSUSERAUTH"( name,
password,resourceauth,dbaauth,scheduleauth,user_group )
as select
SYSUSERPERM.user_name,SYSUSERPERM.password,SYSUSERPERM.resourceauth,SYSUSERPE
RM.dbaauth,SYSUSERPERM.scheduleauth,SYSUSERPERM.user_group
from SYS.SYSUSERPERM

1286 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Compatibility views

See also
● “SYSUSERAUTHORITY system view” on page 1255
● “SYSUSERPERM compatibility view (deprecated)” on page 1287

SYSUSERLIST compatibility view (deprecated)


The SYSUSERAUTH view is provided for compatibility with older versions of the software.

Each row of the SYSUSERLIST view describes a user, without exposing their user_id and password.
Each user is identified by their user name.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSUSERLIST"( name,
resourceauth,dbaauth,scheduleauth,user_group )
as select
SYSUSERPERM.user_name,SYSUSERPERM.resourceauth,SYSUSERPERM.dbaauth,SYSUSERPER
M.scheduleauth,SYSUSERPERM.user_group
from SYS.SYSUSERPERM

See also
● “SYSUSERPERM compatibility view (deprecated)” on page 1287

SYSUSERPERM compatibility view (deprecated)


This view is deprecated because it only shows the authorities and permissions available in previous
versions. You should change your application to use the SYSUSERAUTHORITY system view instead.

Each row of the SYSUSERPERM view describes one user ID.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSUSERPERM"
as select b.user_id,
b.object_id,
b.user_name,
b.password,
if exists(select * from SYS.ISYSUSERAUTHORITY
where ISYSUSERAUTHORITY.user_id = b.user_id and ISYSUSERAUTHORITY.auth
= 'RESOURCE') then
'Y' else 'N' endif as resourceauth,
if exists(select * from SYS.ISYSUSERAUTHORITY
where ISYSUSERAUTHORITY.user_id = b.user_id and ISYSUSERAUTHORITY.auth
= 'DBA') then
'Y' else 'N' endif as dbaauth,
'N' as scheduleauth,
if exists(select * from SYS.ISYSUSERAUTHORITY
where ISYSUSERAUTHORITY.user_id = b.user_id and ISYSUSERAUTHORITY.auth
= 'PUBLISH') then

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1287


Views

'Y' else 'N' endif as publishauth,


if exists(select * from SYS.ISYSUSERAUTHORITY
where ISYSUSERAUTHORITY.user_id = b.user_id and ISYSUSERAUTHORITY.auth
= 'REMOTE DBA') then
'Y' else 'N' endif as remotedbaauth,
if exists(select * from SYS.ISYSUSERAUTHORITY
where ISYSUSERAUTHORITY.user_id = b.user_id and ISYSUSERAUTHORITY.auth
= 'GROUP') then
'Y' else 'N' endif as user_group,
r.remarks
from SYS.ISYSUSER as b
left outer join SYS.ISYSREMARK as r on(b.object_id = r.object_id)

See also
● “SYSUSERAUTHORITY system view” on page 1255
● “SYSUSER system view” on page 1254
● “SYSREMARK system view” on page 1227

SYSUSERPERMS compatibility view (deprecated)


This view is deprecated because it only shows the authorities and permissions available in previous
versions. You should change your application to use the SYSUSERAUTHORITY and SYSUSER system
views instead.

Similar to the SYSUSERPERM view, each row of the SYSUSERPERMS view describes one user ID.
However, password information is not included. All users are allowed to read from this view.

The tables and columns that make up this view are provided in the SQL statement below. To learn more
about a particular table or column, use the links provided beneath the view definition.
ALTER VIEW "SYS"."SYSUSERPERMS"
as select
SYSUSERPERM.user_id,SYSUSERPERM.user_name,SYSUSERPERM.resourceauth,SYSUSERPER
M.dbaauth,

SYSUSERPERM.scheduleauth,SYSUSERPERM.user_group,SYSUSERPERM.publishauth,SYSUS
ERPERM.remotedbaauth,SYSUSERPERM.remarks
from SYS.SYSUSERPERM

See also
● “SYSUSERPERM compatibility view (deprecated)” on page 1287
● “SYSUSERAUTHORITY system view” on page 1255
● “SYSUSER system view” on page 1254

Views for Transact-SQL compatibility


The Adaptive Server Enterprise and SQL Anywhere system catalogs are different. The Adaptive Server
Enterprise system tables and views are owned by the user dbo, and exist partly in the master database,
partly in the sybsecurity database, and partly in each individual database. The SQL Anywhere system
tables and views are owned by the special user SYS and exist separately in each database.

1288 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


Views for Transact-SQL compatibility

To assist in preparing compatible applications, SQL Anywhere provides the following set of views owned
by the special user dbo, which correspond to their Adaptive Server Enterprise counterparts. Where
architectural differences make the contents of a particular Adaptive Server Enterprise table or view
meaningless in a SQL Anywhere context, the view is empty, containing just the column names and data
types.

View name Description

syscolumns One row for each column in a table or view, and for each parameter in a procedure

syscomments One or more rows for each view, rule, default, trigger, and procedure, giving the SQL
definition statement

sysindexes One row for each clustered or nonclustered index, one row for each table with no in-
dexes, and an additional row for each table containing text or image data.

sysobjects One row for each table, view, procedure, rule, trigger default, log, or (in tempdb only)
temporary object

systypes One row for each system-supplied or user-defined data type

sysusers One row for each user allowed in the database

syslogins One row for each valid user account

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1289


1290 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1
about, 75
Index @@max_connections global variable
about, 75
@@maxcharlen global variable
Symbols about, 75
% comment indicator @@ncharsize global variable
about, 79 about, 75
% operator @@nestlevel global variable
modulo function, 275 about, 75
& @@pack_received global variable
bitwise operator, 11 about, 75
- comment indicator @@pack_sent global variable
about, 79 about, 75
/* comment indicator @@packet_errors global variable
about, 79 about, 75
// comment indicator @@procid global variable
about, 79 about, 75
0x @@rowcount global variable
binary literals, 6 about, 75
@@char_convert global variable @@servername global variable
about, 75 about, 75
@@client_csid global variable @@spid global variable
about, 75 about, 75
@@client_csname global variable @@sqlstatus global variable
about, 75 about, 75
@@connections global variable @@textsize global variable
about, 75 about, 75
@@cpu_busy global variable @@thresh_hysteresis global variable
about, 75 about, 75
@@dbts global variable @@timeticks global variable
about, 75 about, 75
@@error global variable @@total_errors global variable
about, 75 about, 75
@@fetch_status global variable @@total_read global variable
about, 75 about, 75
@@identity global variable @@total_write global variable
about, 75 about, 75
description, 78 @@tranchained global variable
triggers, 78 about, 75
@@idle global variable @@trancount global variable
about, 75 about, 75
@@io_busy global variable @@transtate global variable
about, 75 about, 75
@@isolation global variable @@version global variable
about, 75 about, 75
@@langid global variable @HttpMethod
about, 75 HTTP_HEADER function, 243
@@language global variable @HttpQueryString

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1291


Index

HTTP_HEADER function, 243 syntax, 146


@HttpStatus header Adaptive Server Enterprise
HTTP_RESPONSE_HEADER function, 245 converting stored procedures to Watcom SQL
sa_set_http_header_info system procedure, 1134 syntax, 380
@HttpURI CREATE DATABASE statement, 509
HTTP_HEADER function, 243 migrating to SQL Anywhere using sa_migrate
@HttpVersion system procedure, 1084
HTTP_HEADER function, 243 system procedures, 999
@mp:id metaproperty ADD clause
openxml system procedure, 1002 ALTER DBSPACE statement , 405
@mp:localname metaproperty ALTER PUBLICATION statement, 425
openxml system procedure, 1002 ALTER TABLE statement , 453
@mp:namespaceuri metaproperty ADD OPTION clause
openxml system procedure, 1002 ALTER SYNCHRONIZATION SUBSCRIPTION
@mp:prefix metaproperty statement [MobiLink] , 448
openxml system procedure, 1002 ALTER SYNCHRONIZATION USER statement
@mp:xmltext metaproperty [MobiLink] , 450
openxml system procedure, 1002 ADD PCTFREE clause
[ESQL] ALTER MATERIALIZED VIEW statement, 418
statement indicators, 398 ADD table-constraint clause
[Interactive SQL] ALTER TABLE statement , 458
statement indicators, 398 ADD | ALTER | DELETE SCHEDULE clause
[SP] ALTER EVENT statement, 409
statement indicators, 398 adding
[T-SQL] columns using the ALTER TABLE statement, 451
statement indicators, 398 indexes using the CREATE INDEX statement, 553
^ Java classes, 787
bitwise operator, 11 messages, 563
| servers, 601
bitwise operator, 11 ADDRESS clause
~ ALTER REMOTE MESSAGE TYPE statement,
bitwise operator, 11 426
ALTER SYNCHRONIZATION SUBSCRIPTION
A statement [MobiLink] , 448
ABS function ALTER SYNCHRONIZATION USER statement
syntax, 145 [MobiLink] , 450
ABSOLUTE clause CREATE PUBLICATION statement [MobiLink]
FETCH statement , 729 [SQL Remote], 596
ACCENT clause CREATE SYNCHRONIZATION
CREATE DATABASE statement, 509 SUBSCRIPTION statement [MobiLink], 630
AccentSensitive property CREATE SYNCHRONIZATION USER, 632
DB_EXTENDED_PROPERTY function, 197 GRANT CONSOLIDATE statement [SQL
Accept-Encoding Remote], 754
HTTP_HEADER function, 242 GRANT REMOTE statement [SQL Remote], 758
AcceptCharset option addresses
sa_set_http_option system procedure, 1135 SQL Remote publishers, 426
ACOS function AES encryption algorithm
CREATE DATABASE statement, 508

1292 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


CREATE ENCRYPTED FILE statement, 524 ALL PRIVILEGES clause
DECRYPT function, 204 REVOKE statement, 863
ENCRYPT function, 210 ALL PRIVILEGES permission clause
AES256 encryption algorithm GRANT statement, 762
CREATE DATABASE statement, 508 ALL search condition
CREATE ENCRYPTED FILE statement, 524 syntax, 34
DECRYPT function, 204 ALLOCATE DESCRIPTOR statement
ENCRYPT function, 210 embedded SQL syntax, 398
AES256_FIPS encryption algorithm allocating
CREATE DATABASE statement, 508 disk space using the ALTER DBSPACE statement,
CREATE ENCRYPTED FILE statement, 524 405
DECRYPT function, 204 memory for descriptor areas, 398
ENCRYPT function, 210 alphabetic characters
AES_FIPS encryption algorithm defined, 4
CREATE DATABASE statement, 508 alphabetical list of binary data types
CREATE ENCRYPTED FILE statement, 524 about, 117
DECRYPT function, 204 alphabetical list of bit array data types
ENCRYPT function, 210 about, 99
AFTER clause alphabetical list of date and time data types
CREATE TRIGGER statement, 651 about, 101
AFTER MESSAGE BREAK clause alphabetical list of money data types
WAITFOR statement, 957 about, 98
AFTER triggers alphabetical list of numeric data types
CREATE TRIGGER statement , 651 about, 89
aggregate functions ALTER clause
alphabetical list, 133 ALTER TABLE statement , 459
ALGORITHM clause REVOKE statement, 863
CREATE ENCRYPTED FILE statement, 524 ALTER DATABASE statement
CREATE ENCRYPTED TABLE DATABASE FORCE START clause, 403
statement, 522 SET PARTNER FAILOVER clause, 402
aliases syntax, 400
DELETE statement, 679 ALTER DATABASE UPGRADE statement
for columns, 874 syntax, 400
UPDATE statement, 950 ALTER DATATYPE statement
ALL syntax, 407
keyword in SELECT statement, 873 ALTER DBSPACE statement
ALL authority clause syntax, 405
GRANT statement, 762 ALTER DOMAIN statement
ALL clause syntax, 407
CREATE EVENT statement, 526 ALTER EVENT statement
DESCRIBE statement, 682 syntax, 408
DISCONNECT statement [ESQL] [Interactive ALTER EXTERNAL ENVIRONMENT statement
SQL] statement, 688 syntax, 410
MEDIAN function, 270 ALTER FUNCTION statement
REVOKE statement, 863 syntax, 412
SELECT statement, 873 ALTER INDEX statement
ALL permission clause syntax, 413
GRANT statement, 762 ALTER LOGIN POLICY statement

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1293


Index

syntax, 415 syntax, 468


ALTER MATERIALIZED VIEW statement ALTER TRANSACTION LOG clause
syntax, 417 ALTER DATABASE statement, 401
ALTER MIRROR SERVER statement ALTER TRIGGER statement
syntax, 420 syntax, 469
ALTER OPTION clause ALTER USER statement
ALTER SYNCHRONIZATION SUBSCRIPTION character set conversion on passwords, 471
statement [MobiLink] , 448 password maximum length, 471
ALTER SYNCHRONIZATION USER statement passwords, character set conversion on, 471
[MobiLink] , 450 syntax, 470
ALTER PARENT FROM clause ALTER VIEW statement
ALTER MIRROR SERVER statement, 421 DISABLE clause, 473
ALTER permission ENABLE clause, 473
GRANT statement, 761 RECOMPILE clause, 473
REVOKE statement, 863 syntax, 472
ALTER permission clause altering
GRANT statement, 762 ALTER PUBLICATION statement, 425
ALTER PROCEDURE statement ALTER TABLE statement, 451
syntax, 423 columns using the ALTER TABLE statement, 451
ALTER PUBLICATION statement data types using the ALTER DOMAIN statement,
MobiLink syntax, 425 407
SQL Remote syntax, 425 databases using the ALTER DATABASE
ALTER REMOTE MESSAGE TYPE statement statement, 400
SQL Remote syntax, 426 dbspaces using the ALTER DBSPACE statement,
ALTER SEQUENCE statement 405
syntax, 427 domains using the ALTER DOMAIN statement,
ALTER SERVER statement 407
syntax, 428 events using the ALTER EVENT statement, 408
ALTER SERVICE statement [HTTP web service] indexes using the ALTER INDEX statement, 413
syntax, 431 login policy options using ALTER LOGIN
ALTER SERVICE statement [SOAP web service] POLICY statement, 415
syntax, 436 login policy options using ALTER USER
ALTER SPATIAL REFERENCE SYSTEM statement statement, 470
syntax, 442 materialized views using the ALTER
ALTER STATISTICS statement MATERIALIZED VIEW statement, 417
syntax, 445 procedures using the ALTER PROCEDURE
ALTER SYNCHRONIZATION PROFILE statement statement, 423
MobiLink syntax, 446 remote server attributes using the ALTER
ALTER SYNCHRONIZATION SUBSCRIPTION SERVER statement, 428
statement SQL Remote ALTER PUBLICATION statement,
MobiLink syntax, 447 425
ALTER SYNCHRONIZATION USER statement SQL Remote remote message types, 426
MobiLink syntax, 449 text configuration objects, 465
ALTER TABLE statement text indexes using ALTER TEXT INDEX
syntax, 451 statement, 468
ALTER TEXT CONFIGURATION statement triggers using the ALTER TRIGGER statement,
syntax, 465 469
ALTER TEXT INDEX statement views using the ALTER VIEW statement, 472

1294 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


altering synchronization profiles supported operating systems using the BACKUP
ALTER SYNCHRONIZATION PROFILE statement, 477
statement [MobiLink], 446 archives
alternate server names creating database backups using the BACKUP
defining with CREATE MIRROR SERVER statement, 477
statement, 564 restoring databases from, 855
AND ARGN function
bitwise operators, 11 syntax, 147
logical operators description, 9 arithmetic operators
three-valued logic, 55 Modulo, 10
ANGULAR UNIT OF MEASURE clause SQL syntax, 10
ALTER SPATIAL REFERENCE SYSTEM ARRAY clause
statement, 443 EXECUTE statement, 722
CREATE SPATIAL REFERENCE SYSTEM FETCH statement, 730
statement, 619 PUT statement [ESQL], 837
ANSI articles
equivalency using the REWRITE function, 324 SYSARTICLE system view, 1196
ansi_nulls option SYSARTICLECOL system view, 1196
Microsoft SQL Server compatibility, 902 AS clause
ansi_permissions option ALTER MIRROR SERVER statement, 420
setting with Transact-SQL SET statement, 901 ALTER SERVICE statement [HTTP web service],
ansinull option 431
setting with Transact-SQL SET statement, 901 ALTER SERVICE statement [SOAP web service],
ANY search condition 436
syntax, 35 ALTER VIEW statement, 472
apostrophes CONNECT statement [ESQL] [Interactive SQL],
in SQL strings, 7 504
APPEND clause CREATE DBSPACE statement, 515
OUTPUT statement, 825 CREATE DOMAIN statement, 519
UNLOAD statement, 939 CREATE FUNCTION statement, 548
application profiling CREATE MATERIALIZED VIEW statement, 561
setting the tracing level, 1140 CREATE MESSAGE statement, 563
approximate data types CREATE MIRROR SERVER statement, 564
about, 89 CREATE PROCEDURE statement [T-SQL], 583
arbiter servers CREATE TRIGGER [Transact-SQL] statement,
changing with ALTER MIRROR SERVER 657
statement, 421 CREATE VIEW statement, 662
defining with CREATE MIRROR SERVER DELETE statement, 678
statement, 565 START DATABASE statement, 907
arc-cosine function UPDATE statement, 948
ACOS function, 146 ASC | DESC clause
arc-sine function CREATE INDEX statement, 554
ASIN function, 148 ASCII
arc-tangent function function and syntax, 147
ATAN function, 149 ASE COMPATIBLE clause
ATAN2 function, 150 CREATE DATABASE statement, 509
archive backups ASIN function
syntax, 148

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1295


Index

assertions ALTER SERVICE statement [SOAP web service],


regular expression examples, 26 436
regular expressions, 26 CREATE SERVICE statement [HTTP web
assigning service], 433, 607
logins for remote servers, 534 CREATE SERVICE statement [SOAP web
values to SQL variables, 899 service], 439, 614
asterisks AUTO clause
allowed syntax in a CONTAINS clause, 50 BACKUP statement, 480
allowed syntax in a full text query string, 50 AUTO COMPRESSED clause
using in subqueries, 662 LOAD TABLE statement, 797
AT clause AUTO REFRESH clause
ALTER EVENT statement, 409 CREATE TEXT INDEX statement, 649
CREATE EVENT statement, 530 AUTO TUNE WRITERS clause
CREATE EXISTING TABLE statement, 532 BACKUP statement, 479
CREATE PROCEDURE statement, 588 AUTO UPDATE clause
CREATE TABLE statement, 635 ALTER STATISTICS statement, 445
GRANT statement, 762 auto_add_fan_out option
ATAN function SET MIRROR OPTION statement, 884
syntax, 149 auto_add_server option
ATAN2 function SET MIRROR OPTION statement, 884
syntax, 150 auto_commit option
ATN2 function Interactive SQL option, 889
syntax, 150 auto_failover option
ATOMIC clause SET MIRROR OPTION statement, 884
BEGIN statement, 485 AUTOINCREMENT
ATTACH TRACING statement @@identity, 78
diagnostic tracing, 475 GET_IDENTITY function, 227
syntax, 475 resetting the value, 1112
ATTENDED clause AUTOINCREMENT clause
BACKUP statement, 479 CREATE TABLE statement, 633
attributes AUTOINCREMENT default
altering remote server using the ALTER SERVER CREATE TABLE statement, 454, 638
statement, 428 AutoMultiProgrammingLevel property
auditing setting with sa_server_option, 1126
adding comments, 1009 AutoMultiProgrammingLevelStatistics property
disabling using sa_disable_auditing_type system setting with sa_server_option, 1126
procedure, 1042 AUTOSTOP clause
enabling using sa_enable_auditing_type system START DATABASE statement, 908
procedure, 1044 AvailForOptimization property
authentication_string option sa_materialized_view_info system procedure, 1078
SET MIRROR OPTION statement, 884 average function
authorities AVG function, 150
GRANT statement, 760 AVG function
granting REMOTE DBA, 757 syntax, 150
AUTHORIZATION clause
ALTER SERVICE statement [HTTP web service], B
431 back quotes

1296 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


database objects, 4 BEGIN TRANSACTION statement
SQL identifiers, 4 Transact-SQL syntax, 488
backslashes beginning
in SQL strings, 7 user-defined transactions using the BEGIN
not allowed in SQL identifiers, 4 TRANSACTION statement, 488
BACKUP authority BETWEEN ... AND clause
GRANT statement, 760 CREATE EVENT statement, 529
REVOKE statement, 863 BETWEEN clause
BACKUP authority clause CREATE SPATIAL REFERENCE SYSTEM
GRANT statement, 762 statement, 616
BACKUP clause WINDOW clause, 962
REVOKE statement, 863 BETWEEN search condition
BACKUP statement syntax, 37
syntax, 477 BIGINT data type
backup.syb comparing with dates and times, 125
about, 479 syntax, 89
backups binary
BACKUP authority, 762 escape characters, 6
BACKUP statement, 477 BINARY data type
creating events using the CREATE EVENT syntax, 117
statement, 526 binary data types
creating using the BACKUP statement, 477 BINARY, 117
restoring databases from, 855 decoding, 152
starting on a read-only database server, 481 encoding, 152
to tape using the BACKUP statement, 477 getting from columns, 749
base 10 logarithm IMAGE, 117
LOG10 function, 266 LONG BINARY, 118
base tables UNIQUEIDENTIFIER, 118
CREATE TABLE statement, 643 VARBINARY, 119
BASE64_DECODE function binary large objects
syntax, 152 binary data types, 117
BASE64_ENCODE function exporting, 1192
syntax, 152 GET DATA statement, 749
BEFORE clause getting from columns, 749
CREATE TRIGGER statement, 651 importing ASE generated BCP files, 798
BEFORE keyword, CONTAINS search condition inserting using the xp_read_file system procedure,
not supported in full text search, 50 1182
BEFORE triggers SET statement example, 901
CREATE TRIGGER statement , 651 transaction log considerations, 405
BEGIN DECLARE statement binary literals
embedded SQL syntax, 666 special characters, 6
BEGIN keyword bind variables
TSQL compatibility, 486 describing cursors, 681
BEGIN SNAPSHOT statement EXECUTE statement, 722
syntax, 483 OPEN statement, 822
BEGIN statement BIND VARIABLES FOR clause
syntax, 484 DESCRIBE statement [ESQL], 681
Transact-SQL syntax, 486 bit array conversions

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1297


Index

about, 128 blocking


bit array data types identifying, 1020
about, 99 blocks
LONG VARBIT, 99 identifying, 1020
VARBIT, 100 troubleshooting, 1071
bit arrays BOM (byte order mark)
about, 99 loading data from UTF-16 or UTF-8 data file, 804
converting, 128 brackets
data types, 99 database objects, 4
BIT data type SQL identifiers, 4
syntax, 90 branches
BIT_AND function MERGE statement, 816
syntax, 153 branching
BIT_LENGTH function MERGE statement, 816
syntax, 154 BREAK statement
BIT_OR function Transact-SQL syntax, 490
syntax, 155 bulk loading
BIT_SUBSTR function LOAD TABLE statement, 792
syntax, 155 bulk operations
BIT_XOR function unloading data using the UNLOAD statement, 937
syntax, 157 BY clause
bits INPUT statement, 773
converting, 128 BY LOCK clause
bitwise operators PREPARE statement [ESQL] statement, 833
syntax, 11 BY TIMESTAMP clause
BLANK PADDING clause PREPARE statement [ESQL] statement, 833
CREATE DATABASE statement, 509 BY VALUES clause
BLOBs PREPARE statement [ESQL] statement, 833
configuring BLOB indexing at table creation, 637 BYE statement
configuring BLOB indexing using ALTER TABLE Interactive SQL syntax, 725
statement, 457 bypassing optimization
exporting, 1192 avoiding using FORCE NO OPTIMIZATION
GET DATA statement, 749 clause, 877
importing ASE generated BCP files, 798 avoiding using FORCE OPTIMIZATION option,
INLINE clause, CREATE TABLE statement, 636 877
inserting using the SET statement, 899 BYTE ORDER MARK
inserting using the xp_read_file system procedure, loading data from UTF-16 or UTF-8 data file, 804
1182 read or write option in the CSCONVERT function,
PREFIX clause, CREATE TABLE statement, 636 183
querying within BLOBs, 741 BYTE ORDER MARK clause
SET statement example, 901 INPUT statement, 774
transaction log considerations, 405 LOAD TABLE statement, 796
BLOCK clause openxml system procedure, 1003
FETCH statement , 730 OUTPUT statement, 826
OPEN statement, 823 UNLOAD statement, 939
block fetches BYTE_LENGTH function
FETCH statement, 730 syntax, 157
OPEN statement, 823 BYTE_SUBSTR function

1298 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


syntax, 158 NULLIF function, 288
syntax, 16
C case sensitivity
cache comparison operators, 8
flushing, 1047 LIKE search condition, 42
CACHE clause REGEXP search condition, 44
ALTER SEQUENCE statement, 428 REGEXP_SUBSTR function, 306
CREATE SEQUENCE statement, 600 SIMILAR TO search condition, 46
CacheSizingStatistics property CASE statement
setting with sa_server_option, 1127 syntax, 493
calendar date CaseSensitivity property
ISO 8601, 102 DB_EXTENDED_PROPERTY function, 197
CALIBRATE DBSPACE clause CAST function
ALTER DATABASE statement, 401 data type conversions, 122
CALIBRATE DBSPACE TEMPORARY clause syntax, 159
ALTER DATABASE statement, 401 catalog
CALIBRATE GROUP READ clause default system views, 1195
ALTER DATABASE statement, 401 system tables, 965
CALIBRATE PARALLEL READ clause viewing data in system tables, 965
ALTER DATABASE statement, 401 catalog data
CALIBRATE SERVER clause viewing, 965
ALTER DATABASE statement, 401 CATALOG ONLY clause
calibrating RESTORE DATABASE statement, 855
cost models using the ALTER DATABASE catalog procedures
statement, 400 alphabetical list , 1001
database servers using the ALTER DATABASE catalog procedures (ASE)
statement, 400 sp_column_privileges, 1000
loading and unloading cost models using sp_columns, 1000
sa_load_cost_model system procedure, 1070 sp_fkeys, 1000
loading and unloading cost models using sp_pkeys, 1000
sa_unload_cost_model system procedure, 1154 sp_special_columns, 1000
parallel I/O capabilities, 403 sp_sproc_columns, 1000
CALL statement sp_statistics, 1000
in Transact-SQL, 724 sp_stored_procedures, 1000
syntax, 491 sp_tables, 1000
calling procedures Transact-SQL list, 999
CALL statement, 491 Transact-SQL, list, 1000
capabilities catalog system procedures
remote servers, 1197 about, 995
SYSCAPABILITY system view, 1197 CatalogCollation property
CAPABILITY clause DB_EXTENDED_PROPERTY function, 197
ALTER SERVER statement, 429 CEILING function
CASCADE clause syntax, 160
CREATE TABLE statement, 633 CERTIFICATE clause
CASE clause CREATE FUNCTION statement [web clients],
CREATE DATABASE statement, 510 544
CASE expression CREATE PROCEDURE statement [web clients],
579

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1299


Index

CHAR data type character strings


byte-length semantics, 81 about, 5
character-length semantics, 81 character substitution
comparing with dates and times, 125 comparisons between CHAR and NCHAR, 123
comparing with NCHAR data type, 123 lossy character set conversions, 123
syntax, 81 character-length semantics
using DESCRIBE on a CHAR column, 81 CHAR data type, 81
CHAR function VARCHAR data type, 87
syntax, 161 CHARINDEX function
CHAR_LENGTH function syntax, 163
syntax, 162 CharSet property
character classes DB_EXTENDED_PROPERTY function, 197
sub-character classes, 21 CharsetConversion option
support special character classes, 21 sa_set_http_option system procedure, 1135
character data CHECK clause
storage, 81 ALTER TABLE statement , 456
strings, 5 CREATE DOMAIN statement, 520
character data types CREATE MATERIALIZED VIEW statement, 561
about, 81 CREATE TABLE statement, 642
CHAR, 81 search conditions, 32
LONG NVARCHAR, 83 CHECK conditions
LONG VARCHAR, 83 CREATE TABLE statement, 640
NCHAR, 84 CHECK CONSTRAINTS clause
NTEXT, 85 LOAD TABLE statement, 796
NVARCHAR, 85 CHECK EVERY clause
TEXT, 86 WAITFOR statement, 957
UNIQUEIDENTIFIERSTR, 87 CHECK ON COMMIT clause
VARCHAR, 87 CREATE TABLE statement, 643
XML, 88 checkpoint logs
character functions CHECKPOINT statement, 497
alphabetical list, 142 CHECKPOINT statement
character set conversion syntax, 497
comparisons between CHAR and NCHAR, 123 checkpointing
comparisons between data types, 122 databases using the CHECKPOINT statement, 497
comparisons between numeric data types, 125 checkpoints
converting NCHAR to CHAR, 128 using the CHECKPOINT statement, 497
lossy conversions, 123 CHECKSUM clause
passwords, CREATE USER statement, 659 ALTER DATABASE statement, 402
passwords, GRANT statement, 763 CREATE DATABASE statement, 510
substitution characters, 123 START DATABASE statement, 908
character set conversion on passwords checksums
ALTER USER statement, 471 altering database settings, 402
character sets creating databases with, 510
COMPARE function, 165 starting databases with, 908
converting during expression evaluation, 123 VALIDATE CHECKSUM statement, 955
lossy character set conversions, 123 validating, 955
SORTKEY function, 339 child_creation option
substitution characters, 123 SET MIRROR OPTION statement, 884

1300 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


CLASS clause OUTPUT statement, 826
ALTER SERVER statement, 429 coefficient of determination
CREATE SERVER statement, 602 about, 313
REMOVE JAVA statement, 852 COL_LENGTH function
classes syntax, 144
Java methods, 138 COL_NAME function
removing Java, 851 syntax, 144
clause order in SQL COLLATION clause
syntax conventions, 396 collation tailoring, 511
clauses CREATE DATABASE statement, 511
order of, SQL conventions, 396 Collation property
CLEAR statement DB_EXTENDED_PROPERTY function, 197
Interactive SQL syntax, 497 collation sequences
clearing CREATE DATABASE statement, 511
Interactive SQL panes, 497 LIKE search condition, 41
client files collation tailoring
READ_CLIENT_FILE function, 304 COLLATION clause, CREATE DATABASE
WRITE_CLIENT_FILE function, 382 statement, 511
client statement caching COMPARE function, 165
RequestLogFile property, 1130 NCHAR COLLATION clause, CREATE
CLIENTPORT clause DATABASE statement, 513
CREATE FUNCTION statement [web clients], SORTKEY function, 339
545 collations
CREATE PROCEDURE statement [web clients], REGEXP search condition, 44
579 REGEXP_SUBSTR function, 306
Clockwise format SIMILAR TO search condition, 46
CREATE SPATIAL REFERENCE SYSTEM SORTKEY function, 339
statement, 622 tailoring at database creation time, 511
CLOSE statement CollectStatistics property
embedded SQL syntax, 498 setting with sa_server_option, 1127
syntax, 498 COLUMN clause
close_on_endtrans option DESCRIBE statement [ESQL], 681
setting with Transact-SQL SET statement, 901 GET DATA statement , 750
closing column compression
connections using the DROP CONNECTION ALTER TABLE statement, 451
statement, 689 CREATE TABLE statement, 633
cursors using the CLOSE statement [ESQL] [SP], retrieving compression statistics, 1014
498 column constraints
Interactive SQL, 725 adding using the ALTER TABLE statement, 456
CLUSTERED clause changing using the ALTER TABLE statement, 459
ALTER INDEX statement, 413 column definition
CREATE INDEX statement, 554 CREATE TABLE statement, 636
clustered indexes COLUMN DELIMITED BY clause
creating using ALTER INDEX statement, 413 UNLOAD statement, 939
COALESCE function column names
syntax, 164 syntax, 14
code pages column statistics
INPUT statement, 774 only partially updated by LOAD TABLE, 804

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1301


Index

selectivity estimates, 56 syntax, 165


SYSCOLSTAT system view, 1199 comparing
SYSCOLSTATS consolidated view, 1267 CHAR and NCHAR, 123
updating using CREATE STATISTICS, 625 COMPARE function, 165
COLUMN WIDTHS clause comparing dates and times
INPUT statement, 774 about, 125
OUTPUT statement, 826 comparison operators
column-name data conversion, 122
common element in SQL syntax, 395 syntax, 8
columns Transact-SQL compatibility, 8
aliases, 874 comparisons
altering using the ALTER TABLE statement, 451 CHAR and NCHAR values, 123
constraints and defaults with domains, 121 dates, 125
constraints in CREATE TABLE statement, 640 numeric data types, 125
domains, 121 search conditions, 32
getting binary data from, 749 times, 125
permissions on, 1198 compatibility
renaming, 461 datetime, 127
SQL Remote updating, 945 NULLs, 65
SYSTABCOL view, 1244 T-SQL expressions and QUOTED IDENTIFIER
updating without logging, 963 option, 31
user-defined data types, 121 Transact-SQL comparison operators, 8
combining Transact-SQL expressions, 31
result of multiple SELECT statements, 936 Transact-SQL global variables, 75
comma-separated lists Transact-SQL local variables, 73
LIST function syntax, 261 Transact-SQL views, 1288
commands views, 1280
executing operating system, 931 compatibility of expressions
COMMENT statement about, 31
syntax, 499 compatibility views
comments about, 1280
adding to database objects using the COMMENT SYSCOLLATION, 1280
statement, 499 SYSCOLLATIONMAPPINGS, 1280
syntax, 79 SYSCOLUMN, 1281
COMMENTS INTRODUCED BY clause SYSFKCOL, 1282
LOAD TABLE statement, 796 SYSFOREIGNKEY, 1283
commit SYSINDEX, 1283
preparing for two-phase, 835 SYSINFO, 1284
COMMIT statement SYSIXCOL, 1285
preparing for two-phase, 835 SYSTABLE, 1285
referential integrity, 1011 SYSUSERLIST, 1287
syntax, 501 SYSUSERPERM, 1287
committing SYSUSERPERMS, 1288
transactions using the COMMIT statement, 501 compound statements
communication protocols BEGIN statement, 484
multiple settings in MobiLink, 632 BEGIN statement [TSQL], 486
COMPARE function TSQL compatibility, 486
collation tailoring, 165 COMPRESS function

1302 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


syntax, 166 CONNECT statement
COMPRESSED clause embedded SQL syntax, 504
ALTER TABLE statement , 456 Interactive SQL syntax, 504
CREATE TABLE statement, 636 CONNECT TO clause
LOAD TABLE statement, 797 GRANT statement, 763
UNLOAD statement, 939 CONNECT TRACING statement
compressed columns populating sa_diagnostic_tracing_level table, 991
ALTER TABLE statement, 451 connecting
retrieving compression statistics, 1014 creating events using the CREATE EVENT
compressing statement, 526
tables using the ALTER TABLE statement, 451 databases using the CONNECT statement, 504
compressing columns Connection
CREATE TABLE statement, 636 HTTP_RESPONSE_HEADER function, 244
compressing strings on Unix CONNECTION CLOSE clause
COMPRESS function, 166 ALTER SERVER statement, 429
compression connection-level variables
COMPRESS function, 166 definition, 72
statistics, 1018 syntax, 74
COMPUTE clause connection-name
ALTER TABLE statement , 458 common element in SQL syntax, 395
CREATE TABLE statement, 643 CONNECTION_EXTENDED_PROPERTY function
COMPUTES clause syntax, 169
LOAD TABLE statement, 797 CONNECTION_PROPERTY function
concatenating strings syntax, 171
string operators, 10 connection_string option
concurrency ALTER MIRROR SERVER statement, 422
locking tables, 808 CREATE MIRROR SERVER statement, 565
condition connections
common element in SQL syntax, 395 creating events for failed connections, 526
conditions cursor list, 1069
CONTAINS, 47 disabling connections to a server, 1120
EXISTS, 53 disallowing with RAISERROR, 839
search, 32 DROP CONNECTION statement, 689
SQL search conditions, 32 dropping in Interactive SQL, 688
subqueries in, 34 enabling pooling, 904
three-valued logic, 55 generating a list of connection IDs, 1023
CONFIGURATION clause setting, 881
CREATE TEXT INDEX statement, 649 setting a maximum number, 839
CONFIGURE statement ConnsDisabled property
Interactive SQL syntax, 503 setting with sa_server_option, 1127
CONFLICT function ConnsDisabledForDB property
syntax, 167 setting with sa_server_option, 1127
conflicts ConsoleLogFile property
CONFLICT function for SQL Remote, 167 setting with sa_server_option, 1127
CONNECT clause ConsoleLogMaxSize property
REVOKE statement, 863 setting with sa_server_option, 1127
CONNECT permission CONSOLIDATE permissions
GRANT statement, 763 granting, 754

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1303


Index

REVOKE CONSOLIDATE statement, 860 FROM clause, 742


CONSOLIDATED clause CONTAINS search condition
CREATE EVENT statement, 526 allowed syntax for special characters, 52
consolidated databases fuzzy matching, 47
SQL Remote revoking permissions, 860 search conditions, 32
consolidated views syntax, 47
about, 1260 use of BEFORE keyword unsupported, 50
SYSARTICLECOLS, 1264 Content-Length
SYSARTICLES, 1265 HTTP_RESPONSE_HEADER function, 244
SYSCAPABILITIES, 1265 Content-Type
SYSCATALOG, 1266 HTTP_RESPONSE_HEADER function, 244
SYSCOLAUTH, 1266 CONTINUE clause
SYSCOLSTATS, 1267 WHENEVER statement [ESQL], 959
SYSCOLUMNS, 1267 CONTINUE statement
SYSFOREIGNKEYS, 1268 Transact-SQL syntax, 507
SYSGROUPS, 1269 control statements
SYSINDEXES, 1269 BREAK syntax, 490
SYSOPTIONS, 1270 CALL statement, 491
SYSPROCAUTH, 1270 CASE statement, 493
SYSPROCPARMS, 1271 CASE statement [T-SQL], 495
SYSPROCS, 1271 CONTINUE statement syntax, 507
SYSPUBLICATIONS, 1272 GOTO Transact-SQL statement, 754
SYSREMOTEOPTION2, 1272 IF statement, 769
SYSREMOTEOPTIONS, 1273 LEAVE statement, 790
SYSREMOTETYPES, 1273 LOOP statement, 810
SYSREMOTEUSERS, 1274 Transact-SQL CONTINUE statement, 960
SYSSUBSCRIPTIONS, 1274 Transact-SQL IF statement, 771
SYSSYNC2, 1275 Transact-SQL WHILE statement, 960
SYSSYNCPUBLICATIONDEFAULTS, 1275 WHILE statement, 810
SYSSYNCS, 1276 conventions
SYSSYNCSCRIPTS, 1276 SQL language syntax, 1
SYSSYNCSUBSCRIPTIONS, 1277 syntax, 396
SYSSYNCUSERS, 1277 conversion
SYSTABAUTH, 1278 CAST, 159
SYSTRIGGERS, 1278 converting DOUBLE to NUMERIC, 130
SYSUSERAUTH, 1286 data type conversions, 122
SYSUSEROPTIONS, 1279 NCHAR to CHAR, 128
SYSVIEWS, 1279 strings to dates, 127
constants when evaluating expressions, 122
about, 6 conversion between character sets
syntax, 14 about, 123
Transact-SQL, 31 conversion functions
CONSTRAINT clause alphabetical list, 135
CREATE TABLE statement, 633 data type, 135
constraints conversion when using comparison operators
column, CREATE TABLE statement, 640 about, 122
renaming, 461 CONVERT function
CONTAINS clause data type conversions, 122

1304 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


syntax, 172 cost models
CONVERT USING clause calibrating the database server, 400
CREATE SPATIAL UNIT OF MEASURE loading, 1070
statement, 624 recalibrating using the ALTER DATABASE
converting statement, 400
ambiguous dates and strings, 103 unloading, 1154
bit arrays, 128 cost-based optimization
bits, 128 avoiding using FORCE NO OPTIMIZATION
data types, 122 clause, 877
SQL and Java, 130 forcing for procedures, 877
using comparison operators, 122 forcing using FORCE OPTIMIZATION option,
converting NULL constants to NUMERIC and string 877
types COT function
about, 128 syntax, 176
converting strings cotangent function
about, 142 COT function, 176
Cookie COUNT clause
HTTP_HEADER function, 242 GET DESCRIPTOR statement [ESQL], 751
COORDINATE clause SET DESCRIPTOR statement [ESQL], 882
ALTER SPATIAL REFERENCE SYSTEM COUNT function
statement, 443 syntax, 177
CREATE SPATIAL REFERENCE SYSTEM COUNT_BIG function
statement, 620 syntax, 179
coordinated universal time COUNT_SET_BITS function
CURRENT UTC TIMESTAMP, 63 syntax, 180
UTC TIMESTAMP, 71 CounterClockwise format
COPY clause CREATE SPATIAL REFERENCE SYSTEM
BACKUP statement, 479 statement, 622
copy nodes COVAR_POP function
dropping servers, 699 syntax, 181
copy servers COVAR_SAMP function
changing with ALTER MIRROR SERVER syntax, 182
statement, 421 CREATE DATABASE statement
defining with CREATE MIRROR SERVER syntax, 508
statement, 565 CREATE DATATYPE statement
copyright syntax, 519
retrieving, 1181 CREATE DBSPACE statement
CORR function syntax, 515
syntax, 175 CREATE DECRYPTED DATABASE statement
correlation function syntax, 517
CORR function, 175 CREATE DECRYPTED FILE statement
correlation names syntax, 518
DELETE statement, 679 CREATE DOMAIN statement
UPDATE statement, 950 syntax, 519
COS function using, 120
syntax, 176 CREATE ENCRYPTED DATABASE statement
cosine function syntax, 521
COS function, 176 CREATE ENCRYPTED FILE statement

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1305


Index

example of usage to change an encryption key, 526 CREATE SEQUENCE statement


syntax, 524 syntax, 599
CREATE ENCRYPTED TABLE DATABASE CREATE SERVER statement
statement syntax, 601
syntax, 521 CREATE SERVICE statement [HTTP web service]
CREATE EVENT clause syntax, 605
CREATE EVENT statement, 527 CREATE SERVICE statement [SOAP web service]
CREATE EVENT statement syntax, 611
syntax, 526 CREATE SPATIAL REFERENCE SYSTEM
CREATE EXISTING TABLE statement statement
sp_remote_columns system procedure, 1166 syntax, 616
sp_remote_tables system procedure, 1172 CREATE SPATIAL UNIT OF MEASURE statement
syntax, 532 syntax, 624
CREATE EXTERNLOGIN statement CREATE STATISTICS statement
syntax, 534 syntax, 625
CREATE FUNCTION statement CREATE SUBSCRIPTION statement
syntax, 548 SQL Remote syntax, 626
syntax for creating web services functions, 541 CREATE SYNCHRONIZATION PROFILE
syntax for interfacing to native functions, 535 statement
Transact-SQL example, 552 MobiLink syntax, 628
CREATE INDEX statement CREATE SYNCHRONIZATION SUBSCRIPTION
syntax, 553 statement
table use, 555 MobiLink syntax, 629
CREATE LOCAL TEMPORARY TABLE statement CREATE SYNCHRONIZATION USER statement
syntax, 556 MobiLink syntax, 631
CREATE LOGIN POLICY statement CREATE TABLE clause
syntax, 558 INPUT statement, 774
CREATE MATERIALIZED VIEW statement OUTPUT statement, 826
syntax, 560 CREATE TABLE statement
CREATE MESSAGE statement remote tables, 635
Transact-SQL syntax, 563 syntax, 633
CREATE MIRROR SERVER statement Transact-SQL, 644
syntax, 564 CREATE TEMPORARY PROCEDURE statement
CREATE ON clause syntax, 585
GRANT statement, 764 CREATE TEXT CONFIGURATION statement
REVOKE statement, 863 syntax, 647
CREATE PROCEDURE statement CREATE TEXT INDEX statement
syntax, 585 syntax, 649
syntax for creating web services procedures, 575 CREATE TRIGGER statement
syntax for interfacing to native procedures, 567 syntax, 651
Transact-SQL syntax, 583 Transact-SQL syntax, 657
CREATE PUBLICATION statement trigger operation conditions, 653
MobiLink syntax, 592 CREATE USER statement
SQL Remote syntax, 592 character set conversion on passwords, 659
CREATE REMOTE MESSAGE TYPE statement password maximum length, 659
SQL Remote syntax, 596 passwords, character set conversion on, 659
CREATE SCHEMA statement syntax, 658
syntax, 597 CREATE VARIABLE statement

1306 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


syntax, 660 creating domains
CREATE VIEW statement CREATE DOMAIN statement, 519
syntax, 661 creating external logins
CREATEDIRS clause CREATE EXTERNLOGIN statement, 534
CREATE SERVER statement, 603 creating indexes
creating CREATE INDEX statement, 553
backups of databases using the BACKUP creating login policies
statement, 477 CREATE LOGIN POLICY statement, 558
CREATE INDEX statement, 553 creating materialized views
CREATE MATERIALIZED VIEW statement, 560 CREATE MATERIALIZED VIEW statement, 560
CREATE PUBLICATION statement, 592 creating synchronization profiles
CREATE SYNCHRONIZATION PROFILE CREATE SYNCHRONIZATION PROFILE
statement, 628 statement [MobiLink], 628
CREATE SYNCHRONIZATION creating synchronization subscriptions
SUBSCRIPTION statement, 629 CREATE SYNCHRONIZATION
CREATE TABLE statement, 633 SUBSCRIPTION statement [MobiLink], 629
CREATE TRIGGER statement, 651 creating tables
CREATE VIEW statement, 661 CREATE TABLE statement, 633
creating users using CREATE USER statement, creating views
658 CREATE VIEW statement, 661
cursors, 666 CROSS APPLY clause
database files using the CREATE DBSPACE FROM clause, 742
statement, 515 CROSS JOIN clause
databases using the CREATE DATABASE FROM clause SQL syntax, 738
statement, 508 CSCONVERT function
local temporary tables, 672 syntax, 183
local temporary tables using the CREATE LOCAL CUBE operation
TEMPORARY TABLE statement, 556 GROUP BY clause, 767
messages, 563 WITH CUBE clause, 767
proxy tables, 635 CUME_DIST function
proxy tables using sp_remote_tables system syntax, 185
procedure, 1172 CURRENT clause
proxy tables using the CREATE EXISTING DISCONNECT statement [ESQL] [Interactive
TABLE statement, 532 SQL] statement, 688
savepoints, 870 CURRENT DATABASE clause
schemas, 597 CREATE TABLE statement, 633
servers, 601 CURRENT DATABASE special value
SQL Remote remote message types, 596 syntax, 58
SQL variables using CREATE VARIABLE CURRENT DATE clause
statement, 660 CREATE TABLE statement, 633
SQL variables using DECLARE statement, 673 CURRENT DATE function
stored procedures, 585 TODAY function, 363
subscriptions, 626 CURRENT DATE special value
text configuration objects for full text search, 647 syntax, 58
text indexes for full text search, 649 CURRENT PUBLISHER clause
triggers in Transact-SQL, 657 CREATE TABLE statement, 633
creating databases CURRENT PUBLISHER data type
CREATE DATABASE statement, 508 setting, 756

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1307


Index

CURRENT PUBLISHER special value listing per connection, 1069


syntax, 59 looping over, 733
CURRENT REMOTE USER clause OPEN statement, 822
CREATE TABLE statement, 633 opening, 821
CURRENT REMOTE USER special value preparing statements, 833
syntax, 59 re-describing in external procedures, 570
CURRENT TIME clause re-describing in user defined procedures, 587
CREATE TABLE statement, 633 updatability set in SELECT statement, 876
CURRENT TIME special value CYCLE clause
syntax, 60 ALTER SEQUENCE statement, 428
CURRENT TIMESTAMP clause CREATE SEQUENCE statement, 600
CREATE TABLE statement, 633
CURRENT TIMESTAMP default D
CREATE TABLE statement, 453, 637 data
CURRENT TIMESTAMP special value exporting from tables into files, 825
syntax, 61 importing into tables from files, 773
CURRENT USER clause selecting rows, 871
CREATE TABLE statement, 633 data access plans
CURRENT USER special value getting text specification, 727
syntax, 62 DATA clause
CURRENT UTC TIMESTAMP clause GET DESCRIPTOR statement [ESQL], 751
CREATE TABLE statement, 633 SET DESCRIPTOR statement [ESQL], 882
CURRENT UTC TIMESTAMP default data type conversion functions
CREATE TABLE statement, 454, 638 about, 135
CURRENT UTC TIMESTAMP special value data type conversions
syntax, 63 about, 122
CURRENT_TIMESTAMP special value CAST, 159
syntax, 61 comparing CHAR and NCHAR values, 123
CURRENT_USER special value comparison operators, 122
syntax, 62 converting DOUBLE to NUMERIC, 130
CurrentMultiProgrammingLevel property converting NCHAR to CHAR, 128
setting with sa_server_option, 1127 Java-to-SQL, 130
cursors SQL to Java, 130
changing database option settings, 888 SQL-to-Java, 131
CLOSE statement [ESQL] [SP], 498 when evaluating expressions, 122
declaring, 666 data types
declaring in Transact-SQL, DECLARE CURSOR altering using the ALTER DOMAIN statement,
statement, 670 407
declaring in Transact-SQL, SELECT statement, BIGINT data type, 89
880 BINARY data type, 117
deleting rows from, 676 BIT data type, 90
DESCRIBE statement [ESQL], 681 CHAR data type, 81
describing behavior in external procedures, 570 character, 81
describing behavior in user defined procedures, comparing values, 122
587 compatibility, 127
EXPLAIN statement syntax, 727 converting for comparison operators, 122
fetching rows from, 728 converting Java and SQL, 130
inserting rows using, 837

1308 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


CREATE DOMAIN statement, 519 database cleaner
DATE data type, 107 about, 1012
DATETIME data type, 108 sa_clean_database system procedure, 1012
DATETIMEOFFSET data type, 109 database encryption
DECIMAL data type, 91 CREATE ENCRYPTED DATABASE statement,
DOUBLE data type, 92 521
dropping user-defined using the DROP database extraction
DATATYPE statement, 691 SQL Remote REMOTE RESET statement , 850
FLOAT data type, 93 database files
IMAGE data type, 117 decrypting using CREATE DECRYPTED FILE
INTEGER data type, 94 statement, 518
LONG BINARY data type, 118 decrypting with CREATE DECRYPTED
LONG NVARCHAR data type, 83 DATABASE statement, 517
LONG VARBIT data type, 99 dropping using the DROP DATABASE statement,
LONG VARCHAR data type, 83 690
NCHAR, 84 encrypting using the CREATE ENCRYPTED
NCHAR (NATIONAL CHAR), 84 DATABASE statement, 521
NTEXT data type, 85 encrypting using the CREATE ENCRYPTED
NUMERIC data type, 95 FILE statement, 524
NVARCHAR data type, 85 storing indexes in, 554
REAL data type, 96 database ID numbers
retrieving, 222 DB_ID function, 201
rounding errors, 89 database mirroring
SMALLDATETIME data type, 111 ALTER MIRROR SERVER statement, 420
SMALLINT data type, 97 CREATE MIRROR SERVER statement, 564
SMALLMONEY data type, 99 dropping servers, 699
special values, 58 initiating a failover, 402
SQL conversion functions, 135 LOAD TABLE statement restrictions, 804
SYSDOMAIN system view, 1203 SET MIRROR OPTION statement, 883
SYSEXTERNLOGIN system view, 1207 database names
SYSUSERTYPE system view, 1256 returning with the DB_NAME function, 201
TEXT data type, 86 database objects
TIME data type, 112 adding comments using the COMMENT statement,
TIMESTAMP data type, 113 499
TIMESTAMP WITH TIME ZONE data type, 115 identifying, 4
TINYINT data type, 97 database options
Unicode, 81 fetching rows from cursors, 888
UNIQUEIDENTIFIER data type, 118 initial settings and sp_login_environment system
UNIQUEIDENTIFIERSTR data type, 87 procedure, 1164
user-defined domains, 120 initial settings and sp_tsql_environment system
VARBINARY data type, 119 procedure, 1173
VARBIT data type, 100 quoted_identifier and T-SQL compatibility, 31
VARCHAR data type, 87 setting in Transact-SQL, 901
XML data type, 88 Transact-SQL compatibility, 1173
data-type user-defined options, 887
common element in SQL syntax, 395 database schemas
DATABASE clause system tables, 965
CONNECT statement, 504 system views, 1195

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1309


Index

database server messages window upgrading jConnect using the ALTER


displaying messages on, 818 DATABASE statement, 400
database servers validating using sa_validate system procedure,
database mirroring, ALTER MIRROR SERVER 1157
statement, 420 DataLastModified property
database mirroring, CREATE MIRROR SERVER sa_materialized_view_info system procedure, 1078
statement, 564 DATALENGTH function
read-only scale-out, ALTER MIRROR SERVER syntax, 186
statement, 420 DATATYPE clause
read-only scale-out, CREATE MIRROR SERVER ALTER SERVICE statement [SOAP web service],
statement, 564 436
setting options with sa_server_option system CREATE SERVICE statement [SOAP web
procedure, 1120 service], 437, 612
START SERVER statement, 910 Date
STOP SERVER statement, 921 HTTP_RESPONSE_HEADER function, 244
DATABASE SIZE clause date and time data types
CREATE DATABASE statement, 511 about, 101
database validation DATE, 107
VALIDATE CHECKSUM statement, 955 DATETIME, 108
VALIDATE INDEX statement, 955 DATETIMEOFFSET, 109
DatabaseCleaner property ISO 8601, 102
setting with sa_server_option, 1127 SMALLDATETIME, 111
databases TIME, 112
backing up using the BACKUP statement, 477 TIMESTAMP, 113
checkpointing using the CHECKPOINT statement, TIMESTAMP WITH TIME ZONE, 115
497 DATE data type
connecting to using the CONNECT statement, 504 comparing with dates and times, 125
creating an encrypted copy of a database, 521 ISO 8601 calendar date, 102
creating files using the CREATE DBSPACE ISO 8601 ordinal date, 102
statement, 515 ISO 8601 week date, 102
creating using the CREATE DATABASE resolving ambiguous dates, 103
statement, 508 sending dates and times to the database, 102
default system views, 1195 syntax, 107
disabling connections, 1120 DATE function
dropping files using the DROP DATABASE syntax, 187
statement, 690 date functions
loading bulk data into, 792 alphabetical list, 136
migrating, 1083 date parts
restoring from archives, 855 about, 136
returning the location of the current database, 200 DATEADD function
schema (list of tables), 1195 syntax, 188
schema (list of views), 965 DATEDIFF function
starting, 907 syntax, 189
SYSFILE system view, 1281 datefirst option
system procedures, 995 SET statement syntax, 901
system tables, 965 DATEFORMAT function
unloading data using the UNLOAD statement, 937 syntax, 191
DATENAME function

1310 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


syntax, 192 syntax, 202
DATEPART function db_register_a_callback function
syntax, 192 using with MESSAGE TO CLIENT, 821
dates DBA
comparing, 125 granting authority with GRANT statement, 762
conversion functions, 136 DBA authority
converting from strings, 127 GRANT statement, 760
February 29, 107 REVOKE statement, 863
generating table of, 1115 DBA authority clause
inserting, 107 GRANT statement, 762
interpretation, 107 DBA clause
leap years, 107 REVOKE statement, 863
queries, 106 DBA PASSWORD clause
query the current system date, 229 CREATE DATABASE statement, 511
retrieving, 107 DBA USER clause
sending to the database, 102 CREATE DATABASE statement, 511
SQL Anywhere, 101 DBFILE ONLY clause
storing, 101 BACKUP statement, 478
datetime DBFreePercent event condition
conversion functions, 136 about, 215
DATETIME data type DBFreeSpace event condition
sending dates and times to the database, 102 about, 215
syntax, 108 dbmlsync utility
DATETIME function specifying location using ALTER EXTERNAL
syntax, 193 ENVIRONMENT statement , 410
DATETIMEOFFSET data type dbname FORCE START clause
sending dates and times to the database, 102 ALTER DATABASE statement, 402
syntax, 109 dbo user
DAY function RowGenerator system table, 994
syntax, 194 Transact-SQL compatibility views, 1288
day of week DBSize event condition
DOW function, 209 about, 215
DAYNAME function dbspaces
syntax, 195 adding comments using the COMMENT statement,
DAYS function 499
syntax, 195 adding pages, 405
DB2 altering using the ALTER DBSPACE statement,
migrating to SQL Anywhere using sa_migrate 405
system procedure, 1084 creating using the CREATE DBSPACE statement,
db_charset 515
CSCONVERT function, 183 decrypting using CREATE DECRYPTED
DB_EXTENDED_PROPERTY function DATABASE statement, 517
syntax, 197 decrypting using CREATE DECRYPTED FILE
DB_ID function statement, 518
syntax, 201 determining available space, 1043
DB_NAME function dropping using the DROP DBSPACE statement,
syntax, 201 692
DB_PROPERTY function

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1311


Index

encrypting using the CREATE ENCRYPTED exceptions using DECLARE statement, 673
DATABASE statement, 521 host variables in embedded SQL, 666
encrypting using the CREATE ENCRYPTED variables using DECLARE statement, 673
FILE statement, 524 decoding data
granting usage permissions, 761 BASE64_DECODE function, 152
SYSFILE system view, 1281 HTML_DECODE function, 237
deadlock reporting HTTP_DECODE function, 240
sa_report_deadlocks system procedure, 1110 DECOMPRESS function
deadlock_logging property syntax, 203
setting with sa_server_option, 1127 DECRYPT function
DeadlockLogging property syntax, 204
setting with sa_server_option, 1127 decrypting
deadlocks files using CREATE DECRYPTED DATABASE
logging, 1127 statement, 517
sa_report_deadlocks system procedure, 1110 files using CREATE DECRYPTED FILE
DEALLOCATE DESCRIPTOR statement statement, 518
embedded SQL syntax, 665 materialized views using SQL, 417
DEALLOCATE statement tables using the ALTER TABLE statement, 451
syntax, 665 DEFAULT
deallocating specifying in a CALL statement, 491
descriptor areas, 665 DEFAULT clause
DEBUG ONLY clause ALTER TABLE statement , 453
MESSAGE statement, 819 CREATE DOMAIN statement, 519
debugging CREATE SERVICE statement [HTTP web
controlling MESSAGE statement behavior, 818 service], 605
TRACEBACK, 364 CREATE SERVICE statement [SOAP web
DebuggingInformation property service], 611
setting with sa_server_option, 1127 CREATE TABLE statement, 637
DECIMAL data type special values, 453, 637
syntax, 91 DEFAULT LAST USER
DECLARE CURSOR statement avoid replicating columns in SQL Remote, 782
embedded SQL syntax, 666 DEFAULT login policy
syntax, 666 about, 558
Transact-SQL syntax, 670 DEFAULT TIMESTAMP columns
DECLARE EXCEPTION TIMESTAMP special value, 69
used with BEGIN statement, 484 default values
DECLARE LOCAL TEMPORARY TABLE CURRENT DATABASE, 58
statement CURRENT DATE, 58
syntax, 672 CURRENT PUBLISHER, 59
DECLARE statement CURRENT REMOTE USER, 59
syntax, 673 CURRENT TIME, 60
used with BEGIN statement, 484 CURRENT TIMESTAMP, 61
used with BEGIN statement [TSQL], 486 CURRENT USER, 62
declaring CURRENT UTC TIMESTAMP, 63
cursors, 666 CURRENT_TIMESTAMP, 61
cursors in Transact-SQL, DECLARE CURSOR CURRENT_USER, 62
statement, 670 INSERT statement, 780
cursors in Transact-SQL, SELECT statement, 880 LAST USER, 63

1312 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQLCODE, 67 GRANT statement, 761
SQLSTATE, 67 REVOKE statement, 863
TIMESTAMP, 69 DELETE permission clause
USER, 70 GRANT statement, 762
using DEFAULT for optional parameters, 491 DELETE statement
UTC TIMESTAMP, 71 (positioned) statement syntax, 676
DEFAULT VALUES clause setting database options, 680
INSERT statement, 780 syntax, 678
defaults DELETE statement (positioned)
CREATE TABLE statement, 637 embedded sql syntax, 676
INSERT statement, 780 DELETE TABLE clause
DEFAULTS clause ALTER PUBLICATION statement, 425
LOAD TABLE statement, 797 DELETE TYPE clause
DEFINITION clause ALTER EVENT statement, 409
ALTER SPATIAL REFERENCE SYSTEM deleting
statement, 443 all rows from a table, 933
CREATE SPATIAL REFERENCE SYSTEM columns using the ALTER TABLE statement, 451
statement, 618 database files using the DROP DATABASE
definitions statement, 690
altering tables using the ALTER TABLE dbspaces using the DROP DBSPACE statement,
statement, 451 692
defragmenting domains, 692
REORGANIZE TABLE, 852 events using the DROP EVENT statement, 693
DEGREES function functions using the DROP FUNCTION statement,
syntax, 206 695
DELAY clause granting permissions, 863
WAITFOR statement, 957 indexes using the DROP INDEX statement, 695
DELETE ALL OPTION clause Java classes, 851
ALTER SYNCHRONIZATION SUBSCRIPTION materialized views using the DROP
statement [MobiLink] , 448 MATERIALIZED VIEW statement, 697
ALTER SYNCHRONIZATION USER statement optimizer statistics using the DROP STATISTICS
[MobiLink] , 450 statement, 706
DELETE clause prepared statements using the DROP
CREATE LOCAL TEMPORARY TABLE STATEMENT statement, 706
statement, 556 procedures using the DROP PROCEDURE
CREATE PUBLICATION statement [MobiLink] statement, 700
[SQL Remote], 592 rows from cursors, 676
CREATE TRIGGER statement, 652 rows from databases, 678
DECLARE LOCAL TEMPORARY TABLE SQL variables using the DROP VARIABLE
statement, 672 statement, 716
MERGE statement, 814 START SYNCHRONIZATION DELETE
REVOKE statement, 863 statement, 915
DELETE OPTION clause STOP SYNCHRONIZATION DELETE statement,
ALTER SYNCHRONIZATION SUBSCRIPTION 924
statement [MobiLink] , 448 tables using the DROP TABLE statement, 711
ALTER SYNCHRONIZATION USER statement text configuration objects, 712
[MobiLink] , 450 triggers using the DROP FUNCTION statement,
DELETE permission 695

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1313


Index

triggers using the DROP statement, 714 setting, 882


views using the DROP VIEW statement, 716 UPDATE (positioned) statement, 943
DELIMITED BY clause DESCRIPTOR clause
LOAD TABLE statement, 797 EXECUTE statement, 722
OUTPUT statement, 826 descriptors
UNLOAD statement, 939 DESCRIBE statement [ESQL], 681
DELIMITED clause FETCH statement, 728
INPUT statement, 774 preparing statements, 833
delimited strings DETACH TRACING statement
compatibility with ASE, 31 diagnostic tracing, 687
delimiting SQL strings syntax, 687
about, 4 deterministic behavior
DENSE_RANK function external functions, 537
syntax, 206 user-defined functions, 549
denying diagnostic tracing
granting permissions, 863 ATTACH TRACING statement, 475
dependencies deleting records, 1110
determining using sa_dependent_views system DETACH TRACING statement, 687
procedure, 1033 REFRESH TRACING LEVEL statement, 848
dependent variables sa_diagnostic_auxiliary_catalog table, 980
regression line, 308 sa_diagnostic_blocking table, 981
derived tables sa_diagnostic_cachecontents table, 982
example in a FROM clause, 741 sa_diagnostic_connection table, 982
FROM clause SQL syntax, 738 sa_diagnostic_cursor table, 983
lateral, 741 sa_diagnostic_deadlock table, 984
using in subqueries, 662 sa_diagnostic_hostvariable table, 985
DESCRIBE clause sa_diagnostic_internalvariable table, 986
PREPARE statement, 833 sa_diagnostic_query table, 987
DESCRIBE CONNECTION statement sa_diagnostic_request table, 989
Interactive SQL syntax, 684 sa_diagnostic_statement table, 990
DESCRIBE statement sa_diagnostic_statistics table, 990
DT_DESCRIBE_INPUT, 682 sa_diagnostic_tracing_level table, 991
DT_HIDDEN_COLUMN, 667 sa_save_trace_data system procedure, 1116
DT_KEY_COLUMN, 667 sa_set_tracing_level system procedure, 1140
DT_PROCEDURE_IN, 682 tables, about, 980
DT_PROCEDURE_OUT, 682 diagnostic tracing level
embedded SQL syntax, 681 setting at the command line, 1140
Interactive SQL syntax, 684 diagnostics
long column names, 683 sa_performance_statistics system procedure, 1101
describing DIFFERENCE function
cursor behavior in external procedures, 570 syntax, 208
cursor behavior in user defined procedures, 587 directory access servers
cursors, 681 CREATE SERVER statement, 601
descriptor areas DIRECTORY clause
allocating memory for, 398 BACKUP statement, 477
deallocating, 665 START DATABASE statement, 908
EXECUTE statement, 722 DISABLE clause
getting information from, 751 ALTER EVENT statement, 408

1314 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


ALTER MATERIALIZED VIEW statement, 418 SELECT statement, 873
ALTER SERVICE statement [HTTP web service], DISTINCT keyword
431 about, 873
ALTER SERVICE statement [SOAP web service], DML
436 selecting from, 743
ALTER VIEW statement, 473 DO clause
CREATE SERVICE statement [HTTP web FOR statement, 733
service], 433, 607 documentation
CREATE SERVICE statement [SOAP web conventions for SQL syntax, 395
service], 439, 614 DOMAIN | DATATYPE clause
DISABLE USE IN OPTIMIZATION clause CREATE DOMAIN statement, 520
ALTER MATERIALIZED VIEW statement, 418 domains
DISABLE VIEW DEPENDENCIES clause about, 120
ALTER TABLE statement, 462 altering using the ALTER DOMAIN statement,
disabled objects 407
permissions, 764 CREATE DOMAIN statement, 519
disabling connections dropping using the DROP DOMAIN statement,
to all databases on a server, 1127 692
to individual databases, 1127 nullability, 520
DISCONNECT statement Transact-SQL, 121
embedded SQL syntax, 688 DOUBLE data type
Interactive SQL syntax, 688 comparing with dates and times, 125
disconnecting converting to NUMERIC, 130
creating events using the CREATE EVENT syntax, 92
statement, 526 double hyphen
DROP CONNECTION statement, 689 comment indicator, 79
DISH double quotes
CREATE SERVICE statement [SOAP web database objects, 4
service], 437, 612 not allowed in SQL identifiers, 4
DISH services double slash
forward slashes not allowed in name, 437, 611 comment indicator, 79
disk space DOW function
creating events using the CREATE EVENT syntax, 209
statement, 526 download-only
creating out of disk space events, 526 CREATE PUBLICATION syntax, 592
determining available space, 1043 DRIVER clause
disk transfer time model INPUT statement, 773
calibrating using the ALTER DATABASE DriveType property
statement, 400 DB_EXTENDED_PROPERTY function, 197
current value, 1050 DROP clause
restoring the default using the ALTER ALTER TABLE statement , 460
DATABASE statement, 400 DROP EXTERNLOGIN statement, 694
displaying DROP CONNECTION statement
messages, 818 syntax, 689
messages in the messages window, 836 DROP DATABASE statement
DISTINCT clause syntax, 690
MEDIAN function, 270 DROP DATATYPE statement
NULL, 65 syntax, 691

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1315


Index

DROP DBSPACE statement SQL Remote syntax, 707


syntax, 692 DROP SYNCHRONIZATION PROFILE statement
DROP DOMAIN statement MobiLink syntax, 709
syntax, 692 DROP SYNCHRONIZATION SUBSCRIPTION
DROP EVENT statement statement
syntax, 693 syntax, 709
DROP EXTERNLOGIN statement DROP SYNCHRONIZATION USER statement
syntax, 694 MobiLink syntax, 710
DROP FUNCTION statement DROP TABLE clause
syntax, 695 ALTER PUBLICATION statement, 425
DROP INDEX statement DROP TABLE statement
syntax, 695 syntax, 711
DROP LOGIN POLICY statement DROP TEXT CONFIGURATION statement
syntax, 696 syntax, 712
DROP MATERIALIZED VIEW statement DROP TEXT INDEX statement
syntax, 697 syntax, 713, 714
DROP MESSAGE statement DROP TRIGGER statement
syntax, 698 syntax, 714
DROP MIRROR SERVER statement DROP USER statement
syntax, 699 syntax, 715
DROP PCTFREE clause DROP VARIABLE statement
ALTER MATERIALIZED VIEW statement, 418 syntax, 716
DROP PREFILTER clause DROP VIEW statement
ALTER TEXT CONFIGURATION statement, 466 syntax, 716
DROP PROCEDURE statement DropBadStatistics property
syntax, 700 setting with sa_server_option, 1127
DROP PUBLICATION statement dropping
MobiLink syntax, 701 columns using the ALTER TABLE statement, 451
SQL Remote syntax, 701 connections in Interactive SQL, 688
DROP REMOTE MESSAGE TYPE statement connections using the DROP CONNECTION
SQL Remote syntax, 701 statement, 689
DROP SEQUENCE statement database files using the DROP DATABASE
syntax, 702 statement, 690
DROP SERVER statement dbspaces using the DROP DBSPACE statement,
syntax, 703 692
DROP SERVICE statement domains using the DROP DOMAIN statement, 692
syntax, 704 DROP PUBLICATION statement, 701
DROP SPATIAL REFERENCE SYSTEM statement DROP SUBSCRIPTION statement, 707
syntax, 704 DROP SYNCHRONIZATION SUBSCRIPTION
DROP SPATIAL UNIT OF MEASURE statement statement, 709
syntax, 705 DROP SYNCHRONIZATION USER statement,
DROP STATEMENT statement 710
embedded SQL syntax, 706 events using the DROP EVENT statement, 693
DROP STATISTICS statement functions using the DROP FUNCTION statement,
syntax, 706 695
DROP STOPLIST clause indexes using the DROP INDEX statement, 695
ALTER TEXT CONFIGURATION statement, 465 login policies using DROP LOGIN POLICY
DROP SUBSCRIPTION statement statement, 696

1316 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


login policies using DROP USER statement, 715 DT_DESCRIBE_INPUT
logins for remote servers, 694 DESCRIBE statement, 682
materialized views using the DROP DT_HIDDEN_COLUMN
MATERIALIZED VIEW statement, 697 DESCRIBE statement, 667
messages using the DROP MESSAGE statement, DT_KEY_COLUMN
698 DESCRIBE statement, 667
optimizer statistics using the DROP STATISTICS DT_PROCEDURE_IN
statement, 706 DESCRIBE statement, 682
prepared statements using the DROP DT_PROCEDURE_OUT
STATEMENT statement, 706 DESCRIBE statement, 682
procedures using the DROP PROCEDURE DUMMY
statement, 700 Row Constructor algorithm, 965
remote message types, 701 system table, 965
remote servers using the DROP SERVER DYNAMIC RESULT SETS clause
statement, 703 CREATE PROCEDURE statement [External call],
spatial reference system using the DROP 570
SPATIAL REFERENCE SYSTEM statement, 704 DYNAMIC SCROLL clause
SQL variables using the DROP VARIABLE DECLARE CURSOR statement, 667
statement, 716 FOR statement, 733
tables using the DROP TABLE statement, 711 DYNAMIC SCROLL cursors
text configuration objects, 712 declaring, 666
text indexes for full text search, 713 dynamic SQL
triggers using the DROP FUNCTION statement, executing procedures in, 719
695
triggers using the DROP statement, 714 E
users using the REVOKE statement, 863 elements
views using the DROP VIEW statement, 716 SQL language syntax, 1
web services using the DROP SERVICE statement, ELLIPSOID clause
704 ALTER SPATIAL REFERENCE SYSTEM
dropping connections statement, 443
DROP CONNECTION statement, 689 CREATE SPATIAL REFERENCE SYSTEM
dropping indexes statement, 621
DROP statement, 695 ELSE
dropping materialized views CASE expression, 16
DROP MATERIALIZED VIEW statement, 697 IF expressions, 15
dropping remote procedures ELSE clause
DROP PROCEDURE statement, 700 IF statement, 769
dropping synchronization profiles IF statement [T-SQL], 771
DROP SYNCHRONIZATION PROFILE ELSEIF clause
statement [MobiLink], 709 IF statement, 769
dropping tables email
DROP TABLE statement, 711 extended system procedures, 996
dropping views system procedures, 1183
DROP VIEW statement, 716 embedded SQL
DropUnusedStatistics property ALLOCATE DESCRIPTOR syntax, 398
setting with sa_server_option, 1127 BEGIN DECLARE statement syntax, 666
DSN clause CLOSE statement syntax, 498
INPUT statement, 773

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1317


Index

CONNECT statement syntax, 504 INPUT statement, 774


DEALLOCATE DESCRIPTOR statement syntax, LOAD TABLE statement, 797
665 OUTPUT statement, 826
DECLARE CURSOR statement syntax, 666 READ statement [Interactive SQL], 840
DELETE (positioned) statement syntax, 676 UNLOAD statement, 939
DESCRIBE statement syntax, 681 encoding data
DISCONNECT statement syntax, 688 BASE64_ENCODE function, 152
DROP STATEMENT statement syntax, 706 HTML_ENCODE function, 238
END DECLARE statement syntax, 666 encodings
EXECUTE IMMEDIATE statement syntax, 719 CREATE DATABASE statement, 511
EXECUTE statement syntax, 722 ENCRYPT function
EXPLAIN statement syntax, 727 syntax, 210
FETCH statement syntax, 728 ENCRYPTED clause
GET DATA statement syntax, 749 ALTER MATERIALIZED VIEW statement, 418
GET DESCRIPTOR statement syntax, 751 CREATE DATABASE statement, 512
GET OPTION statement syntax, 753 CREATE TABLE statement, 635
INCLUDE statement syntax, 772 LOAD TABLE statement, 798
OPEN statement syntax, 821 UNLOAD statement, 939
PREPARE statement syntax, 833 ENCRYPTED DATABASE clause
PUT statement syntax, 837 CREATE ENCRYPTED DATABASE statement,
SET CONNECTION statement syntax, 881 522
SET DESCRIPTOR statement syntax, 882 ENCRYPTED TABLE clause
SET SQLCA statement syntax, 898 CREATE DATABASE statement, 512
UPDATE (positioned) statement, 943 ENCRYPTED TABLE DATABASE clause
WHENEVER statement syntax, 959 CREATE ENCRYPTED TABLE DATABASE
ENABLE clause statement, 522
ALTER MATERIALIZED VIEW statement, 417 encrypting
ALTER SERVICE statement [HTTP web service], databases, CREATE ENCRYPTED DATABASE
431 statement, 521
ALTER SERVICE statement [SOAP web service], materialized views using SQL, 417
436 encrypting tables
ALTER VIEW statement, 473 ALTER TABLE statement, 451
CREATE SERVICE statement [HTTP web encryption
service], 433, 607 CREATE DATABASE statement, 512
CREATE SERVICE statement [SOAP web CREATE DECRYPTED DATABASE statement,
service], 439, 614 517
ENABLE USE IN OPTIMIZATION clause CREATE ENCRYPTED FILE statement, 524
ALTER MATERIALIZED VIEW statement, 418 encryption algorithms
ENABLE | DISABLE clause CREATE DATABASE statement, 512
CREATE EVENT statement, 530 encryption keys
encoding changing the key for an encrypted database, 526
INPUT statement, 774 END
LOAD TABLE syntax, 792 CASE expression, 16
OUTPUT statement, 826 END CASE
READ statement, 840 CASE expression, 16
UNLOAD statement, 937 END DECLARE statement
ENCODING clause embedded SQL syntax, 666
CREATE DATABASE statement, 511 END FOR clause

1318 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


FOR statement, 733 OUTPUT statement, 825
END IF ESCAPE clause
IF expressions, 15 LIKE search condition, 39
END IF clause escape sequences
IF statement, 769 backslashes in SQL strings, 7
END keyword hexadecimal values in SQL strings, 7
TSQL compatibility, 486 new line characters in SQL strings, 7
END LOOP clause single quotes in SQL strings, 7
LOOP statement, 810 Unicode, 371
END statement Unicode values in SQL strings, 7
used with BEGIN statement, 484 ESCAPES clause
used with BEGIN statement [TSQL], 486 INPUT statement, 775
ENDIF LOAD TABLE statement, 798
IF expressions, 15 OUTPUT statement, 827
ENDIF clause UNLOAD statement, 939
IF statement, 769 ESQL
ending statement indicators, 398
rolling back transactions, 865 establishing
engines savepoints, 870
starting database, 910 ESTIMATE function
stopping database, 921 syntax, 212
ENVIRONMENT clause ESTIMATE_SOURCE function
INSTALL EXTERNAL OBJECT statement, 785 syntax, 213
environments estimates
altering using ALTER EXTERNAL explicit selectivity estimates, 56
ENVIRONMENT statement, 410 EvenOdd format
error messages CREATE SPATIAL REFERENCE SYSTEM
ERRORMSG function, 212 statement, 622
ERRORMSG function event conditions
syntax, 212 list, 215
ErrorNumber event condition event handlers
about, 215 hiding using the ALTER EVENT statement, 408
errors EVENT_CONDITION function
creating events using the CREATE EVENT syntax, 215
statement, 526 EVENT_CONDITION_NAME function
RAISERROR statement, 838 syntax, 216
signaling, 906 EVENT_PARAMETER function
trapping in embedded SQL, 959 syntax, 217
user-defined messages, 1256 events
ESCAPE CHARACTER clause adding comments using the COMMENT statement,
INPUT statement, 775 499
LOAD TABLE statement, 798 ALTER EVENT statement, 408
OUTPUT statement, 826 altering using the ALTER EVENT statement, 408
UNLOAD statement, 940 CREATE EVENT statement, 526
escape characters disabling, 408
about , 7 DROP EVENT statement, 693
binary literals, 6 dropping using the DROP EVENT statement, 693
INPUT statement, 773 EVENT_PARAMETER, 217

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1319


Index

scheduling using the ALTER EVENT statement, Interactive SQL, 725


408 procedures, 858
scheduling using the CREATE EVENT statement, EXP function
526 syntax, 219
TRIGGER EVENT statement, 932 EXPERIENCE_ESTIMATE function
triggering, 932 syntax, 220
EVERY clause Expires
CREATE EVENT statement, 529 HTTP_RESPONSE_HEADER function, 244
EXCEPT clause EXPLAIN statement
setting database options, 718 embedded SQL syntax, 727
EXCEPT statement EXPLANATION function
syntax, 717 syntax, 221
EXCEPTION clause explicit selectivity estimates
BEGIN statement, 484 about, 56
exceptions exponential function
declaring using DECLARE statement, 673 EXP function, 219
resignaling, 854 exporting
signaling, 906 BLOBs, 1192
exclusive OR unloading data using the UNLOAD statement, 937
bitwise operator, 11 exporting data
EXEC statement tables into files, 825
Transact-SQL syntax, 724 expressions
EXECUTE IMMEDIATE statement about, 12
syntax, 719 arithmetic operators, 10
EXECUTE LOGIN permission CASE expressions, 16
GRANT statement, 760 column names, 14
EXECUTE statement common element in SQL syntax, 395
embedded SQL syntax, 722 constants, 14
Transact-SQL syntax, 724 data types of, 222
Transact-SQL syntax, about, 724 IF expressions, 15
executing SQL operator precedence, 12
operating system commands, 931 string operators, 10
prepared statements, 722 subqueries, 15
resuming execution of procedures, 857 syntax, 12
SQL statements from files, 840 Transact-SQL compatibility, 31
stored procedures in Transact-SQL, 724 EXPRTYPE function
execution plans syntax, 222
example of saving a plan to a file, 230 extended procedures
execution time about, 996
START LOGGING statement, 913 external environments
EXISTS search condition adding comments using the COMMENT statement,
search conditions, 32 499
syntax, 53 starting using the START EXTERNAL
exit codes ENVIRONMENT statement, 911
EXIT statement [Interactive SQL], 725 stopping using the STOP EXTERNAL
EXIT statement ENVIRONMENT statement, 919
Interactive SQL syntax, 725 external functions
exiting

1320 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


interfacing to native functions using CREATE SQL Remote ALTER REMOTE MESSAGE
FUNCTION statement, 535 TYPE statement, 426
interfacing to native procedures using CREATE SQL Remote CREATE REMOTE MESSAGE
PROCEDURE statement, 567 TYPE statement, 596
external logins File property
assigning for remote servers, 534 DB_EXTENDED_PROPERTY function, 197
dropping for remote servers, 694 file size
EXTERNAL NAME clause creating events using the CREATE EVENT
ALTER TEXT CONFIGURATION statement, 465 statement, 526
CREATE FUNCTION statement [external filename
procedures], 537 common element in SQL syntax, 395
CREATE PROCEDURE statement [external files
procedures], 571 allocating space for database, 405
external objects creating database using the CREATE DBSPACE
creating using the INSTALL EXTERNAL statement, 515
OBJECT statement, 785 decrypting using CREATE DECRYPTED FILE
removing using the REMOVE EXTERNAL statement, 518
OBJECT statement, 851 decrypting with CREATE DECRYPTED
SYSEXTERNENVOBJECT system view, 1206 DATABASE statement, 517
external procedures encrypting using the CREATE ENCRYPTED
interfacing to native procedures using CREATE FILE statement, 524
PROCEDURE statement, 567 exporting data from tables into, 825
external term breakers importing data into tables from, 773
ALTER TEXT CONFIGURATION statement, 466 querying within files, 741
reading on a client computer, 304
F reading SQL statements from, 840
FALSE conditions writing to a client computer, 382
IS FALSE search condition, 54 xp_read_file system procedure, 1182
three-valued logic, 55 xp_write_file system procedure, 1192
FASTFIRSTROW table hint FileSize property
FROM clause, 745 DB_EXTENDED_PROPERTY function, 197
features filler() column name
locking, 807 FROM clause, 741
February 29 LOAD TABLE statement, 792
about, 107 FIRST clause
FETCH statement DELETE statement, 679
embedded SQL syntax, 728 FETCH statement , 729
syntax, 728 SELECT statement, 873
fetching UPDATE statement, 949
rows from cursors, 728 FIRST_VALUE function
FILE clause syntax, 223
DROP REMOTE MESSAGE TYPE statement, FLOAT data type
701 comparing with dates and times, 125
GRANT CONSOLIDATE statement [SQL syntax, 93
Remote], 754 FLOOR function
FILE message type syntax, 225
FOLLOWING clause
WINDOW clause, 962

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1321


Index

FOR clause START SYNCHRONIZATION SCHEMA


ALTER SYNCHRONIZATION SUBSCRIPTION CHANGE statement, 917
statement [MobiLink] , 448 FOR UPDATE BY clause
CREATE SUBSCRIPTION statement [SQL SELECT statement, 876
Remote], 626 FOR UPDATE BY LOCK clause
CREATE SYNCHRONIZATION SELECT statement, 876
SUBSCRIPTION statement [MobiLink], 630 FOR UPDATE BY TIMESTAMP clause
CREATE TRIGGER [Transact-SQL] statement, SELECT statement, 876
657 FOR UPDATE BY VALUES clause
DECLARE CURSOR statement [T-SQL], 670 SELECT statement, 876
DESCRIBE statement [ESQL], 681 FOR UPDATE clause
DROP SUBSCRIPTION statement [SQL Remote], CREATE TRIGGER [Transact-SQL] statement,
707 657
DROP SYNCHRONIZATION SUBSCRIPTION DECLARE CURSOR statement [T-SQL], 670
statement, 710 FETCH statement, 730
MESSAGE statement, 819 FOR statement, 734
SELECT statement, 876 PREPARE statement [ESQL] statement, 833
START SUBSCRIPTION statement [SQL SELECT statement, 876
Remote], 914 FOR UPDATE OF clause
STOP SUBSCRIPTION statement [SQL Remote], SELECT statement, 877
922 FOR UPLOAD clause
SYNCHRONIZE SUBSCRIPTION statement ALTER PUBLICATION statement, 425
[SQL Remote], 930 CREATE PUBLICATION statement [MobiLink]
FOR DELETE clause [SQL Remote], 592
CREATE TRIGGER [Transact-SQL] statement, FOR XML clause
657 EXCEPT statement, 717
FOR DOWNLOAD ONLY clause INTERSECT statement, 788
CREATE PUBLICATION statement [MobiLink] SELECT statement, 877
[SQL Remote], 592 FORCE BUILD clause
FOR EACH clause REFRESH MATERIALIZED VIEW statement,
CREATE TRIGGER statement, 653 844
FOR INSERT clause REFRESH TEXT INDEX statement, 847
CREATE TRIGGER [Transact-SQL] statement, FORCE clause
657 REFRESH TEXT INDEX statement, 847
FOR OLAP WORKLOAD clause FORCE INCREMENTAL clause
CREATE INDEX statement, 555 REFRESH TEXT INDEX statement, 847
CREATE TABLE statement, 643 FORCE INDEX
FOR OLAP WORKLOAD option index hints, 745
ALTER TABLE statement, 451 FORCE NO OPTIMIZATION clause
FOR READ ONLY clause DELETE statement, 680
DECLARE CURSOR statement [T-SQL], 670 INSERT statement, 782
FOR statement, 734 SELECT statement, 877
PREPARE statement [ESQL] statement, 833 UPDATE statement, 951
SELECT statement, 876 FORCE OPTIMIZATION clause
START DATABASE statement, 908 DELETE statement, 680
FOR statement EXCEPT statement, 718
syntax, 733 INSERT statement, 782
FOR TABLES clause INTERSECT statement, 789

1322 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


MERGE statement, 816 FORMAT TEXT clause
SELECT statement, 877 INPUT statement, 775
UNION statement, 936 LOAD TABLE statement, 798
UPDATE statement, 951 FORMAT XML clause
FORCE PASSWORD CHANGE clause LOAD TABLE statement, 799
ALTER USER statement, 471 FORWARD TO statement
CREATE USER statement, 658 syntax, 736
FORCE START clause fragmentation
ALTER DATABASE statement, 403 defragmenting using REORGANIZE TABLE, 852
FOREIGN KEY clause sa_index_density system procedure, 1063
ALTER INDEX statement, 413 sa_table_fragmentation , 1145
CREATE TABLE statement, 633 FREE PAGE ELIMINATION clause
REORGANIZE TABLE statement, 853 BACKUP statement, 480
VALIDATE statement, 955 FreePages property
foreign keys DB_EXTENDED_PROPERTY function, 197
adding comments using the COMMENT statement, frequency
499 sending messages, GRANT CONSOLIDATE
ALTER INDEX statement, 413 statement [SQL Remote], 754
clustering using the ALTER INDEX statement, sending messages, GRANT REMOTE statement
413 [SQL Remote] , 758
consolidated views, 1268 FROM clause
integrity constraints in CREATE TABLE CREATE DECRYPTED DATABASE statement,
statement, 641 517
renaming using the ALTER INDEX statement, 413 CREATE DECRYPTED FILE statement, 518
sp_remote_exported_keys system procedure, 1166 CREATE ENCRYPTED DATABASE statement,
sp_remote_imported_keys system procedure, 1167 522
system views, 1208 CREATE ENCRYPTED FILE statement, 524
unnamed in CREATE TABLE statement, 641 CREATE ENCRYPTED TABLE DATABASE
foreign tables statement, 522
system views, 1208 CREATE TEXT CONFIGURATION statement,
forest 648
in unparsed XML document, 388 DELETE (positioned) statement [ESQL] [SP]
FORMAT BCP clause statement, 676
LOAD TABLE statement, 798 DELETE statement, 679
FORMAT clause GRANT statement, 763
ALTER SERVICE statement [SOAP web service], INSTALL EXTERNAL OBJECT statement, 785
436 INSTALL JAVA statement, 788
CREATE SERVICE statement [SOAP web LOAD TABLE statement, 794
service], 438, 613 PUT statement [ESQL], 837
INPUT statement, 775 RESTORE DATABASE statement, 855
LOAD TABLE statement, 798 REVOKE REMOTE DBA statement [SQL
OUTPUT statement, 827 Remote], 861
UNLOAD statement, 939 REVOKE statement, 863
FORMAT FIXED clause SELECT statement, 875
INPUT statement, 775 selecting from DML, 743
FORMAT SHAPEFILE clause selecting from stored procedures, 740
INPUT statement, 776 syntax, 738
LOAD TABLE statement, 799 UPDATE (positioned) statement, 943

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1323


Index

UPDATE statement, 950 creating SQL stored functions, 548


FROM FILE clause creating using the CREATE FUNCTION statement
INSTALL EXTERNAL OBJECT statement, 785 [Web service], 541
INSTALL JAVA statement, 787 data type conversion SQL, 135
FROM SERVER clause date and time, 136
ALTER MIRROR SERVER statement, 421 dropping using the DROP FUNCTION statement,
CREATE MIRROR SERVER statement, 565 695
FROM VALUE clause exiting from user-defined, 858
INSTALL EXTERNAL OBJECT statement, 785 HTTP, 141
FTP clause image SQL, 145
GRANT CONSOLIDATE statement [SQL indexes on, 554
Remote], 754 interfacing to native functions using CREATE
FTP message type FUNCTION statement, 535
SQL Remote ALTER REMOTE MESSAGE interfacing to native procedures using CREATE
TYPE statement, 426 PROCEDURE statement, 567
SQL Remote CREATE REMOTE MESSAGE introduction, 133
TYPE statement, 596 Java, 138
full text search miscellaneous, 140
ALTER TEXT CONFIGURATION statement, 465 native function calls, 537
ALTER TEXT INDEX statement, 468 numeric, 140
asterisk, allowed syntax, 50 ranking, 135
CONTAINS clause in the FROM clause, 738 replacing external function interface, 536
CONTAINS search condition, 47 returning values from user-defined, 858
CREATE TEXT CONFIGURATION statement, SOAP, 141
647 string, 142
CREATE TEXT INDEX statement, 649 system, 144
DROP TEXT CONFIGURATION statement, 712 temporary, 549
DROP TEXT INDEX statement, 713 text SQL, 145
hyphen, allowed syntax, 51 types of functions, 133
operator precedence, 50 user defined, 138
REFRESH TEXT INDEX statement, 846 functions, aggregate
sa_char_terms system procedure, 1009 about, 133
sa_nchar_terms system procedure, 1094 AVG, 150
sa_refresh_text_indexes system procedure, 1109 BIT_AND, 153
sa_text_index_stats system procedure, 1149 BIT_OR, 155
sa_text_index_vocab system procedure, 1150 BIT_XOR, 157
sa_text_index_vocab_nchar system procedure, COUNT, 177
1152 COUNT_BIG, 179
snapshot isolation compatibility, 650 FIRST_VALUE, 223
syntax for special characters, 52 GROUPING, 231
TRUNCATE TEXT INDEX statement, 935 LAST_VALUE, 255
warning about using non-alphanumerics in query LIST, 261
string, 49 MAX, 268
functions MEDIAN, 269
aggregate, 133 MIN, 271
ALTER FUNCTION statement, 412 SET_BITS, 334
bit array, 135 STDDEV, 346
compared to procedures, 139 STDDEV_POP, 346

1324 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


STDDEV_SAMP, 348 SYSDATETIMEOFFSET, 358
SUM, 355 TODATETIMEOFFSET, 362
VAR_POP, 375 TODAY, 363
VAR_SAMP, 377 WEEKS, 380
VARIANCE, 380 YEAR, 390
functions, bit YEARS, 391
GET_BIT, 226 YMD, 392
functions, bit array functions, HTTP
about, 135 HTTP_HEADER, 242
alphabetical list, 135 HTTP_RESPONSE_HEADER, 244
BIT_LENGTH, 154 HTTP_VARIABLE, 245
BIT_SUBSTR, 155 NEXT_HTTP_HEADER, 282
COUNT_SET_BITS, 180 NEXT_HTTP_RESPONSE_HEADER, 284
SET_BIT, 333 NEXT_HTTP_VARIABLE, 285
functions, data type conversion functions, Java and SQL user defined
about, 135 about, 138
CAST, 159 functions, miscellaneous
CONVERT, 172 about, 140
HEXTOINT, 234 ARGN, 147
INTTOHEX, 250 COALESCE, 164
ISDATE, 251 CONFLICT, 167
ISNULL, 253 ERRORMSG, 212
functions, date and time ESTIMATE, 212
about, 136 ESTIMATE_SOURCE, 213
DATE, 187 EXPERIENCE_ESTIMATE, 220
DATEADD, 188 EXPLANATION, 221
DATEDIFF, 189 GET_IDENTITY, 227
DATEFORMAT, 191 GRAPHICAL_PLAN, 229
DATENAME, 192 GREATER, 231
DATEPART, 192 IDENTITY, 247
DATETIME, 193 IFNULL, 248
DAY, 194 INDEX_ESTIMATE, 249
DAYNAME, 195 ISNUMERIC, 254
DAYS, 195 LESSER, 260
DOW, 209 NEWID, 279
GETDATE, 228 NULLIF, 288
HOUR, 235 NUMBER, 288
HOURS, 235 PLAN, 294
MINUTE, 272 REWRITE, 324
MINUTES, 273 SQLDIALECT, 343
MONTH, 275 TRACEBACK, 364
MONTHNAME, 276 TRACED_PLAN, 364
MONTHS, 277 TRANSACTSQL, 365
NOW, 287 VAREXISTS, 379
QUARTER, 300 WATCOMSQL, 380
SECOND, 331 functions, numeric
SECONDS, 332 about, 140
SWITCHOFFSET, 358 ABS, 145

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1325


Index

ACOS, 146 HASH function, 232


ASIN, 148 INSERTSTR, 249
ATAN, 149 LCASE, 257
ATAN2, 150 LEFT, 258
ATN2, 150 LENGTH, 259
CEILING, 160 LOCATE, 264
CONNECTION_PROPERTY, 171 LOWER, 266
COS, 176 LTRIM, 267
COT, 176 NCHAR, 278
DEGREES, 206 PATINDEX, 290
EXP, 219 READ_CLIENT_FILE, 304
FLOOR, 225 REPEAT, 321
LOG, 265 REPLACE, 321
LOG10, 266 REPLICATE, 323
MOD, 275 REVERSE, 323
PI, 294 RIGHT, 326
POWER, 295 RTRIM, 330
RADIANS, 301 SIMILAR, 336
RAND, 301 SORTKEY, 339
REMAINDER, 320 SOUNDEX, 342
ROUND, 327 SPACE, 343
SIGN, 335 STR, 349
SIN, 337 STRING, 350
SQRT, 345 STRTOUUID, 351
TAN, 359 STUFF, 352
TRUNCATE, 368 SUBSTRING, 353
TRUNCNUM, 368 TO_CHAR, 360
functions, ranking TO_NCHAR, 361
about, 135 TRIM, 367
functions, SOAP UCASE, 370
NEXT_SOAP_HEADER, 286 UNICODE, 370
SOAP_HEADER, 338 UNISTR, 371
functions, string UPPER, 372
about, 142 UUIDTOSTR, 374
ASCII, 147 WRITE_CLIENT_FILE, 382
BYTE_LENGTH, 157 XMLAGG, 383
BYTE_SUBSTR, 158 XMLCONCAT, 384
CHAR, 161 XMLELEMENT, 385
CHAR_LENGTH, 162 XMLFOREST, 388
CHARINDEX, 163 XMLGEN, 389
COMPARE, 165 functions, system
COMPRESS function, 166 DATALENGTH, 186
CONNECTION_EXTENDED_PROPERTY, 169 DB_EXTENDED_PROPERTY, 197
CSCONVERT, 183 DB_ID, 201
DECOMPRESS function, 203 DB_NAME, 201
DECRYPT function, 204 DB_PROPERTY, 202
DIFFERENCE, 208 EVENT_CONDITION, 215
ENCRYPT function, 210 EVENT_CONDITION_NAME, 216

1326 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


EVENT_PARAMETER, 217 altering database settings, 402
ISENCRYPTED, 252 creating databases with, 510
NEXT_CONNECTION, 280 validating, 955
NEXT_DATABASE, 282 global temporary tables
PROPERTY, 297 CREATE TABLE statement, 633
PROPERTY_DESCRIPTION, 296 global variables
PROPERTY_NAME, 298 @@identity, 78
PROPERTY_NUMBER, 299 alphabetical list, 75
SUSER_ID, 356 definition, 72
SUSER_NAME, 357 triggers and @@identity, 78
TSEQUAL, 368 global_database_id option
USER_ID, 373 CREATE TABLE statement, 455, 638
USER_NAME, 374 globally unique identifiers
functions, text and image SQL syntax for NEWID function, 279
about, 145 goodness of fit
TEXTPTR, 360 regression lines, 313
fuzzy searches GOTO clause
CONTAINS search condition, 47 WHENEVER statement [ESQL], 959
GOTO statement
G Transact-SQL syntax, 754
geometries GRANT CONNECT TO statement
troubleshooting using st_geometry_dump, 1174 GRANT statement, 761
GET DATA statement GRANT CONSOLIDATE statement
embedded SQL syntax, 749 SQL Remote syntax, 754
GET DESCRIPTOR statement GRANT CREATE ON statement
embedded SQL syntax, 751 syntax, 760
GET OPTION statement GRANT PUBLISH statement
embedded SQL syntax, 753 SQL Remote syntax, 756
GET_BIT function GRANT REMOTE DBA statement
syntax, 226 MobiLink syntax, 757
GET_IDENTITY function SQL Remote syntax, 757
syntax, 227 GRANT REMOTE statement
GETDATE function SQL Remote syntax, 758
query the current system date, 229 GRANT statement
syntax, 228 character set conversion on passwords, 763
getting password maximum length, 763
binary data from columns, 749 passwords, character set conversion on, 763
information from descriptor areas, 751 reviewing permissions, 1198
option values, 753 syntax, 760
GLOBAL AUTOINCREMENT GRANT USAGE ON SEQUENCE clause
creating events using the CREATE EVENT GRANT statement, 764
statement, 526 granting
GLOBAL AUTOINCREMENT clause authorities, 760
CREATE TABLE statement, 633 CONSOLIDATE permissions, 754
GLOBAL AUTOINCREMENT default permissions, 760
CREATE TABLE statement, 455, 638 PUBLISH permissions, 756
global checksums REMOTE DBA authority, 757
REMOTE permissions, 758

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1327


Index

GRAPHICAL_PLAN function RAISERROR statement, 838


syntax, 229 HASH function
GREATER function syntax, 232
syntax, 231 hashing
grid size supported algorithms, 232
ALTER SPATIAL REFERENCE SYSTEM HAVING clause
statement, 443 search conditions, 32
CREATE SPATIAL REFERENCE SYSTEM SELECT statement, 875
statement, 621 HEADER clause
GROUP BY clause CREATE FUNCTION statement [web clients],
CUBE operation, 767 542
GROUPING SETS operation, 766 CREATE PROCEDURE statement [web clients],
ROLLUP operation, 767 578
SELECT statement, 875 HELP statement
syntax, 766 Interactive SQL syntax, 769
GROUP clause hexadecimal
ALTER SERVICE statement [SOAP web service], converting to and from hexadecimal values, 6
436 converting using CAST, CONVERT, HEXTOINT,
CREATE SERVICE statement [SOAP web and INTTOHEX functions, 6
service], 437, 612 HEXADECIMAL clause
GRANT statement, 762 LOAD TABLE statement, 801
REVOKE statement, 863 OUTPUT statement, 827
grouping UNLOAD statement, 940
GROUP BY clause, 766 hexadecimal constants
regular expressions, 19 converting to and from hexadecimal values, 6
statements in a BEGIN statement, 484 treated as binary, 6
statements in a BEGIN statement [TSQL], 486 hexadecimal escape sequences
GROUPING function in SQL strings, 7
syntax, 231 hexadecimal strings
GROUPING SETS operation about, 234
GROUP BY clause, 766 HEXTOINT function
groups syntax, 234
GRANT statement, 760 high availability
GUIDs ALTER MIRROR SERVER statement, 420
SQL syntax for NEWID function, 279 CREATE MIRROR SERVER statement, 564
SQL syntax for STRTOUUID function, 351 hinting
SQL syntax for UUIDTOSTR function, 374 index hinting using the FROM clause, 745
UNIQUEIDENTIFIER data type, 118 histograms
gzip utility creating using CREATE STATISTICS, 625
COMPRESS function, 166 only partially updated by LOAD TABLE, 804
DECOMPRESS function, 203 retrieving, 1051
selectivity estimates, 56
H SYSCOLSTAT system view, 1199
HANDLER clause updating using CREATE STATISTICS, 625
CREATE EVENT statement, 530 HISTORY clause
handling ATTACH TRACING statement, 475
errors in embedded SQL, 959 BACKUP statement, 479
RESTORE DATABASE statement, 856

1328 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


HOLDLOCK clause Expires, 244
READTEXT statement [T-SQL], 842 Location, 244
HOLDLOCK table hint sa_set_http_header_info system procedure, 1134
FROM clause, 744 Server, 244
Host Transfer-Encoding, 244
HTTP_HEADER function, 242 User-Agent, 244
host variables WWW-Authenticate, 244
common element in SQL syntax, 395 HTTP services
declaring in embedded SQL, 666 creating using CREATE SERVICE statement
hostvar [HTTP web service], 605
common element in SQL syntax, 395 HTTP system procedures
HOUR function alphabetical list, 996
syntax, 235 HTTP_BODY function
HOURS function syntax, 239
syntax, 235 HTTP_DECODE function
HTML syntax, 240
CREATE SERVICE statement [HTTP web HTTP_ENCODE function
service], 431, 606 syntax, 241
HTML_DECODE function HTTP_HEADER function
syntax, 237 syntax, 242
HTML_ENCODE function HTTP_RESPONSE_HEADER function
syntax, 238 syntax, 244
HTTP HTTP_VARIABLE function
setting headers, 1134 syntax, 245
setting options, 1135 HttpMethod
setting options for SOAP headers, 1139 HTTP_HEADER function, 243
HTTP functions HttpQueryString
alphabetical list, 141 HTTP_HEADER function, 243
HTTP headers HttpStatus header
HTTP_HEADER function, 242 HTTP_RESPONSE_HEADER function, 245
HTTP_RESPONSE_HEADER function, 244 sa_set_http_header_info system procedure, 1134
HTTP request headers HttpURI
@HttpMethod, 243 HTTP_HEADER function, 243
@HttpQueryString, 243 HttpVersion
@HttpURI, 243 HTTP_HEADER function, 243
@HttpVersion, 243 hyphens
Accept-Encoding, 242 allowed syntax in a CONTAINS clause, 51
Cookie, 242 allowed syntax in a full text query string, 51
Host, 242
Referer, 242 I
returning names and values, 1059 I/O
User-Agent, 242 recalibrating the I/O cost model, 403
HTTP response headers IDENTIFIED BY clause
@HttpStatus, 245 ALTER SPATIAL REFERENCE SYSTEM
Connection, 244 statement, 443
Content-Length, 244 CREATE EXTERNLOGIN statement, 534
Content-Type, 244
Date, 244

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1329


Index

CREATE SPATIAL REFERENCE SYSTEM CREATE INDEX statement, 554


statement, 617 CREATE PUBLICATION statement [MobiLink]
CREATE USER statement, 658 [SQL Remote], 593
GRANT REMOTE DBA statement [MobiLink] CREATE TABLE statement, 636
[SQL Remote], 757 CREATE TEXT INDEX statement, 649
IDENTIFIED BY password clause IF statement
ALTER USER statement, 471 syntax, 769
CONNECT statement, 504 Transact-SQL syntax, 771
identifiers IF UPDATE clause
about, 4 CREATE TRIGGER [Transact-SQL] statement,
maximum length in SQL Anywhere, 4 657
syntax, 4 in triggers, 651
IDENTITY clause in triggers in Transact-SQL, 657
ALTER TABLE statement , 458 IFNULL function
CREATE TABLE statement, 640 syntax, 248
IDENTITY column image backups
@@identity, 78 creating using the BACKUP statement, 477
IDENTITY function IMAGE data type
syntax, 247 syntax, 117
idle server image SQL functions
creating events using the CREATE EVENT about, 145
statement, 526 images
IdleTime event condition reading from the database, 842
about, 215 IMMEDIATE REFRESH clause
IdleTimeout property ALTER MATERIALIZED VIEW statement, 418
setting with sa_server_option, 1128 CREATE MATERIALIZED VIEW statement, 560
IF EXISTS clause CREATE TEXT INDEX statement, 649
DROP EVENT statement, 693 immediate views
DROP EXTERNLOGIN statement, 695 ALTER MATERIALIZED VIEW statement, 417
DROP INDEX statement, 695 permissions not required to update underlying
DROP MATERIALIZED VIEW statement, 697 tables, 419
DROP PROCEDURE statement, 700 importing data
DROP PUBLICATION statement [MobiLink] into tables from files, 773
[SQL Remote], 701 IN clause
DROP SPATIAL REFERENCE SYSTEM CREATE FUNCTION statement, 548
statement, 704 CREATE FUNCTION statement [Web service],
DROP SPATIAL UNIT OF MEASURE statement, 541
705 CREATE MATERIALIZED VIEW statement, 561
DROP SYNCHRONIZATION PROFILE CREATE PROCEDURE statement, 586
statement, 709 CREATE TABLE statement, 635
DROP TABLE statement, 711 CREATE TEXT INDEX statement, 649
DROP TRIGGER statement, 714 LOCK TABLE statement, 808
DROP VARIABLE statement, 716 IN EXCLUSIVE MODE clause
DROP VIEW statement, 716 LOCK TABLE statement, 809
IF expressions IN search condition
search conditions, 32 syntax, 46
syntax, 15 IN SHARE MODE clause
IF NOT EXISTS clause LOCK TABLE statement, 808

1330 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


IN | ON clause physical indexes recorded in SYSPHYSIDX
CREATE INDEX statement, 554 system view, 1222
INCLUDE statement primary keys, 555
embedded SQL syntax, 772 renaming using the ALTER INDEX statement, 413
INCREMENT BY clause system views, 1211
ALTER SEQUENCE statement, 428 table use, 555
CREATE SEQUENCE statement, 599 unique, 553
independent variables VALIDATE statement, 955
regression line, 307 views, 555
INDEX clause virtual, 553
ALTER INDEX statement, 413 INDICATOR clause
ALTER TABLE statement, 457 GET DESCRIPTOR statement [ESQL], 751
CREATE TABLE statement, 637 SET DESCRIPTOR statement [ESQL], 882
FROM clause, 745 indicators
REORGANIZE TABLE statement, 853 comments, 79
VALIDATE statement, 955 initializing
INDEX FOR clause databases using the CREATE DATABASE
DESCRIBE statement, 685 statement, 508
index hints INLINE clause
FROM clause, 745 ALTER TABLE statement , 457
INDEX ONLY clause CREATE TABLE statement, 636
FROM clause, 745 INNER JOIN clause
INDEX_COL function FROM clause SQL syntax, 738
syntax, 144 INOUT clause
INDEX_ESTIMATE function CREATE PROCEDURE statement, 586
syntax, 249 INPUT clause
indexes DESCRIBE statement, 682
adding comments using the COMMENT statement, INPUT INTO statement
499 Interactive SQL syntax, 773
ALTER INDEX statement, 413 INPUT statement
automatically created, 555 cannot be used in stored procedures, 778
built-in functions, 553 Interactive SQL syntax, 773
clustering using the ALTER INDEX statement, syntax, 773
413 INSENSITIVE clause
compressing, 852 DECLARE CURSOR statement, 668
CREATE INDEX statement, 553 FOR statement, 733
detecting index fragmentation using INSERT clause
sa_index_density, 1063 CREATE PUBLICATION statement [MobiLink]
detecting skewed indexes using sa_index_density, [SQL Remote], 592
1063 CREATE TRIGGER statement, 652
DROP INDEX statement, 695 REVOKE statement, 863
foreign keys, 555 INSERT INTO statement
functions, 554 syntax, 780
levels, 1065 INSERT permission
naming, 555 GRANT statement, 761
optimizing for OLAP workloads, 555 REVOKE statement, 863
owner, 555 INSERT permission clause
GRANT statement, 763

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1331


Index

INSERT statement CONFIGURE statement syntax, 503


setting database options, 782 CONNECT statement syntax, 504
syntax, 780 DESCRIBE CONNECTION statement syntax, 684
updating views, 783 DESCRIBE statement syntax, 684
inserting DISCONNECT statement syntax, 688
BLOBs using the SET statement, 899 EXIT statement syntax, 725
data using LOAD TABLE statement, 792 HELP statement syntax, 769
multi-row, 722 INPUT statement syntax, 773
rows in bulk, 792 OUTPUT statement, 825
rows into tables, 780 PARAMETERS statement syntax, 830
rows using cursors, 837 procedure profiling, 1120
wide inserts, 722 QUIT statement syntax, 725
inserting BLOBs READ statement syntax, 840
using xp_read_file system procedure, 1182 RESUME statement unsupported, 857
INSERTSTR function return codes, 725
syntax, 249 SET CONNECTION statement syntax, 881
INSTALL EXTERNAL OBJECT statement SET OPTION statement syntax, 889
syntax, 785 specifying encoding for INPUT statement, 774
INSTALL JAVA statement specifying encoding for OUTPUT statement, 826
installing Java classes, 787 specifying encoding for READ statement, 840
syntax, 787 START DATABASE statement, 907
installing START LOGGING statement syntax, 913
Java classes, 787 START SERVER statement syntax, 910
INSTEAD OF clause STOP LOGGING statement syntax, 921
CREATE TRIGGER statement, 651 SYSTEM statement syntax, 931
INSTEAD OF triggers internal storage format
altering views, 473 ALTER SPATIAL REFERENCE SYSTEM
CREATE TRIGGER statement, 651 statement, 444
creating views, 662 CREATE SPATIAL REFERENCE SYSTEM
dropped by CREATE OR REPLACE VIEW, 662 statement, 622
replacing views, 662 international languages and character sets
INTEGER data type substitution characters, 123
comparing with dates and times, 125 INTERSECT ALL clause
syntax, 94 INTERSECT statement, 788
integers INTERSECT clause
generating table of , 1115 INTERSECT statement, 788
INTEGRATED LOGIN clause setting database options, 789
REVOKE statement, 863 INTERSECT DISTINCT clause
integrated logins INTERSECT statement, 788
adding comments using the COMMENT statement, INTERSECT statement
499 syntax, 788
GRANT statement, 761 intersecting
REVOKE statement, 863 result of multiple SELECT statements, 788
integrity Interval event condition
constraints in CREATE TABLE statement, 640 about, 215
Interactive SQL INTO clause
BYE statement syntax, 725 EXECUTE statement, 722
CLEAR statement syntax, 497 EXPLAIN statement [ESQL], 727

1332 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


FETCH statement , 729 syntax, 54
GET DATA statement , 749 IS UNKNOWN search condition
GET OPTION statement [ESQL], 753 syntax, 54
INPUT statement, 777 ISDATE function
MERGE statement, 812 syntax, 251
OUTPUT statement, 825 ISENCRYPTED function
PUT statement [ESQL], 837 syntax, 252
SELECT statement, 874 ISNULL function
INTO CLIENT FILE clause syntax, 253
UNLOAD statement, 938 ISNUMERIC function
INTO DESCRIPTOR clause syntax, 254
PUT statement [ESQL], 837 ISO 8601
INTO FILE clause support, 102
UNLOAD statement, 938 isolation level
INTO LOCAL TEMPORARY TABLE clause clause, 822
SELECT statement, 875 ISOLATION LEVEL clause
INTO VARIABLE clause OPEN statement, 822
UNLOAD statement, 938 isolation levels
INTTOHEX function ISOLATION LEVEL clause, 822
syntax, 250 table hints, 744
inverse flattening isolation_level option
defined, 1234 overriding in a MERGE statement, 816
invoking overriding in a SELECT statement, 878
procedures using the CALL statement, 491 setting for DELETE statements, 680
IOParallelism property setting for EXCEPT statement, 718
DB_EXTENDED_PROPERTY function, 197 setting for INSERT statements, 782
IPAddressMonitorPeriod property setting for INTERSECT statement, 789
setting with sa_server_option, 1128 setting for UNION statement, 936
IS setting for UPDATE statements, 951
logical operators description, 9 ISYSARTICLE
three-valued logic, 55 system table, 965
IS DISTINCT FROM search condition ISYSARTICLECOL
syntax, 36 system table, 966
IS FALSE search condition ISYSATTRIBUTE
syntax, 54 system table, 966
IS NOT DISTINCT FROM search condition ISYSATTRIBUTENAME
syntax, 36 system table, 966
IS NOT NULL search condition ISYSCAPABILITY
syntax, 54 system table, 966
IS NOT OF expressions ISYSCHECK
search conditions, 32 system table, 966
IS NULL search condition ISYSCOLPERM
syntax, 54 system table, 966
IS OF expressions ISYSCOLSTAT
search conditions, 32 encrypted if database is encrypted, 967
IS OF type-expression encrypted if table encryption enabled, 967
search conditions, 33 loading statistics, 792
IS TRUE search condition system table, 967

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1333


Index

ISYSCONSTRAINT ISYSMVOPTIONNAME
system table, 967 system table, 972
ISYSDBFILE ISYSOBJECT
system table, 967 system table, 972
ISYSDBSPACE ISYSOPTION
system table, 968 system table, 972
ISYSDBSPACEPERM ISYSOPTSTAT
system table, 968 system table, 972
ISYSDEPENDENCY ISYSPHYSIDX
system table, 967 system table, 972
ISYSDOMAIN ISYSPROCEDURE
system table, 968 system table, 973
ISYSEVENT ISYSPROCPARM
system table, 968 system table, 973
ISYSEXTERNLOGIN ISYSPROCPERM
encrypted if database is encrypted, 968 system table, 973
encrypted if table encryption enabled, 968 ISYSPROXYTAB
system table, 968 system table, 973
ISYSFKEY ISYSPUBLICATION
system table, 969 system table, 973
ISYSGROUP ISYSREMARK
system table, 969 system table, 974
ISYSHISTORY ISYSREMOTEOPTION
system table, 969 system table, 974
ISYSIDX ISYSREMOTEOPTIONTYPE
system table, 969 system table, 974
ISYSIDXCOL ISYSREMOTETYPE
system table, 969 system table, 974
ISYSJAR ISYSREMOTEUSER
system table, 970 system table, 974
ISYSJARCOMPONENT ISYSSCHEDULE
system table, 970 system table, 975
ISYSJAVACLASS ISYSSEQUENCE
system table, 970 system table, 975
ISYSLOGINMAP ISYSSEQUENCEPERM
system table, 970 system table, 975
ISYSLOGINPOLICY ISYSSERVER
system table, 970 adding servers, 601
ISYSLOGINPOLICYOPTION remote servers for Component Integration
system table, 971 Services, 601
ISYSMIRROROPTION system table, 975
system table, 971 ISYSSOURCE
ISYSMIRRORSERVER system table, 975
system table, 971 ISYSSPATIALREFERENCESYSTEM
ISYSMIRRORSERVEROPTION system table, 976
system table, 971 ISYSSQLSERVERTYPE
ISYSMVOPTION system table, 976
system table, 971 ISYSSUBSCRIPTION

1334 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


system table, 976 J
ISYSSYNC
JAR clause
system table, 976
INSTALL JAVA statement, 787
ISYSSYNCPROFILE
REMOVE JAVA statement, 852
system table, 976
JAR files
ISYSSYNCSCRIPT
adding comments using the COMMENT statement,
system table, 977
499
ISYSTAB
INSTALL JAVA statement, 787
system table, 977
removing, 851
ISYSTABCOL
Java
system table, 977
converting Java and SQL, 130
ISYSTABLEPERM
installing, 787
system table, 978
system tables, 994
ISYSTEXTCONFIG
user defined functions, 138
system table, 977
Java and SQL data type conversion
ISYSTEXTIDX
about, 130
system table, 977
Java classes
ISYSTEXTIDXTAB
adding comments using the COMMENT statement,
system table, 978
499
ISYSTRIGGER
loaded in the database, 1068
system table, 978
troubleshooting, 1068
ISYSTYPEMAP
Java data types
system table, 978
converting from SQL, 131
ISYSUNITOFMEASURE
converting to SQL, 130
system table, 978
Java to SQL data type conversion
ISYSUSER
about, 130
encrypted if database is encrypted, 979
Java VM
encrypted if table encryption enabled, 979
STOP JAVA statement, 920
system table, 979
JavaScript Object Notation
ISYSUSERAUTHORITY
CREATE SERVICE statement [HTTP web
system table, 979
service], 431, 606
ISYSUSERMESSAGE
jConnect
system table, 979
CREATE DATABASE statement, 512
ISYSUSERTYPE
JCONNECT clause
system table, 979
ALTER DATABASE statement, 401
ISYSVIEW
CREATE DATABASE statement, 512
system table, 979
JDBC
ISYSWEBSERVICE
data type conversion, 130
adding HTTP services using CREATE SERVICE
Java to SQL data type conversion, 130
statement [HTTP web service], 605
SQL to Java data type conversion, 131
adding SOAP over HTTP services, 611
upgrading database components, 400
altering HTTP web services, 431
join operators
altering SOAP over HTTP services, 436
compatibility with ASE, 12
system table, 980
joins
iterating
ANSI equivalency, 324
over cursors, 733
deleting rows based on joins, 678
FROM clause SQL syntax, 738

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1335


Index

SQL Remote updates based on, 946 CREATE FUNCTION statement [External call],
updates based on, 951 538
JSON CREATE PROCEDURE statement [External call],
CREATE SERVICE statement [HTTP web 572
service], 431, 606 LANGUAGE C_ESQL64 clause
CREATE FUNCTION statement [External call],
K 538
Kerberos CREATE PROCEDURE statement [External call],
adding comments using the COMMENT statement, 572
499 LANGUAGE C_ODBC32 clause
case sensitivity of principals, 764 CREATE FUNCTION statement [External call],
granting Kerberos login, 761 538
revoking KERBEROS LOGIN, 863 CREATE PROCEDURE statement [External call],
KERBEROS LOGIN clause 572
REVOKE statement, 863 LANGUAGE C_ODBC64 clause
Kerberos logins CREATE FUNCTION statement [External call],
GRANT statement, 761 538
KEY clause CREATE PROCEDURE statement [External call],
ALTER DATABASE statement, 402 572
CREATE DECRYPTED DATABASE statement, LANGUAGE CLR clause
517 CREATE FUNCTION statement [External call],
CREATE DECRYPTED FILE statement, 518 538
CREATE ENCRYPTED DATABASE statement, CREATE PROCEDURE statement [External call],
522 572
CREATE ENCRYPTED FILE statement, 524 language elements
CREATE ENCRYPTED TABLE DATABASE syntax, 1
statement, 522 LANGUAGE JAVA clause
DROP DATABASE statement, 690 CREATE FUNCTION statement [External call],
RESTORE DATABASE statement, 856 539
START DATABASE statement, 908 CREATE PROCEDURE statement [External call],
KEY JOIN clause 573
FROM clause SQL syntax, 738 LANGUAGE PERL clause
keys CREATE FUNCTION statement [External call],
CREATE SEQUENCE statement, 599 538
keywords CREATE PROCEDURE statement [External call],
how to use SQL reserved words in syntax, 1 572
list of SQL reserved words, 1 LANGUAGE PHP clause
sa_reserved_words system procedure, 1112 CREATE FUNCTION statement [External call],
kind tests 539
supported by openxml system procedure, 1004 CREATE PROCEDURE statement [external
procedures], 573
large binary objects
L getting from columns, 749
labels
large databases
for statements, 396
index storage, 554
statements, 754
LAST clause
LANGUAGE C_ESQL32 clause
FETCH statement , 729
LAST USER clause

1336 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


CREATE TABLE statement, 633 CREATE SPATIAL REFERENCE SYSTEM
LAST USER default statement, 619
CREATE TABLE statement, 456, 639 LIST function
LAST USER special value syntax, 261
syntax, 63 lists
LAST_VALUE function LIST function syntax, 261
syntax, 255 sa_split_list system procedure, 1142
lateral derived tables literals
FROM clause outer references, 741 about, 6
LCASE function LivenessTimeout property
syntax, 257 setting with sa_server_option, 1128
leap years LOAD STATISTICS statement
about, 107 syntax, 792
LEAVE statement LOAD TABLE statement
syntax, 790 syntax, 792
LEFT function using with database mirroring, 804
syntax, 258 loading
LEFT OUTER JOIN clause bulk inserts, 792
FROM clause SQL syntax, 738 cost models, 1070
LEN function fails if table has an immediate text index, 803
syntax, 259 fails if table referenced by an immediate views,
LENGTH clause 803
GET DESCRIPTOR statement [ESQL], 751 LOAD TABLE statement, 792
SET DESCRIPTOR statement [ESQL], 882 loading data from a file on the client computer, 794
LENGTH function loading data from a file on the database server
syntax, 259 computer, 794
LESSER function loading data from a specified value, 795
syntax, 260 shapefiles using st_geometry_load_shapefile
LIKE search condition system procedure, 1178
case-sensitivity, 41 loading data
collations, 41 multibyte character sets, 801
compared to REGEXP and SIMILAR TO, 37 LOCAL DATABASE clause
pattern length, 40 ATTACH TRACING statement, 475
syntax, 39 local temporary tables
LIKE, REGEXP, and SIMILAR TO search conditions creating, 672
about, 37 creating using the CREATE LOCAL
LIMIT clause TEMPORARY TABLE statement, 556
ATTACH TRACING statement, 475 local variables
SELECT statement, 873 definition, 72
limiting the number of rows returned syntax, 73
about, 871 LOCATE function
line interpretation, spatial data syntax, 264
planar type, 619 Location
round-earth type, 619 HTTP_RESPONSE_HEADER function, 244
LINEAR UNIT OF MEASURE clause LOCATION clause
ALTER SPATIAL REFERENCE SYSTEM ALTER EXTERNAL ENVIRONMENT statement,
statement, 443 411
LOCK FEATURE statement

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1337


Index

syntax, 807 DROP LOGIN POLICY statement, 696


LOCK TABLE statement locked option, 558
syntax, 808 max_connections option, 558
locked accounts max_days_since_login option, 558
determining cause, 1058 max_failed_login_attempts option, 558
locked option max_non_dba_connections, 558
login policies, 558 password_expiry_on_next_login option, 558
locking password_grace_time option, 558
blocks, 1020 password_life_time option, 558
features, 807 LOGIN POLICY
tables, 808 ALTER USER statement, 470
locks LOGIN POLICY clause
displaying, 1071 CREATE USER statement, 658
types, 1072 logins
log files assigning for remote servers, 534
allocating space using ALTER DBSPACE, 405 disabling connections to a server, 1120
analyzing the request log using dropping for remote servers, 694
sa_get_request_profile, 1053 obtaining status, 1058
analyzing the request log using LogSize event condition
sa_get_request_times, 1054 about, 215
determining available space, 1043 LONG BINARY data type
LOG function syntax, 118
syntax, 265 long column names
LOG10 function retrieving, 683
syntax, 266 LONG NAMES clause
LogDiskSpace system event DESCRIBE statement, 683
example, 216 LONG NVARCHAR data type
logfile option describing, 83
ALTER MIRROR SERVER statement, 422 syntax, 83
CREATE MIRROR SERVER statement, 566 LONG VARBIT data type
LogFreePercent event condition syntax, 99
about, 215 LONG VARCHAR data type
LogFreeSpace event condition syntax, 83
about, 215 LOOP clause
logging LOOP statement, 810
deadlocks, 1127 LOOP statement
START LOGGING statement, 913 syntax, 810
STOP LOGGING statement, 921 looping
updating columns without, 963 over cursors, 733
logical operators lossy conversions
syntax, 9 about, 123
three-valued logic, 55 LOWER function
login policies syntax, 266
adding comments using the COMMENT statement, lowercase strings
499 LCASE function, 257
ALTER LOGIN POLICY statement, 415 LOWER function, 266
CREATE LOGIN POLICY statement, 558 LTRIM function
default login policy, 558 syntax, 267

1338 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


M ALTER MATERIALIZED VIEW statement, 417
altering materialized views owned by someone
MANUAL REFRESH clause
else, 418
ALTER MATERIALIZED VIEW statement, 418
altering using SQL, 417
CREATE MATERIALIZED VIEW statement, 560
CREATE MATERIALIZED VIEW statement, 560
CREATE TEXT INDEX statement, 649
creating using SQL, 560
manual views
creation options stored in SYSMVOPTION, 1219
ALTER MATERIALIZED VIEW statement, 417
decrypting using SQL, 417
MAPI
determining status, 1077
extended system procedures, 996
disabling use in optimization using SQL, 417
MAPI and SMTP system procedures, 1186
disabling using SQL, 417
return codes for MAPI and SMTP system
DROP MATERIALIZED VIEW statement, 697
procedures, 997
dropping using SQL, 697
starting email sessions, 1188
enabling use in optimization using SQL, 417
stopping email sessions, 1191
enabling using SQL, 417
MAPI and SMTP system procedures
encrypting using SQL, 417
return codes, 997
listing all materialized views in the database, 1077
MATCH clause
permissions required for immediate views, 419
ALTER TABLE statement , 456
querying using index hints, 745
CREATE TABLE statement, 641
querying using table hints, 744
MATCH FULL clause
REFRESH MATERIALIZED VIEW statement,
CREATE TABLE statement, 642
843
MATCH SIMPLE clause
refreshing using SQL, 843
CREATE TABLE statement, 642
setting isolation level for refreshing, 843
match types
testing eligibility for becoming an immediate view,
referential integrity, 641
1076
MATCH UNIQUE FULL clause
unloading using the UNLOAD statement, 937
CREATE TABLE statement, 642
validating indexes, 955
MATCH UNIQUE SIMPLE clause
materialized-view-name
CREATE TABLE statement, 642
common element in SQL syntax, 395
MATERIALIZED VIEW clause
materialized_view_optimization option
TRUNCATE statement, 933
overriding in a SELECT statement, 877
VALIDATE statement, 955
setting for DELETE statements, 680
MATERIALIZED VIEW OPTIMIZATION clause
setting for EXCEPT statement, 718
DELETE statement, 680
setting for INSERT statements, 782
EXCEPT statement, 718
setting for INTERSECT clauses, 789
INSERT statement, 782
setting for INTERSECT statement, 789
INTERSECT statement, 789
setting for UNION statement, 936
SELECT statement, 877
setting for UPDATE statements, 951
UPDATE statement, 951
mathematical expressions
MATERIALIZED VIEW OPTIMIZATION option
arithmetic operators, 10
MERGE statement, 816
MAX function
materialized view properties
syntax, 268
RefreshType property, 1078
MAX WRITE clause
materialized views
BACKUP statement, 480
adding comments using the COMMENT statement,
max_connections option
499
login policies, 558
ALTER INDEX statement, 413
max_days_since_login option

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1339


Index

login policies, 558 creating, 563


max_disconnected_time option displaying, 818
SET MIRROR OPTION statement, 884 dropping remote types, 701
max_failed_login_attempts option dropping using the DROP MESSAGE statement,
login policies, 558 698
max_non_dba_connections option MESSAGE statement, 818
login policies, 558 SQL Remote altering remote types, 426
max_query_tasks option SQL Remote creating remote types, 596
overriding in a MERGE statement, 816 messages windows
overriding in a SELECT statement, 878 printing messages in, 836
setting for DELETE statements, 680 metacharacters
setting for EXCEPT statement, 718 list of metacharacters used in regular expressions,
setting for INSERT statements, 782 19
setting for INTERSECT statement, 789 metaproperties
setting for UNION statement, 936 LOAD TABLE statement, 800
setting for UPDATE statements, 951 openxml system procedure, 1002
max_retry_connect_time option METHODS clause
SET MIRROR OPTION statement, 884 ALTER SERVICE statement [HTTP web service],
maximum 431
date ranges, 107 ALTER SERVICE statement [SOAP web service],
MAXIMUM TERM LENGTH clause 436
ALTER TEXT CONFIGURATION statement, 465 CREATE SERVICE statement [HTTP web
MaxMultiProgrammingLevel property service], 433, 608
setting with sa_server_option, 1128 CREATE SERVICE statement [SOAP web
MAXVALUE clause service], 439, 614
ALTER SEQUENCE statement, 428 migrating databases
CREATE SEQUENCE statement, 600 sa_migrate system procedure, 1083
MEDIAN function MIME base64
syntax, 269 decoding data, 152
MEMBERSHIP IN GROUP clause encoding data, 152
GRANT statement, 762 MIN function
REVOKE statement, 863 syntax, 271
memory minimum
allocating for descriptor areas, 398 date ranges, 107
MERGE clause MINIMUM TERM LENGTH clause
ALTER SYNCHRONIZATION PROFILE ALTER TEXT CONFIGURATION statement, 465
statement, 446 MinMultiProgrammingLevel property
MERGE statement setting with sa_server_option, 1128
syntax, 811 MINUTE function
merging syntax, 272
MERGE statement, 811 MINUTES function
message control parameters syntax, 273
setting, 892 MINVALUE clause
MESSAGE statement ALTER SEQUENCE statement, 428
syntax, 818 CREATE SEQUENCE statement, 599
MessageCategoryLimit property MIRROR clause
setting with sa_server_option, 1128 CREATE DATABASE statement, 513
messages mirror servers

1340 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


adding comments using the COMMENT statement, START SYNCHRONIZATION SCHEMA
499 CHANGE statement, 916
ALTER MIRROR SERVER statement, 420 STOP SYNCHRONIZATION DELETE statement,
altering with the ALTER MIRROR SERVER 924
statement, 420 STOP SYNCHRONIZATION SCHEMA
changing with ALTER MIRROR SERVER CHANGE statement, 929
statement, 420 MobiLink users
CREATE MIRROR SERVER statement, 564 ALTER SYNCHRONIZATION USER statement,
creating with the CREATE MIRROR SERVER 449
statement , 564 CREATE SYNCHRONIZATION USER
defining with CREATE MIRROR SERVER statement, 631
statement, 564 DROP SYNCHRONIZATION USER statement,
dropping with the DROP MIRROR SERVER 710
statement, 699 MOD function
mirroring syntax, 275
dropping servers, 699 money
MirrorServerState property money data types, 98
DB_EXTENDED_PROPERTY function, 197 MONEY data type
MirrorState property syntax, 98
DB_EXTENDED_PROPERTY function, 197 money data types
mixed storage format MONEY, 98
ALTER SPATIAL REFERENCE SYSTEM SMALLMONEY, 99
statement, 444 monitoring performance
CREATE SPATIAL REFERENCE SYSTEM execution time determination, 1054
statement, 622 MONTH function
MobiLink syntax, 275
ALTER PUBLICATION statement, 425 MONTHNAME function
ALTER SYNCHRONIZATION PROFILE syntax, 276
statement, 446 MONTHS function
ALTER SYNCHRONIZATION SUBSCRIPTION syntax, 277
statement, 447 multi-row fetches
ALTER SYNCHRONIZATION USER statement, FETCH statement, 730
449 OPEN statement, 823
CREATE PUBLICATION statement, 592 multi-row inserts
CREATE SYNCHRONIZATION PROFILE about, 722
statement, 628 multibyte character sets
CREATE SYNCHRONIZATION loading data, 801
SUBSCRIPTION statement, 629 unloading data, 940
CREATE SYNCHRONIZATION USER multiple result sets
statement, 631 retrieving, 857
DROP PUBLICATION statement, 701 multiprogramming level
DROP SYNCHRONIZATION PROFILE controlling automatic tuning, 1126
statement, 709 setting current value, 1127
DROP SYNCHRONIZATION SUBSCRIPTION setting maximum value, 1128
statement, 709 setting minimum value, 1128
START SYNCHRONIZATION DELETE viewing statistics, 1126
statement, 915

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1341


Index

N INSTALL EXTERNAL OBJECT statement, 785


INSTALL JAVA statement, 787
n-gram
new line characters
ALTER TEXT CONFIGURATION statement, 466
in SQL strings, 7
NAME clause
NEW SUBSCRIBE BY clause
GET DESCRIPTOR statement [ESQL], 751
UPDATE statement, 948
named parameters
UPDATE statement [SQL Remote] , 945
allowed when calling procedures, 491
NEWID function
names
syntax, 279
column names, 14
NEXT clause
NAMESPACE clause
FETCH statement , 729
CREATE FUNCTION statement [web clients],
NEXT_CONNECTION function
544
syntax, 280
CREATE PROCEDURE statement [web clients],
NEXT_DATABASE function
581
syntax, 282
native function calls
NEXT_HTTP_HEADER function
functions, 537
syntax, 282
interfacing to native functions using CREATE
NEXT_HTTP_RESPONSE_HEADER function
FUNCTION statement, 535
syntax, 284
interfacing to native procedures using CREATE
NEXT_HTTP_VARIABLE function
PROCEDURE statement, 567
syntax, 285
procedures, 571
NEXT_SOAP_HEADER function
native procedures
syntax, 286
interfacing to native procedures using CREATE
NextScheduleTime property
PROCEDURE statement, 567
DB_EXTENDED_PROPERTY function, 197
NATURAL JOIN clause
NO COPY clause
FROM clause SQL syntax, 738
BACKUP statement, 480
NCHAR COLLATION clause
NO INDEX clause
collation tailoring, 513
ALTER TABLE statement, 457
CREATE DATABASE statement, 513
CREATE TABLE statement, 637
NCHAR data type
FROM clause, 745
comparing with CHAR data type, 123
NO RESULT SET clause
describing, 84
CREATE PROCEDURE statement, 587
syntax, 84
CREATE PROCEDURE statement [External call],
use with the LIKE search condition, 42
570
use with the REGEXP search condition, 44
CREATE PROCEDURE statement [T-SQL], 583
use with the SIMILAR TO search condition, 46
NO SCROLL clause
using DESCRIBE on an NCHAR column, 84
DECLARE CURSOR statement, 667
NCHAR function
FOR statement, 733
syntax, 278
NO SCROLL cursors
NcharCollation property
declaring, 666
DB_EXTENDED_PROPERTY function, 197
NOLOCK table hint
NEAR clause
FROM clause, 744
CONTAINS search condition, 47
NONCLUSTERED clause
nesting
ALTER INDEX statement, 413
user-defined transactions using the BEGIN
NOSTRIP clause
TRANSACTION statement, 488
INPUT statement, 777
NEW clause
NOT

1342 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


bitwise operators, 11 converting to string types, 128
logical operators description, 9 NULL values
three-valued logic, 55 domains, 520
NOT COMPRESSED clause NULLABLE clause
LOAD TABLE statement, 797 GET DESCRIPTOR statement [ESQL], 751
NOT DETERMINISTIC clause NULLIF function
CREATE FUNCTION statement [External call], about, 288
535 using with CASE expressions, 17
CREATE FUNCTION statement [external number
procedures], 537 common element in SQL syntax, 395
CREATE FUNCTION statement [user defined], NUMBER function
549 SQL Remote updates, 946
NOT ENCRYPTED clause syntax, 288
ALTER MATERIALIZED VIEW statement, 418 number of rows
LOAD TABLE statement, 798 system views, 1241
NOT NULL clause NUMERIC data type
ALTER TABLE statement , 453 comparing with dates and times, 125
CREATE EXISTING TABLE statement, 532 converting from DOUBLE, 130
CREATE TABLE statement, 637 syntax, 95
NOT TRANSACTIONAL clause numeric data types
CREATE LOCAL TEMPORARY TABLE about, 89
statement, 557 BIGINT, 89
CREATE TABLE statement, 635 BIT, 90
DECLARE LOCAL TEMPORARY TABLE converting DOUBLE to NUMERIC, 130
statement, 672 DECIMAL, 91
NOTFOUND clause DOUBLE, 92
WHENEVER statement [ESQL], 959 FLOAT, 93
NOW function INTEGER, 94
syntax, 287 NUMERIC, 95
NTEXT data type REAL, 96
syntax, 85 SMALLINT, 97
NULL TINYINT, 97
about, 64 numeric functions
ASE compatibility, 65 alphabetical list, 140
ISNULL function, 253 NVARCHAR data type
NULL value, 64 describing, 85
returned by functions if a NULL argument is syntax, 85
specified, 133 using DESCRIBE on an NVARCHAR column, 85
space allocated for NULL values, 64
three-valued logic, 64 O
NULL clause OBJECT_ID function
ALTER TABLE statement , 453 syntax, 144
CASE statement, 493 OBJECT_NAME function
CASE statement [T-SQL], 495 syntax, 144
CREATE DOMAIN statement, 520 ODBC
CREATE TABLE statement, 637 declaring static cursors, 666
NULL constants OFFSET clause
converting to NUMERIC, 128

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1343


Index

GET DATA statement , 750 CREATE TEXT INDEX statement, 649


SELECT statement, 873 CREATE TRIGGER [Transact-SQL] statement,
OLAP 657
CUBE operation, 767 DROP STATISTICS statement, 706
GROUP BY clause, 766 DROP TEXT INDEX statement, 713
GROUPING function, 231 MERGE statement, 813
GROUPING SETS operation, 766 REVOKE statement, 863
ROLLUP operation, 767 START DATABASE statement, 907
WINDOW clause, 961 TRUNCATE TEXT INDEX statement, 935
OLAP functions VALIDATE statement, 955
AVG function, 150 ON COMMIT clause
COUNT function, 177 CREATE LOCAL TEMPORARY TABLE
COUNT_BIG function, 179 statement, 557
COVAR_POP function, 181 CREATE TABLE statement, 635
CUME_DIST function, 185 DECLARE LOCAL TEMPORARY TABLE
DENSE_RANK function, 206 statement, 672
MAX function, 268 ON DATABASE clause
MEDIAN function, 269 STOP DATABASE statement, 918
MIN function, 271 ON EXCEPTION RESUME clause
PERCENT_RANK function, 292 about, 588
RANK function, 303 CREATE FUNCTION statement [user defined],
REGR_AVGX function, 307 549
REGR_AVGY function, 308 CREATE PROCEDURE statement, 588
REGR_COUNT function, 310 ON EXISTING clause
REGR_INTERCEPT function, 311 INSERT statement, 781
REGR_R2 function, 313 ON EXISTING ERROR clause
REGR_SLOPE function, 314 BACKUP statement, 479
REGR_SXX function, 315 behavior with DEFAULT columns, 782
REGR_SXY function, 317 ON EXISTING SKIP clause
ROW_NUMBER function, 327 behavior with DEFAULT columns, 782
STDDEV function, 346 ON phrase
STDDEV_POP function, 346 search conditions, 32
STDDEV_SAMP function, 348 ON SUBSCRIPTION clause
SUM function, 355 START SYNCHRONIZATION SCHEMA
VAR_POP function, 375 CHANGE statement, 917
VAR_SAMP function, 377 on_tsql_error option
OLD KEY clause and ON EXCEPTION RESUME clause, 588
CREATE ENCRYPTED FILE statement, 524 OPEN statement
CREATE ENCRYPTED TABLE DATABASE embedded SQL syntax, 821
statement, 522 syntax, 821
OLD SUBSCRIBE BY clause WITH HOLD cursors, 821
UPDATE statement, 948 opening cursors
UPDATE statement [SQL Remote] , 945 OPEN statement, 821
ON clause OPENSTRING clause
ALTER STATISTICS statement, 445 example, 749
ALTER TRIGGER statement, 469 FROM clause, 741
CREATE EVENT statement, 529 openxml system procedure
CREATE INDEX statement, 553 list of supported metaproperties, 1002

1344 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


not owned by dbo, 995 setting for INSERT statements, 782
supported kind tests, 1004 setting for INTERSECT statement, 789
syntax, 1001 setting for UNION statement, 936
operating systems setting for UPDATE statements, 951
executing commands, 931 optimizer
operational servers CREATE STATISTICS statement, 625
ALTER MIRROR SERVER statement, 420 explicit selectivity estimates, 56
CREATE MIRROR SERVER statement, 564 optimizer plans
operator precedence getting text specification, 727
full text search, 50 optimizer statistics
syntax, 12 dropping using the DROP STATISTICS statement,
operators 706
about, 8 optimizer tables
arithmetic operators, 10 about, 980
bitwise operators, 11 OPTION clause
comparison operators, 8 CREATE SYNCHRONIZATION
logical operators description, 9 SUBSCRIPTION statement [MobiLink], 630
precedence of operators, 12 CREATE SYNCHRONIZATION USER, 632
string operators, 10 DELETE statement, 680
optimization EXCEPT statement, 718
avoiding using FORCE NO OPTIMIZATION INSERT statement, 782
clause, 877 INTERSECT statement, 789
defining existing tables and, 533 MERGE statement, 816
forcing using FORCE OPTIMIZATION option, SELECT statement, 877
877 UNION statement, 936
optimization_goal option UPDATE statement, 951
overriding in a MERGE statement, 816 options
overriding in a SELECT statement, 878 getting values, 753
setting for DELETE statements, 680 initial settings for sp_login_environment system
setting for EXCEPT statement, 718 procedure, 1164
setting for INSERT statements, 782 initial settings for sp_tsql_environment system
setting for INTERSECT statement, 789 procedure, 1173
setting for UNION statement, 936 overriding, 1120
setting for UPDATE statements, 951 quoted_identifier and T-SQL compatibility, 31
optimization_level option SET OPTION statement, 886
overriding in a MERGE statement, 816 setting in Interactive SQL, 889
overriding in a SELECT statement, 878 setting in Transact-SQL, 901
setting for DELETE statements, 680 setting remote, 892
setting for EXCEPT statement, 718 setting with sp_tsql_environment system
setting for INSERT statements, 782 procedure, 1173
setting for INTERSECT statement, 789 SYSOPTIONS consolidated view, 1270
setting for UNION statement, 936 system views, 1221
setting for UPDATE statements, 951 SYSUSEROPTIONS consolidated view, 1279
optimization_workload option options watch list
overriding in a MERGE statement, 816 configuring with sa_server_option, 1128
overriding in a SELECT statement, 878 OptionWatchAction property
setting for DELETE statements, 680 setting with sa_server_option, 1128
setting for EXCEPT statement, 718 OptionWatchList property

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1345


Index

setting with sa_server_option, 1128 syntax conventions, 396


OR ordinal date
bitwise operators, 11 ISO 8601, 102
logical operators description, 9 ORGANIZATION clause
three-valued logic, 55 ALTER SPATIAL REFERENCE SYSTEM
OR REPLACE clause statement, 443
CREATE FUNCTION statement [External call], CREATE SPATIAL REFERENCE SYSTEM
535 statement, 618
CREATE FUNCTION statement [external original storage format
procedures], 536 ALTER SPATIAL REFERENCE SYSTEM
CREATE FUNCTION statement [user defined], statement, 444
549 CREATE SPATIAL REFERENCE SYSTEM
CREATE FUNCTION statement [Web service], statement, 622
541 OUT clause
CREATE MIRROR SERVER statement, 564 CREATE PROCEDURE statement, 586
CREATE PROCEDURE statement, 585 out of disk space
CREATE PROCEDURE statement [External call], creating events using the CREATE EVENT
567 statement, 526
CREATE PROCEDURE statement [T-SQL], 583 OUTER APPLY clause
CREATE PROCEDURE statement [web clients], FROM clause, 742
576 outer references
CREATE SEQUENCE statement, 599 FROM clause, 741
CREATE SPATIAL REFERENCE SYSTEM lateral derived tables, 741
statement, 616 OUTPUT clause
CREATE SYNCHRONIZATION PROFILE CREATE PROCEDURE statement [T-SQL], 583
statement, 628 DESCRIBE statement, 682
CREATE TRIGGER statement, 651 OUTPUT statement
CREATE VARIABLE statement, 660 syntax, 825
CREATE VIEW statement, 662 output_log_send_limit
Oracle databases SQL Remote syntax, 892
migrating to SQL Anywhere using sa_migrate output_log_send_now
system procedure, 1084 SQL Remote syntax, 892
ORDER BY clause output_log_send_on_error
about, 875 SQL Remote syntax, 892
DELETE statement, 679 overflow errors
EXCEPT statement, 717 AVG function, 151
INTERSECT statement, 788 SUM function, 356
SELECT statement, 871 owner
UPDATE statement, 950 common element in SQL syntax, 395
UPDATE statement [SQL Remote] , 945 OWNER.TABLE.COLUMN clause
WINDOW clause, 962 DESCRIBE statement [ESQL], 681
ORDER clause OwnerName property
CREATE TRIGGER statement, 652 sa_materialized_view_info system procedure, 1078
LOAD TABLE statement, 801
UNLOAD statement, 940 P
order of operations packages
SQL operator precedence, 12 installing Java classes, 787
order of SQL clauses

1346 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


removing Java classes, 851 character set conversion, CREATE USER
PAGE SIZE clause statement, 659
CREATE DATABASE statement, 512 character set conversion, GRANT statement, 763
page sizes maximum length, ALTER USER statement, 471
creating databases, 512 maximum length, CREATE USER statement, 659
page usage maximum length, GRANT statement, 763
tables, 1146 sa_verify_password system procedure, 1159
page_timeout option passwords, character set conversion on
SET MIRROR OPTION statement, 884 ALTER USER statement, 471
parallel backups PATINDEX function
BACKUP statement, 477 syntax, 290
parameterized views pattern length
about, 663 LIKE search condition, 40
parameters pattern matching
Interactive SQL script files, 830 case-sensitivity, 41
PARAMETERS statement collations, 41
Interactive SQL syntax, 830 LIKE search condition, 39
PARTITION BY clause PATINDEX function, 290
WINDOW clause, 961 pattern length, 40
partner servers REGEXP search condition, 43
ALTER MIRROR SERVER statement, 420 SIMILAR TO search condition, 45
changing with ALTER MIRROR SERVER PCTFREE clause
statement, 421 CREATE LOCAL TEMPORARY TABLE
CREATE MIRROR SERVER statement, 564 statement, 556
defining with CREATE MIRROR SERVER CREATE TABLE statement, 643
statement, 565 DECLARE LOCAL TEMPORARY TABLE
PASSTHROUGH FOR clause statement, 672
PASSTHROUGH statement [SQL Remote], 831 LOAD TABLE, 801
PASSTHROUGH FOR SUBSCRIPTION clause PCTFREE setting
PASSTHROUGH statement [SQL Remote], 831 ALTER TABLE statement, 451
passthrough mode CREATE LOCAL TEMPORARY TABLE syntax,
PASSTHROUGH statement [SQL Remote], 831 556
starting, 831 CREATE TABLE statement, 633
stopping, 831 DECLARE LOCAL TEMPORARY TABLE
PASSTHROUGH ONLY clause syntax, 672
PASSTHROUGH statement [SQL Remote], 831 LOAD TABLE syntax, 792
PASSTHROUGH statement percent sign
SQL Remote syntax, 831 comment indicator, 79
PASSTHROUGH STOP clause PERCENT_RANK function
PASSTHROUGH statement [SQL Remote], 831 syntax, 292
password_expiry_on_next_login option performance
login policies, 558 compression statistics, 1018
password_grace_time option preallocating space, 405
login policies, 558 recalibrating the database server, 400
password_life_time option recalibrating the I/O cost model, 403
login policies, 558 SQL Remote updates, 947
passwords PERL clause
INSTALL EXTERNAL OBJECT statement, 785

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1347


Index

permissions ALTER SPATIAL REFERENCE SYSTEM


dbspaces, 761 statement, 443
disabled objects, 764 CREATE SPATIAL REFERENCE SYSTEM
GRANT statement, 760 statement, 619
granting CONSOLIDATE, 754 plans
granting PUBLISH, 756 and cursors, 294
granting REMOTE, 758 example of saving a plan to a file, 230
procedures, 761 EXPLANATION function, 221
revoking, 863 getting text specification, 727
revoking ALL, 863 GRAPHICAL_PLAN function, 229
revoking ALTER, 863 PLAN function, 294
revoking BACKUP, 863 TRACED_PLAN function, 364
revoking CONNECT, 863 policy options
revoking CREATE ON, 863 altering using ALTER LOGIN POLICY statement,
revoking DBA, 863 415
revoking DELETE, 863 altering using ALTER USER statement, 470
revoking EXECUTE, 863 POLYGON FORMAT clause
revoking for sequences, 864 ALTER SPATIAL REFERENCE SYSTEM
revoking GROUP, 863 statement, 444
revoking INSERT, 863 CREATE SPATIAL REFERENCE SYSTEM
revoking INTEGRATED LOGIN, 863 statement, 621
revoking KERBEROS LOGIN, 863 polygon formats
revoking MEMBERSHIP IN GROUP, 863 Clockwise, 622
revoking PROFILE, 863 CounterClockwise, 622
revoking REFERENCES, 863 EvenOdd, 622
revoking RESOURCE, 863 polygon orientation
revoking SELECT, 863 Clockwise, 622
revoking UPDATE, 863 CounterClockwise, 622
revoking VALIDATE, 863 EvenOdd, 622
sequences, 761 pooling
SQL Remote REVOKE REMOTE statement, 862 enabling connection pooling, 904
SQL Remote revoking CONSOLIDATE, 860 population covariance
SQL Remote revoking PUBLISH, 860 about, 181
SQL Remote revoking REMOTE DBA, 861 population variance
SYSCOLAUTH view, 1266 about, 375
SYSCOLPERM system view, 1198 position locks
SYSTABAUTH consolidated view, 1278 sa_locks system procedure, 1073
SYSTABLEPERM system view, 1246 positioned DELETE statement
PHP clause syntax, 676
INSTALL EXTERNAL OBJECT statement, 785 POWER function
physical indexes syntax, 295
recorded in SYSPHYSIDX system view, 1222 precedence
PI function SQL operator precedence, 12
syntax, 294 PRECEDING clause
PLAN function WINDOW clause, 962
syntax, 294 PRECISION clause
planar model GET DESCRIPTOR statement [ESQL], 751
SET DESCRIPTOR statement [ESQL], 882

1348 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


predicates CREATE LOCAL TEMPORARY TABLE
about, 32 statement, 556
ALL search condition, 34 DECLARE LOCAL TEMPORARY TABLE
ANY search condition, 35 statement, 672
BETWEEN search condition, 37 PRIMARY KEY clause
comparison operators, 8 ALTER INDEX statement, 413
CONTAINS search condition, 47 ALTER TABLE statement , 456
EXISTS search condition, 53 CREATE TABLE statement, 640
explicit selectivity estimates, 56 REORGANIZE TABLE statement, 853
IN search condition, 46 VALIDATE statement, 955
IS DISTINCT FROM, 36 PRIMARY KEY constraint clause
IS NOT DISTINCT FROM, 36 CREATE TABLE statement, 640
IS NOT NULL search condition, 54 primary key locks
IS NULL search condition, 54 sa_locks system procedure, 1073
IS TRUE or FALSE search conditions, 54 primary keys
IS UNKNOWN search condition, 54 ALTER INDEX statement, 413
LIKE search condition, 39 clustering using the ALTER INDEX statement,
REGEXP search condition, 43 413
SIMILAR TO search condition, 45 CREATE SEQUENCE statement, 599
SOME search condition, 35 generating unique values, 279
SQL subqueries in, 34 generating unique values using UUIDs, 279
syntax, 32 integrity constraints in CREATE TABLE
three-valued logic, 55 statement, 640
preferred option order of columns in CREATE TABLE statement,
ALTER MIRROR SERVER statement, 422 640
CREATE MIRROR SERVER statement, 566 remote tables and the sp_remote_exported_keys
PREFILTER EXTERNAL NAME clause system procedure , 1166
ALTER TEXT CONFIGURATION statement, 466 remote tables and the sp_remote_imported_keys
prefilters system procedure, 1167
ALTER TEXT CONFIGURATION statement, 466 renaming using the ALTER INDEX statement, 413
dropping using ALTER TEXT UUIDs and GUIDs, 279
CONFIGURATION statement, 466 primary servers
PREFIX clause changing with ALTER MIRROR SERVER
ALTER TABLE statement , 457 statement, 420
CREATE TABLE statement, 636 defining with CREATE MIRROR SERVER
prefix searches statement, 564
CONTAINS search condition, 47 primary tables
PREPARE statement system views, 1208
embedded SQL syntax, 833 PRINT statement
PREPARE TO COMMIT statement Transact-SQL syntax, 836
syntax, 835 printing
prepared statements messages in the messages window, 836
dropping using the DROP STATEMENT PRIOR clause
statement, 706 FETCH statement , 729
executing, 722 procedure calls
preparing invoking using the CALL statement, 491
for two-phase commit, 835 PROCEDURE clause
PRESERVE clause ALTER DATABASE statement, 401

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1349


Index

CREATE PUBLICATION statement [MobiLink] Transact-SQL list, 999


[SQL Remote], 592 variable result sets, CREATE PROCEDURE
DESCRIBE statement, 685 statement , 586
procedure parameters variable result sets, CREATE PROCEDURE
listing in Interactive SQL, 684 statement [External call], 569
procedure profiling variable result sets, DESCRIBE statement [ESQL],
disabling from Interactive SQL, 1128 683
enabling from Interactive SQL, 1128 variable result sets, PREPARE statement, 834
in Interactive SQL, 1120 product name
sa_procedure_profile system procedure, 1103 retrieving, 1181
summary of procedures, 1105 PROFILE authority
viewing in Interactive SQL, 1105 GRANT statement, 760
ProcedureProfiling property REVOKE statement, 863
setting with sa_server_option, 1128 PROFILE authority clause
procedures GRANT statement, 762
adding comments using the COMMENT statement, PROFILE clause
499 REVOKE statement, 863
alphabetical list , 1001 ProfileFilterConn property
alphabetical list of system procedures, 1001 setting with sa_server_option, 1129
altering using the ALTER PROCEDURE ProfileFilterUser property
statement, 423 setting with sa_server_option, 1129
compared to functions, 139 profiling
CREATE PROCEDURE statement, 583 PROFILE authority, 762
creating in Transact-SQL, 583 PROMPT clause
creating SQL stored procedures, 585 INPUT statement, 777
creating web services, 575 properties
dropping using the DROP PROCEDURE CONNECTION_PROPERTY function, 171
statement, 700 DB_PROPERTY function, 202
executing in dynamic SQL, 719 PROPERTY function, 297
executing stored in Transact-SQL, 724 Properties property
exiting, 858 DB_EXTENDED_PROPERTY function, 197
extended list, 996 PROPERTY function
GRANT statement, 761 syntax, 297
interfacing to native procedures using CREATE PROPERTY_DESCRIPTION function
PROCEDURE statement, 567 syntax, 296
invoking using the CALL statement, 491 PROPERTY_NAME function
named parameters allowed when calling, 491 syntax, 298
native function calls, 571 PROPERTY_NUMBER function
RAISERROR statement, 838 syntax, 299
replacing external procedure interface, 569 proximity searches
replacing user-defined procedures, 586 CONTAINS search condition, 47
replacing web services, 576 PROXY clause
replicating using the ALTER PROCEDURE CREATE FUNCTION statement [web clients],
statement, 423 545
resuming execution of, 857 CREATE PROCEDURE statement [web clients] ,
returning values from, 858 579
selecting from, 740 proxy procedures
system, 995 creating web services, 575

1350 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


proxy tables Interactive SQL, 725
CREATE TABLE statement, 635 QuittingTime property
creating using the CREATE EXISTING TABLE setting with sa_server_option, 1129
statement, 532 quotation marks
PUBLIC clause compatibility with ASE, 31
SET OPTION statement, 886 database objects, 4
PUBLICATION clause single vs. double, 31
UPDATE statement, 948 SQL identifiers, 4
UPDATE statement [SQL Remote] , 945 QUOTE clause
publications LOAD TABLE statement, 801
ALTER PUBLICATION statement, 425 OUTPUT statement, 828
CREATE PUBLICATION statement, 592 UNLOAD statement, 940
DROP PUBLICATION statement, 701 quoted_identifier option
SQL Remote UPDATE statement , 947 setting with Transact-SQL SET statement, 901
UPDATE statement, 951 T-SQL expression compatibility, 31
PUBLISH permissions QUOTES clause
granting, 756 LOAD TABLE statement, 801
SQL Remote revoking, 860 UNLOAD statement, 940
publisher
address, 701 R
GRANT PUBLISH statement, 756 R-squared
remote, 758 regression lines, 313
SQL Remote address, 596 RADIANS function
SQL Remote addresses, 426 syntax, 301
PunctuationSensitivity property RAISERROR clause
DB_EXTENDED_PROPERTY function, 197 MERGE statement, 814
PURGE clause RAISERROR statement
FETCH statement, 730 syntax, 838
PUT statement raising
embedded SQL syntax, 837 RAISERROR statement, 838
putting RAND function
rows into cursors, 837 syntax, 301
random numbers
Q RAND function, 301
quantifiers range
expression quantifiers, 19 date type, 107
QUARTER function RANGE clause
syntax, 300 WINDOW clause, 962
query block RANK function
common element in SQL syntax, 395 syntax, 303
query-block ranking functions
common element in SQL syntax, 395 alphabetical list, 135
query-expression CUME_DIST function, 185
common element in SQL syntax, 395 DENSE_RANK function, 206
QUIT statement PERCENT_RANK function, 292
Interactive SQL syntax, 725 RANK function, 303
quitting rate properties

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1351


Index

incrementing values, 1155 text and image values from the database, 842
setting values, 1156 reading files
RAW using xp_read_file, 1182
CREATE SERVICE statement [HTTP web reading SQL statements from files
service], 431, 606 about, 840
raw properties READONLY clause
incrementing values, 1155 CREATE SERVER statement, 603
setting values, 1156 READPAST table hint
re-describing cursors FROM clause, 744
CREATE PROCEDURE statement, 587 ReadPK locks
CREATE PROCEDURE statement [External call], sa_locks system procedure, 1073
570 READTEXT statement
read committed Transact-SQL syntax, 842
FROM clause, 744 READUNCOMMITTED table hint
READ COMMITTED clause FROM clause, 744
REFRESH MATERIALIZED VIEW statement, REAL data type
843 comparing with dates and times, 125
read only syntax, 96
backups that do not require recovery, 481 REBUILD clause
defining read only mirror server, 564 ALTER INDEX statement, 414
locking tables, 808 RECOMPILE clause
read only scale out ALTER FUNCTION statement, 412
ALTER MIRROR SERVER statement, 420 ALTER PROCEDURE statement, 423
CREATE MIRROR SERVER statement, 564 ALTER VIEW statement, 473
dropping servers, 699 RECOVER clause
SET MIRROR OPTION statement, 883 BACKUP statement, 480
READ statement REFERENCES clause
syntax, 840 ALTER TABLE statement , 456
read uncommitted CREATE TABLE statement, 641
FROM clause, 744 REVOKE statement, 863
READ UNCOMMITTED clause REFERENCES permission
REFRESH MATERIALIZED VIEW statement, GRANT statement, 761
843 REVOKE statement, 863
READ_CLIENT_FILE function REFERENCES permission clause
syntax, 304 GRANT statement, 763
READCLIENTFILE authority REFERENCING clause
GRANT statement, 760 CREATE TRIGGER statement, 653
REVOKE statement, 863 referential integrity
READCLIENTFILE authority clause FROM clause, 740
GRANT statement, 762 match clause in CREATE TABLE statement, 641
READCOMMITTED table hint Referer
FROM clause, 744 HTTP_HEADER function, 242
READFILE authority REFRESH clause
GRANT statement, 760 ALTER TEXT INDEX statement, 468
REVOKE statement, 863 CREATE TEXT INDEX statement, 649
READFILE authority clause REFRESH MATERIALIZED VIEW statement
GRANT statement, 762 syntax, 843
reading REFRESH TEXT INDEX statement

1352 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


syntax, 846 REGR_COUNT function, 310
REFRESH TRACING LEVEL statement REGR_INTERCEPT function, 311
diagnostic tracing, 848 REGR_R2 function, 313
syntax, 848 REGR_SLOPE function, 314
REFRESH TRACING LEVELS statement REGR_SXX function, 315
populating sa_diagnostic_tracing_level table, 991 REGR_SXY function, 317
refresh types REGR_SYY function, 319
RefreshType property, 1078 regular expressions
refreshing about, 17
text index REFRESH TEXT INDEX, 846 assertion examples, 26
refreshing materialized views database collations and matching, 38
REFRESH clause, ALTER MATERIALIZED examples, 28
VIEW statement, 418 list of assertions, 26
REFRESH MATERIALIZED VIEWS statement, metacharacters, 19
843 REGEXP search condition, 18
RefreshType property REGEXP syntax, 43
sa_materialized_view_info system procedure, 1078 REGEXP_SUBSTR function, 305
REGEXP search condition SIMILAR TO search condition, 45
compared to LIKE and SIMILAR TO, 37 special character classes, 21
database collation and matching, 44 supported quantifiers, 19
matching sub-character classes, 43 syntax, 18
regular expressions, 18 wildcard, grouping, and sets, 19
syntax, 43 relationships
REGEXP_SUBSTR function system views, 1208
database collation and matching, 306 RELATIVE clause
regular expressions, 18 FETCH statement , 729
syntax, 305 relative paths
REGR_AVGX function INPUT statement, 773
syntax, 307 READ statement , 840
REGR_AVGY function RELEASE SAVEPOINT statement
syntax, 308 syntax, 849
REGR_COUNT function releasing
syntax, 310 savepoints, 849
REGR_INTERCEPT function REMAINDER function
syntax, 311 syntax, 320
REGR_R2 function RememberLastPlan property
syntax, 313 setting with sa_server_option, 1129
REGR_SLOPE function RememberLastStatement property
syntax, 314 setting with sa_server_option, 1129
REGR_SXX function REMOTE clause
syntax, 315 CREATE EVENT statement, 526
REGR_SXY function remote data access
syntax, 317 disconnecting, 429
REGR_SYY function FORWARD TO statement, 736
syntax, 319 REMOTE DBA authority
regression functions granting, 757
REGR_AVGX function, 307 remote DBA permissions
REGR_AVGY function, 308 SQL Remote revoking, 861

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1353


Index

REMOTE LOGIN clause remoteoptiontype view


CREATE EXTERNLOGIN statement, 534 about, 1228
remote message types REMOVE EXTERNAL OBJECT statement
dropping, 701 syntax, 851
SQL Remote altering, 426 REMOVE JAVA statement
SQL Remote creating, 596 syntax, 851
remote options removing
SET REMOTE OPTION statement [SQL Remote], Java classes, 851
892 permissions, 863
REMOTE permissions RENAME clause
granting, 758 ALTER DBSPACE statement , 406
SQL Remote revoking, 862 ALTER DOMAIN statement, 407
remote procedures ALTER INDEX statement, 413
CREATE PROCEDURE statement, 585 ALTER SPATIAL REFERENCE SYSTEM
creating in Transact SQL, 583 statement, 442
RESULT clause requirement, 589 ALTER SYNCHRONIZATION SUBSCRIPTION
REMOTE RESET statement statement [MobiLink] , 448
SQL Remote syntax, 850 ALTER TABLE statement , 461
remote servers ALTER TEXT INDEX statement, 468
altering attributes using the ALTER SERVER RESTORE DATABASE statement, 856
statement, 428 renaming
assigning logins for, 534 columns, 461
capabilities, determining using sp_servercaps, 1172 columns using the ALTER TABLE statement, 451
capabilities, SYSCAPABILITY system view, 1197 constraints, 461
CREATE SERVER statement, 601 tables, 461
CREATE TABLE statement, 633 tables using the ALTER TABLE statement, 451
disconnecting, 429 REORGANIZE TABLE statement
dropping logins for remote servers, 694 syntax, 852
dropping using the DROP SERVER statement, 703 reorganizing tables
sending SQL statements to, 736 REORGANIZE TABLE, 852
SYSCAPABILITYNAME system view, 1197 REPEAT function
remote tables syntax, 321
columns, 1164 REPEATABLE READ clause
CREATE TABLE statement, 635 REFRESH MATERIALIZED VIEW statement,
foreign keys and the sp_remote_exported_keys 843
system procedure, 1166 repeatable reads
foreign keys and the sp_remote_imported_keys FROM clause, 744
system procedure, 1167 REPEATABLEREAD table hint
listing using sp_remote_tables system procedure, FROM clause, 744
1170 REPLACE function
primary keys and the sp_remote_exported_keys syntax, 321
system procedure, 1166 replacing objects
primary keys and the sp_remote_imported_keys sa_make_object, 1074
system procedure, 1167 REPLICATE function
remote users syntax, 323
SQL Remote REVOKE REMOTE statement, 862 replication
remoteoption view ALTER TABLE statement, 451
about, 1228 request log

1354 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


processing with sa_get_request_times profile GRANT statement, 762
procedure, 1130 RESOURCE clause
request logging REVOKE statement, 863
analyzing the request log with RESTART WITH clause
sa_get_request_profile, 1053 ALTER SEQUENCE statement, 427
analyzing the request log with RESTORE DATABASE statement
sa_get_request_times, 1054 syntax, 855
enabling from Interactive SQL, 1130 RESTORE DEFAULT CALIBRATION clause
request timing ALTER DATABASE statement, 401
sa_performance_diagnostics system procedure, restoring
1095 databases from archives, 855
RequestFilterConn property RESULT clause
setting with sa_server_option, 1129 CREATE PROCEDURE statement, 586
RequestFilterDB property CREATE PROCEDURE statement [External call],
setting with sa_server_option, 1130 569
RequestLogFile property result sets
client statement caching, 1130 resuming execution of procedures, 857
setting with sa_server_option, 1130 retrieving multiple result sets, 857
RequestLogging property selecting from stored procedures, 740
setting with sa_server_option, 1130 unloading using the UNLOAD statement, 937
RequestLogMaxSize property variable, CREATE PROCEDURE statement , 586
setting with sa_server_option, 1131 variable, CREATE PROCEDURE statement
RequestLogNumFiles property [External call], 569
setting with sa_server_option, 1131 variable, DESCRIBE statement [ESQL], 683
requests variable, PREPARE statement, 834
obtaining timing information, 1095 RESUME statement
RequestTiming property not supported in Interactive SQL, 857
setting with sa_server_option, 1131 syntax, 857
reserved words resuming
how to use in syntax, 1 execution of procedures, 857
list of SQL keywords, 1 retrieving
sa_reserved_words system procedure, 1112 long column names, 683
SQL Anywhere Server, 1 multiple result sets, 857
using as identifiers, 31 retrieving dates and times from the database
RESET LOGIN POLICY clause about, 106
ALTER USER statement, 471 return codes
RESIGNAL statement EXIT statement [Interactive SQL], 725
syntax, 854 MAPI and SMTP system procedures, 997
resignaling RETURN statement
exceptions, 854 syntax, 858
RESOLVE clause RETURNED_LENGTH clause
CREATE TRIGGER statement, 651 GET DESCRIPTOR statement [ESQL], 751
resolving conflicts returning
CONFLICT function for SQL Remote, 167 values from procedures, 858
RESOURCE authority RETURNS clause
GRANT statement, 760 CREATE FUNCTION statement, 548
REVOKE statement, 863 CREATE FUNCTION statement [External call],
RESOURCE authority clause 535

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1355


Index

CREATE FUNCTION statement [web clients], REWRITE function


542 syntax, 324
REVERSE function RI constraints
syntax, 323 adding, deleting, or altering using the ALTER
REVOKE BACKUP statement TABLE statement, 451
syntax, 863 ALTER TABLE statement, 633
REVOKE CONNECT statement not renamed when underlying index is renamed,
syntax, 863 413
REVOKE CONSOLIDATE statement renaming using ALTER TABLE statement, 461
SQL Remote SQL syntax, 860 RIGHT function
REVOKE CREATE ON statement syntax, 326
syntax, 863 RIGHT OUTER JOIN clause
REVOKE DBA statement FROM clause SQL syntax, 738
syntax, 863 role names
REVOKE EXECUTE clause foreign keys in CREATE TABLE statement, 641
REVOKE statement, 863 role-name
REVOKE GROUP statement common element in SQL syntax, 395
syntax, 863 ROLLBACK statement
REVOKE INTEGRATED LOGIN statement syntax, 865
syntax, 863 ROLLBACK TO SAVEPOINT statement
REVOKE KERBEROS LOGIN statement syntax, 866
syntax, 863 ROLLBACK TRANSACTION statement
REVOKE MEMBERSHIP IN GROUP statement Transact-SQL syntax, 867
syntax, 863 ROLLBACK TRIGGER statement
REVOKE PROFILE statement syntax, 868
syntax, 863 rolling back
REVOKE PUBLISH statement transactions, 867
SQL Remote SQL syntax, 860 transactions to savepoints, 866
REVOKE REMOTE DBA statement triggers, 868
SQL Remote SQL syntax, 861 ROLLUP operation
REVOKE REMOTE statement GROUP BY clause, 767
SQL Remote SQL syntax, 862 GROUPING function, 231
REVOKE RESOURCE statement WITH ROLLUP clause, 767
syntax, 863 ROOT clause
REVOKE statement CREATE SERVER statement, 603
syntax, 863 round earth model
REVOKE VALIDATE statement ALTER SPATIAL REFERENCE SYSTEM
syntax, 863 statement, 443
revoking CREATE SPATIAL REFERENCE SYSTEM
REVOKE statement, 863 statement, 619
SQL Remote CONSOLIDATE permissions, 860 ROUND function
SQL Remote PUBLISH permissions, 860 syntax, 327
SQL Remote remote DBA permissions, 861 round-off errors
SQL Remote REMOTE permissions, 862 about, 89
revoking consolidate permissions rounding errors
SQL Remote CONSOLIDATE permissions, 860 about, 89
revoking consolidated permissions DOUBLE, 92
REVOKE statement, 863 FLOAT, 93

1356 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


REAL, 96 sa_audit_string system procedure
Row Constructor algorithm syntax, 1009
DUMMY system table, 965 sa_char_terms system procedure
ROW DELIMITED BY clause syntax, 1009
LOAD TABLE statement, 801 sa_check_commit system procedure
UNLOAD statement, 940 syntax, 1011
row generator sa_clean_database system procedure
RowGenerator table (dbo), 994 syntax, 1012
sa_rowgenerator system procedure, 1113 sa_column_stats system procedure
row limitation clause syntax, 1014
DELETE statement, 679 sa_conn_activity system procedure
SELECT statement, 873 syntax, 1016
UPDATE statement, 949 sa_conn_compression_info system procedure
row limits syntax, 1018
about, 871 sa_conn_info system procedure
row locks syntax, 1020
sa_locks system procedure, 1073 sa_conn_list system procedure
ROW_NUMBER function syntax, 1023
syntax, 327 sa_conn_options system procedure
rowcount option syntax, 1024
setting with Transact-SQL SET statement, 901 sa_conn_properties system procedure
RowGenerator syntax, 1025
system table, 994 sa_convert_ml_progress_to_timestamp system
ROWID function procedure
syntax, 329 syntax, 1026
rows sa_convert_timestamp_to_ml_progress system
deleting all from a table, 933 procedure
deleting from cursors, 676 syntax, 1027
deleting from databases, 678 sa_copy_cursor_to_temp_table system procedure
fetching from cursors, 728 syntax, 1028
inserting in bulk, 792 sa_db_info system procedure
inserting into tables, 780 syntax, 1029
inserting using cursors, 837 sa_db_list system procedure
limiting number returned, 871 syntax, 1031
SELECT statement, 871 sa_db_properties system procedure
unloading using the UNLOAD statement, 937 syntax, 1032
updating, 948 sa_dependent_views system procedure
ROWS clause syntax, 1033
WINDOW clause, 962 sa_describe_cursor system procedure
RTRIM function syntax, 1035
syntax, 330 sa_describe_query system procedure
rules syntax, 1037
SQL language syntax, 1 sa_describe_shapefile system procedure
syntax, 1040
S sa_diagnostic_auxiliary_catalog table
sa_ansi_standard_packages system procedure about, 980
about, 1007 sa_diagnostic_blocking table
about, 981

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1357


Index

sa_diagnostic_cachecontents table sa_get_server_messages system procedure


about, 982 syntax, 1056
sa_diagnostic_connection table sa_get_table_definition system procedure
about, 982 syntax, 1057
sa_diagnostic_cursor table sa_get_user_status system procedure
about, 983 syntax, 1058
sa_diagnostic_deadlock table sa_http_header_info system procedure
about, 984 syntax, 1059
sa_diagnostic_hostvariable table sa_http_php_page system procedure
about, 985 syntax, 1060
sa_diagnostic_internalvariable table sa_http_php_page_interpreted system procedure
about, 986 syntax, 1060
sa_diagnostic_query table sa_http_variable_info system procedure
about, 987 syntax, 1062
sa_diagnostic_request table sa_index_density system procedure
about, 989 syntax, 1063
sa_diagnostic_statement table sa_index_levels system procedure
about, 990 syntax, 1065
sa_diagnostic_statistics table sa_install_feature system procedure
about, 990 syntax, 1067
sa_diagnostic_tracing_level table sa_java_loaded_classes system procedure
about, 991 syntax, 1068
sa_disable_auditing_type system procedure sa_list_cursors system procedure
syntax, 1042 syntax, 1069
sa_disk_free_space system procedure sa_load_cost_model system procedure
syntax, 1043 syntax, 1070
sa_enable_auditing_type system procedure sa_locks system procedure
syntax, 1044 syntax, 1071
sa_eng_properties system procedure sa_make_object system procedure
syntax, 1045 syntax, 1074
sa_external_library_unload system procedure sa_materialized_view_can_be_immediate system
syntax, 1046 procedure
sa_flush_cache system procedure combining results with sa_materialized_view_info,
syntax, 1047 1080
sa_flush_statistics system procedure syntax, 1076
syntax, 1047 sa_materialized_view_info system procedure
sa_get_bits system procedure AvailForOptimization property, 1078
syntax, 1048 combining results with
sa_get_dtt system procedure sa_materialized_view_can_be_immediate, 1080
syntax, 1050 DataLastModified property, 1078
sa_get_dtt_groupreads system procedure examples, 1080
syntax, 1051 OwnerName property, 1078
sa_get_histogram system procedure Status property, 1078
syntax, 1051 syntax, 1077
sa_get_request_profile system procedure ViewName property, 1078
syntax, 1053 sa_migrate system procedure
sa_get_request_times system procedure syntax, 1083
syntax, 1054 sa_migrate_create_fks system procedure

1358 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


syntax, 1085 sa_server_option system procedure
sa_migrate_create_remote_fks_list system procedure syntax, 1120
syntax, 1087 sa_set_http_header system procedure
sa_migrate_create_remote_table_list system syntax, 1134
procedure sa_set_http_option system procedure
syntax, 1088 syntax, 1135
sa_migrate_create_tables system procedure sa_set_soap_header system procedure
syntax, 1089 syntax, 1139
sa_migrate_data system procedure sa_set_tracing_level system procedure
syntax, 1090 syntax, 1140
sa_migrate_drop_proxy_tables system procedure sa_snapshots system procedure
syntax, 1091 syntax, 1141
sa_mirror_server_status system procedure sa_split_list system procedure
syntax, 1092 syntax, 1142
sa_nchar_terms system procedure sa_statement_text system procedure
syntax, 1094 syntax, 1145
sa_performance_diagnostics system procedure sa_table_fragmentation system procedure
syntax, 1095 syntax, 1145
sa_performance_statistics system procedure sa_table_page_usage system procedure
syntax, 1101 syntax, 1146
sa_post_login_procedure system procedure sa_table_stats system procedure
syntax, 1102 syntax, 1147
sa_procedure_profile system procedure sa_text_index_stats system procedure
syntax, 1103 syntax, 1149
sa_procedure_profile_summary system procedure sa_text_index_vocab system procedure
syntax, 1105 syntax, 1150
sa_recompile_views system procedure sa_text_index_vocab_nchar system procedure
syntax, 1108 syntax, 1152
sa_refresh_materialized_views system procedure sa_transactions system procedure
syntax, 1108 syntax, 1153
sa_refresh_text_indexes system procedure sa_unload_cost_model system procedure
syntax, 1109 syntax, 1154
sa_remove_tracing_data system procedure sa_user_defined_counter_add system procedure
syntax, 1110 syntax, 1155
sa_report_deadlocks system procedure sa_user_defined_counter_set system procedure
syntax, 1110 syntax, 1156
sa_reserved_words system procedure sa_validate system procedure
syntax, 1112 syntax, 1157
sa_reset_identity system procedure sa_verify_password system procedure
syntax, 1112 syntax, 1159
sa_rowgenerator system procedure sample covariance
syntax, 1113 about, 182
sa_save_trace_data system procedure sample variance
syntax, 1116 about, 377
sa_send_udp system procedure SAVE OPTION VALUES clause
syntax, 1116 ALTER TEXT CONFIGURATION statement, 466
sa_server_messages system procedure SAVE TRANSACTION statement
syntax, 1117 Transact-SQL syntax, 869

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1359


Index

SAVEPOINT statement ANY, 35


syntax, 870 BETWEEN, 37
savepoint-name CONTAINS, 47
common element in SQL syntax, 395 EXISTS, 53
savepoints explicit selectivity estimates, 56
creating, 870 IN, 46
releasing, 849 IS DISTINCT FROM, 36
rolling back to savepoints, 866 IS NOT DISTINCT FROM, 36
SCALE clause IS NOT NULL, 54
GET DESCRIPTOR statement [ESQL], 751 IS NULL, 54
SET DESCRIPTOR statement [ESQL], 882 IS TRUE or FALSE search conditions, 54
scale out IS UNKNOWN search condition, 54
dropping servers, 699 LIKE, 39
SET MIRROR OPTION statement, 883 REGEXP, 43
SCHEDULE clause SIMILAR TO, 45
CREATE EVENT statement, 529 SOME, 35
scheduled events subqueries in, 34
triggering, 932 syntax, 32
WAITFOR statement, 957 three-valued logic, 55
scheduling truth value, 54
creating events using the CREATE EVENT search-condition
statement, 526 common element in SQL syntax, 395
events using the ALTER EVENT statement, 408 SECOND function
events using the CREATE EVENT statement, 526 syntax, 331
WAITFOR, 957 SECONDS function
schema locks syntax, 332
sa_locks system procedure, 1073 SECURE clause
schemas ALTER SERVICE statement [HTTP web service],
creating, 597 431
default system views, 1195 ALTER SERVICE statement [SOAP web service],
system tables, 965 436
SCRIPT VERSION clause CREATE SERVICE statement [HTTP web
CREATE SYNCHRONIZATION service], 434, 608
SUBSCRIPTION statement [MobiLink], 630 CREATE SERVICE statement [SOAP web
scripted upload service], 440, 615
converting progress values to a TIMESTAMP, secured features
1026 changing with sa_server_option, 1132
converting progress values to an UNSIGNED SecureFeatures property
BIGINT, 1027 setting with sa_server_option, 1132
CREATE PUBLICATION syntax, 592 security
SCROLL clause replication, 757
DECLARE CURSOR statement, 668 SQL Remote replication, 861
FOR statement, 733 SELECT
SCROLL cursors converting T-SQL, 380
declaring, 666 SELECT clause
search conditions REVOKE statement, 863
about, 32 select from DML
ALL, 34 FROM clause, 743

1360 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SELECT list ALTER SEQUENCE statement, 427
describing cursors, 681 CREATE SEQUENCE statement, 599
SELECT list clause DROP SEQUENCE statement, 702
SELECT statement, 874 revoking usage permissions, 864
SELECT LIST FOR clause sequences
DESCRIBE statement [ESQL], 681 adding comments using the COMMENT statement,
SELECT permission 499
GRANT statement, 761 ALTER SEQUENCE statement, 427
REVOKE statement, 863 CREATE SEQUENCE statement, 599
SELECT permission clause CREATE TABLE statement, 454, 638
GRANT statement, 763 DROP SEQUENCE statement, 702
SELECT statement granting usage permissions, 761
selecting from stored procedures, 740 revoking usage permissions, 864
setting database options, 878 SELECT statement, 878
syntax, 871 serializable
Transact-SQL syntax, 880 FROM clause, 744
selecting SERIALIZABLE clause
for unloading using the UNLOAD statement, 937 REFRESH MATERIALIZED VIEW statement,
forming intersections, 788 843
forming set differences, 717 SERIALIZABLE table hint
forming unions, 936 FROM clause, 744
rows, 871 Server
selectivity estimates HTTP_RESPONSE_HEADER function, 244
source of estimates, 213 server options
user-defined, 56 setting with sa_server_option system procedure,
self_recursion option 1120
setting with Transact-SQL SET statement, 901 server-option clause
SEND AT clause ALTER MIRROR SERVER statement, 422
about, 754 CREATE MIRROR SERVER statement, 565
GRANT CONSOLIDATE statement [SQL ServerIdle system event
Remote], 754 example, 820
GRANT REMOTE statement [SQL Remote], 758 servers
publish, 756 altering remote attributes using the ALTER
SEND EVERY clause SERVER statement, 428
about, 754 creating, 601
GRANT CONSOLIDATE statement [SQL creating events for idle servers using the CREATE
Remote], 754 EVENT statement, 526
GRANT REMOTE statement [SQL Remote], 758 dropping remote servers , 703
sending starting database, 910
SQL statements to remote servers, 736 stopping database, 921
sending dates and times to the database services
about, 102 adding comments using the COMMENT statement,
SENSITIVE clause 499
DECLARE CURSOR statement, 668 altering HTTP services using ALTER SERVICE
FOR statement, 734 statement [HTTP web service], 431
sequence generator altering SOAP services using ALTER SERVICE
adding comments using the COMMENT statement, statement [SOAP web service], 436
499

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1361


Index

dropping web services using the DROP SERVICE SQL Remote syntax, 892
statement, 704 SET SCRIPT VERSION clause
SessionTimeout option ALTER SYNCHRONIZATION SUBSCRIPTION
sa_set_http_option system procedure, 1135 statement [MobiLink] , 448
SET clause START SYNCHRONIZATION SCHEMA
CREATE FUNCTION statement [web clients], CHANGE statement, 917
545 SET SESSION AUTHORIZATION statement
CREATE PROCEDURE statement [web clients], syntax, 904
579 SET SQLCA statement
redirection URIs, 579 embedded SQL syntax, 898
UPDATE (positioned) statement, 943 SET statement
UPDATE statement, 949 Interactive SQL syntax, 889
UPDATE statement [SQL Remote] , 945 syntax, 899
SET CONNECTION statement Transact-SQL syntax, 901
embedded SQL syntax, 881 SET TEMPORARY OPTION statement
Interactive SQL syntax, 881 Interactive SQL syntax, 889
SET DESCRIPTOR statement syntax, 886
embedded SQL syntax, 882 SET_BIT function
SET HIDDEN clause syntax, 333
ALTER EVENT statement, 410 SET_BITS function
ALTER FUNCTION statement, 412 syntax, 334
ALTER MATERIALIZED VIEW statement, 417 sets
ALTER PROCEDURE statement, 423 regular expressions, 19
ALTER VIEW statement, 473 setting
SET MIRROR OPTION statement connections, 881
syntax, 883 descriptor areas, 882
set operators options, 886
EXCEPT statement, 717 options in Interactive SQL, 889
INTERSECT statement, 788 options in Transact-SQL, 901
NULL, 65 remote options, 892
set difference, 717 SQLCAs, 898
set intersection, 788 users, 904
set union, 936 values of SQL variables, 899
UNION statement, 936 SETUSER statement
SET OPTION statement syntax, 904
Interactive SQL syntax, 889 shapefiles
syntax, 886 loading using the INPUT statement, 773
Transact-SQL syntax, 901 loading using the LOAD TABLE statement, 799
SET PARTNER FAILOVER clause loading using the st_geometry_load_shapefile
ALTER DATABASE statement, 402 system procedure, 1178
SET PERMANENT statement SHARE BY ALL clause
Interactive SQL syntax, 889 CREATE TABLE statement, 635
SET REMOTE OPTION statement shutting down
common options, 894 databases, 918
file options, 894 SIGN function
ftp options, 895 syntax, 335
http options, 895 SIGNAL statement
smtp options, 897 syntax, 906

1362 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


signaling snapshot isolation
errors, 838 BEGIN SNAPSHOT statement, 483
exceptions, 854 sa_snapshots system procedure, 1141
SIMILAR function sa_transactions system procedure, 1153
syntax, 336 using with full text search, 650
SIMILAR TO search condition snapshots
compared to REGEXP and LIKE, 37 BEGIN SNAPSHOT statement, 483
database collation and matching, 46 SOAP
matching sub-character classes, 45 CREATE SERVICE statement [SOAP web
regular expressions, 18 service], 437, 612
syntax, 45 SOAP functions
SIN function alphabetical list, 141
syntax, 337 SOAP headers
SIZE clause setting, 1139
ATTACH TRACING statement, 475 SOAP over HTTP services
skew CREATE SERVICE statement [SOAP web
detecting in indexes using sa_index_density, 1063 service], 611
SKIP clause SOAP services
LOAD TABLE statement, 801 data typing, 437, 612
MERGE statement, 815 SOAP system procedures
slash-asterisk alphabetical list, 996
comment indicator, 79 SOAP_HEADER function
slope syntax, 338
regression lines, 314 SOAPHEADER clause
SMALLDATETIME data type CREATE FUNCTION statement [web clients],
sending dates and times to the database, 102 542
syntax, 111 CREATE PROCEDURE statement [web clients],
SMALLINT data type 581
comparing with dates and times, 125 SOME search condition
syntax, 97 syntax, 35
SMALLMONEY data type sort keys
syntax, 99 generating using the SORTKEY function, 339
SMTP sorting
extended system procedures, 996 SORTKEY function, 339
return codes, 997 SORTKEY function
starting email sessions, 1189 collation tailoring, 339
stopping email sessions, 1192 syntax, 339
SMTP clause SOUNDEX function
GRANT CONSOLIDATE statement [SQL syntax, 342
Remote], 754 SP
snap to grid statement indicators, 398
SNAP TO GRID clause, ALTER SPATIAL sp_addgroup system procedure
REFERENCE SYSTEM statement, 443 Adaptive Server Enterprise system procedures, 999
SNAP TO GRID clause, CREATE SPATIAL sp_addlogin system procedure
REFERENCE SYSTEM statement, 621 Adaptive Server Enterprise system procedures, 999
SNAPSHOT clause sp_addmessage system procedure
REFRESH MATERIALIZED VIEW statement, about, 563
843 Adaptive Server Enterprise system procedures, 999

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1363


Index

sp_addtype system procedure sp_special_columns catalog procedure


Adaptive Server Enterprise system procedures, 999 about, 1000
sp_adduser system procedure sp_sproc_columns catalog procedure
Adaptive Server Enterprise system procedures, 999 about, 1000
sp_changegroup system procedure sp_statistics catalog procedure
Adaptive Server Enterprise system procedures, 999 about, 1000
sp_column_privileges catalog procedure sp_stored_procedures catalog procedure
about, 1000 about, 1000
sp_columns catalog procedure sp_tables catalog procedure
about, 1000 about, 1000
sp_dropgroup system procedure sp_tsql_environment system procedure
Adaptive Server Enterprise system procedures, 999 syntax, 1173
sp_droplogin system procedure SPACE function
Adaptive Server Enterprise system procedures, 999 syntax, 343
sp_dropmessage system procedure spatial data
Adaptive Server Enterprise system procedures, 999 ALTER SPATIAL REFERENCE SYSTEM
sp_droptype system procedure statement, 442
Adaptive Server Enterprise system procedures, 999 CREATE SPATIAL REFERENCE SYSTEM
sp_dropuser system procedure statement, 616
Adaptive Server Enterprise system procedures, 999 CREATE SPATIAL UNIT OF MEASURE
sp_fkeys catalog procedure statement, 624
about, 1000 disassembling geometries, 1174
sp_forward_to_remote_server system procedure DROP SPATIAL REFERENCE SYSTEM
syntax, 1159 statement, 704
sp_get_last_synchronize_result system procedure DROP SPATIAL UNIT OF MEASURE statement,
syntax, 1161 705
sp_getmessage system procedure importing ESRI shapefiles, 799
Adaptive Server Enterprise system procedures, 999 ISYSSPATIALREFERENCESYSTEM system
sp_helptext system procedure table, 976
Adaptive Server Enterprise system procedures, 999 ISYSUNITOFMEASURE system table, 978
sp_login_environment system procedure st_geometry_load_shapefile system procedure,
syntax, 1164 1178
sp_password system procedure TREAT function, 365
Adaptive Server Enterprise system procedures, 999 troubleshooting invalid geometries, 1174
sp_pkeys catalog procedure spatial reference systems
about, 1000 adding comments using the COMMENT statement,
sp_remote_columns system procedure 499
syntax, 1164 installing predefined , 1067
sp_remote_exported_keys system procedure special character classes
syntax, 1166 regular expressions, 21
sp_remote_imported_keys system procedure special characters
syntax, 1167 allowed syntax in a full text query string, 52
sp_remote_primary_keys system procedure SQL strings, 7
syntax, 1169 used in binary, 6
sp_remote_tables system procedure used in strings , 7
syntax, 1170 special tables
sp_servercaps system procedure about, 965
syntax, 1172 special values

1364 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


about, 58 return NULL if you specify NULL argument, 133
CREATE TABLE statement, 453, 637 SOAP, 141
CURRENT DATABASE, 58 string, 142
CURRENT DATE, 58 system, 144
CURRENT PUBLISHER, 59 text, 145
CURRENT REMOTE USER, 59 types of functions, 133
CURRENT TIME, 60 user defined, 138
CURRENT TIMESTAMP, 61 SQL keywords
CURRENT USER, 62 list of reserved words, 1
CURRENT UTC TIMESTAMP, 63 sa_reserved_words system procedure, 1112
CURRENT_TIMESTAMP, 61 SQL language elements
CURRENT_USER, 62 about, 1
LAST USER, 63 SQL Remote
NULL, 64 articles SYSARTICLE, 1196
SQLCODE, 67 articles SYSARTICLECOL, 1196
SQLSTATE, 67 creating subscriptions, 626
TIMESTAMP, 69 setting remote options, 892
USER, 70 SYSARTICLE system view, 1196
UTC TIMESTAMP, 71 SYSARTICLECOL system view, 1196
special views SYSPUBLICATION system view, 1226
about, 1195 SYSPUBLICATIONS consolidated view, 1272
special-value SYSREMOTEOPTION system view, 1228
common element in SQL syntax, 396 SYSREMOTEOPTIONS consolidated view, 1273
Specification property SYSREMOTEOPTIONTYPE system view, 1228
DB_EXTENDED_PROPERTY function, 197 SYSREMOTETYPE system view, 1229
SQL SYSREMOTETYPES consolidated view, 1273
alphabetical list of SQL Anywhere Server SYSREMOTEUSER system view, 1229
statements, 398 SYSREMOTEUSERS consolidated view, 1274
SQL descriptor area SQL Remote system views
INCLUDE statement, 772 article system view, 1196
inserting rows using cursors, 837 SYSARTICLECOL, 1196
SQL descriptor areas SYSPUBLICATION system view, 1226
DESCRIBE statement [ESQL], 681 SYSPUBLICATIONS consolidated view, 1272
SQL Flagger SYSREMOTEOPTION, 1228
SQLFLAGGER function, 344 SYSREMOTEOPTIONS consolidated view, 1273
testing a SQL statement for non-core extensions, SYSREMOTEOPTIONTYPE, 1228
1007 SYSREMOTETYPES consolidated view, 1273
SQL functions SYSREMOTEUSER , 1229
aggregate, 133 SYSREMOTEUSERS consolidated view, 1274
bit array, 135 SQL script files
data type conversion, 135 parameters for Interactive SQL, 830
date and time, 136 reading SQL statements from, 840
HTTP, 141 SQL SECURITY clause
image, 145 CREATE FUNCTION statement [External call],
introduction, 133 536
miscellaneous, 140 CREATE FUNCTION statement [user defined],
numeric, 140 549
ranking, 135 CREATE PROCEDURE statement, 588

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1365


Index

CREATE PROCEDURE statement [External call], IS NULL search condition, 54


571 IS TRUE or FALSE search condition, 54
SQL Server keywords, 1
migrating to SQL Anywhere using sa_migrate LAST USER special value, 63
system procedure, 1084 LIKE search condition, 39
SQL standards local variables, 73
testing compliance, 344 logical operators, 9
SQL statements NULL value, 64
alphabetical list of SQL Anywhere Server operator precedence, 12
statements, 398 operators, 8
documentation conventions, 395 predicates, 32
installing Java classes, 787 REGEXP search condition, 43
sending to remote servers, 736 search conditions, 32
SQL syntax SIMILAR TO search condition, 45
ALL search condition, 34 SOME search condition, 35
alphabetical list of SQL Anywhere Server special values, 58
statements, 398 SQLCODE special value, 67
alphabetical list of system procedures, 1001 SQLSTATE special value, 67
ANY search condition, 35 string operators, 10
arithmetic operators, 10 strings, 5
BETWEEN search condition, 37 subqueries, 15
bitwise operators, 11 subqueries in search conditions, 34
CASE expression, 16 three-valued logic, 55
column names, 14 TIMESTAMP special value, 69
comments, 79 Transact-SQL expression compatibility, 31
comparison operators, 8 USER special value, 70
connection-level variables, 74 UTC TIMESTAMP special value, 71
constants , 6 variables, 72
constants in expressions, 14 SQL to Java data type conversion
CONTAINS search condition, 47 about, 131
CURRENT DATABASE special value, 58 SQL variables
CURRENT DATE special value, 58 creating, 660
CURRENT PUBLISHER special value, 59 declaring, 673
CURRENT REMOTE USER special value, 59 dropping using the DROP VARIABLE statement,
CURRENT TIME special value, 60 716
CURRENT TIMESTAMP special value, 61 setting values, 899
CURRENT USER special value, 62 SQL/1999
CURRENT UTC TIMESTAMP special value, 63 testing SQL compliance, 344
CURRENT_TIMESTAMP special value, 61 SQL/19992
CURRENT_USER special value, 62 testing SQL compliance, 344
documentation conventions, 395 SQL/2003
EXISTS search condition, 53 testing SQL compliance, 344
expressions, 12 SQL/2008
functions, 133 testing SQL compliance, 344
identifiers, 4 SQLCA
IF expressions, 15 INCLUDE statement, 772
IN search condition, 46 SQLCA clause
IS NOT NULL search condition, 54 INCLUDE statement, 772

1366 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQLCAs syntax, 1178
setting, 898 ST_SPATIAL_REFERENCE_SYSTEMS
SQLCODE consolidated view, 1261
special value, 67 ST_UNITS_OF_MEASURE
SQLDA consolidated view, 1264
allocating memory for, 398 standard deviation
deallocating, 665 STDDEV function, 346
DESCRIBE statement [ESQL], 681 STDDEV_POP function, 346
EXECUTE statement, 722 STDDEV_SAMP function, 348
getting information from, 751 START AT clause
inserting rows using cursors, 837 DELETE statement, 679
setting, 882 SELECT statement, 873
UPDATE (positioned) statement, 943 UPDATE statement, 949
SQLDA clause START DATABASE statement
INCLUDE statement, 772 syntax, 907
SQLDescribeCol START DATE clause
describing CHAR data types, 81 ALTER EVENT statement, 409
describing NCHAR data types, 84 CREATE EVENT statement, 529
describing NVARCHAR data types, 85 START EXTERNAL ENVIRONMENT statement
describing VARCHAR data types, 87 syntax, 911
SQLDIALECT function START JAVA statement
syntax, 343 syntax, 912
SQLERROR clause START LOGGING statement
WHENEVER statement [ESQL], 959 Interactive SQL syntax, 913
SQLFLAGGER function START SERVER statement
syntax, 344 Interactive SQL syntax, 910
SQLSetConnectAttr START SUBSCRIPTION statement
using with MESSAGE TO CLIENT, 821 SQL Remote syntax, 914
SQLSTATE START SYNCHRONIZATION DELETE statement
conformance with ISO/ANSI standard, 67 MobiLink syntax, 915
special value, 67 START SYNCHRONIZATION SCHEMA CHANGE
SQLWARNING clause statement
WHENEVER statement [ESQL], 959 MobiLink syntax, 916
SQRT function START TIME clause
syntax, 345 ALTER EVENT statement, 409
square brackets CREATE EVENT statement, 529
database objects, 4 START WITH clause
SQL identifiers, 4 CREATE SEQUENCE statement, 599
square root function starting
SQRT function, 345 creating events using the CREATE EVENT
SRIDs statement, 526
choosing a SRID when creating a spatial reference database servers, 910
system, 617 databases, 907
ST_GEOMETRY_COLUMNS external environments using START EXTERNAL
consolidated view, 1260 ENVIRONMENT statement, 911
st_geometry_dump system procedure Java VM using the START JAVA statement, 912
syntax, 1174 logging in Interactive SQL, 913
st_geometry_load_shapefile system procedure passthrough mode, 831

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1367


Index

SQL Remote subscriptions during database sa_materialized_view_info system procedure, 1078


extraction, 850 STDDEV function
subscriptions, 914 syntax, 346
state information files STDDEV_POP function
ALTER MIRROR SERVER statement, 422 syntax, 346
CREATE MIRROR SERVER statement, 566 STDDEV_SAMP function
state_file option syntax, 348
ALTER MIRROR SERVER statement, 422 STOP clause
CREATE MIRROR SERVER statement, 566 WHENEVER statement [ESQL], 959
statement label STOP DATABASE clause
common element in SQL syntax, 396 STOP DATABASE statement, 918
statement labels STOP DATABASE statement
GOTO Transact-SQL statement, 754 syntax, 918
statement syntax STOP EXTERNAL ENVIRONMENT statement
alphabetical list of SQL Anywhere Server syntax, 919
statements, 398 STOP JAVA statement
documentation conventions, 395 syntax, 920
statement-list STOP LOGGING statement
common element in SQL syntax, 396 Interactive SQL syntax, 921
statements STOP SERVER statement
alphabetical list of SQL Anywhere Server syntax, 921
statements, 398 STOP SUBSCRIPTION statement
dropping prepared statements, 706 SQL Remote syntax, 922
executing prepared, 722 STOP SYNCHRONIZATION DELETE statement
grouping in the BEGIN statement, 484 MobiLink syntax, 924
grouping in the BEGIN statement [TSQL], 486 STOP SYNCHRONIZATION SCHEMA CHANGE
preparing, 833 statement
static cursors MobiLink syntax, 929
declaring, 666 STOPLIST clause
statistics ALTER TEXT CONFIGURATION statement, 465
CREATE STATISTICS statement, 625 stoplists
dropping using the DROP STATISTICS statement, CREATE STOPLIST clause, 465
706 STOPLIST clause, 465
flushing to disk, 1047 stopping
loading, 792 database servers, 921
only partially updated by LOAD TABLE, 804 external environments using STOP EXTERNAL
retrieving using sa_get_histogram system ENVIRONMENT statement, 919
procedure, 1051 Java VM, 920
SYSCOLSTAT system view, 1199 logging in Interactive SQL, 921
updating using the ALTER SERVICE statement, passthrough mode, 831
445 stopping databases
STATISTICS clause STOP DATABASE statement, 918
LOAD TABLE statement, 803 stopping subscriptions
statistics cleaner STOP SUBSCRIPTION statement, 922
controlling with sa_server_option, 1132 STORAGE FORMAT clause
StatisticsCleaner property ALTER SPATIAL REFERENCE SYSTEM
setting with sa_server_option, 1132 statement, 444
Status property

1368 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


CREATE SPATIAL REFERENCE SYSTEM removing trailing blanks , 330
statement, 622 replacing, 321
storage formats SQL functions, 142
ALTER SPATIAL REFERENCE SYSTEM Transact-SQL, 31
statement, 444 STRIP clause
CREATE SPATIAL REFERENCE SYSTEM LOAD TABLE statement, 802
statement, 622 strong encryption
stored functions CREATE DATABASE statement, 512
native function calls, 537 STRTOUUID function
stored procedures syntax, 351
converting T-SQL, 380 STUFF function
creating, 585 syntax, 352
creating in Transact SQL, 583 su
creating web services, 575 setting users, 904
executing in dynamic SQL, 719 sub-character classes
executing in Transact-SQL, 724 REGEXP search condition, 43
INPUT statement cannot be used, 778 regular expressions, 21
native function calls, 571 SIMILAR TO search condition, 45
selecting from, 740 SUBDIRS clause
system procedures, 995 CREATE SERVER statement, 603
STR function subqueries
syntax, 349 evaluate to NULL if no matching rows, 15
STRING function in SQL search conditions, 34
syntax, 350 syntax, 15
string functions SUBSCRIBE BY clause
alphabetical list, 142 ALTER PUBLICATION statement, 425
string length CREATE PUBLICATION statement [MobiLink]
LENGTH function, 259 [SQL Remote], 593
string literals UPDATE statement, 948
about, 7 UPDATE statement [SQL Remote] , 945
escape sequences, 7 subscriptions
special characters, 7 ALTER SYNCHRONIZATION SUBSCRIPTION
string operators statement, 447
syntax, 10 CREATE SUBSCRIPTION statement [SQL
string position Remote], 626
LOCATION function, 264 CREATE SYNCHRONIZATION
string-expression SUBSCRIPTION statement, 629
common element in SQL syntax, 396 DROP SUBSCRIPTION statement, 707
string_rtruncation option DROP SYNCHRONIZATION SUBSCRIPTION
setting with Transact-SQL SET statement, 901 statement, 709
strings SQL Remote REMOTE RESET statement , 850
about, 5 SQL Remote UPDATE statement, 947
ambiguous conversions of two-digit years, 103 START SUBSCRIPTION statement [SQL
changing the interpretation of delimited strings, 31 Remote], 914
converting to dates, 127 STOP SUBSCRIPTION statement [SQL Remote],
delimiter, 31 922
escape characters, 7 SYNCHRONIZE SUBSCRIPTION statement
quotation marks, 31 [SQL Remote], 930

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1369


Index

UPDATE statement, 951 CURRENT_USER special value, 62


substitution characters documentation conventions, 395
comparisons between CHAR and NCHAR, 123 IF expressions, 15
lossy conversions, 123 IS NULL search condition, 54
SUBSTR function IS TRUE or FALSE search condition, 54
syntax, 353 LAST USER special value, 63
SUBSTRING function LEN function, 259
syntax, 353 list of SQL reserved words, 1
substrings local variables, 73
about, 353 logical operators, 9
replacing, 321 NULL value, 64
SUM function predicates, 32
syntax, 355 search conditions, 32
super types special values, 58
about, 122 SQL CURRENT REMOTE USER special value,
SUSER_ID function 59
syntax, 356 SQL CURRENT TIME special value, 60
SUSER_NAME function SQL expressions, 12
syntax, 357 SQL functions, 133
SWITCHOFFSET function SQL identifiers, 4
syntax, 358 SQL keywords, 1
synchronization_mode option SQL operator precedence, 12
SET MIRROR OPTION statement, 884 SQL operators, 8
SYNCHRONIZE statement SQL statements, 398
MobiLink syntax, 925 SQL subqueries, 15
SYNCHRONIZE SUBSCRIPTION statement SQL subqueries in search conditions, 34
SQL Remote syntax, 930 SQL variables, 72
synchronizing subscriptions SQLCODE special value, 67
SYNCHRONIZE SUBSCRIPTION statement SQLSTATE special value, 67
[SQL Remote], 930 string operators, 10
syntax strings, 5
arithmetic operators, 10 testing compliance against a standard, 344
bitwise operators, 11 three-valued logic, 55
CASE expression, 16 TIMESTAMP special value, 69
column names, 14 Transact-SQL expression compatibility, 31
comments, 79 USER special value, 70
comparison operators, 8 UTC TIMESTAMP special value, 71
connection-level variables, 74 syntax conventions
constants , 6 SQL statements, 396
constants in expressions, 14 SYS
conventions, 396 default system views, 1195
CURRENT DATABASE special value, 58 system tables, 965
CURRENT DATE special value, 58 SYSARTICLE
CURRENT PUBLISHER special value, 59 system view, 1196
CURRENT TIMESTAMP special value, 61 SYSARTICLECOL
CURRENT USER special value, 62 system view, 1196
CURRENT UTC TIMESTAMP special value, 63 SYSARTICLECOLS
CURRENT_TIMESTAMP special value, 61 consolidated view, 1264

1370 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SYSARTICLES SYSEXTERNENVOBJECT
consolidated view, 1265 system view, 1206
SYSCAPABILITIES SYSEXTERNLOGIN
consolidated view, 1265 system view, 1207
SYSCAPABILITY SYSFILE
system view, 1197 compatibility view (deprecated), 1281
SYSCAPABILITYNAME SYSFKCOL
system view, 1197 compatibility view (deprecated), 1282
SYSCATALOG SYSFKEY
consolidated view, 1266 system view, 1208
SYSCHECK SYSFOREIGNKEY
system view, 1198 compatibility view (deprecated), 1283
SYSCOLAUTH SYSFOREIGNKEYS
consolidated view, 1266 consolidated view, 1268
SYSCOLLATION SYSGROUP
compatibility view (deprecated), 1280 system view, 1209
SYSCOLLATIONMAPPINGS SYSGROUPS
compatibility view (deprecated), 1280 consolidated view, 1269
SYSCOLPERM SYSHISTORY
system view, 1198 system view, 1209
SYSCOLSTAT SYSIDX
system view, 1199 system view, 1211
SYSCOLSTATS SYSIDXCOL
consolidated view, 1267 system view, 1213
SYSCOLUMN SYSINDEX
compatibility view (deprecated), 1281 compatibility view (deprecated), 1283
SYSCOLUMNS SYSINDEXES
consolidated view, 1267 consolidated view, 1269
SYSCONSTRAINT SYSINFO
system view, 1200 compatibility view (deprecated), 1284
SYSDATETIMEOFFSET function SYSIXCOL
syntax, 358 compatibility view (deprecated), 1285
SYSDBFILE SYSJAR
system view, 1201 system view, 1214
SYSDBSPACE SYSJARCOMPONENT
system view, 1202 system view, 1214
SYSDBSPACEPERM SYSJAVACLASS
system view, 1202 system view, 1215
SYSDEPENDENCY SYSLOGINMAP
system view, 1203 system view, 1216
SYSDOMAIN SYSLOGINPOLICY
system view, 1203 system view, 1216
SYSEVENT SYSLOGINPOLICYOPTION
system view, 1204 system view, 1217
SYSEVENTTYPE SYSMIRROROPTION
system view, 1205 system view, 1217
SYSEXTERNENV SYSMIRRORSERVER
system view, 1206 system view, 1217

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1371


Index

SYSMIRRORSERVEROPTION SYSREMOTEUSER
system view, 1218 system view, 1229
SYSMVOPTION SYSREMOTEUSERS
system view, 1219 consolidated view, 1274
SYSMVOPTIONNAME SYSSCHEDULE
system view, 1219 system view, 1231
SYSOBJECT SYSSEQUENCE
system view, 1220 system view, 1232
SYSOPTION SYSSEQUENCEPERM
system view, 1221 system view, 1233
SYSOPTIONS SYSSERVER
consolidated view, 1270 system view, 1233
SYSOPTSTAT SYSSOURCE
system view, 1221 system view, 1234
SYSPHYSIDX SYSSPATIALREFERENCESYSTEM
system view, 1222 system view, 1234
SYSPROCAUTH SYSSQLSERVERTYPE
consolidated view, 1270 system view, 1237
SYSPROCEDURE SYSSUBSCRIPTION
system view, 1223 system view, 1238
SYSPROCPARM SYSSUBSCRIPTIONS
system view, 1224 consolidated view, 1274
SYSPROCPARMS SYSSYNC
consolidated view, 1271 system view, 1238
SYSPROCPERM SYSSYNC2
system view, 1225 consolidated view, 1275
SYSPROCS SYSSYNCPROFILE
consolidated view, 1271 system view, 1240
SYSPROXYTAB SYSSYNCPUBLICATIONDEFAULTS
system view, 1226 consolidated view, 1275
SYSPUBLICATION SYSSYNCS
system view, 1226 consolidated view, 1276
SYSPUBLICATIONS SYSSYNCSCRIPT
consolidated view, 1272 system view, 1240
SYSREMARK SYSSYNCSCRIPTS
system view, 1227 consolidated view, 1276
SYSREMOTEOPTION SYSSYNCSUBSCRIPTIONS
system view, 1228 consolidated view, 1277
SYSREMOTEOPTION2 SYSSYNCUSERS
consolidated view, 1272 consolidated view, 1277
SYSREMOTEOPTIONS SYSTAB
consolidated view, 1273 compatibility view information, 965
SYSREMOTEOPTIONTYPE system view, 1241
system view, 1228 SYSTABAUTH
SYSREMOTETYPE consolidated view, 1278
system view, 1229 SYSTABCOL
SYSREMOTETYPES system view, 1244
consolidated view, 1273 SYSTABLE

1372 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


compatibility view (deprecated), 1285 SYSCOLSTAT, 1199
SYSTABLEPERM SYSCONSTRAINT, 1200
system view, 1246 SYSDBFILE, 1201
system and catalog stored procedures SYSDBSPACE, 1202
about, 1001 SYSDBSPACEPERM, 1202
system calls SYSDEPENDENCY, 1203
from stored procedures, 1180 SYSDOMAIN, 1203
xp_cmdshell system procedure, 1180 SYSEVENT, 1204
system catalog SYSEVENTTYPE, 1205
tables, 965 SYSEXTERNENV, 1206
views, 1195 SYSEXTERNENVOBJECT, 1206
system extended procedures SYSEXTERNLOGIN, 1207
about, 996 SYSFILE , 1281
system functions SYSFKEY, 1208
alphabetical list, 144 SYSGROUP, 1209
compatibility, 144 SYSHISTORY, 1209
system procedures SYSIDX, 1211
about, 995 SYSIDXCOL, 1213
Adaptive Server Enterprise system procedures, 999 SYSJAR, 1214
alphabetical list , 1001 SYSJARCOMPONENT, 1214
creating messages, 563 SYSJAVACLASS, 1215
extended list, 996 SYSLOGINMAP, 1216
HTTP, 996 SYSLOGINPOLICY, 1216
named parameters allowed when calling, 491 SYSLOGINPOLICYOPTION, 1217
SOAP, 996 SYSMIRROROPTION, 1217
Sybase Central, 995 SYSMIRRORSERVER, 1217
Transact-SQL, 999 SYSMIRRORSERVEROPTION, 1218
Transact-SQL list, 999 SYSMVOPTION, 1219
viewing definitions, 995 SYSMVOPTIONNAME, 1219
SYSTEM statement SYSOBJECT, 1220
Interactive SQL syntax, 931 SYSOPTION, 1221
not supported by dbisqlc, 931 SYSOPTSTAT, 1221
system tables SYSPHYSIDX, 1222
about, 965 SYSPROCEDURE, 1223
DUMMY, 965 SYSPROCPARM, 1224
Java, 994 SYSPROCPERM, 1225
RowGenerator, 994 SYSPROXYTAB, 1226
viewing system table data, 965 SYSPUBLICATION, 1226
views, 965 SYSREMARK, 1227
system views SYSREMOTEOPTION, 1228
about, 1195 SYSREMOTEOPTIONTYPE, 1228
alphabetical list of system views, 1195 SYSREMOTETYPE, 1229
SYSARTICLE, 1196 SYSREMOTEUSER, 1229
SYSARTICLECOL, 1196 SYSSCHEDULE, 1231
SYSCAPABILITY, 1197 SYSSEQUENCE, 1232
SYSCAPABILITYNAME, 1197 SYSSEQUENCEPERM, 1233
SYSCHECK, 1198 SYSSERVER, 1233
SYSCOLPERM, 1198 SYSSOURCE, 1234

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1373


Index

SYSSPATIALREFERENCESYSTEM, 1234 SYSUSERPERM


SYSSQLSERVERTYPE, 1237 compatibility view (deprecated), 1287
SYSSUBSCRIPTION, 1238 SYSUSERPERMS
SYSSYNC, 1238 compatibility view (deprecated), 1288
SYSSYNCPROFILE, 1240 SYSUSERTYPE
SYSSYNCSCRIPT, 1240 system view, 1256
SYSTAB, 1241 SYSVIEW
SYSTABCOL, 1244 system view, 1257
SYSTABLEPERM, 1246 SYSVIEWS
SYSTEXTCONFIG, 1248 consolidated view, 1279
SYSTEXTIDX, 1249 consolidated view information, 965
SYSTEXTIDXTAB, 1250 SYSWEBSERVICE
SYSTRIGGER, 1251 system view, 1259
SYSTYPEMAP, 1253
SYSUNITOFMEASURE, 1254 T
SYSUSER, 1254 TABLE clause
SYSUSERAUTHORITY, 1255 ALTER PUBLICATION statement, 425
SYSUSERMESSAGE, 1256 CREATE PUBLICATION statement [MobiLink]
SYSUSERTYPE, 1256 [SQL Remote], 592
SYSVIEW, 1257 DESCRIBE statement, 685
SYSWEBSERVICE, 1259 TRUNCATE statement, 933
Viewing, 1195 VALIDATE statement, 955
SYSTEXTCONFIG table columns
system view, 1248 listing in Interactive SQL, 684
SYSTEXTIDX table constraints
system view, 1249 adding using the ALTER TABLE statement, 458
SYSTEXTIDXTAB adding, deleting, or altering using the ALTER
system view, 1250 TABLE statement, 451
SYSTRIGGER changing using ALTER TABLE statement, 460
system view, 1251 CREATE TABLE statement, 640
SYSTRIGGERS table decryption
consolidated view, 1278 ALTER TABLE statement, 451
SYSTYPEMAP table encryption
system view, 1253 ALTER TABLE statement, 451
SYSUNITOFMEASURE CREATE ENCRYPTED TABLE DATABASE
system view, 1254 statement, 521
SYSUSER table hints
system view, 1254 FROM clause, 744
SYSUSERAUTH table indexes
compatibility view (deprecated), 1286 listing in Interactive SQL, 684
SYSUSERAUTHORITY table list
system view, 1255 FROM clause, 740
SYSUSERLIST table locks
compatibility view (deprecated), 1287 sa_locks system procedure, 1073
SYSUSERMESSAGE table number
system view, 1256 system views, 1241
SYSUSEROPTIONS table pages
consolidated view, 1279

1374 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


setting PCTFREE, 633 about, 215
setting PCTFREE using the ALTER TABLE TEMPORARY clause
statement, 451 ALTER DBSPACE statement , 405
setting PCTFREE using the CREATE LOCAL CREATE PROCEDURE statement, 585
TEMPORARY TABLE statement, 556 temporary dbspace
setting PCTFREE using the LOAD TABLE calibrating, 401
statement, 792 temporary files
table-list determining available space, 1043
common element in SQL syntax, 396 temporary functions
table-name about, 549
common element in SQL syntax, 396 TEMPORARY keyword
TABLE.COLUMN clause CREATE FUNCTION statement [user defined],
DESCRIBE statement [ESQL], 681 549
tables temporary options
adding comments using the COMMENT statement, SET OPTION statement, 886
499 setting in Interactive SQL, 889
ALTER TABLE statement, 451 temporary procedures
altering using the ALTER TABLE statement, 451 CREATE PROCEDURE statement, 585
bulk loading, 792 temporary stored procedures
CREATE TABLE statement, 633 creating, 585
creating local temporary, 672 temporary tables
creating local temporary tables using the CREATE CREATE TABLE statement, 633
LOCAL TEMPORARY TABLE statement, 556 CREATE TABLE usage, 643
creating proxy tables using the CREATE creating local temporary files using the CREATE
EXISTING TABLE statement, 532 LOCAL TEMPORARY TABLE statement, 556
determining dependencies, 1033 declaring local, 672
dropping using the DROP TABLE statement, 711 Transact-SQL CREATE TABLE statement, 644
encrypting with CREATE ENCRYPTED TABLE views disallowed on local, 662
DATABASE statement, 521 TempSize event condition
exporting data into files from, 825 about, 215
generating definition with sa_get_table_definition TERM BREAKER clause
system procedure, 1057 ALTER TEXT CONFIGURATION statement, 466
importing data from files into, 773 TERM BREAKER EXTERNAL NAME clause
inserting rows into, 780 ALTER TEXT CONFIGURATION statement, 465
locking, 808 term breakers
renaming, 461 specifying an external term breaker library, 466
reorganizing, 852 using sa_char_terms to test how strings are broken
SQL Remote updating, 945 into terms, 1009
truncating, 933 using sa_nchar_terms to test how strings are
unloading using the UNLOAD statement, 937 broken into terms, 1094
TAN function warning about using non-alphanumerics in query
syntax, 359 string, 49
tape drives terms
creating database backups using the BACKUP MAXIMUM TERM LENGTH clause, 465
statement, 477 MINIMUM TERM LENGTH clause, 465
TempFreePercent event condition TERM BREAKER clause, 466
about, 215 text
TempFreeSpace event condition

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1375


Index

reading from the database using the READTEXT DATETIMEOFFSET, 109


statement, 842 overview, 101
text configuration objects SMALLDATETIME, 111
adding comments using the COMMENT statement, TIMESTAMP, 113
499 TIMESTAMP WITH TIME ZONE, 115
ALTER TEXT CONFIGURATION statement, 465 time functions
CREATE TEXT CONFIGURATION statement, alphabetical list, 136
647 time of day
dropping, 712 storing, 101
using sa_char_terms to test how strings are broken time zone
into terms, 1009 CURRENT UTC TIMESTAMP, 63
using sa_nchar_terms to test how strings are UTC TIMESTAMP, 71
broken into terms, 1094 times
TEXT data type comparing, 125
syntax, 86 conversion functions, 136
text functions queries, 106
about, 145 sending to the database, 102
text indexes TIMESTAMP clause
adding comments using the COMMENT statement, CREATE TABLE statement, 633
499 TIMESTAMP data type
ALTER TEXT INDEX statement, 468 comparing with dates and times, 125
CREATE TEXT INDEX statement, 649 sending dates and times to the database, 102
creation options stored in SYSMVOPTION, 1219 syntax, 113
dropping, 713 TIMESTAMP default
listing using sa_text_index_stats, 1149 CREATE TABLE statement, 453, 637
refreshing using REFRESH TEXT INDEX, 846 TIMESTAMP special value
refreshing using sa_refresh_text_indexes, 1109 syntax, 69
truncating, 935 TIMESTAMP WITH TIME ZONE data type
validating, 955 comparing with dates and times, 125
TEXTPTR function sending dates and times to the database, 102
syntax, 360 syntax, 115
textsize option timestamps
setting with Transact-SQL SET statement, 901 comparing, 125
THEN comparisons using TIMESTAMP WITH
IF expressions, 15 TIMEZONE, 116
THEN clause conversions using TIMESTAMP WITH
IF statement, 769 TIMEZONE, 116
three-valued logic TINYINT data type
NULL value, 64 syntax, 97
syntax, 55 TO clause
TIME clause ALTER SYNCHRONIZATION SUBSCRIPTION
WAITFOR statement, 957 statement [MobiLink] , 448
TIME data type CONNECT statement, 504
comparing with dates and times, 125 CREATE EXTERNLOGIN statement, 534
sending dates and times to the database, 102 CREATE SUBSCRIPTION statement [SQL
syntax, 112 Remote], 626
time data types CREATE SYNCHRONIZATION
DATETIME, 108 SUBSCRIPTION statement [MobiLink], 630

1376 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


DROP EXTERNLOGIN statement, 694 setting the sa_set_tracing_level system procedure,
DROP SYNCHRONIZATION SUBSCRIPTION 1140
statement, 709 trademark information
GRANT CONSOLIDATE statement [SQL retrieving, 1181
Remote], 754 Transact-SQL
GRANT REMOTE DBA statement [MobiLink] alphabetical list of SQL Anywhere Server
[SQL Remote], 757 statements, 398
MESSAGE statement, 818 ANSI equivalency, 324
PASSTHROUGH statement [SQL Remote], 831 bitwise operators, 11
START SUBSCRIPTION statement [SQL CASE statement [T-SQL], 495
Remote], 914 catalog procedures, 1000
STOP SUBSCRIPTION statement [SQL Remote], comparison operators, 8
922 constants, 31
SYNCHRONIZE SUBSCRIPTION statement CONTINUE statement syntax, 960
[SQL Remote], 930 converting SELECT statements, 380
UNLOAD statement, 938 converting stored procedures, 380
TO_CHAR function CREATE FUNCTION statement, 552
syntax, 360 CREATE MESSAGE statement, 563
TO_NCHAR function CREATE PROCEDURE statement, 583
syntax, 361 CREATE SCHEMA statement syntax, 597
TODATETIMEOFFSET function CREATE TABLE statement syntax, 644
syntax, 362 CREATE TRIGGER statement syntax, 657
TODAY function datetime compatibility, 127
syntax, 363 DECLARE CURSOR statement syntax, 670
tolerance domains, 121
altering tolerance for spatial calculations, 443 EXECUTE statement syntax, 724
setting tolerance for spatial calculations, 621 GOTO statement syntax, 754
TOLERANCE clause IF statement syntax, 771
ALTER SPATIAL REFERENCE SYSTEM local variables, 73
statement, 443 money data types, 98
CREATE SPATIAL REFERENCE SYSTEM outer join operators, 12
statement, 621 PRINT statement syntax, 836
TOP clause quoted_identifier option, 31
DELETE statement, 679 READTEXT statement syntax, 842
SELECT statement, 873 SELECT statement, 880
UPDATE statement, 949 SET OPTION statement syntax, 901
TRACEBACK function SET statement syntax, 901
syntax, 364 SQL expression compatibility, 31
TRACED_PLAN function statement indicators, 398
syntax, 364 strings, 31
tracing system and catalog procedures, 999
ATTACH TRACING statement, 475 system functions, 144
DETACH TRACING statement, 687 system procedures, 999
REFRESH TRACING LEVEL statement, 848 time compatibility, 127
tracing data user-defined data types, 121
saving using sa_save_trace_data system procedure, WHILE statement syntax, 960
1116 WRITETEXT statement syntax, 963
tracing levels Transact-SQL compatibility

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1377


Index

global variables, 75 chained, 488


views, 1288 unchained, 488
Transact-SQL statements transactions
BEGIN TRANSACTION syntax, 488 beginning user-defined using the BEGIN
ROLLBACK TRANSACTION syntax, 867 TRANSACTION statement, 488
SAVE TRANSACTION syntax, 869 committing using the COMMIT statement, 501
Transact-SQL string to date/time conversions creating savepoints, 870
about, 127 nesting user-defined transactions using the BEGIN
transaction isolation level option TRANSACTION statement, 488
setting with Transact-SQL SET statement, 901 rolling back, 867
transaction log rolling back and the SAVE TRANSACTION
allocating space using ALTER DBSPACE, 405 statement, 869
backing up using the BACKUP statement, 477 rolling back using the ROLLBACK statement, 865
decrypting using CREATE DECRYPTED rolling back using the ROLLBACK TO
DATABASE statement, 517 SAVEPOINT statement, 866
decrypting using CREATE DECRYPTED FILE TRANSACTSQL function
statement, 518 syntax, 365
determining available space, 1043 Transfer-Encoding
encrypting using the CREATE ENCRYPTED HTTP_RESPONSE_HEADER function, 244
DATABASE statement, 521 TRANSFORM DEFINITION clause
encrypting using the CREATE ENCRYPTED ALTER SPATIAL REFERENCE SYSTEM
FILE statement, 524 statement, 443
renaming without backup, 478 CREATE SPATIAL REFERENCE SYSTEM
TRUNCATE TABLE statement, 933 statement, 618
truncating without backup, 478 TRANSLOG clause
TRANSACTION LOG clause ALTER DBSPACE statement , 405
CREATE DATABASE statement, 513 trapping
transaction log mirror errors in embedded SQL, 959
decrypting using CREATE DECRYPTED TREAT function
DATABASE statement, 517 syntax, 365
decrypting using CREATE DECRYPTED FILE TRIGGER EVENT statement
statement, 518 syntax, 932
determining available space, 1043 triggering
encrypting using the CREATE ENCRYPTED events, 932
DATABASE statement, 521 triggers
encrypting using the CREATE ENCRYPTED @@identity global variable, 78
FILE statement, 524 adding comments using the COMMENT statement,
TRANSACTION LOG ONLY clause 499
BACKUP statement, 478 altering using the ALTER TRIGGER statement,
TRANSACTION LOG RENAME [MATCH] clause 469
BACKUP statement, 478 creating in Transact-SQL, 657
TRANSACTION LOG TRUNCATE clause creating using CREATE TRIGGER statement, 651
BACKUP statement, 478 DELETING condition, 54
transaction management dropping using the DROP FUNCTION statement,
BEGIN TRANSACTION statement, 488 695
in Transact-SQL, 488 dropping using the DROP statement, 714
Transact-SQL, 501 INSERTING condition, 54
transaction modes operation conditions, 54

1378 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


rolling back, 868 CREATE PROCEDURE statement [web clients],
row-level, 654 577
TRUNCATE TABLE statement, 934 CREATE SERVICE statement [HTTP web
UPDATING condition, 54 service], 431, 606
TRIM function CREATE SERVICE statement [SOAP web
syntax, 367 service], 437, 612
troubleshooting CREATE SPATIAL REFERENCE SYSTEM
locks, 1071 statement, 619
logging operations, 1128 CREATE SPATIAL UNIT OF MEASURE
non-standard disk drives, 403 statement, 624
TRUE conditions CREATE SYNCHRONIZATION
IS TRUE search condition, 54 SUBSCRIPTION statement [MobiLink], 630
three-valued logic, 55 CREATE SYNCHRONIZATION USER, 632
TRUNCATE function GET DESCRIPTOR statement [ESQL], 751
syntax, 368 GRANT CONSOLIDATE statement [SQL
TRUNCATE MATERIALIZED VIEW statement Remote], 754
syntax, 933 GRANT REMOTE statement [SQL Remote], 758
TRUNCATE statement MESSAGE statement, 818
syntax, 933 SET DESCRIPTOR statement [ESQL], 882
TRUNCATE TABLE statement type conversion
syntax, 933 about, 122
TRUNCATE TEXT INDEX statement type expressions
syntax, 935 search conditions, 32
truncating TYPE PLANAR clause
fails if the table has an immediate text index, 933 ALTER SPATIAL REFERENCE SYSTEM
fails if the table is referenced by an immediate statement, 443
views, 933 CREATE SPATIAL REFERENCE SYSTEM
tables, 933 statement, 619
text indexes, 935 TYPE ROUND EARTH clause
TRUNCNUM function ALTER SPATIAL REFERENCE SYSTEM
syntax, 368 statement, 443
TSEQUAL function CREATE SPATIAL REFERENCE SYSTEM
syntax, 368 statement, 619
TYPE clause
ALTER SERVICE statement [HTTP web service], U
431 UCASE function
ALTER SERVICE statement [SOAP web service], syntax, 370
436 UDF
ALTER SPATIAL REFERENCE SYSTEM user defined function, defined, 138
statement, 443 UDP packets
ALTER SYNCHRONIZATION SUBSCRIPTION sending, 1116
statement [MobiLink] , 448 UltraLite
ALTER SYNCHRONIZATION USER statement return NULL if you specify NULL argument, 133
[MobiLink] , 450 UNBOUNDED keyword
CREATE EVENT statement, 528 FOLLOWING clause of WINDOW clause, 962
CREATE FUNCTION statement [web clients], PRECEDING clause of WINDOW clause, 962
542 UNCONDITIONALLY clause

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1379


Index

STOP DATABASE statement, 918 compressing strings, 166


STOP SERVER statement, 922 decompressing strings, 203
undoing UNKNOWN conditions
changes by rolling back transactions, 865 IS UNKNOWN search condition, 54
Unicode UNLIMITED clause
escape sequences, 371 CREATE LOGIN POLICY statement, 558
UNICODE function, 370 UNLOAD statement
UNISTR function, 371 syntax, 937
Unicode data UNLOAD TABLE statement
storage, 81 syntax, 937
Unicode data types unloading
about, 81 cost models, 1154
UNICODE function data using the UNLOAD statement, 937
syntax, 370 result sets using the UNLOAD statement, 937
UNION statement unloading data
setting database options, 936 multibyte character sets, 940
syntax, 936 UNSIGNED BIGINT data type
unions syntax, 89
multiple SELECT statements, 936 UNSIGNED INTEGER data type
unique syntax, 94
constraint in CREATE TABLE statement, 640 UNSIGNED SMALLINT data type
UNIQUE clause syntax, 97
ALTER TABLE statement , 456 UNSIGNED TINYINT data type
CREATE INDEX statement, 553 syntax, 97
CREATE TABLE statement, 642 unzip utility
DECLARE CURSOR statement, 667 DECOMPRESS function, 203
unique indexes UPDATE clause
about, 553 CREATE PUBLICATION statement [MobiLink]
UNIQUEIDENTIFIER data type [SQL Remote], 592
syntax, 118 CREATE TRIGGER statement, 652
UNIQUEIDENTIFIERSTR data type INSTALL EXTERNAL OBJECT statement, 785
syntax, 87 REVOKE statement, 863
UNISTR function update column permission
syntax, 371 SYSCOLPERM system view, 1198
units of measure UPDATE permission
adding comments using the COMMENT statement, GRANT statement, 761
499 REVOKE statement, 863
ALTER SPATIAL REFERENCE SYSTEM UPDATE permission clause
statement, 442 GRANT statement, 763
CREATE SPATIAL REFERENCE SYSTEM UPDATE SET clause
statement, 616 MERGE statement, 815
CREATE SPATIAL UNITS OF MEASURE UPDATE statement
statement, 624 (positioned) statement syntax, 943
installing predefined , 1067 setting database options, 951
ST_UNITS_OF_MEASURE system view, 1264 SQL Remote syntax, 945
universally unique identifiers syntax, 948
SQL syntax for NEWID function, 279 updates
Unix based on joins, 951

1380 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SQL Remote joins, 946 defined, 138
updating exiting from, 858
columns without logging, 963 Java, 138
publications and subscriptions, 951 user defined properties
rows, 948 incrementing values, 1155
SQL Remote tables and columns, 945 setting values, 1156
UPDLOCK table hint user estimates
FROM clause, 744 about, 56
upgrading databases user IDs
ALTER DATABASE statement, 400 restrictions, 763
UPPER function revoking, 863
syntax, 372 system views, 1241
uppercase characters views, 1286
UPPER function, 372 USER special value
uppercase strings syntax, 70
UCASE function, 370 USER TYPES clause
UPPER function, 372 DESCRIBE statement, 681
URI redirection User-Agent
CREATE PROCEDURE statement [web clients], HTTP_HEADER function, 242
579 HTTP_RESPONSE_HEADER function, 244
URL clause user-defined data types
ALTER SERVICE statement [HTTP web service], about, 120
431 CREATE DOMAIN statement, 519
CREATE FUNCTION statement [web clients], dropping using the DROP DATATYPE statement,
542 691
CREATE PROCEDURE statement [web clients], Transact-SQL, 121
577 user-defined functions
CREATE SERVICE statement [HTTP web CREATE FUNCTION statement, 548
service], 432, 606 returning values from, 858
USAGE ON SEQUENCE clause user-defined options
GRANT statement, 760 temporary settings unsupported, 887
REVOKE statement, 863 user-supplied selectivity estimates
USE DEFAULT clause about, 56
CREATE TABLE statement, 633 user_estimates option
USER overriding in a MERGE statement, 816
CONNECT statement, 504 overriding in a SELECT statement, 878
USER clause setting for DELETE statements, 680
ALTER SERVICE statement [HTTP web service], setting for EXCEPT statement, 718
431 setting for INSERT statements, 782
ALTER SERVICE statement [SOAP web service], setting for INTERSECT statement, 789
436 setting for UNION statement, 936
CREATE SERVICE statement [HTTP web setting for UPDATE statements, 951
service], 434, 608 USER_ID function
CREATE SERVICE statement [SOAP web syntax, 373
service], 440, 615 USER_NAME function
CREATE TABLE statement, 633 syntax, 374
user defined functions userid
about, 138 common element in SQL syntax, 396

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1381


Index

users CREATE TABLE statement, 454, 638


adding comments using the COMMENT statement, UTC TIMESTAMP special value
499 syntax, 71
ALTER SYNCHRONIZATION USER statement, UTF-16 encoding
449 CSCONVERT function, 183
altering using ALTER USER statement, 470 LOAD TABLE statement, 796, 797
CREATE SYNCHRONIZATION USER UNLOAD statement, 939
statement, 631 UUIDs
creating using CREATE USER statement, 658 SQL syntax for NEWID function, 279
DROP SYNCHRONIZATION USER statement, SQL syntax for STRTOUUID function, 351
710 SQL syntax for UUIDTOSTR function, 374
dropping, 863 UNIQUEIDENTIFIER data type, 118
dropping using DROP USER statement, 715 UUIDTOSTR function
obtaining status, 1058 syntax, 374
setting, 904
USING AUTO PARENT clause V
ALTER MIRROR SERVER statement, 421 VALIDATE authority
CREATE MIRROR SERVER statement, 565 GRANT statement, 760
USING clause REVOKE statement, 863
ALTER PUBLICATION statement, 425 VALIDATE authority clause
ALTER SERVER statement, 429 GRANT statement, 762
CREATE PUBLICATION statement [MobiLink] VALIDATE CHECKSUM statement
[SQL Remote], 592 syntax, 955
CREATE SERVER statement, 602 VALIDATE clause
DECLARE CURSOR statement, 668 REVOKE statement, 863
EXECUTE statement, 722 VALIDATE DATABASE statement
FOR statement, 733 syntax, 955
INPUT statement, 777 VALIDATE INDEX statement
MERGE statement, 813 syntax, 955
OUTPUT statement, 828 VALIDATE MATERIALIZED VIEW statement
USING CLIENT FILE clause syntax, 955
LOAD TABLE statement, 794 VALIDATE statement
USING COLUMN clause syntax, 955
LOAD TABLE statement, 795 VALIDATE TABLE statement
USING DESCRIPTOR clause syntax, 955
EXPLAIN statement [ESQL], 727 VALIDATE TEXT INDEX statement
GET DATA statement , 749 syntax, 955
GET OPTION statement [ESQL], 753 validating
OPEN statement, 822 checksums, 955
PUT statement [ESQL], 837 indexes using VALIDATE statement, 955
UPDATE (positioned) statement, 943 sa_validate system procedure, 1157
USING FILE clause tables using VALIDATE TABLE statement, 955
LOAD TABLE statement, 794 VALIDATE statement, 955
USING VALUE clause validation
LOAD TABLE statement, 795 VALIDATE authority, 762
UTC TIMESTAMP clause VALUE clause
CREATE TABLE statement, 633 GET DESCRIPTOR statement [ESQL], 751
UTC TIMESTAMP default

1382 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


SET DESCRIPTOR statement [ESQL], 882 UPDATE statement, 948
values UPDATE statement [SQL Remote] , 945
returning from procedures, 858 verifying
VALUES clause passwords, 1159
INSERT statement, 780 version number
VAR_POP function retrieving, 1181
syntax, 375 view dependencies
VAR_SAMP function unloading/reloading databases, 1108
syntax, 377 viewing
VARBINARY data type Interactive SQL procedure profiling data, 1105
syntax, 119 ViewName property
VARBIT data type sa_materialized_view_info system procedure, 1078
syntax, 100 views
VARCHAR data type about, 1195
byte-length semantics, 87 adding comments using the COMMENT statement,
character-length semantics, 87 499
syntax, 87 altering materialized views owned by someone
using DESCRIBE on a VARCHAR column, 87 else, 473
VAREXISTS function altering using the ALTER VIEW statement, 472
syntax, 379 compatibility views, 1280
variable result sets consolidated views, 1260
from procedures, CREATE PROCEDURE CREATE MATERIALIZED VIEW statement, 560
statement, 586 CREATE VIEW statement, 661
from procedures, CREATE PROCEDURE determining dependencies, 1033
statement [External call], 569 DROP VIEW statement, 716
from procedures, DESCRIBE statement [ESQL], indexes, 555
683 parameterized views, 663
from procedures, PREPARE statement, 834 sa_recompile_views system procedure, 1108
variable-name system views, 1196
common element in SQL syntax, 396 Transact-SQL compatibility, 1288
variables updating using INSERT statement, 783
connection-level variables, 74 VIRTUAL clause
creating SQL, 660 CREATE INDEX statement, 553
declaring using DECLARE statement, 673 VM
dropping SQL variables using the DROP START JAVA statement, 912
VARIABLE statement, 716 STOP JAVA statement, 920
getting from within a descriptor area, 751
global variables, 75 W
initial value, 674 WAIT AFTER END clause
local variables, 73 BACKUP statement, 478
setting values, 899 WAIT BEFORE START clause
syntax, 72 BACKUP statement, 478
using in view definitions, 663 WAITFOR statement
VARIANCE function syntax, 957
syntax, 380 watch list
VERBOSE clause configuring with sa_server_option, 1128
OUTPUT statement, 828 Watcom SQL
VERIFY clause

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1383


Index

DECLARE statement, 673 setting with sa_server_option, 1133


Watcom SQL statements WebClientLogging property
rewriting to Transact-SQL, 365 setting with sa_server_option, 1133
WATCOMSQL function week date
syntax, 380 ISO 8601, 102
web clients WEEKS function
creating web client functions using CREATE syntax, 380
FUNCTION statement [Web service], 541 WHEN
web service client log file CASE expression, 16
setting name, 1133 WHEN clause
web services CASE statement , 493
adding comments using the COMMENT statement, CASE statement [T-SQL] , 495
499 CREATE TRIGGER statement, 653
alphabetical list of functions, 141 WHEN MATCHED clause
alphabetical list of system procedures, 996 MERGE statement, 814
altering HTTP services using ALTER SERVICE WHEN NOT MATCHED clause
statement [HTTP web service], 431 MERGE statement, 814
altering SOAP services using ALTER SERVICE WHENEVER statement
statement [SOAP web service], 436 embedded SQL syntax, 959
creating using CREATE SERVICE statement WHERE clause
[HTTP web service], 605 ALTER EVENT statement, 409
creating using CREATE SERVICE statement ALTER PUBLICATION statement, 425
[SOAP web service], 611 CREATE EVENT statement, 528
HTML_DECODE function, 237 CREATE PUBLICATION statement [MobiLink]
HTML_ENCODE function, 238 [SQL Remote], 593
HTTP_BODY function, 239 DELETE statement, 679
HTTP_DECODE function, 240 search conditions, 32
HTTP_ENCODE function, 241 SELECT statement, 875
HTTP_HEADER function, 242 UPDATE statement, 950
HTTP_RESPONSE_HEADER function, 244 UPDATE statement [SQL Remote] , 945
HTTP_VARIABLE function, 245 WHERE CURRENT OF clause
list of web services-related system procedures, 996 DELETE (positioned) statement [ESQL] [SP]
NEXT_HTTP_HEADER function, 282 statement, 676
NEXT_HTTP_RESPONSE_HEADER function, WHILE clause
284 LOOP statement, 810
NEXT_HTTP_VARIABLE function, 285 WHILE statement
NEXT_SOAP_HEADER function, 286 Transact-SQL syntax, 960
sa_http_header_info system procedure, 1059 wide inserts
sa_http_php_page system procedure, 1060 about, 722
sa_http_php_page_interpreted system procedure, wildcards
1060 expression wildcards, 19
sa_http_variable_info system procedure, 1062 LIKE search condition, 39
sa_set_http_header_info system procedure, 1134 PATINDEX function, 290
sa_set_http_option system procedure, 1135 REGEXP search condition, 43
sa_set_soap_header system procedure, 1139 SIMILAR TO search condition, 45
SOAP_HEADER function, 338 WINDOW clause
system view, 1259 SELECT statement, 875
WebClientLogFile property syntax, 961

1384 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


window functions REFRESH MATERIALIZED VIEW statement,
AVG function, 150 843
COUNT function, 177 REFRESH TEXT INDEX statement, 846
COUNT_BIG function, 179 REVOKE REMOTE DBA statement [SQL
COVAR_POP function, 181 Remote], 868
CUME_DIST function, 185 SELECT statement, 873
DENSE_RANK function, 206 WITH COMMENT clause
MAX function, 268 BACKUP statement, 479
MEDIAN function, 269 WITH CONTENT LOGGING clause
MIN function, 271 LOAD TABLE statement, 803
PERCENT_RANK function, 292 required for database mirroring, 804
RANK function, 303 WITH ESCAPES clause
REGR_AVGX function, 307 EXECUTE IMMEDIATE statement, 720
REGR_AVGY function, 308 WITH EXCLUSIVE MODE clause
REGR_COUNT function, 310 REFRESH MATERIALIZED VIEW statement,
REGR_INTERCEPT function, 311 843
REGR_R2 function, 313 REFRESH TEXT INDEX statement, 846
REGR_SLOPE function, 314 WITH EXECUTE clause
REGR_SXX function, 315 PREPARE statement, 833
REGR_SXY function, 317 WITH EXPRESS CHECK clause
ROW_NUMBER function, 327 VALIDATE statement, 955
STDDEV function, 346 WITH FILE NAME LOGGING clause
STDDEV_POP function, 346 LOAD TABLE statement, 802
STDDEV_SAMP function, 348 WITH GRANT OPTION clause
SUM function, 355 syntax, 763
VAR_POP function, 375 WITH HOLD clause
VAR_SAMP function, 377 LOCK TABLE statement, 808
window-name OPEN statement, 822
common element in SQL syntax, 396 WITH HOLD cursors
window-spec DECLARE CURSOR statement [ESQL] [SP], 666
syntax in window functions, 961 locking, 822
windows (OLAP) OPEN statement, 822
WINDOW clause, 961 WITH ISOLATION LEVEL clause
WITH AUTO NAME clause REFRESH MATERIALIZED VIEW statement,
INSERT statement, 781 843
MERGE statement, 813 REFRESH TEXT INDEX statement, 846
WITH BATCH clause WITH LOG clause
EXECUTE IMMEDIATE statement, 720 WRITETEXT statement [T-SQL], 963
WITH CHECK OPTION clause WITH MAX clause
ALTER VIEW statement, 473 ALLOCATE DESCRIPTOR statement [ESQL],
CREATE VIEW statement, 662 399
WITH CHECKPOINT clause WITH NULLS NOT DISTINCT clause
LOAD TABLE statement, 802 CREATE INDEX statement, 555
WITH CHECKPOINT LOG clause WITH OPTION clause
BACKUP statement, 479 SETUSER statement, 904
WITH clause WITH QUOTES clause
INTERSECT statement, 788 EXECUTE IMMEDIATE statement, 720
WITH RECOMPILE clause

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1385


Index

CREATE PROCEDURE statement [T-SQL], 583 CREATE FUNCTION statement [web clients],
WITH RECURSIVE clause 544
SELECT statement, 873 CREATE PROCEDURE statement [web clients],
WITH RESULT SET clause 581
EXECUTE IMMEDIATE statement, 720 CREATE SERVICE statement [SOAP web
WITH ROW LOGGING clause service], 437, 612
LOAD TABLE statement, 802 WWW-Authenticate
required for database mirroring, 804 HTTP_RESPONSE_HEADER function, 244
WITH SAVE clause
DETACH TRACING statement, 687 X
WITH SCRIPTED UPLOAD clause XLOCK table hint
CREATE PUBLICATION statement [MobiLink] FROM clause, 744
[SQL Remote], 592 XML
WITH SERVER NAME clause CREATE SERVICE statement [HTTP web
START DATABASE statement, 908 service], 431, 606
WITH SHARE MODE clause loading from, using the LOAD TABLE statement,
REFRESH MATERIALIZED VIEW statement, 799
844 openxml system procedure, 1001
REFRESH TEXT INDEX statement, 847 XML data type, 88
WITH TEXTPTR clause XMLAGG function, 383
GET DATA statement , 750 XMLCONCAT function, 384
WITH TRUNCATE AT CHECKPOINT clause XMLELEMENT function, 385
START DATABASE statement, 907 XMLFOREST function, 388
WITH VARIABLE RESULT clause XMLGEN function, 389
DESCRIBE statement [ESQL], 683 XML data type
PREPARE statement, 834 syntax, 88
WITHOUT SAVE clause XMLAGG function
DETACH TRACING statement, 687 syntax, 383
WORK clause XMLATTRIBUTES parameter
COMMIT statement, 501 XMLELEMENT function, 385
REVOKE REMOTE DBA statement [SQL XMLCONCAT function
Remote], 865 syntax, 384
write checksums XMLELEMENT function
validating, 955 syntax, 385
WRITE_CLIENT_FILE function XMLFOREST function
syntax, 382 syntax, 388
WRITECLIENTFILE authority XMLGEN function
GRANT statement, 760 syntax, 389
REVOKE statement, 863 xp_cmdshell system procedure
WRITECLIENTFILE authority clause syntax, 1180
GRANT statement, 762 xp_msver system procedure
WriteNoPK locks syntax, 1181
sa_locks system procedure, 1073 xp_read_file system procedure
WRITETEXT statement syntax, 1182
Transact-SQL syntax, 963 xp_scanf system procedure
writing files syntax, 1183
using xp_write_file, 1192 xp_sendmail system procedure
WSDL

1386 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1


syntax, 1183
xp_sprintf system procedure
syntax, 1188
xp_startmail system procedure
syntax, 1188
xp_startsmtp system procedure
enabling in McAfee VirusScan, 1191
possible conflicts with virus scanner settings, 1191
syntax, 1189
xp_stopmail system procedure
syntax, 1191
xp_stopsmtp system procedure
syntax, 1192
xp_write_file system procedure
syntax, 1192

Y
YEAR function
syntax, 390
YEARS function
syntax, 391
YMD function
syntax, 392

Z
zip utility
COMPRESS function, 166

Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1 1387


1388 Copyright © 2012, iAnywhere Solutions, Inc. - SQL Anywhere 12.0.1

You might also like