DB Reference 12
DB Reference 12
SQL Reference
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
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;
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.
identified if in index
of off on open
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 first character of the identifier is not an alphabetic character (as defined below).
● 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.
● Double quotes
● 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.
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.
● 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.
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.
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 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'.
● 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:
Operator Description
= Equal to
Operator Description
!= Not equal to
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.
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:
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:
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:
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 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.
String operators
expression || expression String concatenation (two vertical bars). If either string is NULL, it is
treated as the empty string for concatenation.
expression + expression Alternative string concatenation. When using the + concatenation operator,
you must ensure the operands are explicitly set to character data types rather than relying on implicit data
conversion.
For example, the following query returns the integer value 579:
You can use the CAST or CONVERT function to explicitly convert data types.
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 OR
^ bitwise exclusive OR
~ bitwise NOT
The bitwise operators &, | and ~ are not interchangeable with the logical operators AND, OR, and NOT.
Example
For example, the following statement selects rows in which the correct bits are set.
SELECT *
FROM tableA
WHERE ( options & 0x0101 ) <> 0;
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.
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
| 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
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.
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
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.
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
Subqueries in expressions
A subquery is a SELECT statement that is nested inside another SELECT, INSERT, UPDATE, or
DELETE statement, or another subquery.
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 }
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.
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.
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;
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
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.
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
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:
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 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.
● whether the regular expression is being used with the SIMILAR TO or REGEXP search conditions, or
the REGEXP_SUBSTR function
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:
[ 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.
% 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,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.
^ 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.
● 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.
: The colon is used within a character set to specify a subcharacter class. For example,
'[[:alnum:]]'.
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.
[: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.
[: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).
[: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.
Equivalent to [[:alnum:]_]..
Equivalent to \x{hh}.
Equivalent to $.
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:
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:
● password has at least one digit (zero width positive assertion with [[:digit:]])
● password has at least two alphabetic characters (zero width positive assertion with
[[:alpha:]].*[[:alpha:]])
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.
(?! 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.
(?<= 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.
(?<! 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.
(?> 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.
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.
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
Note that backslashes should be doubled if the examples are used in literal strings (for example, '.+@.+
\\..+')
Credit Card Numbers (REGEXP only): Matches (Visa): 4123 6453 2222 1746
Discover:
6011\s[0-9]{4}\s[0-9]{4}\s[0-9]{4}
Java Comments (REGEXP only): Matches Java comments that are between /* and
*/, or one line comments prefaced by //.
/\*.*\*/|//[^\n]*
Non-Matches: a=1
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
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
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).
You cannot use SQL reserved words as identifiers if the quoted_identifier option is Off.
The following statement changes the setting of the quoted_identifier option to Off:
SET quoted_identifier Off;
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 )
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 :
=
|>
|<
| >=
| <=
| <>
| !=
| !<
| !>
trigger-operation :
INSERTING
| DELETING
| UPDATING [ ( column-name-string ) ]
| UPDATE( column-name )
Parameters
● ALL search condition
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.
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
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.
See also
● “Comparison operators” on page 8
comparison-operator:
=
|>
|<
| >=
| <=
| <>
| !=
| !<
| !>
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...
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.
comparison-operator:
=
|>
|<
| >=
| <=
| <>
| !=
| !<
| !>
Remarks
The keywords ANY and SOME are synonymous.
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...
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.
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 )
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 ))
See also
● “Query predicates” [SQL Anywhere Server - SQL Usage]
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.
● 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.
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.
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.
○ 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
Syntax
The syntax for the LIKE search condition is as follows:
Parameters
● expression The string to be searched.
● 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.
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_'
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
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.
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 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.
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.
● 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.
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.
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).
Therefore, the expression a1 matches the pattern a1, but not the patterns 'a1 ' (a1, with a space after it) or
a1_.
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
Syntax
expression [ NOT ] REGEXP pattern [ ESCAPE escape-expression ]
Parameters
● expression The string to be searched.
● escape-expression The escape character to be used in the match. The default is the backslash
character (\).
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:]]'.
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.
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
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.
Syntax
expression [ NOT ] SIMILAR TO pattern [ ESCAPE escape-expression ]
Parameters
● expression The expression to be searched.
● 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 '['.
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
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.
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
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:
● 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 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.
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
| 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
Parameters
● and-expression Use and-expression to specify that both primary-expression and simple-
expression must be found in the text index.
An ampersand (&) can be used instead of AND, and can abut the expressions or terms on either side
(for example, 'a &b').
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"'.
● 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'.
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:
● 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'.
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.
● 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.
1. FUZZY, NEAR
2. AND NOT
3. AND
4. OR
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".
'th*&best' 'th* AND Find any term beginning with th, and the term best.
best' and 'th*
best'
'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.
Note
Interpretation of query strings containing asterisks can vary depending on the text configuration object
settings.
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 -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.
'wild - west' 'wild west', and 'wild Find the term wild, and the term west.
AND west'
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.
vertical bar (|) The vertical bar is equivalent to OR, and can be
specified as follows:
● 'a|b'
● 'a |b'
● 'a | b'
● 'a| b'
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
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.
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.
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.
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.
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]
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
OR operator
OR TRUE FALSE UNKNOWN
NOT operator
TRUE FALSE UNKNOWN
IS operator
IS TRUE FALSE UNKNOWN
See also
● “NULL special value” on page 64
Occasionally, the statistics may become inaccurate or relevant statistics may be unavailable. This
condition is most likely to arise when few queries have been executed since a large amount of data was
added, updated, or deleted. In this situation, 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.
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.
Data type
string
See also
● “Expressions” on page 12
Data type
DATE
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
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]
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]
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
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.
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.
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
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.
See also
● “Expressions” on page 12
● “LAST USER special value” on page 63
● “USER special value” on page 70
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
Data type
String
Remarks
LAST USER can be used as a default value in columns with character data types.
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
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.
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.
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.
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:
Permissions
Must be connected to the database.
Side effects
None.
● 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:
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' );
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
Data type
String
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:
42Rxx Syntax error: referential integrity (for example, attempt to create second primary
key)
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
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.
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
Data type
string
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
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.
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]
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
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.
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;
Running this batch from Interactive SQL displays the message local_var = 10 on the Messages tab
of the Interactive SQL Results pane.
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.
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.
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.
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.
In Embedded SQL, global variables can be selected into a host variable list.
@@connections The number of logins since the server was last started.
@@dbts A value of type TIMESTAMP representing the last generated value used for all
columns defined with DEFAULT TIMESTAMP.
@@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].
@@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:
@@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.
@@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).
@@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.
The @@rowcount is not reset to zero by any statement which does not affect
rows, such as an IF statement.
@@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:
@@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.
See also
● “@@identity global variable” on page 78
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.
Comments
Comments are used to attach explanatory text to SQL statements or statement blocks. The database server
does not execute comments.
● -- (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;
See also
● “Keyboard shortcuts for Interactive SQL” [SQL Anywhere Server - Database Administration]
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.
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]
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.
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
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
The SQL/2008 standard supports explicit character- or byte-length semantics as SQL language feature
T061.
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.
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
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.
See also
● “CHAR data type” on page 81
● “VARCHAR data type” on page 87
● “LONG NVARCHAR data type” on page 83
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.
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.
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
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
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.
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.
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
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
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
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.
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:
Type being described Database character Client character set Result of DESCRIBE
set
See also
● “CHAR data type” on page 81
● “LONG VARCHAR data type” on page 83
● “NVARCHAR data type” on page 85
The SQL/2008 standard supports explicit character- or byte-length semantics as SQL language feature
T061.
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.
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]
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].
Syntax
[ UNSIGNED ] BIGINT
Remarks
The BIGINT data type is an exact numeric data type: its accuracy is preserved after arithmetic operations.
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
Syntax
BIT
Remarks
BIT is an integer type that can store the values 0 or 1.
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
● 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.
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.
Remarks
The DECIMAL data type is an exact numeric data type; its accuracy is preserved to the least significant
digit after arithmetic operations.
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.
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]
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.
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
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
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.
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
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.
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.
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
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 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.
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]
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.
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
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.
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
Syntax
[ UNSIGNED ] TINYINT
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.
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
Syntax
MONEY
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
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
The bit array data types supported by SQL Anywhere include VARBIT and LONG VARBIT.
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
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
● 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.
● 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 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.
● using ODBC or OLE DB, as a binary value (using an ODBC TIMESTAMP_STRUCT structure for
example)
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.
● 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.
● 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).
● 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
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).
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.
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'.
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'.
The non-ISO AM and PM designators are also supported. For example, '11:59:59 PM' is equivalent to
'23:59:59'.
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
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.
● 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.
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
● Using ODBC or OLE DB, as a binary value (using an ODBC TIMESTAMP_STRUCT structure for
example)
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.
● timestamp - integer Subtract the specified number of days from a date or timestamp.
● date - date Compute the number of days between two dates or timestamps.
● date + time Create a timestamp combining the given date and time.
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.
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
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.
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
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.
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.
Note
When the precision of the DATETIME value is reduced, built-in functions that pertain to minutes or
seconds will produce meaningless results.
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
● 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.
Syntax
DATETIMEOFFSET
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.
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.
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
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.
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
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.
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
● 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.
Syntax
TIMESTAMP
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.
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
● Transact-SQL Adaptive Server Enterprise uses the DATETIME type for TIMESTAMP values.
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.
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
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.
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
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.
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
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
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
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
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
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.
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
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:
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
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.
● 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.
● 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
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.
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
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]
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 )
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]
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:
● REAL » DOUBLE
For example, if the two arguments are of types BIT and TINYINT, they are converted to NUMERIC.
The table below summarizes the conversions that are implicit when comparing certain data types with
date, time, or date-time data types.
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- 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.
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.
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
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.
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.
For example, if the two arguments have REAL and CHAR data types, they are both converted to
NUMERIC.
See also
● “Comparisons between CHAR and NCHAR” on page 123
● 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]
Examples
SELECT CAST( CAST( 1 AS BIT ) AS VARBIT ) returns a VARBIT(1) containing 1.
Examples
SELECT CAST( 0x8181 AS VARBIT ) returns a VARBIT(16) containing 1000000110000001.
Example
SELECT CAST( '001100' AS VARBIT ) returns a VARBIT(6) containing 001100.
Example
SELECT CAST( CAST( '11000010' AS VARBIT ) AS INTEGER ) returns 194 (110000102
= 0xC2 = 194).
Examples
SELECT CAST( CAST( '1111' AS VARBIT ) AS BINARY ) returns 0xF0 (11112 becomes
111100002 = 0xF0).
Example
SELECT CAST( CAST( '01110' AS VARBIT ) AS VARCHAR ) returns the character string
'01110'.
See also
● “CAST function [Data type conversion]” on page 159
● “CONVERT function [Data type conversion]” on page 172
String CHAR
String VARCHAR
String TEXT
java.math.BigDecimal NUMERIC
java.math.BigDecimal MONEY
java.math.BigDecimal SMALLMONEY
boolean BIT
byte TINYINT
short SMALLINT
int INTEGER
long 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
CHAR String
VARCHAR String
TEXT String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
MONEY java.math.BigDecimal
SMALLMONEY java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[ ]
VARBINARY byte[ ]
IMAGE byte[ ]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
See also
● “Supported spatial data types and their hierarchy” [SQL Anywhere Server - Spatial Data Support]
Unless otherwise specified in the documentation, NULL is returned for a function if any argument is
NULL.
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.
List of functions
The following aggregate functions are available:
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.
List of functions
The following data type conversion functions are available:
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.
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());
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
Hour hh 0-23
Minute mi 0-59
Second ss 0-59
Millisecond ms 0-999
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.
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.
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.
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.
Functions:
● can return a single value of arbitrary type, and allow you to declare the returned type using the
RETURNS clause
Procedures:
● can be referenced in the FROM clause of a query, or using a CALL statement, or using a Transact-SQL
EXECUTE statement
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]
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:
Numeric functions
Numeric functions perform mathematical operations on numerical data types or return numeric
information.
List of functions
The following numeric functions are available:
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.
List of functions
The following string functions are available:
System functions
System functions return system information.
List of functions
The following system functions are available:
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.
INDEX_COL ( table-name, index-id, key_# [, userid ] ) Returns the name of the indexed column
List of functions
The following text and image function is available:
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.
Syntax
ABS( numeric-expression )
Parameters
● numeric-expression The number whose absolute value is to be returned.
Returns
An absolute value of the numeric expression.
INT INT
FLOAT FLOAT
DOUBLE DOUBLE
NUMERIC NUMERIC
Example
The following statement returns the value 66.
SELECT ABS( -66 );
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
Example
The following statement returns the arc-cosine value for 0.52.
SELECT ACOS( 0.52 );
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.
Example
The following statement returns the value 6.
SELECT ARGN( 6, 1,2,3,4,5,6 );
Syntax
ASCII( string-expression )
Parameters
● string-expression The string.
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
Example
The following statement returns the value 90.
SELECT ASCII( 'Z' );
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
Example
The following statement returns the arc-sine value for 0.52.
SELECT ASIN( 0.52 );
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
Example
The following statement returns the arc-tangent value for 0.52.
SELECT ATAN( 0.52 );
Syntax
{ ATN2 | ATAN2 }( numeric-expression-1, numeric-expression-2 )
Parameters
● numeric-expression-1 The numerator 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
Example
The following statement returns the arc-tangent value for the ratio 0.52 to 0.60.
Syntax 1
AVG( [ ALL | DISTINCT ] numeric-expression )
Syntax 2
AVG( [ ALL ] numeric-expression ) OVER ( window-spec )
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.
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
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]
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 )
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
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 ) );
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
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;
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
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')
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).
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
● 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:
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
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')
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.
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.
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
Example
The following statement returns 1101:
SELECT BIT_SUBSTR( '001101', 3 );
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
Example
The following example generates four rows containing a CHAR column, then converts the values to
VARBIT.
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.
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.
If the string is in a multibyte character set, the BYTE_LENGTH value may differ from the number of
characters returned by CHAR_LENGTH.
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
Example
The following statement returns the value 12.
SELECT BYTE_LENGTH( 'Test Message' );
Syntax
BYTE_SUBSTR( string-expression, start [, length ] )
Parameters
● string-expression The string from which the substring is taken.
● start An integer expression indicating the start of the substring. A positive integer starts from the
beginning of the string, with the first character being position 1. A negative integer specifies a
substring starting from the end of the string, the final character being at position -1.
● length An integer expression indicating the length of the substring. A positive length specifies the
number of bytes to be taken starting at the start position. A negative length 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
Example
The following statement returns the value Test.
SELECT BYTE_SUBSTR( 'Test Message', 1, 4 );
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.
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
Example
The following function ensures a string is used as a date:
The value of the expression 1 + 2 is calculated, and the result is then cast into a single-character string.
Syntax
{ CEILING | CEIL } ( numeric-expression )
Parameters
● numeric-expression The number whose ceiling is to be calculated.
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
Example
The following statement returns the value 60.
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
Example
The following statement returns the value Y.
SELECT CHAR( 89 );
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.
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.
See also
● “BYTE_LENGTH function [String]” on page 157
● “String functions” on page 142
Example
The following statement returns the value 8.
SELECT CHAR_LENGTH( 'Chemical' );
Syntax
CHARINDEX( string-expression-1, string-expression-2 )
Parameters
● string-expression-1 The string for which you are searching.
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.
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
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
Surname GivenName
Kuo Felicia
Kelly Moira
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
Example
The following statement returns the value 34.
SELECT COALESCE( NULL, 34, 13, 0 );
Syntax
COMPARE(
string-expression-1,
string-expression-2
[, { collation-id
| collation-name[(collation-tailoring-string) ] } ]
)
Parameters
● string-expression-1 The first 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.
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:
Value Meaning
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.
See also
● “SORTKEY function [String]” on page 339
● “String functions” on page 142
Example
The following example performs three comparisons using the COMPARE function:
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.
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.
● 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.
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
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' ) );
Syntax
CONFLICT( column-name )
Parameters
● column-name The name of the column being tested for conflicts.
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]
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'
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';
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:
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;
Syntax
CONNECTION_EXTENDED_PROPERTY(
{ property-id | property-name }
[, property-specific-argument [, connection-id ] ]
)
Parameters
● property-id The connection property ID.
● 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.
○ Progress
● 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).
● 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.
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
Example
The following example returns the CHAR character set of the current connection as it is known by the
Java standard:
Syntax
CONNECTION_PROPERTY(
{ integer-expression-1 | string-expression }
[ , integer-expression-2 ] )
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].
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
Example
The following statement returns the number of prepared statements being maintained.
SELECT CONNECTION_PROPERTY( 'PrepStmt' );
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 ] )
Parameters
● datatype The data type to which the expression is 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).
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]
8 108 hh:nn:ss
10 110 mm-dd-yy[yy]
11 111 [yy]yy/mm/dd
12 112 [yy]yymmdd
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
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
...
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 );
Syntax
CORR( dependent-expression, independent-expression )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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:
See also
● “Aggregate functions” on page 133
● “COVAR_POP function [Aggregate]” on page 181
● “STDDEV_POP function [Aggregate]” on page 346
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;
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
Example
The following statement returns the value of the cosine of an angle 0.52 radians.
SELECT COS( 0.52 );
Syntax
COT( 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
● “COS function [Numeric]” on page 176
● “SIN function [Numeric]” on page 337
● “TAN function [Numeric]” on page 359
Example
The following statement returns the cotangent value of 0.52.
SELECT COT( 0.52 );
Syntax 1
COUNT( [ * | [ ALL | DISTINCT ] expression ] )
Syntax 2
COUNT( [ * | [ ALL ]expression ] ) OVER ( window-spec )
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.
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
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.
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;
Syntax 1
COUNT_BIG( [ * | [ ALL | DISTINCT ] expression ] )
Syntax 2
COUNT_BIG( [ * | [ ALL ] expression ]) OVER ( window-spec )
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
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.
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.
Example
The following statement returns the value 4:
Syntax 1
COVAR_POP( dependent-expression, independent-expression )
Syntax 2
COVAR_POP( dependent-expression, independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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
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
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;
Syntax 1
COVAR_SAMP( dependent-expression, independent-expression )
Syntax 2
COVAR_SAMP( dependent-expression, independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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.
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
Example
The following example returns the value 74782.9460054052.
SELECT COVAR_SAMP( Salary, ( 2008 - YEAR( BirthDate ) ) )
FROM Employees;
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.
● 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
Examples
This fragment converts the mytext column from the Traditional Chinese character set to the Simplified
Chinese character set:
This fragment converts the mytext column from the database character set to the Simplified Chinese
character set:
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.
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;
Syntax
CUME_DIST( ) OVER ( window-spec )
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].
See also
● “DENSE_RANK function [Ranking]” on page 206
● “PERCENT_RANK function [Ranking]” on page 292
● “RANK function [Ranking]” on page 303
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');
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:
SMALLINT 2
INTEGER 4
DOUBLE 8
Example
The following statement returns the length of the longest string in the CompanyName column.
SELECT MAX( DATALENGTH( CompanyName ) )
FROM Customers;
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.
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
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;
Syntax
DATEADD( date-part, integer-expression, timestamp-expression )
date-part :
year
| quarter
| month
| week
| day
| dayofyear
| hour
| minute
| second
| 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.
Returns
TIMESTAMP WITH TIME ZONE if timestamp-expression is a TIMESTAMP WITH TIME ZONE;
otherwise TIMESTAMP.
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 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 ));
Syntax
DATEDIFF( date-part, date-expression-1, date-expression-2 )
date-part :
year
| quarter
| month
| week
| day
| 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.
Example
The following statement returns 1.
SELECT DATEDIFF( hour, '4:00AM', '5:50AM' );
Syntax
DATEFORMAT( datetime-expression, string-expression )
Parameters
● datetime-expression The datetime to be converted.
For information about date format descriptions, see “timestamp_format option” [SQL Anywhere
Server - Database Administration].
Returns
VARCHAR
Remarks
Any allowable date format can be used for the string-expression.
Example
The following statement returns the value Jan 01, 1989.
SELECT DATEFORMAT( '1989-01-01', 'Mmm dd, yyyy' );
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
Example
The following statement returns the value May.
SELECT DATENAME( month, '1987/05/02' );
Syntax
DATEPART( date-part, timestamp-expression )
Parameters
● date-part The date part to be returned.
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
Example
The following statement returns the value 5.
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:
Syntax
DATETIME( expression )
Parameters
● expression The expression to be converted. It is generally a string.
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
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' );
Syntax
DAY( date-expression )
Parameters
● date-expression The date as a DATE data type.
Returns
SMALLINT
Remarks
The DAY function returns an integer between 1 and 31, corresponding to the day of the month in the
argument.
Example
The following statement returns the value 12.
SELECT DAY( '2001-09-12' );
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.
Example
The following statement returns the value Saturday.
SELECT DAYNAME ( '1987/05/02' );
Syntax 1
DAYS( timestamp-expression )
Syntax 2
DAYS( timestamp-expression, timestamp-expression )
Syntax 3
DAYS( timestamp-expression, integer-expression )
Parameters
● timestamp-expression A TIMESTAMP value.
For information about casting data types, see “CAST function [Data type conversion]” on page 159.
Returns
INTEGER with Syntax 1 or Syntax 2.
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
Example
The following statement returns the integer 729889.
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).
The following statements return the TIMESTAMP value 1999-07-14 00:00:00.000. It is recommended
that you use the second example (DATEADD).
Syntax
DB_EXTENDED_PROPERTY(
{ property-id | property-name }
[, property-specific-argument
[, database-id | database-name ] ]
)
Parameters
● property-id The database property ID to query.
For a complete list of database properties, see “Accessing database property values” [SQL Anywhere
Server - Database Administration].
○ 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.
● 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].
● 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].
○ 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
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.
○ 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.
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.
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:
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
Example
The following statement returns the location of the current database:
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:
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]
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( );
Syntax
DB_NAME( [ database-id ] )
Parameters
● database-id The ID of the database. The database-id must be a numeric expression.
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
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 );
Syntax
DB_PROPERTY(
{ property-id | property-name }
[, database-id | database-name ]
)
Parameters
● property-id The database property ID.
● database-id The database ID number, as returned by the DB_ID function. Typically, the database
name is used.
Returns
VARCHAR, LONG VARCHAR
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
Example
The following statement returns the page size of the current database, in bytes.
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.
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
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;
Syntax
DECRYPT( string-expression, key
[, algorithm ]
)
algorithm :
'AES'
| 'AES256'
| 'AES_FIPS'
| 'AES256_FIPS'
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]
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;
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.
Example
The following statement returns the value 29.79380534680281.
SELECT DEGREES( 0.52 );
Syntax
DENSE_RANK( ) OVER ( window-spec )
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]
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');
Syntax
DIFFERENCE ( string-expression-1, string-expression-2 )
Parameters
● string-expression-1 The first 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
Example
The following statement returns similarity between the words test and chest:
SELECT DIFFERENCE( 'test', 'chest' );
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.
Example
The following statement returns the value 5.
SELECT DOW( '1998-07-09' );
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;
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
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]
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.
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]
Example
The following statement returns the error message for SQLCODE -813.
SELECT ERRORMSG( -813 );
Syntax
ESTIMATE( column-name [, value [, relation-string ] ] )
Parameters
● column-name The column used in the estimate.
● value The value to which the column is compared. 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
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;
Syntax
ESTIMATE_SOURCE(
column-name
[, value
[, relation-string ] ]
)
Parameters
● column-name The name of the column that is being investigated.
● value The value to which the column is compared. 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].
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.
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
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;
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:
DBFreeSpace MB DBDiskSpace
DBSize MB GrowDB
LogFreeSpace MB LogDiskSpace
LogSize MB GrowLog
TempFreeSpace MB TempDiskSpace
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
Example
The following event definition uses the EVENT_CONDITION function:
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.
See also
● “CREATE EVENT statement” on page 526
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:
● 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.
○ 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.
○ 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.
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]
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 ) );
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.
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.
Example
The statement returns the value 3269017.3724721107.
SELECT EXP( 15 );
Syntax
EXPERIENCE_ESTIMATE(
column-name
[, value
[, relation-string ] ]
)
Parameters
● column-name The name of the column that is being investigated.
● 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
Example
The following statement returns NULL.
SELECT DISTINCT EXPERIENCE_ESTIMATE( EmployeeID, 200, '>' )
FROM Employees;
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
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.
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
Example
The following statement passes a SELECT statement as a string parameter and returns the plan for
executing the query.
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 ....'.
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:
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
Example
The following statement returns smallint when executed against the SQL Anywhere sample database.
SELECT EXPRTYPE( 'SELECT LineID FROM SalesOrderItems', 1 );
Syntax
FIRST_VALUE( [ ALL ] expression [ { RESPECT | IGNORE } NULLS ] )
OVER ( window-spec )
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.
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
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;
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.
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
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
Example
The following statement returns a Floor value of 123:
SELECT FLOOR (123);
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.
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
Example
The following statement returns the value 1:
SELECT GET_BIT( '00110011' , 4 );
Syntax
GET_IDENTITY( table_name [, number_to_allocate ] )
Parameters
● table_name A string indicating the name of the table, including, optionally, the owner name.
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. 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
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 );
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.
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
Example
The following statement returns the system date and time.
SELECT GETDATE( );
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.
Value Description
Value Description
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
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
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.
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',
2,
'keyset-driven', 'for update' );
Syntax
GREATER( expression-1, expression-2 )
Parameters
● expression-1 The first 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
Example
The following statement returns the value 10.
SELECT GREATER( 10, 5 ) FROM dummy;
Syntax
GROUPING( group-by-expression )
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.
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]
Example
For examples of this function, see “Detection of NULLs using the GROUPING function” [SQL Anywhere
Server - SQL Usage].
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:
● CRC32 returns a hexadecimal string. Use the HEXTOINT function to convert the hexadecimal string to
a 32-bit integer.
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:
● 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
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,
user_name CHAR(80),
user_pwd CHAR(80) );
INSERT INTO user_info
VALUES ( '1', 's_phillips', HASH( 'mypass', 'SHA256' ) );
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:
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:
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.
See also
● “INTTOHEX function [Data type conversion]” on page 250
Example
The following statement returns the value 420.
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.
Example
The following statement returns the value 21:
Syntax 1
HOURS ( timestamp-expression )
Syntax 2
HOURS ( timestamp-expression, timestamp-expression )
Syntax 3
HOURS ( time-or-timestamp-expression, integer-expression )
Parameters
● time-or-timestamp-expression A value of type TIME or TIMESTAMP.
For information about casting data types, see “CAST function [Data type conversion]” on page 159.
Returns
INTEGER with Syntax 1 or Syntax 2.
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
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).
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 );
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
" "
' '
& &
< <
> >
Characters Substitution
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
Examples
SELECT HTML_DECODE('<p>The piano was made ' ||
'by ‘Steinway & Sons’.</p>')
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
" "
Characters Substitution
' '
& &
< <
> >
See also
● “HTML_DECODE function [Miscellaneous]” on page 237
● “Web services functions” on page 141
● “Web services system procedures” on page 996
Examples
The following example returns the string '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN"> '.
SELECT HTML_ENCODE('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">')
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.
Remarks
If the request body does not exist, or if the function is not called from a web service, a NULL value is
returned.
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
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
Examples
SELECT HTTP_DECODE('http%3A%2F%2Fdcx.sybase.com')
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
Character Substitution
| %7C
} %7D
character codes nn that are less than 0x20 and greater than 0x7f %nn
See also
● “HTTP_DECODE function [Web service]” on page 240
● “Web services functions” on page 141
● “Web services system procedures” on page 996
Examples
SELECT HTTP_ENCODE('/opt&id=123&text=''oid:c\x09d ef''')
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.
● Accept-Encoding A list of encodings for the response that are acceptable to the client application.
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
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 );
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.
● 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.
The following special header allows access to the status within the response of a server response.
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
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;
Syntax
HTTP_VARIABLE( var-name [ , instance [ , attribute ] ] )
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.
○ '@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.
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.
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
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' );
Syntax
IDENTITY( expression )
Parameters
● expression An expression. The expression is parsed, but is ignored during the execution of the
function.
Returns
INT
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
Example
The following statement returns a sequentially-numbered list of employees.
SELECT IDENTITY( 10 ), Surname FROM Employees;
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.
Returns
The data type returned depends on the data type of expression-2 and expression-3.
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 );
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
Example
The following statement returns the percentage of EmployeeID values estimated to be greater than 200.
SELECT INDEX_ESTIMATE( EmployeeID, 200, '>' )
FROM Employees;
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.
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
Example
The following statement returns the value backoffice.
SELECT INSERTSTR( 0, 'office ', 'back' );
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.
See also
● “HEXTOINT function [Data type conversion]” on page 234
Example
The following statement returns the value 0000009c.
SELECT INTTOHEX( 156 );
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.
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
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;
Syntax
ISENCRYPTED( string, key[, algorithm ] )
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
Example
The following fragment illustrates the use of the ISENCRYPTED function:
SELECT ISENCRYPTED( ENCRYPT ('test_string', 'key' ), 'key');
Syntax
ISNULL( expression, expression [, ...] )
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
Example
The following statement returns the value -66.
SELECT ISNULL( NULL ,-66, 55, 45, NULL, 16 );
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.
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;
Syntax
LAST_VALUE( [ ALL ] expression[ { RESPECT | IGNORE } NULLS ] )
OVER ( window-spec )
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.
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
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:
Jose Martinez makes the highest salary in department 500, and Scott Evans makes the highest salary in
department 400.
Syntax
LCASE( string-expression )
Parameters
● string-expression The string to be converted to lowercase.
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
Example
The following statement returns the value chocolate.
Syntax
LEFT( string-expression, integer-expression )
Parameters
● string-expression The string.
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 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
Example
The following statement returns the first 5 characters of each Surname value in the Customers table.
SELECT LEFT( Surname, 5) FROM Customers;
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.
See also
● “BYTE_LENGTH function [String]” on page 157
● “International languages and character sets” [SQL Anywhere Server - Database Administration]
● “String functions” on page 142
Example
The following statement returns the value 9.
Syntax
LESSER( expression-1, expression-2 )
Parameters
● expression-1 The first 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
Example
The following statement returns the value 5.
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:
Returns
● LONG VARCHAR
● LONG NVARCHAR
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.
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,...
LIST( EmployeeID )
191,703,750,868,921,1013,1570,...
The following statement sorts the employee IDs by the last name of the employee:
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:
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, ';' ):
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.
See also
● “String functions” on page 142
● “CHARINDEX function [String]” on page 163
Example
The following statement returns the value 8.
SELECT LOCATE(
'office party this week - rsvp as soon as possible',
'party',
2 );
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;
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
Example
The following statement returns the natural logarithm of 50.
SELECT LOG( 50 );
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
Example
The following statement returns the base 10 logarithm for 50.
SELECT LOG10( 50 );
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.
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
Example
The following statement returns the value chocolate.
SELECT LOWER( 'chOCOLate' );
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.
See also
● “RTRIM function [String]” on page 330
● “TRIM function [String]” on page 367
● “String functions” on page 142
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' );
Syntax 1
MAX( [ ALL | DISTINCT ] expression )
Syntax 2
MAX( [ ALL ] expression ) OVER ( window-spec )
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].
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
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;
Syntax 1
MEDIAN( [ ALL | DISTINCT ] numeric-expression )
Syntax 2
MEDIAN( [ ALL ] numeric-expression ) OVER ( window-spec )
Parameters
● numeric-expression The expression whose median is calculated over a set of rows.
● 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
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.
The following statement returns the median salary by state from the Employees table:
Syntax 1
MIN( [ ALL | DISTINCT ] expression )
Syntax 2
MIN( [ ALL ] expression ) OVER ( window-spec )
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.
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
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;
Syntax
MINUTE( timestamp-expression )
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.
Example
The following statement returns the value 22.
SELECT MINUTE( '1998-07-13 12:22:34' );
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.
Returns
INTEGER with Syntax 1 or Syntax 2.
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
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' );
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).
The following statement returns 'TIME', illustrating that the MINUTES function returns a TIME value
when it is called with a TIME argument.
Syntax
MOD( dividend, divisor )
Parameters
● dividend The dividend, or numerator 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
Example
The following statement returns the value 2.
SELECT MOD( 5, 3 );
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.
Example
The following statement returns the value 7.
SELECT MONTH( '1998-07-13' );
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
Example
The following statement returns the value September.
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.
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.
● 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
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' );
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);
Syntax
NCHAR( integer )
Parameters
● integer The number to be converted to the corresponding Unicode code point.
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
Example
The following example returns the ALEF Arabic letter, which is Unicode code point U+627:
SELECT NCHAR( 1575 );
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.
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
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 );
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.
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.
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 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 );
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.
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
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
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;
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
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 );
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
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 );
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.
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
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;
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
Example
The following statement returns the current date and time.
SELECT NOW( * );
Syntax
NULLIF( expression-1, expression-2 )
Parameters
● expression-1 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
Example
The following statement returns the value a:
SELECT NULLIF( 'a', 'b' );
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.
See also
● “INSERT statement” on page 780
Example
The following statement returns a sequentially-numbered list of departments.
SELECT NUMBER( * ), DepartmentName
FROM Departments
WHERE DepartmentID > 5
ORDER BY DepartmentName;
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
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).
See also
● “LIKE search condition” on page 39
● “LOCATE function [String]” on page 264
● “String functions” on page 142
Example
The following statement returns the value 2.
SELECT PATINDEX( '%hoco%', 'chocolate' );
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:
the quick brown fox $$$$ 4 21 the quick $$$$ jumped over the
jumped over the lazy dog brown fox 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
the quick brown fox$$ 4 20 the quick $$ jumped over the lazy
jumped over the lazy dog brown fox dog
$
Syntax
PERCENT_RANK( ) OVER ( window-spec )
Returns
The PERCENT_RANK function returns a DOUBLE value between 0 and 1.
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
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');
PI function [Numeric]
Returns the numeric value PI.
Syntax
PI( [ * ] )
Returns
DOUBLE
Remarks
This function returns a DOUBLE value.
Example
The following statement returns the value 3.141592653...
SELECT PI( * );
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.
● update-status A string parameter accepting one of the following values indicating how the
optimizer should treat the given cursor:
Value Description
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
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' );
Syntax
POWER( numeric-expression-1, numeric-expression-2 )
Parameters
● numeric-expression-1 The base.
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.
Example
The following statement returns the value 64.
SELECT POWER( 2, 6 );
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.
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]
Example
The following statement returns the description Number of index insertions.
SELECT PROPERTY_DESCRIPTION( 'IndAdd' );
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.
● second-parameter You can specify a second parameter for some properties, as follows:
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].
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].
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
Example
The following statement returns the name of the current database server:
SELECT PROPERTY( 'Name' );
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.
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]
Example
The following statement returns the server-level property associated with property ID 102.
SELECT PROPERTY_NAME( 102, 'server' );
Syntax
PROPERTY_NUMBER( property-name )
Parameters
● property-name A property name.
Returns
INT
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]
Example
The following statement returns an integer value. The actual value changes from release to release.
SELECT PROPERTY_NUMBER( 'PAGESIZE' );
Syntax
QUARTER( timestamp-expression )
Parameters
● timestamp-expression The date you want the quarter for.
Returns
INTEGER
Remarks
The quarters are as follows:
1 January 1 to March 31
2 April 1 to June 30
3 July 1 to September 30
4 October 1 to December 31
Example
The following statement returns the value 2.
SELECT QUARTER( '1987/05/02' );
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.
Example
The following statement returns a value of approximately 0.5236.
SELECT RADIANS( 30 );
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.
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].
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:
Syntax
RANK( ) OVER ( window-spec )
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
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');
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
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.
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:
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]
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
Syntax
REGEXP_SUBSTR( expression,
regular-expression
[, start-offset [ , occurrence-number [, escape-expression ] ] ] )
Parameters
● expression The string to be searched.
● 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
Example
The following example breaks values in the Employees.Street column into street number and street name:
street_num street_name
7 Pleasant Street
... ...
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:
Syntax 1
REGR_AVGX( dependent-expression , independent-expression )
Syntax 2
REGR_AVGX( dependent-expression , independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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 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
Example
The following example calculates the average of the dependent variable, employee age.
SELECT REGR_AVGX( Salary, ( 2008 - YEAR( BirthDate ) ) )
FROM Employees;
Syntax 1
REGR_AVGY( dependent-expression , independent-expression )
Syntax 2
REGR_AVGY( dependent-expression , independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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
Example
The following example calculates the average of the independent variable, employee salary.
SELECT REGR_AVGY( Salary, ( YEAR( NOW( )) - YEAR( BirthDate ) ) )
FROM Employees;
Syntax 1
REGR_COUNT( dependent-expression , independent-expression )
Syntax 2
REGR_COUNT( dependent-expression , independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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].
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
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;
Syntax 1
REGR_INTERCEPT( dependent-expression , independent-expression )
Syntax 2
REGR_INTERCEPT( dependent-expression , independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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:
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
Example
The following example returns the y-intercept of the linear regression line.
Syntax 1
REGR_R2( dependent-expression , independent-expression )
Syntax 2
REGR_R2( dependent-expression , independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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].
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
Example
The following example returns the coefficient of determination for the regression line.
SELECT REGR_R2( Salary, ( YEAR( NOW( )) - YEAR( BirthDate ) ) )
FROM Employees;
Syntax 1
REGR_SLOPE( dependent-expression , independent-expression )
Syntax 2
REGR_SLOPE( dependent-expression , independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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:
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
Example
The following example returns the value 935.3429749445614.
SELECT REGR_SLOPE( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )
FROM Employees;
Syntax 1
REGR_SXX( dependent-expression , independent-expression )
Syntax 2
REGR_SXX( dependent-expression , independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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].
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
Example
The following example returns the value 5916.4800000000105.
SELECT REGR_SXX( Salary, ( YEAR( NOW() ) - YEAR( BirthDate ) ) )
FROM Employees;
Syntax 1
REGR_SXY( dependent-expression , independent-expression )
Syntax 2
REGR_SXY( dependent-expression , independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
Returns
DOUBLE
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
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;
Syntax 1
REGR_SYY( dependent-expression , independent-expression )
Syntax 2
REGR_SYY( dependent-expression , independent-expression )
OVER ( window-spec )
Parameters
● dependent-expression The variable that is affected by the independent variable.
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].
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
Example
The following example returns the value 26, 708, 672,843.3002.
SELECT REGR_SYY( Salary, ( YEAR( NOW( )) - YEAR( BirthDate ) ) )
FROM Employees;
Syntax
REMAINDER( dividend, divisor )
Parameters
● dividend The dividend, or numerator 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
Example
The following statement returns the value 2.
SELECT REMAINDER( 5, 3 );
Syntax
REPEAT( string-expression, integer-expression )
Parameters
● string-expression The string 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.
See also
● “REPLICATE function [String]” on page 323
● “String functions” on page 142
Example
The following statement returns the value repeatrepeatrepeat.
SELECT REPEAT( 'repeat', 3 );
Syntax
REPLACE( original-string, search-string, replace-string )
Parameters
If any argument is NULL, the function returns NULL.
● 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.
See also
● “SUBSTRING function [String]” on page 353
● “CHARINDEX function [String]” on page 163
● “String functions” on page 142
Example
The following statement returns the value xx.def.xx.ghi.
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%';
Syntax
REPLICATE( string-expression, integer-expression )
Parameters
● string-expression The string 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.
See also
● “REPEAT function [String]” on page 321
● “String functions” on page 142
Example
The following statement returns the value repeatrepeatrepeat.
SELECT REPLICATE( 'repeat', 3 );
Syntax
REVERSE( string-expression )
Parameters
● string-expression The string to be reversed.
Returns
● LONG VARCHAR
● LONG NVARCHAR
Remarks
This function supports NCHAR inputs and/or outputs.
See also
● “String functions” on page 142
Example
The following statement returns the value cba.
SELECT REVERSE( 'abc' );
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.
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:
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]
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 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):
Syntax
RIGHT( string-expression, integer-expression )
Parameters
● string-expression The string to return the rightmost characters for.
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
Example
The following statement returns the last 5 characters of each Surname value in the Customers table.
SELECT RIGHT( Surname, 5) FROM Customers;
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
Example
The following statement returns the value 123.200.
Syntax
ROW_NUMBER( ) OVER ( window-spec )
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.
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
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');
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 8
Driscoll 48023.690 UT 9
Hildebrand 45829.000 UT 10
Lynch 24903.000 UT 19
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.
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
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';
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.
See also
● “TRIM function [String]” on page 367
● “LTRIM function [String]” on page 267
● “String functions” on page 142
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 ' );
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.
Example
The following statement returns the value 25.
SELECT SECOND( '1998-07-13 21:21:25' );
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.
Returns
UNSIGNED BIGINT with Syntax 1.
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-
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
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' );
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.
Returns
LONG VARBIT
Remarks
The default value of bit-expression is a bit array of length bit-position, containing all bits set to 0
(FALSE).
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
Example
The following statement returns the value 00100011:
SELECT SET_BIT( '00110011', 4 , 0);
Syntax
SET_BITS( expression )
Parameters
● expression The expression used to determine which bits to set to 1. This is typically a column
name.
Returns
LONG VARBIT
Remarks
Rows where the specified values are NULL are ignored.
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:
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
Example
The following statements return a bit array with the 2nd, 5th, and 10th bits set to 1 (or 0100100001):
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
Remarks
For negative numbers, the SIGN function returns -1.
Example
The following statement returns the value -1
SELECT SIGN( -550 );
Syntax
SIMILAR( string-expression-1, string-expression-2 )
Parameters
● string-expression-1 The first 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
Example
The following statement returns the value 75, indicating that the two values are 75% similar.
SELECT SIMILAR( 'toast', 'coast' );
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
Example
The following statement returns the SIN value of 0.52.
SELECT SIN( 0.52 );
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.
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
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;
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.
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.
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)'.
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
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).
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)' );
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.
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
Example
The following statement returns two identical numbers, 3827, representing the sound of each name.
SELECT SOUNDEX( 'Smith' ), SOUNDEX( 'Smythe' );
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
Example
The following statement returns a string containing 10 spaces.
SELECT SPACE( 10 );
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
Example
The following statement returns the string Transact-SQL.
SELECT
SQLDIALECT( 'SELECT EmployeeName = Surname FROM Employees' )
FROM dummy;
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:
Returns
LONG VARCHAR
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]
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' );
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.
Example
The following statement returns the value 3.
SELECT SQRT( 9 );
See also
● “STDDEV_SAMP function [Aggregate]” on page 348
Syntax 1
STDDEV_POP( numeric-expression )
Syntax 2
STDDEV_POP( numeric-expression ) OVER ( window-spec )
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:
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].
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
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;
Syntax 1
STDDEV_SAMP( numeric-expression )
Syntax 2
STDDEV_SAMP( numeric-expression ) OVER ( window-spec )
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:
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].
See also
● “WINDOW clause” on page 961
● “Aggregate functions” on page 133
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:
Syntax
STR( numeric-expression [, length [, decimal ] ] )
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.
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
Example
The following statement returns a string of six spaces followed by 1235, for a total of ten characters.
SELECT STR( 1234.56 );
Syntax
STRING( string-expression [, ... ] )
Parameters
● string-expression The string to be evaluated.
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
Example
The following statement returns the value testing123.
SELECT STRING( 'testing', NULL, 123 );
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.
Syntax
STRTOUUID( string-expression )
Parameters
● string-expression A string in the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
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.
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
Example
The following statements are equivalent and return the result 0x6c2b64a93c6f47dc901536b9ed49fec2.
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.
● 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
Example
The following statement returns the value chocolate pie.
SELECT STUFF( 'chocolate cake', 11, 4, 'pie' );
Syntax
{ SUBSTRING | SUBSTR } ( string-expression, start
[, length ] )
Parameters
● string-expression The string from which a substring is to be returned.
● 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
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:
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.
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
Example
The following table shows the values returned by the SUBSTRING function.
Example Result
Syntax 1
SUM( [ ALL | DISTINCT ] expression )
Syntax 2
SUM( [ ALL ] expression ) OVER ( window-spec )
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.
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].
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
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.
Syntax
SUSER_ID( [ user-name ] )
Parameters
● user-name The user name for the user ID you are searching for.
Returns
INT
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
Example
The following statement returns the ID for the GROUPO user.
SELECT SUSER_ID( 'GROUPO' );
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
Example
The following statement returns the user name for a user with ID 101.
SELECT SUSER_NAME( 101 );
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
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;
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
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 ));
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
Example
The following statement returns the value of the tan of 0.52.
SELECT TAN( 0.52 );
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.
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;
Syntax
TO_CHAR( string-expression [, source-charset-name ] )
Parameters
● string-expression The string to be converted.
Returns
LONG VARCHAR
Remarks
If source-charset-name is specified, then this function is equivalent to:
For more information about db_charset, see “CSCONVERT function [String]” on page 183.
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
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:
Syntax
TO_NCHAR( string-expression [, source-charset-name ] )
Parameters
● string-expression The string to be converted
Returns
LONG NVARCHAR
Remarks
If source-charset-name is specified then this function is equivalent to:
For more information about nchar_charset, see “CSCONVERT function [String]” on page 183.
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
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:
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
Example
The following example converts a TIMESTAMP value to a TIMESTAMP WITH TIME ZONE 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.
Example
The following statements return the current day according to the system clock.
SELECT TODAY( * );
SELECT CURRENT DATE;
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.
Example
To use the traceback function, enter the following after an error occurs while executing a procedure:
SELECT TRACEBACK( * );
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.
Returns
LONG VARCHAR
Remarks
This function is for use by Sybase Central.
See also
● “sa_diagnostic_query table” on page 987
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
Example
The following statement returns the string 'SELECT EmployeeName=empl_name FROM
Employees'.
SELECT TRANSACTSQL( 'SELECT empl_name as EmployeeName FROM Employees' ) FROM
dummy;
Syntax
TREAT ( geometry-expression AS subtype )
Parameters
● geometry-expression The expression to be converted.
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
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 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;
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;
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
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 ' );
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]
Example
The following statement returns the value 600.
Syntax
TSEQUAL ( timestamp-expression-1, timestamp-expression-2 )
Parameters
● timestamp-expression-1 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.
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
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'
WHERE ID = '300'
AND TSEQUAL( LastUpdated, old_ts_value );
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
Example
The following statement returns the value CHOCOLATE.
SELECT UCASE( 'ChocoLate' );
Syntax
UNICODE( nchar-string-expression )
Parameters
● nchar-string-expression The NCHAR string whose first character is to be converted to an
integer.
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
Example
The following example returns the integer 65536:
SELECT UNICODE(UNISTR( '\u010000data' ));
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.
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
Examples
The following example returns the string Hello.
The following example combines the UTF-16 surrogate pair D800-DF02 into the Unicode code point
10302.
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.
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
Example
The following statement returns the value CHOCOLATE.
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
Example
The following statement returns the GROUPO 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
Example
The following statement returns the user name for user ID 101.
SELECT USER_NAME( 101 );
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.
Syntax
UUIDTOSTR( uuid-expression )
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.
See also
● “NEWID function [Miscellaneous]” on page 279
● “STRTOUUID function [String]” on page 351
● “String functions” on page 142
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.
Executing the following SELECT statement returns all the data in the newly created table.
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:
The UUIDTOSTR function is not needed for databases created with version 9.0.2 or later.
Syntax 1
VAR_POP( numeric-expression )
Syntax 2
VAR_POP( numeric-expression ) OVER ( window-spec )
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:
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
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_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;
Syntax 1
VAR_SAMP( numeric-expression )
Syntax 2
VAR_SAMP( numeric-expression ) OVER ( window-spec )
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
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:
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
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:
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
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;
See also
● “VAR_SAMP function [Aggregate]” on page 377
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
Example
The following statement returns the string 'SELECT Surname as last_name FROM
Employees'.
SELECT WATCOMSQL( 'SELECT last_name = Surname FROM Employees' ) FROM dummy;
Syntax 1
WEEKS( timestamp-expression )
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.
Returns
INTEGER with Syntax 1 or Syntax 2.
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.
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);
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.
● 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:
● The client application must have write permissions on the computer being written to.
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
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
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]
Example
The following statement generates an XML document that shows the orders placed by each customer.
Syntax
XMLCONCAT( xml-value [, ... ])
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
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;
Syntax
XMLELEMENT( { NAME element-name-expression } | string-expression
[, XMLATTRIBUTES ( attribute-value-expression [ AS attribute-name ],... ) ]
[, element-content-expression,... ]
)
Parameters
● element-name-expression An identifier. For each row, an XML element with the same name as
the identifier is generated.
● 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 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.
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.
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
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;
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.
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
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;
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:
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.
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
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;
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.
Example
The following example returns the value 2001.
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.
For information about casting data types, see “CAST function [Data type conversion]” on page 159.
Returns
SMALLINT with Syntax 1 or Syntax 2.
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
Example
The following statements both return -4.
The following statements return the given date advanced 300 years.
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
Example
The following statement returns the value 1998-06-12.
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 );
● 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
● query-block A query block is a simple query expression, or a query expression with an ORDER
BY clause.
● 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."
● 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:
● 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:
● 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:
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:
srs-attribute :
IDENTIFIED BY srs-id
| DEFINITION { definition-string | NULL }
...
● Optional portions Optional portions of a statement are enclosed by square brackets. For example:
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:
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:
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 ]
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.
● [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.
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.
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]
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,
"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;
}
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 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.
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.
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.
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.
● 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
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.
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
Example
The following example disables jConnect support:
The following example sets the transaction log file name associated with demo.db to mynewdemo.log:
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.
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.
○ 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.
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]
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';
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.
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]
Example
The following example renames the Address domain to MailingAddress:
ALTER DOMAIN Address RENAME MailingAddress;
event-type :
BackupEnd
| Connect
| ConnectFailed
| 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 ]
day-of-week : string
start-date : date
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()).
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:
● 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
Syntax
ALTER EXTERNAL ENVIRONMENT environment-name
LOCATION location-string
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
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';
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.
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]
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;
Syntax
ALTER { INDEX index-name
| [ INDEX ] FOREIGN KEY role-name
| [ INDEX ] PRIMARY KEY }
ON [ owner.]object-name { REBUILD | rename-clause | cluster-clause } }
Parameters
rename-clause Specify the new name for the index, primary key, or foreign key.
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.
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 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]
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;
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-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.
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_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.
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.
Permissions
DBA authority
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]
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.
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
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.
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]
Example
The following statements creates the EmployeeConfid88 materialized view and then disables its 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.
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
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.
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.
○ 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.
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
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';
Syntax 1
ALTER PROCEDURE [ owner.]procedure-name procedure-definition
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.
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.
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]
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.
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.
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]
Example
The following statement adds the Customers table to the pub_contact publication.
ALTER PUBLICATION pub_contact
ADD TABLE Customers;
Syntax
ALTER REMOTE MESSAGE TYPE message-system
ADDRESS address
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.
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]
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';
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.
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
Example
The following example sets a new maximum value for a sequence named Test:
ALTER SEQUENCE Test
MAXVALUE 1500;
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.
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
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 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;
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.
○ '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
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.
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:
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
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]
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 *
FROM SYS.SYSTAB;
common-attributes :
[ AUTHORIZATION { ON | OFF } ]
[ ENABLE | DISABLE ]
[ METHODS 'method,...' ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]
method :
DEFAULT
| POST
| HEAD
| NONE
common-attributes :
[ AUTHORIZATION { ON | OFF } ]
[ ENABLE | DISABLE ]
[ METHODS 'method,...' ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]
method :
DEFAULT
| POST
| GET
| HEAD
| NONE
|*
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.
○ 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'.
○ '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:
● 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:
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.
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]
Example
The following example demonstrates how to disable an existing web service using the ALTER SERVICE
statement:
CREATE SERVICE WebServiceTable
TYPE 'SOAP'
AUTHORIZATION OFF
USER DBA
AS SELECT *
FROM SYS.SYSTAB;
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
tolerance-distance : number
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.
TOLERANCE clause For flat-Earth (planar) spatial reference systems, use the TOLERANCE clause
to specify the precision to use when comparing points.
POLYGON FORMAT clause Use the POLYGON FORMAT clause to change the polygon
interpretation. The following values are supported:
○ 'CounterClockwise'
○ 'Clockwise'
○ '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
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]
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';
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
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
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;
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.
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
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
protocol-options : string
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.
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]
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';
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
protocol-options : string
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.
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]
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
| 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 ) ]
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
Parameters
Adding clauses The following section explains the clauses used for adding columns or table
constraints to a table:
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.
● 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.
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).
● 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.
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.
LAST USER can be used as a default value in columns with character data types.
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.
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.
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.
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.
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.
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.
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.
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.
DROP DEFAULT Drops the default value set for the table or specified column. Existing values do not
change.
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.
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.
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.
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:
Global temporary tables cannot be altered unless all users that have referenced the temporary table have
disconnected.
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]
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.
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 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;
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 ]
}
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.
Stoplist terms should not contain non-alphanumeric characters. The stoplist length must be less than 8000
bytes.
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
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
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
Example
The following statements create a text configuration object, maxTerm16, and then change the maximum
term length to 16:
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;
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.
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]
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;
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]
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
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.
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
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;
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.
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.
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]
Syntax
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
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]
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;
BACKUP statement
Backs up a database and transaction log.
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 }
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.
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;
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:
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.
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
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
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.
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]
● Windows Mobile Only the BACKUP DATABASE DIRECTORY syntax (syntax 1) is supported
on Windows Mobile.
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.
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:
● support for snapshots transactions has not been enabled for the database.
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]
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
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
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;
Syntax
BEGIN
statement-list
END
statement-list :
sql-statement
| variable-declaration
| cursor-declaration
| temporary-table-declaration
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.
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]
Example
The example below declares the following variables:
BEGIN
DECLARE v1 INT = 5
DECLARE v2, v3 CHAR(10) = 'abc'
// ...
END
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.
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]
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.
PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
BEGIN TRANSACTION
PRINT @@trancount
COMMIT
PRINT @@trancount
COMMIT
PRINT @@trancount
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]
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
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:
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:
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]
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
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.
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
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;
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.
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]
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
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.
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]
Syntax
CLEAR
Remarks
Closes any open result sets and leaves the contents of the SQL Statements pane unchanged
Permissions
None.
Side effects
Closes the cursor associated with the data being cleared.
See also
● “Interactive SQL” [SQL Anywhere Server - Database Administration]
Syntax
CLOSE cursor-name
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
Example
The following examples close cursors in embedded SQL.
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
| 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
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.
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.
Example
The following examples show how to add and remove a comment.
COMMENT
ON TABLE Employees
IS 'Employee information';
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:
You can use the Commit connection property to return the number of commits on the current connection.
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.
● 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.
● Pressing Ctrl+Shift+C.
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.
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
Example
The following statement commits the current transaction:
COMMIT;
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.
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]
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.
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.
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.
For example, if the following batch is executed while connected to a database, the two tables are
created in the same database.
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.
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]
● 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";
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]
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
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'
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.
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.
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.
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
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 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;
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.
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]
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:
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)';
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.
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.
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]
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;
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.
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
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';
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
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.
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
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';
Syntax
CREATE { DOMAIN | DATATYPE } [ AS ] domain-name data-type
[ [ NOT ] NULL ]
[ DEFAULT default-value ]
[ CHECK ( condition ) ]
domain-name : identifier
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:
○ 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.
See also
● “allow_nulls_by_default option” [SQL Anywhere Server - Database Administration]
● “DROP DOMAIN statement” on page 692
● “SQL data types” on page 81
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})');
algorithm :
'SIMPLE'
| 'AES'
| 'AES256'
| 'AES_FIPS'
| 'AES256_FIPS'
[ 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.
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).
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]
Example
The following example creates an encrypted copy of the sample database called demoEnc.db. The new
database is encrypted with AES256 encryption.
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.
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.
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
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.
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]
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';
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.
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
| 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.
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.
The TempDiskSpace event type checks the amount of temporary disk space.
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.
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.
● 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.
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.
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.
After each execution of an event handler, a COMMIT occurs if no errors occurred. A ROLLBACK occurs
if there was an error.
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]
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
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:
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
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.
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:
● 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.
Side effects
Automatic commit.
See also
● “CREATE TABLE statement” on page 633
● “Proxy table locations” [SQL Anywhere Server - SQL Usage]
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';
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.
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
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.
Permissions
Only users with DBA authority can add or modify an external login for login-name.
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]
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;
Syntax
CREATE [ OR REPLACE ] FUNCTION [ owner.]function-name
( [ parameter, ... ] )
RETURNS data-type
[ SQL SECURITY { INVOKER | DEFINER } ]
[ [ 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.
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).
[ 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.
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]';
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.
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.
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).
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.
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).
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).
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).
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.
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]
○ 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 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 optional DEFAULT clause for a specific routine parameter is a vendor extension.
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.
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
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.
○ text/plain
○ text/html
○ text/xml
The keywords for the TYPE clause have the following meanings:
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>
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';
○ 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:
○ 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';
○ 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:
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)'
● if CHUNK is set to AUTO, either 1.0 or 1.1 is used, depending on whether the client is sending in
CHUNK mode
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.
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
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:
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.
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]
Examples
The following statement creates a function named cli_test1 that returns images from the get_picture
service running on localhost:
The following statement issues an HTTP request with the URL http://localhost/get_picture?
image=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.
The following statement issues an HTTP request with the URL http://localhost/get_picture?
image=widget:
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
...
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.
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 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.
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.
[ 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.
compound-statement A set of SQL statements bracketed by BEGIN and END, and separated by
semicolons.
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.
Side effects
Automatic commit, even for temporary functions.
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]
○ 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:
Examples
The following function concatenates a firstname string and a lastname string.
CREATE FUNCTION fullname(
firstname CHAR(30),
lastname CHAR(30) )
RETURNS CHAR(61)
BEGIN
DECLARE name CHAR(61);
SET name = firstname || ' ' || lastname;
RETURN (name);
END;
The following 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;
fullname('joe', 'smith')
joe smith
Fran Whitney
Matthew Cobb
Philip Chin
Julie Jordan
...
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.
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
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.
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.
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.
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.
Side effects
Automatic commit. Creating an index on a function (an implicit computed column) also causes a
checkpoint.
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]
Example
Create a two-column index on the Employees table.
CREATE INDEX employee_name_index
ON Employees
( Surname, GivenName );
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 );
Syntax
CREATE LOCAL TEMPORARY TABLE table-name
( { column-definition [ column-constraint ... ] | table-constraint | pctfree }, ... )
[ ON COMMIT { DELETE | PRESERVE } ROWS | NOT TRANSACTIONAL ]
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.
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]
TEMPORARY TABLE statement appear in the system catalog; this is not the case with SQL
Anywhere.
Example
The following example creates a local temporary table called TempTab:
CREATE LOCAL TEMPORARY TABLE TempTab ( number INT )
ON COMMIT PRESERVE ROWS;
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.
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_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.
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.
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]
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;
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.
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:
● NOT ENCRYPTED
● 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.
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
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;
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.
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
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.
○ 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.
○ 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.
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.
○ 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 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.
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]
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';
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
|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.
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:
○ 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.
RESULT clause The RESULT clause declares the number and type of columns in the result set. The
parenthesized list following the RESULT keyword defines the result column names and types. This
information is returned by the embedded SQL DESCRIBE or by ODBC SQLDescribeCol when a CALL
statement is being described.
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
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
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.
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.
● 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).
● 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).
● 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).
● 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).
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.
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]
○ 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.
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 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.
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 ]
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.
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:
○ 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.
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.
○ text/plain
○ text/html
○ text/xml
The keywords for the TYPE clause have the following meanings:
For example, the following request is produced when a client submits a request from the URL,
http://localhost/WebServiceName?arg1=param1&arg2=param2:
For example, the following request is produced when a client submits a request the URL, http://
localhost/WebServiceName?arg1=param1&arg2=param2:
○ 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';
○ 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';
○ 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';
○ '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)
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:
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.
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)'
● if CHUNK is set to AUTO, either 1.0 or 1.1 is used, depending on whether the client is sending in
CHUNK mode
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.
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
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
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.
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.
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]
Example
The following example creates a web services client procedure named FtoC.
Syntax
The following subset of the Transact-SQL CREATE PROCEDURE statement is supported in SQL
Anywhere.
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.
● 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;
Permissions
Must have RESOURCE authority.
Side effects
Automatic commit.
See also
● “CREATE FUNCTION statement” on page 548
● “CREATE PROCEDURE statement” on page 585
● 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
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.
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
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.
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:
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:
○ 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.
RESULT clause The RESULT clause declares the number and type of columns in the result set. The
parenthesized list following the RESULT keyword defines the result column names and types. This
information is returned by the embedded SQL DESCRIBE or by ODBC SQLDescribeCol when a CALL
statement is being described.
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.
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.
○ 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
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]
○ 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 AT clause.
○ The RESULT and NO RESULT SET clauses. The SQL/2008 standard uses the RETURNS
keyword.
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;
END IF;
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;
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;
article-definition :
TABLE table-name [ ( column-name, ... ) ]
[ WHERE search-condition ]
article-definition :
TABLE table-name [ ( column-name, ... ) ]
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.
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.
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]
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 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
);
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
)
);
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
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]
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';
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
● Transact-SQL Supported by Adaptive Server Enterprise, which supports GRANT and REVOKE
statements within the CREATE SCHEMA statement.
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 );
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.
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.
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.
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]
○ 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;
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 }
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:
○ 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).
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.
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
database server runs as a specific user, so file permissions are based on the permissions granted to the
database server user.
Permissions
DBA authority.
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]
Example
The following example creates a SQL Anywhere remote server named testsa, using the SQL Anywhere
ODBC driver.
The following example directly loads the SQL Anywhere ODBC driver without using the ODBC driver
manager:
The following example creates an Adaptive Server Enterprise (ASE) remote server named ase_prod using
the ASE ODBC driver.
The following example creates a remote server for the Oracle server named oracle723. Its ODBC data
source name is 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;;;.';
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;;;.';
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
((), 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.
○ '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
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.
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:
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
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 [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]
● 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;
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.
common-attributes :
[ AUTHORIZATION { ON | OFF } ]
[ ENABLE | DISABLE ]
[ METHODS 'method,...' ]
[ SECURE { ON | OFF } ]
[ USER { user-name | NULL } ]
method :
DEFAULT
| POST
| HEAD
| NONE
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, //).
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.
○ 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'.
○ '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:
● 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:
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.
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]
● Transact-SQL CREATE SERVICE is supported by Adaptive Server Enterprise for SOAP types
only.
Syntax
{ CREATE [ OR REPLACE ] SPATIAL REFERENCE SYSTEM
|CREATE SPATIAL REFERENCE SYSTEM IF NOT EXISTS }
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
tolerance-distance : number
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.
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.
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'.
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.
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.
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.
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.
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.
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).
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.
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
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"]],
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;
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
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]
Example
The following example creates a spatial unit of measure named Test.
CREATE SPATIAL UNIT OF MEASURE Test
TYPE LINEAR
CONVERT USING 15;
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
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
Example
The following statement updates the column statistics for the ProductID column of the SalesOrderItems
table:
CREATE STATISTICS SalesOrderItems ( ProductID );
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.
Permissions
DBA authority
Side effects
Automatic commit.
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]
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;
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.
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.
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
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
protocol-options : string
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.
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.
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.
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]
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';
Syntax
CREATE SYNCHRONIZATION USER ml-username
[ TYPE network-protocol ]
[ ADDRESS protocol-options ]
[ OPTION option=value, ... ]
ml-username : identifier
network-protocol :
tcpip
| http
| https
| tls
protocol-options : string
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.
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.
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]
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.
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 ... ]
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
| SET DEFAULT
| RESTRICT
location-string :
remote-server-name.[db-name].[owner].object-name
| remote-server-name;[db-name];[owner];object-name
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';
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.
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.
○ 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
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 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.
○ 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.
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).
○ 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.
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.
LAST USER can be used as a default value in columns with character data types.
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.
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.
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.
○ 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.
● 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.
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.
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.
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.
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
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
● 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:
○ 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 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,
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);
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));
Syntax
CREATE TEXT CONFIGURATION [ owner.]new-config-name
FROM [ owner.]existing-config-name
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
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.
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].
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
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.
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
trigger-type :
BEFORE
| AFTER
| INSTEAD OF
| RESOLVE
trigger-event :
DELETE
| INSERT
| UPDATE
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:
○ INSERT clause Invoked whenever a new row is inserted into the table associated with the trigger.
○ 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.
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
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.
Remarks
The CREATE TRIGGER statement creates a trigger associated with a table in the database, and stores the
trigger in the database.
The trigger is declared as either a row-level trigger, in which case it executes before or after each row is
modified, or as a statement-level trigger, in which case it executes after the entire triggering statement is
completed.
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]
Some features of SQL Anywhere triggers are vendor extensions. These include:
○ 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.
● 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 )
);
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
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;
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 ) */
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;
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.
Transact-SQL triggers are executed AFTER the triggering statement has executed.
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]
● 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.
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.
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.
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]
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;
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:
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
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 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;
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.
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
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;
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
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
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.
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
Example
EXEC SQL BEGIN DECLARE SECTION;
char *surname, initials[5];
int dept;
EXEC SQL END DECLARE SECTION;
Syntax 1 [ESQL]
DECLARE cursor-name
[ UNIQUE ]
[ NO SCROLL
| DYNAMIC SCROLL
| SCROLL
| 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
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_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.
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.
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:
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;
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.
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.
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]
○ 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 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-
○ 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;
END LOOP;
CLOSE cur_employee;
END
Syntax
DECLARE LOCAL TEMPORARY TABLE table-name
( { column-definition [ column-constraint ... ] | table-constraint | pctfree }, ... )
[ ON COMMIT { DELETE | PRESERVE } ROWS
| NOT TRANSACTIONAL ]
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.
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.
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]
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).
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
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]
declaration using the keywords DECLARE HANDLER. The DECLARE...EXCEPTION syntax is not
allowed in T-SQL 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
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:
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;
Syntax
DELETE [ [FROM ]table ] WHERE CURRENT OF cursor-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.
● 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
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;
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
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.
Each item in the ORDER BY list can be labeled as ASC for ascending order (the default) or DESC for
descending order.
OPTION clause Use this clause to specify hints for executing the statement. The following hints are
supported:
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]
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 );
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
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.
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.
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.
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.
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.
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.
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
○ 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;
}
object-name :
table
| view
| materialized view
| procedure
| function
Parameters
INDEX FOR clause Indicates that you want to see the indexes for the specified object-name.
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:
● 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:
● 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:
● In/Out Information about what is passed to, or returned from, the parameter. Possible values are:
○ 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.
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 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]
Examples
Describe the columns in the Departments table:
DESCRIBE TABLE Departments;
DepartmentID integer 0 1
DepartmentName char(40) 0 0
DepartmentHeadID integer 1 0
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.
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
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.
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]
Example
The following statement shows how to use DISCONNECT in embedded SQL:
The following statement shows how to use DISCONNECT from Interactive SQL to disconnect all
connections:
DISCONNECT ALL;
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.
Permissions
DBA authority
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]
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;
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.
Permissions
Required permissions are set using the database server -gu option. The default setting is to require DBA
authority.
You must specify a key if you want to drop a strongly encrypted database
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]
Example
Drop the database temp.db, in the C:\temp directory:
DROP DATABASE 'c:\temp\temp.db';
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
Example
Drop MyDatatype from the database. If the data type does not exist, an error is returned.
DROP DATATYPE MyDatatype;
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]
Example
Drop MyDBSpace from the database. If the dbspace does not exist, an error is returned.
DROP DBSPACE MyDBSpace;
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
Example
Drop the domain MyDomain from the database. If the domain does not exist, an error is returned.
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.
See also
● “CREATE EVENT statement” on page 526
● “ALTER EVENT statement” on page 408
● “TRIGGER EVENT statement” on page 932
Example
Drop MyEvent from the database. If the event does not exist, an error is returned.
DROP EVENT MyEvent;
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
Example
DROP EXTERNLOGIN DBA TO sybase1;
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
Example
Drop MyFunction from the database. If the function does not exist, an error is returned.
DROP FUNCTION MyFunction;
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.
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]
Example
Drop MyIndex from the database. If the index does not exist, an error is returned.
DROP INDEX MyIndex;
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.
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]
Examples
The following example creates a login policy, Test11, and then deletes it.
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.
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
Example
Drop MyMaterializedView from the database. If the materialized view does not exist, an error is returned.
DROP MATERIALIZED VIEW MyMaterializedView;
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.
See also
● “PRINT statement [T-SQL]” on page 836
● “CREATE MESSAGE statement [T-SQL]” on page 563
● “ISYSUSERMESSAGE system table” on page 979
Example
Drop MyMessage from the database. If the message does not exist, an error is returned.
DROP MESSAGE MyMessage;
Syntax
DROP MIRROR SERVER mirror-server-name
Remarks
Cloud note: This statement is not supported on tenant databases in the cloud.
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
Example
The following statement removes the mirror server named scaleout_server_root from the database:
DROP MIRROR SERVER scaleout_server_root;
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
Example
Drop MyProcedure from the database. If the procedure does not exist, an error is returned.
DROP PROCEDURE MyProcedure;
Syntax
DROP PUBLICATION [ IF EXISTS ] [ owner.]publication-name
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]
Example
The following statement drops the pub_contact publication.
DROP PUBLICATION pub_contact;
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]
Example
The following statement drops the FILE message type from a database.
DROP REMOTE MESSAGE TYPE file;
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.
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
Example
The following example drops a sequence named Test:
DROP SEQUENCE Test;
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.
Side effects
Automatic commit.
See also
● “CREATE SERVER statement” on page 601
Example
DROP SERVER ase_prod;
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
Example
The following SQL statement illustrates how to drop a web service named WebServiceTable:
DROP SERVICE WebServiceTable;
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.
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]
Example
The following example drops a spatial reference system named TEST.
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]
Example
The following example drops a spatial unit of measure named TEST.
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
Example
The following are examples of DROP STATEMENT use:
Syntax
DROP STATISTICS [ ON ] [owner.]object-name [ ( column-list ) ]
object-name :
table-name
| 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
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.
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
Example
The following statement drops a subscription for the SamS user ID to the pub_contact publication.
DROP SUBSCRIPTION TO pub_contact
FOR SamS;
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
Syntax
DROP SYNCHRONIZATION SUBSCRIPTION {subscription-name |
TO publication-name
[ FOR ml-username, ... ]}
Parameters
subscription-name Specifies the name of the subscription to drop.
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]
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;
Syntax
DROP SYNCHRONIZATION USER ml-username, ...
ml-username : identifier
Remarks
Drop one or more synchronization users from a MobiLink remote database.
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
Example
Remove MobiLink user ml_user1 from the database.
DROP SYNCHRONIZATION USER ml_user1;
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.
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
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;
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.
Permissions
Must be the owner of the text configuration object or have DBA authority.
Side effects
Automatic commit
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
Example
The following statements create and drop the mytextconfig text configuration object:
CREATE TEXT CONFIGURATION mytextconfig FROM default_char;
DROP TEXT CONFIGURATION mytextconfig;
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
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
Example
The following statements create and drop the TextIdx text index:
CREATE TEXT INDEX TextIdx ON MarketingInformation ( Description )
DROP TEXT INDEX TextIdx ON MarketingInformation;
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]
Example
Drop MyTrigger from the database. If the trigger does not exist, an error is returned.
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]
Example
The following example drops the user SQLTester from a database.
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
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.
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
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
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).
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:
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 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.
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
● 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].
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 }
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.
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.
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 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
● 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)
)
BEGIN
EXECUTE IMMEDIATE
'CREATE TABLE ' || tablename ||
' ( column1 INT PRIMARY KEY)'
END;
Syntax 1
EXECUTE statement
[ USING { hostvar-list | [ SQL ] DESCRIPTOR sqlda-name } ]
[ INTO { into-hostvar-list | [ SQL ] DESCRIPTOR into-sqlda-name } ]
[ ARRAY :row-count ]
sqlda-name : identifier
into-sqlda-name : identifier
Syntax 2
EXECUTE IMMEDIATE statement
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
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]
The EXECUTE IMMEDIATE statement supported with embedded SQL is also part of optional SQL
language feature B031.
Example
Execute a DELETE.
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.
Side effects
None.
See also
● “CALL statement” on page 491
● “EXECUTE statement [ESQL]” on page 722
● “EXECUTE IMMEDIATE statement [SP]” on page 719
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;
Syntax
{ EXIT | QUIT | BYE } [ return-code ]
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.
See also
● “SET OPTION statement” on page 886
● “Interactive SQL” [SQL Anywhere Server - Database Administration]
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;
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;
Syntax
EXPLAIN PLAN FOR CURSOR cursor-name
{ INTO hostvar | USING DESCRIPTOR sqlda-name }
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].
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]
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 );
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 ]
[ PURGE ]
[ BLOCK n ]
[ FOR UPDATE ]
[ ARRAY fetch-count ]
cursor-position :
NEXT | PRIOR | FIRST | LAST
| { ABSOLUTE | RELATIVE } row-count
sqlda-name : identifier
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.
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.
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.
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.
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:
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.
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.
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]
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;
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
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.
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.
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
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;
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;
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.
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 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:
● 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
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, ... ) ]
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( ) } [ , ... ]
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 }
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
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;
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.
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.
● 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:
● 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.
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).
INSERT FINAL
DELETE 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.
● 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.
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.
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
SERIALIZ- Sets the behavior to be equivalent to isolation level 3. This table hint is synony-
ABLE mous with HOLDLOCK.
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.
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.
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.
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).
● 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.
Permissions
The FILE clause of openstring-expression requires either DBA or READFILE authority.
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]
○ CROSS JOIN, FULL OUTER JOIN, and NATURAL JOIN constitute optional SQL/2008 feature
F401.
○ 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.
○ 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.
○ KEY JOIN.
○ OPENSTRING.
○ all table hints, including the use of WITH, FORCE INDEX, READPAST and isolation level hints.
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 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;
Syntax
GET DATA cursor-name
COLUMN column-num
OFFSET start-offset
[ WITH TEXTPTR ]
{ USING DESCRIPTOR sqlda-name | INTO 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.
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
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;
Syntax
GET DESCRIPTOR descriptor-name
{ hostvar = COUNT | VALUE { integer | hostvar } assignment, ... }
assignment :
hostvar =
TYPE
| LENGTH
| PRECISION
| SCALE
| 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.
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]
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 );
}
Syntax
GET OPTION [ userid.]option-name
{ INTO hostvar | USING DESCRIPTOR sqlda-name }
option-name :
identifier
| string
| hostvar
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
Example
The following statement illustrates use of GET OPTION.
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.
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
Syntax
GRANT CONSOLIDATE
TO userid
message-system :
FILE | FTP | SMTP
address : string
Parameters
userid The user ID for the user to be granted the permission.
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
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]
Example
GRANT CONSOLIDATE TO con_db
TYPE SMTP
ADDRESS 'Singer, Samuel';
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;
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.
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]
Example
GRANT PUBLISH TO publisher_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.
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]
Examples
You can grant REMOTE DBA authority to a user ID named dbremote as follows:
GRANT REMOTE DBA
TO dbremote
IDENTIFIED BY dbremote;
Syntax
GRANT REMOTE TO userid, ...
TYPE message-system, ...
ADDRESS address-string, ...
[ SEND { EVERY | AT } send-time ]
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.
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
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
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.
authority :
BACKUP
| DBA
| PROFILE
| READCLIENTFILE
| READFILE
| [ RESOURCE | ALL ]
| VALIDATE
| WRITECLIENTFILE
permission :
ALL [ PRIVILEGES ]
| ALTER
| DELETE
| INSERT
| REFERENCES [ ( column-name, ... ) ]
| SELECT [ ( column-name, ... ) ]
| UPDATE [ ( column-name, ... ) ]
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.
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.
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.
○ 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 "";
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.
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 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.
● 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]
Syntax 4 is also a core feature of SQL/2008, used for granting EXECUTE permissions on stored
procedures.
Example
Create a new database user.
GRANT CONNECT TO SQLTester
IDENTIFIED BY welcome
ON Employees
TO Laurel;
More than one permission can be granted in a single statement. Separate the permissions with commas.
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.
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
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.
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.
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;
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]
○ 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.
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.
Permissions
None.
Side effects
None.
See also
● “Interactive SQL” [SQL Anywhere Server - Database Administration]
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 }
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.
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
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;
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.
Example
The following example illustrates the use of the Transact-SQL IF statement:
IF (SELECT max(ID) FROM sysobjects) < 100
RETURN
ELSE
BEGIN
PRINT 'These are the user-created objects'
SELECT name, type, ID
FROM sysobjects
WHERE ID < 100
END
The following two statement blocks illustrate Transact-SQL and Watcom SQL compatibility:
/* Transact-SQL IF statement */
IF @v1 = 0
PRINT '0'
ELSE IF @v1 = 1
PRINT '1'
ELSE
PRINT 'other'
/* Watcom SQL IF statement */
IF v1 = 0 THEN
PRINT '0'
ELSEIF v1 = 1 THEN
PRINT '1'
ELSE
PRINT 'other'
END IF
Syntax
INCLUDE filename
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.
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 ]
connection-string :
{ DRIVER=odbc-driver-name
| DSN=odbc-data-source } [ ; { connection-parameter = value } ]
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.
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 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 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).
○ 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.
○ 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.
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.
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';
○ 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';
○ 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,
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
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.
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.
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]
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
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
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
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:
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.
● 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.
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
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
Create the table MyTable5 and populate it using the WITH AUTO NAME syntax.
Insert a new department, executing the statement at isolation level 3, rather than using the current
isolation level setting of the database.
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 (), (), ();
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
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
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 =
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.
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.
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.
See also
● “REMOVE JAVA statement” on page 851
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.
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-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:
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
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
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
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]
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
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.
Permissions
DBA authority
Side effects
None.
See also
● “ISYSCOLSTAT system table” on page 967
● “Unload utility (dbunload)” [SQL Anywhere Server - Database Administration]
Syntax
LOAD [ INTO ] TABLE [ owner.]table-name
[ ( column-name, ... ) ]
load-source
[ 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 }
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
}
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:
○ 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.
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.
○ 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.
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 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 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
'//' ...
If COMMENTS INTRODUCED BY is omitted, the data file must not contain comments because they
are interpreted as data.
○ 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 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 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.
○ 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:
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:
row-xpath xpath
NAMESPACES namespaces
● 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.
○ @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.
○ 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.
○ 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:
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
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:
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.
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.
○ 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.
○ 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:
○ 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.
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
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.
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]
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) );
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;
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.
When the synchronization schema feature is locked, the following statements cannot be executed by other
connections:
Permissions
DBA authority
Side effects
None
See also
● “LOCK TABLE statement” on page 808
Example
The following statement prevents other connections from using the synchronization schema feature:
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
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]
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;
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.
Permissions
None.
Side effects
None.
See also
● “FOR statement” on page 733
● “CONTINUE statement” on page 507
● “WHILE statement [T-SQL]” on page 960
● 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;
...
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
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, ... )
option-name : identifier
option-value :
hostvar (indicator allowed)
| string
| identifier
| number
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.
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.
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-
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:
○ 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.
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.
○ 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.
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.
OPTION clause Use this clause to specify hints for executing the statement. The following hints are
supported:
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.
Side effects
Any triggers defined for target-object are fired.
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]
○ OPTION clause
○ DEFAULTS 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
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:
○ 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:
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.
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.
For example, the window is not displayed in the following example because the event occurs outside a
connection.
However, in the following example, the message is written to the database server messages window.
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.
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
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( );
Syntax 1 [ESQL]
OPEN cursor-name
[ USING { DESCRIPTOR sqlda-name | hostvar, ... } ]
[ WITH HOLD ]
[ ISOLATION LEVEL isolation-level ]
[ BLOCK n ]
Syntax 2 [SP]
OPEN cursor-name
[ WITH HOLD ]
[ ISOLATION LEVEL isolation-level ]
sqlda-name : identifier
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.
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.
○ 0
○ 1
○ 2
○ 3
○ SNAPSHOT
○ STATEMENT SNAPSHOT
○ READONLY STATEMENT SNAPSHOT
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.
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
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]
● 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;
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-format :
TEXT
| FIXED
| HTML
| SQL
| XML
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
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 '!'
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.
○ 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.
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.
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
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]
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;
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";
Syntax
PARAMETERS parameter1, parameter2, ...
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]
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]
Syntax 1
PASSTHROUGH [ ONLY ] FOR userid, ...
Syntax 2
PASSTHROUGH [ ONLY ] FOR SUBSCRIPTION
TO [ owner. ]publication-name [ ( constant ) ]
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.
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 ;
Syntax
PREPARE statement-name
FROM statement [ FOR { UPDATE [ cursor-concurrency ] | READ ONLY } ]
[ DESCRIBE describe-type INTO [ [ SQL ] DESCRIPTOR ] descriptor ]
[ WITH EXECUTE ]
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.
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.
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.
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]
Example
The following statement prepares a simple query:
EXEC SQL PREPARE employee_statement FROM
'SELECT Surname FROM Employees';
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
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;
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
Example
The following statement displays a message:
The following statement illustrates the use of placeholders in the PRINT statement:
Syntax
PUT cursor-name
{ USING DESCRIPTOR sqlda-name | FROM hostvar-list }
[ INTO { DESCRIPTOR sqlda-name | hostvar-list } ]
[ ARRAY :row-count ]
sqlda-name : identifier
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.
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]
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.
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
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
Syntax
READ [ ENCODING encoding ] filename [ parameter ] ...
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:
● 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]
Example
The following are examples of the READ statement.
READ status.rpt '160';
READ birthday.sql [>= '1988-1-1'] [<= '1988-1-30'];
To process a file that uses a specific OEM codepage, you need to specify the codepage. For example:
dbisql READ ENCODING 'cp437' myfile.sql
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
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;
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 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
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.
Side effects
Any open cursors that reference the materialized view are closed.
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
Example
Suppose you create a materialized view, EmployeeConfid99, and then populate it with data using the
following statements:
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].
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.
○ 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
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.
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
Example
The following statement refreshes a text index called MarketingTextIndex, forcing it to be rebuilt.
REFRESH TEXT INDEX MarketingTextIndex ON MarketingInformation
FORCE BUILD;
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
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
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.
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.
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]
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]
Example
The following statement resets the subscriptions for remote user SamS:
REMOTE RESET SamS;
COMMIT;
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
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.
Permissions
● DBA authority
Example
The following statement removes a Java class named Demo from the current database:
The following statement removes a Java jar named myJar from the current database:
Syntax
REORGANIZE TABLE [ owner.]table-name
[ { PRIMARY KEY
| FOREIGN KEY foreign-key-name
| INDEX index-name } ]
Parameters
Reorganize the table according to the values in one of the following:
PRIMARY KEY clause Reorganizes the primary key index for the table.
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 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.
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.
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;
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.
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
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;
Syntax
RESTORE DATABASE filename
FROM archive-root
[ CATALOG ONLY
| [ RENAME dbspace-name TO new-dbspace-name ] ... ]
[ HISTORY { ON | OFF } ]
[ KEY encryption-key ]
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.
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:
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.
Side effects
None.
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]
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
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.
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]
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.
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.
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]
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;
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;
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]
Example
● The following statement revokes consolidated status from the condb user ID:
REVOKE CONSOLIDATE FROM condb;
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:
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]
Example
REVOKE PUBLISH FROM publisher_ID;
Syntax 1
REVOKE REMOTE DBA
FROM userid, ...
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]
Examples
The following statement revokes REMOTE DBA permission from user S_Beaulieu.
REVOKE REMOTE DBA FROM S_Beaulieu;
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
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]
Example
REVOKE REMOTE FROM SamS;
REVOKE statement
Removes permissions from users.
permission :
BACKUP
| CONNECT
| CREATE ON dbspace
| DBA
| GROUP
| INTEGRATED LOGIN
| KERBEROS LOGIN
| MEMBERSHIP IN GROUP userid, ...
| PROFILE
| READCLIENTFILE
| READFILE
| RESOURCE
| VALIDATE
| WRITECLIENTFILE
table-permission :
ALL [PRIVILEGES]
| ALTER
| DELETE
| INSERT
| REFERENCES [ ( column-name, ... ) ]
| SELECT [ ( column-name, ... ) ]
| UPDATE [ ( column-name, ... ) ]
Syntax 3
REVOKE EXECUTE
ON [ owner.]procedure-name
FROM userid, ...
Syntax 4
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.
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
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 an integrated login mapping from the user profile named Administrator.
REVOKE INTEGRATED LOGIN FROM Administrator;
ROLLBACK statement
Ends a transaction and undo any changes made since the last COMMIT or ROLLBACK.
Syntax
ROLLBACK [ WORK ]
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.
● Pressing Ctrl+Shift+R.
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]
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.
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]
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.
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
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
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.
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
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
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
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
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.
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]
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 ], ...
|*
sequence-expression
sequence-name [ CURRVAL | NEXTVAL ]
FROM table-name
window-name : identifier
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
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 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.
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.
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.
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.
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.
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.
To ensure that a statement acquires an intent lock, you must do one of the following:
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:
○ 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.
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:
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:
● 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.
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.
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]
○ The WINDOW clause and WINDOW aggregate functions comprise optional SQL/2008 language
features T611 and T612.
○ 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.
○ 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 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.
○ 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.
○ 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;
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:
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' );
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]
Example
The following example is in embedded SQL.
From Interactive SQL, set the current connection to the connection named conn1.
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.
Permissions
None.
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]
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;
}
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
Parameters
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.
child_creation read-only automat- automat- Controls whether copy nodes are created
scale-out ic, off, ic automatically.
manual
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
Example
The following statement sets the authentication string for a database mirroring system to abc:
SET MIRROR OPTION authentication_string = 'abc';
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
Parameters
option-value With Syntax 1, option-value can be one of:
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';
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.
The classes of options that can be set with the SET OPTION statement are:
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
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.
Permissions
None required to set your own options.
DBA authority is required to set database options for another user or PUBLIC.
Side effects
If TEMPORARY is not specified, an automatic commit is performed.
See also
● “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
Example
Set the date format option for all users without an individual setting:
SET OPTION PUBLIC.date_format = 'Mmm dd yyyy';
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=;
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).
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.
“on_error option [Interactive SQL]” [SQL Stop, Continue, Prompt, Exit, Prompt
Anywhere Server - Database Administra- Notify_Continue, Notify_Stop,
tion] Notify_Exit
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';
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
| 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_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.
○ 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.
○ 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.
○ 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.
○ 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.
○ 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:
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.
○ 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.
○ 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.
○ 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.
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]
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';
Syntax
SET SQLCA sqlca
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]
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.
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]
● 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;
The following code fragment inserts a large text value into the database.
The following code fragment inserts a large binary value into the database.
Syntax
SET option-name option-value
Remarks
The available options are as follows:
ansinull On or Off
ansi_permissions On or Off
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.
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.
● 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.
● 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
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.
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
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).
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
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
Example
The following statements, executed by a user named DBA, change the user ID to be Joe, then Jane, and
then back to DBA.
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';
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
● Transact-SQL The SIGNAL statement cannot be used in Transact-SQL compound statements and
procedures.
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
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.
○ 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.
○ 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.
○ 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
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.
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.
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]
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;
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.
Permissions
None
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]
Example
Start a database server named sample without starting any databases on it.
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
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
Example
Start the Perl external environment.
START EXTERNAL ENVIRONMENT PERL;
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.
Side effects
None
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]
Example
Start the Java VM.
START JAVA;
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]
Example
Start logging to a file called filename.sql, located in the c: directory.
START LOGGING 'c:\filename.sql';
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.
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]
Example
The following statement starts the subscription of user SamS to the pub_contact publication.
START SUBSCRIPTION TO pub_contact
FOR SamS;
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
Side effects
None.
See also
● “STOP SYNCHRONIZATION DELETE statement [MobiLink]” on page 924
● “ULConnection.StartSynchronizationDelete method [UltraLite.NET]” [UltraLite - .NET
Programming]
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;
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
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.
● You can alter a publication to change the column subsetting of any table 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
Side effects
None.
See also
● “STOP SYNCHRONIZATION SCHEMA CHANGE statement [MobiLink]” on page 929
● “SynchronizationSchemaChangeActive database property” [SQL Anywhere Server - Database
Administration]
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;
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.
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]
Example
Stop the database named sample on the current server.
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].
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
Example
Stop the Perl external environment.
STOP EXTERNAL ENVIRONMENT PERL;
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
Example
Stop the Java VM.
STOP JAVA;
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.
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]
Example
The following example stops the current logging session.
STOP LOGGING;
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.
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]
Example
Stop the current database server, as long as there are no other connections.
STOP SERVER;
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]
Example
The following statement stops the subscription of user SamS to the pub_contact publication.
STOP SUBSCRIPTION TO pub_contact
FOR SamS;
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
Example
For an example, see “START SYNCHRONIZATION DELETE statement [MobiLink]” on page 915.
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
Option Returns
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.
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.
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.
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:
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.
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
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:
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.
Permissions
REMOTE DBA or DBA authority
Side effects
None
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
Example
The following example shows the syntax for synchronizing a synchronization profile named Test1:
SYNCHRONIZE PROFILE Test1;
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]
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;
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.
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]
Example
The following statement synchronizes the subscription of user SamS to the pub_contact publication.
SYNCHRONIZE SUBSCRIPTION
TO pub_contact
FOR SamS;
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]
Example
The following statement launches the Notepad program if the Notepad executable is in your path.
SYSTEM 'notepad.exe';
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
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.
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.
With TRUNCATE TABLE, if all the following criteria are satisfied, a fast form of table truncation is
executed:
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
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.
● 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.
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]
Example
Delete all rows from the Departments table:
TRUNCATE TABLE Departments;
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
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.
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-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:
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.
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]
● 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.
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
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 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.
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.
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:
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.
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.
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.
● Write permissions are required for the directory being written to.
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]
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;
Syntax 2
UPDATE update-table, ...
SET set-item, ...
WHERE CURRENT OF cursor-name
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 }
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.
○ 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
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;
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
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.
WHERE clause The WHERE clause specifies which rows are to be transferred between subscribed
databases.
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 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.
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.
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]
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;
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
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:
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.
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.
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:
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 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.
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.
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.
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]
○ 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".
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,
VALIDATE statement
Validates the current database, or a single table, materialized view, or index in the current database.
object-name :
table-name
| materialized-view-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
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.
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
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.
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]
Examples
The following example waits for three seconds:
WAITFOR DELAY '00:00:03';
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;
// connection 2:
MESSAGE 'here it is' FOR connection 1
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.
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.
Example
The following are examples of the WHENEVER 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
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-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.
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.
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
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]
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;
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.
See also
● “READTEXT statement [T-SQL]” on page 842
● “TEXTPTR function [Text and image]” on page 360
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';
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
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;
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.
See also
● “SYSARTICLE system view” on page 1196
See also
● “SYSARTICLECOL system view” on page 1196
See also
● “SYSCAPABILITY system view” on page 1197
See also
● “SYSCHECK system view” on page 1198
See also
● “SYSCOLPERM system view” on page 1198
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
See also
● “SYSCONSTRAINT system view” on page 1200
See also
● “SYSDEPENDENCY system view” on page 1203
See also
● “SYSDBFILE system view” on page 1201
See also
● “SYSDBSPACE system view” on page 1202
See also
● “SYSDBSPACEPERM system view” on page 1202
See also
● “SYSDOMAIN system view” on page 1203
See also
● “SYSEVENT system view” on page 1204
Note
For databases created using SQL Anywhere 12 or later, this table is always encrypted to protect the data
from unauthorized access.
See also
● “SYSEXTERNLOGIN system view” on page 1207
See also
● “SYSFKEY system view” on page 1208
See also
● “SYSGROUP system view” on page 1209
See also
● “SYSHISTORY system view” on page 1209
See also
● “SYSIDX system view” on page 1211
See also
● “SYSIDXCOL system view” on page 1213
See also
● “SYSJAR system view” on page 1214
See also
● “SYSJARCOMPONENT system view” on page 1214
See also
● “SYSJAVACLASS system view” on page 1215
See also
● “SYSLOGINMAP system view” on page 1216
See also
● “SYSLOGINPOLICY system view” on page 1216
See also
● “SYSLOGINPOLICYOPTION system view” on page 1217
See also
● “SYSMIRROROPTION system view” on page 1217
See also
● “SYSMIRRORSERVER system view” on page 1217
See also
● “SYSMIRRORSERVEROPTION system view” on page 1218
See also
● “SYSMVOPTION system view” on page 1219
See also
● “SYSMVOPTIONNAME system view” on page 1219
See also
● “SYSOBJECT system view” on page 1220
See also
● “SYSOPTION system view” on page 1221
See also
● “SYSOPTSTAT system view” on page 1221
See also
● “SYSPHYSIDX system view” on page 1222
See also
● “SYSPROCEDURE system view” on page 1223
See also
● “SYSPROCPARM system view” on page 1224
See also
● “SYSPROCPERM system view” on page 1225
See also
● “SYSPROXYTAB system view” on page 1226
See also
● “SYSPUBLICATION system view” on page 1226
See also
● “SYSREMARK system view” on page 1227
See also
● “SYSREMOTEOPTION system view” on page 1228
See also
● “SYSREMOTEOPTIONTYPE system view” on page 1228
See also
● “SYSREMOTETYPE system view” on page 1229
See also
● “SYSREMOTEUSER system view” on page 1229
● “REMOTE RESET statement [SQL Remote]” on page 850
See also
● “SYSSCHEDULE system view” on page 1231
See also
● “SYSSEQUENCE system view” on page 1232
See also
● “SYSSEQUENCEPERM system view” on page 1233
See also
● “SYSSERVER system view” on page 1233
See also
● “SYSSOURCE system view” on page 1234
See also
● “SYSSPATIALREFERENCESYSTEM system view” on page 1234
See also
● “SYSSQLSERVERTYPE system view” on page 1237
See also
● “SYSSUBSCRIPTION system view” on page 1238
See also
● “SYSSYNC system view” on page 1238
See also
● “SYSSYNCPROFILE system view” on page 1240
See also
● “SYSSYNCSCRIPT system view” on page 1240
See also
● “SYSTAB system view” on page 1241
See also
● “SYSTABCOL system view” on page 1244
See also
● “SYSTEXTCONFIG system view” on page 1248
See also
● “SYSTEXTIDX system view” on page 1249
See also
● “SYSTEXTIDXTAB system view” on page 1250
See also
● “SYSTABLEPERM system view” on page 1246
See also
● “SYSTRIGGER system view” on page 1251
See also
● “SYSTYPEMAP system view” on page 1253
See also
● “SYSUNITOFMEASURE system view” on page 1254
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
See also
● “SYSUSERAUTHORITY system view” on page 1255
See also
● “SYSUSERMESSAGE system view” on page 1256
See also
● “SYSUSERTYPE system view” on page 1256
See also
● “SYSVIEW system view” on page 1257
See also
● “SYSWEBSERVICE system view” on page 1259
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.
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.
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.
blocked_by UNSIGNED The ID of the connection that held the lock, causing the block.
INT
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.
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.
Columns
Column name Column type Description
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.
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.
query_id UNSIGNED BI- Identifies the query over which this cursor ranges.
GINT
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.
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.
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.
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.
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.
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.
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_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.
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.
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.
cache_size_bytes UNSIGNED The size, in bytes, of the cache at the time this query was opti-
BIGINT mized.
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.
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.
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]
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:
● statement executions
● statement preparations
Columns
Column name Column type Description
logging_ses- UNSIGNED INT The logging session during which the request occurred.
sion_id
finish_time TIMESTAMP For statement execution, the time when the statement comple-
ted; otherwise, NULL.
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.
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.
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.
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.
Columns
Column name Column type Description
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.
Columns
Column Column type Description
name
● 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:
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
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:
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.
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.
row_num SMALLINT
See also
● “sa_rowgenerator system procedure” on page 1113
● SOAP and HTTP services system procedures, for supporting web services.
See also
● “Adaptive Server Enterprise system and catalog procedures” on page 999
Prerequisites
DBA authority.
Many.
1. Use the SQL Anywhere 12 plug-in to connect to the database as a user with DBA authority.
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.
5. In the left pane, select the procedure and in the right pane click the SQL tab.
Results
Next
None.
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]
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.
● xp_startmail Starts a mail session in a specified mail account by logging onto the MAPI message
system.
● xp_startsmtp Starts a mail session in a specified mail account by logging onto the SMTP message
system.
Example
The following procedure notifies a set of people that a backup has been completed.
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
0 Success
5 xp_sendmail failed
15 Insufficient memory
20 Unknown recipient
In addition, the following codes may be returned by the MAPI system procedures:
11 Ambiguous recipient
13 Disk full
14 Failure
16 Invalid session
21 Login failure
23 User abort
24 No MAPI
In addition, the following codes may be returned by the SMTP system procedures:
Return Meaning
code
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.
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.
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.
sp_column_privileges Unsupported
sp_special_columns Returns the optimal set of columns that uniquely identify a row in the speci-
fied table
sp_sproc_columns Returns information about the input and return parameters of a stored pro-
cedure
sp_tables Returns a list of objects that can appear in a FROM clause for the specified
table
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
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.
● @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
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).
○ 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-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 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 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()'.
● 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.
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');
ProductName ProductID
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, &, Sweater, and Set. You can use .
to concatenate the children together in the result set.
SELECT * FROM openxml( '<products>
<ProductType ID="301">Tee & Sweater Set</ProductType>
<ProductType ID="401">Baseball Cap</ProductType>
</products>',
'/products/ProductType' )
WITH ( ProductName LONG VARCHAR '.', ProductID CHAR(3) '@ID');
ProductName ProductID
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>
<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"]');
The following query uses the XPath @attribute expression to generate a result set:
SELECT * FROM openxml( '<Employee
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');
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' )
Syntax
sa_ansi_standard_packages( standard, statement )
Arguments
● standard The standard to use for the core extensions. One of SQL:1999 or SQL:2003.
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');
package_id package_name
package_id package_name
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' );
Syntax
sa_char_terms( ' text' [, 'config-name' [, 'owner' ] ] )
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
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
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.
● CleanablePagesCleaned returns the number of pages that have already been 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:
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.
● 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.
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_length DOUBLE The average length of all non-NULL strings in the column.
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;
Syntax
sa_conn_activity( [ connidparm ] )
Arguments
● connidparm Use this optional INTEGER parameter to specify the connection ID number.
Result set
Column name Data type Description
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
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]
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).
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.
CompPktRate NUMER- Returns a NUMERIC (5,2) value representing the overall com-
IC(5,2) pression rate of packets.
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( );
Syntax
sa_conn_info( [ connidparm ] )
Arguments
● connidparm This optional INTEGER parameter specifies the connection ID number.
Result set
Column Data type Description
name
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.
ClientPort INTEGER Returns the client's TCP/IP port number or 0 if the connection isn't a
TCP/IP connection.
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.
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.
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( );
79 DBA 0 ...
The following example uses the sa_conn_info system procedure to return a result set showing which
connection created a temporary connection.
Connection 8 created the temporary connection that executed a CREATE DATABASE statement.
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
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
Side effects
None
See also
● “sa_db_list system procedure” on page 1031
● “sa_conn_options system procedure” on page 1024
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
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
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]
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
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.
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( );
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;
Syntax
sa_convert_ml_progress_to_timestamp( progress )
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 );
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
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 );
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.
● 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;
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.
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
Syntax
sa_db_info( [ dbidparm ] )
Arguments
● dbidparm Use this optional INTEGER parameter to specify the database ID number.
Result set
Column Data type Description
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.
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.
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
Property Value
Alias demo
ConnCount 1
PageSize 4096
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
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
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.
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.
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
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.
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( );
0 0 ConnCount ...
0 1 IdleCheck ...
0 2 IdleWrite ...
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.
Result set
Column name Data type Description
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:
● 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.
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.
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
domain_name_with_size VAR- The data type name, including size and precision (as
CHAR(160) used in CREATE TABLE or CAST functions).
scale INTEGER The number of digits after the decimal point for numer-
ic data type columns, and zero for all other data types.
nulls_allowed BIT The indicator whether the expression can be NULL (1).
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.
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
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
domain_name_with_size VAR- The data type name, including size and precision (as
CHAR(160) used in CREATE TABLE or CAST functions).
scale INTEGER The number of digits after the decimal point for numer-
ic data type columns, and zero for all other data types.
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.
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:
CHAR(10) 10 10
CHAR(10 CHAR) 40 10
Permissions
None
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.
Syntax
sa_describe_shapefile( shp_filename
, srid
[, encoding ]
)
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
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:
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;
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:
○ permission disables auditing of permission checks, user checks, and SETUSER statements.
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
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' );
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.
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).
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( );
See also
● “Predefined dbspaces” [SQL Anywhere Server - Database Administration]
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:
○ permission enables auditing of permission checks, user checks, and SETUSER statements.
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' );
Syntax
sa_eng_properties( )
Result set
Column name Data type Description
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( );
1 IdleWrite ...
2 IdleChkPt ...
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.
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();
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
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]
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.
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 *
FROM sa_get_bits( @s_depts ) B
JOIN Departments D ON B.bitnum = D.DepartmentID;
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.
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
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.
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
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.
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.
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.
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' );
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.
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.
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]
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.
● 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
If a connection ID is specified, it is used to filter information from the log so that only requests for that
connection are retrieved.
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
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
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 );
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');
Syntax
sa_get_user_status( )
Arguments
None
Result set
Column name Data type Description
failed_logins UNSIGNED INT The number of failed login attempts made by the user.
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
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;
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
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
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
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
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:
● 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
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
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
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
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
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
IndexId UNSIGNED IN- The index ID. This column contains one of the following values:
TEGER
● 0 for primary keys
IndexType CHAR(4) The index type. This column contains one of the following val-
ues:
Density DOUBLE A fraction between 0 and 1 that provides an indication of how full
each index page is (on average).
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
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( );
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
IndexId UNSIGNED IN- The index ID. This column contains one of the following:
TEGER
● 0 for primary keys
IndexType CHAR(4) The index type. This column contains one of the following val-
ues:
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( );
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';
The following returns all units of measure that are based on foot:
Use the following query to find the spatial reference systems that would be installed:
The following statement queries for a spatial reference system by organization and
organization_coordsys_id:
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');
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.
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]
Syntax
sa_list_cursors( )
Result set
Column name Data type Description
scope INTEGER The scope of the call stack where the cursor is open.
is_open BIT The indicator of whether the cursor is currently open (1).
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.
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();
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.
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' );
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
● 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
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.
lock_class CHAR(8) The lock class. One of Schema, Row, Table, or Position.
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:
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.
Table Shared (shared table See “Table locks” [SQL Anywhere Server - SQL Usage].
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.
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].
Syntax
sa_make_object(
objtype,
objname
[, owner
[, tabname ] ]
)
objtype:
'procedure'
| 'function'
| 'view'
| 'trigger'
| 'service'
| 'event'
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' );
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.
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
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:
Use the following query to find the reasons why view10 cannot be changed to an immediate view:
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].
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.
● 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:
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:
● F The underlying tables have not changed since the last refresh,
and the view is considered fresh. The view is enabled and initial-
ized.
● 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.
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.
● 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.
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.
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?
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();
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 );;
view0 E (NULL) N I
view00 E (NULL) N M
● view1 is disabled
● 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.
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.
● 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.
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.
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.
Syntax
sa_migrate_create_fks( 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 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
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' );
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
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' );
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.
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 );
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.
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' );
Syntax
sa_migrate_data( 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.
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' );
Syntax
sa_migrate_drop_proxy_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 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' );
Syntax
sa_mirror_server_status( )
Result set
Column name Data type Description
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.
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.
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
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.
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
Syntax
sa_performance_diagnostics( )
Result set
Column Data type Description
name
● 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
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.
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.
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].
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].
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.
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.
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].
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.
For more information about the values returned for other types of con-
nections, see “AppInfo (APP) connection parameter” [SQL Anywhere
Server - Database Administration].
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()
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;
Syntax
sa_performance_statistics( )
Result set
Column name Data type Description
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
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;
Syntax
sa_post_login_procedure( )
Arguments
None
Result set
The sa_post_login_procedure system procedure returns the following:
Remarks
The sa_post_login_procedure system procedure is the default setting for the post_login_procedure
database option.
Permissions
DBA authority
Side effects
None
See also
● “post_login_procedure option” [SQL Anywhere Server - Database Administration]
● “Login policies” [SQL Anywhere Server - Database Administration]
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.
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 the line has been executed.
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.
● 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.
● P stored procedure
● F function
● E event
● T 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 );
Syntax
sa_procedure_profile_summary(
[ filename
[, save_to_file ] ]
)
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.
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
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.
Before you can profile your database, you must enable profiling.
● P stored procedure
● F function
● E event
● T trigger
● S 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 );
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
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]
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
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( );
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
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).
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
owner INT The connection handle of the connection owning the lock being
waited on.
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
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
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();
Syntax
sa_reset_identity(
tbl_name,
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:
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
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 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]
Example
The following query returns a result set containing one row for each day of the current month.
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.
The following example generates 10 rows of data and inserts them into the NewEmployees table:
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.
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.
The following query returns all years between 1900 and 2058 that have 54 weeks.
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
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.
● 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
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' );
Syntax
sa_server_messages( [ first_msg ] [, num_msgs ] )
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_severi- VAR- Message severity. This column contains one of the following val-
ty CHAR(255) ues:
● WARN Warning.
● ERR Error.
msg_catego- VAR- Message category. This column contains one of the following val-
ry CHAR(255) ues:
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 );
The following command requests 500 messages up to, and including, message 4032:
CALL sa_server_messages( 3 );
The following command requests the first 100 messages in the list:
The following command requests the last 100 messages in the list:
CALL sa_server_messages( );
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).
ConnsDisabled- YES, NO NO
ForDB
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]
● 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.
● 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.
● DatabaseCleaner Do not change the setting of this option except on the recommendation of
iAnywhere Technical Support.
○ 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.
● 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.
● 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.
● MessageCategoryLimit Sets the minimum number of messages of each severity and category that
can be retrieved using the sa_server_messages system procedure.
● 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' );
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.
○ CLEAR returns the profiling counters to zero and disables procedure profiling.
● 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
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.
○ 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.
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.
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
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:
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.
● 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
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 enables logging of all SQL statements, procedure calls, plans, blocking and
unblocking events, and specifies that a new request log be started:
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:
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":
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:
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' );
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.
○ 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:
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
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 (*)
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.
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.
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.
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.
The following example sets the time-out for an HTTP session to 5 minutes:
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
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>' )
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.
● 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.
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:
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.
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]
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.
● 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
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:
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)
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
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.
stmt_text
1 SELECT *
2 FROM car
Syntax
sa_table_fragmentation(
[ tbl_name
[, 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
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' );
Syntax
sa_table_page_usage( )
Result set
Column name Data type Description
PctOfFile INTEGER The percentage of the total database file the table occupies.
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]
Syntax
sa_table_stats( )
Result set
Column name Data type Description
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.
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
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.
text_config_id UNSIGNED BIGINT ID of the text configuration object referenced by the index
doc_count UNSIGNED BIGINT Total number of indexed column values in the text index
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
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( );
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
freq BIGINT The number of indexed values the term appears in.
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
... ...
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
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
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
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.
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.
Permissions
DBA authority
Side effects
None
See also
● “sa_snapshots system procedure” on page 1141
● “Snapshot isolation” [SQL Anywhere Server - SQL Usage]
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.
Permissions
DBA authority
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' );
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:
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 );
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.
● 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:
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:
Syntax
sa_validate(
[ tbl_name [, owner_name ] ]
)
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' );
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
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.
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
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;
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.
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.
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:
Following is a list of events and their associated parm_id values from the synchronize_parameters table:
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);
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.
Permissions
None
Side effects
None
See also
● “login_procedure option” [SQL Anywhere Server - Database Administration]
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.
● 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
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.
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
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' );
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
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' );
The server must be defined with the CREATE SERVER statement to use this system procedure.
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
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
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' );
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_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.
Result set
Column name Data type Description
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.
Permissions
None
Side effects
None
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 ] ] ] ]
)
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
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.
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
Examples
To get a list of all the Microsoft Excel worksheets available from an ODBC data source referenced by a
server named excel:
To get a list of all the tables owned by fred in the production database in an Adaptive Server Enterprise
server named asetest:
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.
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
Example
To display information about the remote server testasa:
CALL sp_servercaps( 'testasa' );
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';
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.
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.
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:
depth INT The depth from the root object to the object associated with this
row.
valid BIT Whether the geometry is valid (1) according to the checking level
specified by the Validate option.
geom ST_Geometry The geometry specification. If SetGeom parameter is set to No, the
geometry specification is not returned in the result set.
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.
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' );
id parent_id depth format valid geom_type geom xmin xmax ymin ymax ...
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' );
id parent_id depth format valid geom_type geom xmin xmax ymin ymax ... details
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';
Syntax
st_geometry_load_shapefile ( shp_filename
, srid
, table_name
[, table_owner ]
[, shp_encoding ] )
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' );
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' );
Syntax
xp_msver( the_option )
Arguments
● the_option The string must be one of the following, enclosed in string delimiters.
Argument Description
ProductVersion The version number, followed by the build number. The format is as follows:
12.0.1.3600
FileDescription Returns the name of the product, followed by the name of the operating sys-
tem.
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.
Version Description
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 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):
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;
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.
● attach_result This INT parameter is provided for Transact-SQL compatibility. It is not used by
SQL Anywhere. The default is 0.
● 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_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
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]';
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!' );
Syntax
xp_startmail(
[ mail_user = mail-login-name ]
[, mail_password = mail-password ] )
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
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]
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 ]
)
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.
● 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.
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]
Syntax
xp_stopmail( )
Permissions
DBA authority
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.
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]
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]
Syntax
xp_write_file(
filename,
file_contents
)
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).
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.
Prerequisites
DBA authority.
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.
5. In the left pane click a view, and in the right pane click the SQL tab.
Results
Next
None.
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.
publication_id UNSIGNED INT A unique identifier for the publication of which the column is a
part.
column_id UNSIGNED INT The column identifier, from the SYSTABCOL system view.
srvid UNSIGNED INT The server to which the capability applies, as listed in the SYS-
SERVER system view.
See also
● “SYSCAPABILITYNAME system view” on page 1197
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
check_id UNSIGNED INT A number that uniquely identifies the constraint in the data-
base.
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.
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.
update_time TIMESTAMP The time of the last update of the column statistics.
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.
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.
● T table constraint
● P primary key
● F foreign key
● U unique constraint
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.
dbspace_id SMALLINT Unique number identifying the dbspace. The system dbspace
contains all system objects and has a dbspace_id of 0.
dbspace_name CHAR(128) A unique name for the dbspace. It is used in the CREATE
TABLE command.
dbspace_id SMALLINT Unique number identifying the dbspace. The system dbspace con-
tains all system objects and has a dbspace_id of 0.
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.
See also
● “GRANT statement” on page 760
● “User IDs, authorities, and permissions” [SQL Anywhere Server - Database Administration]
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.
See also
● “sa_dependent_views system procedure” on page 1033
● “View dependencies” [SQL Anywhere Server - SQL Usage]
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.
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.
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.
● 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.
condition LONG VARCHAR The condition used to control firing of the event handler.
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.
See also
● “SYSEVENTTYPE system view” on page 1205
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
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.
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.
Each row in the SYSEXTERNENVOBJECT system view describes an installed external object. The
underlying system table for this view is ISYSEXTERNENVOBJECT.
extenv_id unsigned bigint The unique identifier for the external environment (SYSEXTER-
NENV.object_id).
name long varchar Identifies the name of the external object as specified in the IN-
STALL statement.
update_time timestamp Identifies the last time the object was modified (or installed).
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.
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.
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.
match_type TINYINT The matching type for the constraint. Matching types include:
● 1 SIMPLE
● 2 FULL
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.
operation CHAR(128) The type of operation performed on the database file. The operation
must be one of the following values:
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.
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:
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.
See also
● “SYSDBSPACE system view” on page 1202
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.
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.
● 2 Foreign key
● 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.
See also
● “SYSIDXCOL system view” on page 1213
● “SYSPHYSIDX system view” on page 1222
● “SYSDBSPACE system view” on page 1202
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.
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.
See also
● “SYSIDX system view” on page 1211
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_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.
See also
● “SYSJARCOMPONENT system view” on page 1214
See also
● “SYSJAR system view” on page 1214
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.
public CHAR(1) Indicates whether the class is public (Y) or private (N).
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.
See also
● “SYSLOGINPOLICYOPTION system view” on page 1217
● “SYSUSER system view” on page 1254
login_option_value LONG VARCHAR The value of the login policy at the time it was created.
See also
● “SYSLOGINPOLICY system view” on page 1216
● “SYSUSER system view” on page 1254
option_value LONG VARCHAR The value of the option when the mirror was created.
See also
● “SYSMIRRORSERVER system view” on page 1217
● “SYSMIRRORSERVEROPTION system view” on page 1218
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.
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.
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
option_value LONG VARCHAR The value of the option when the mirror was created.
See also
● “SYSMIRROROPTION system view” on page 1217
● “SYSMIRRORSERVER system view” on page 1217
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
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]
option_id UNSIGNED INT A number uniquely identifying the option in the database.
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]
object_id UNSIGNED The internal ID for the object, uniquely identifying it in the database.
BIGINT
creation_time TIME- The date and time when the object was created.
STAMP
user_id UNSIGNED INT The user number to whom the option setting applies.
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.
depth UNSIGNED SMALL- The depth (number of levels) of the physical index.
INT
See also
● “SYSIDX system view” on page 1211
● “SYSIDXCOL system view” on page 1213
proc_id UNSIGNED INT Each procedure is assigned a unique number (the procedure
number).
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.
remarks LONG VAR- Remarks about the procedure. This value is stored in the ISYS-
CHAR REMARK system table.
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.
proc_id UNSIGNED INT Uniquely identifies the procedure to which the parameter be-
longs.
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.
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.
"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.
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.
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.
object_id UNSIGNED BI- The internal ID for the publication, uniquely identifying it in the
GINT database.
remarks LONG VAR- Remarks about the publication. This value is stored in the ISYS-
CHAR REMARK system table.
sync_type UNSIGNED INT The type of synchronization for the publication. Values include:
See also
● “Scripted upload” [MobiLink - Client Administration]
● “SYSSYNCSCRIPT system view” on page 1240
object_id UNSIGNED BIGINT The internal ID for the object that has an associated remark.
remarks LONG VARCHAR The remark or comment associated with the object.
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.
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.
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.
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.
remarks LONG VARCHAR Remarks about the remote type. This value is stored in the
ISYSREMARK system table.
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).
address LONG VAR- The address to which SQL Remote messages are to be sent.
CHAR The address must be appropriate for the address_type.
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.
rereceive_count INTEGER Counter to ensure that messages are applied only once at the
current database.
sched_name VARCHAR(128) The name associated with the schedule for the event.
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:
● HH = hours
● NN = minutes
● SS = seconds
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
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.
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.
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.
srvclass LONG VARCHAR The server class, as specified in the CREATE SERVER state-
ment.
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.
See also
● “preserve_source_format option” [SQL Anywhere Server - Database Administration]
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.
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.
organization LONG VAR- The name of the organization that created the coordinate
CHAR system used by the spatial reference system.
srs_type CHAR(11) The type of SRS as defined by the SQL/MM standard. Val-
ues can be one of:
● GEOCENTRIC Unsupported.
● COMPOUND Unsupported.
● VERTICAL Unsupported.
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.
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.
See also
● “ST_SPATIAL_REFERENCE_SYSTEMS consolidated view” on page 1261
● “CREATE SPATIAL REFERENCE SYSTEM statement” on page 616
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.
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.
progress UNSIGNED BI- The log offset of the last successful upload.
GINT
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.
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.
pub_object_id UNSIGNED BIGINT The object ID of the publication to which the script belongs.
table_object_id UNSIGNED BIGINT The object ID of the table to which the script applies.
proc_object_id UNSIGNED BIGINT The object ID of the stored procedure to use for the publica-
tion.
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
table_id UNSIGNED Each table is assigned a unique number (the table number).
INT
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.
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.
last_modified_at TIMESTAMP The time at which the data in the table was last modified. This
column is only updated at checkpoint time.
table_name CHAR(128) The name of the table or view. One creator cannot have two ta-
bles or views with the same name.
● 1 Base table
● 2 Materialized view
● 21 View
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.
● VIEW View
See also
● “SYSVIEW system view” on page 1257
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.
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.
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.
"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).
collect_stats TINYINT Whether the system automatically collects and updates statistics
on this column.
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.
See also
● “CREATE TABLE statement” on page 633
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
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.
See also
● “GRANT statement” on page 760
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.
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.
prefilter LONG VAR- The function and library name for an external prefilter li-
CHAR brary.
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.
exter- LONG VAR- The function and library name for an external term breaker
nal_term_breaker CHAR library.
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]
text_config UNSIGNED BIGINT The object ID of the text configuration object in SYSTEXT-
CONFIG.
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.
● 1 MANUAL
● 2 AUTO
● 3 IMMEDIATE
See also
● “Full text search” [SQL Anywhere Server - SQL Usage]
See also
● “Full text search” [SQL Anywhere Server - SQL Usage]
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
● A INSERT, DELETE
● B INSERT, UPDATE
● C UPDATE COLUMNS
● D DELETE
● E DELETE, UPDATE
● I INSERT
● U UPDATE
trigger_time CHAR(1) The time when the trigger fires relative to the event.
● R RESOLVE
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.
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.
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.
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.
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.
See also
● “SYSLOGINPOLICY system view” on page 1216
● “SYSLOGINPOLICYOPTION system view” on page 1217
user_id UNSIGNED INT The ID of the user to whom the authority belongs.
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.
uid UNSIGNED INT The user number that defined the message.
type_id SMALLINT A unique identifying number for the user-defined data type.
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.
"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.
You can also use the sa_materialized_view_info system procedure for a more readable format of the
information for materialized views.
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.
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
service_id UNSIGNED INT A unique identifying number for 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.
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.
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).
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.
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.
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.
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.
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]
srs_id INT The numeric identifier (SRID) for the spatial reference
system.
● GEOCENTRIC Unsupported.
● COMPOUND Unsupported.
● VERTICAL Unsupported.
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.
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. This is a ratio created by the following
equation:
1/f = (semi-major-axis) / (semi-major-axis
- semi-minor-axis)
organization LONG VAR- The name of the organization that created the coordinate
CHAR system used by the spatial reference system.
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).
transform_definition LONG VAR- Transform definition settings for use when transforming
CHAR data from this SRS to another.
See also
● “SYSSPATIALREFERENCESYSTEM system view” on page 1234
● “CREATE SPATIAL REFERENCE SYSTEM statement” on page 616
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
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
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
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
See also
● “SYSCAPABILITY system view” on page 1197
● “SYSCAPABILITYNAME system view” on page 1197
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
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
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
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
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
'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
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
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
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
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'
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
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.
See also
● “SYSOPTION system view” on page 1221
● “SYSUSER system view” on page 1254
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
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
The tables and columns that make up this view are provided in the ALTER VIEW statement below.
See also
● “SYSPROCEDURE system view” on page 1223
● “SYSUSER system view” on page 1254
● “SYSREMARK system view” on page 1227
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
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
See also
● “SYSREMOTEOPTION system view” on page 1228
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
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
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
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
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.
See also
● “SYSSYNC system view” on page 1238
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.
See also
● “SYSSYNC system view” on page 1238
● “SYSPUBLICATION system view” on page 1226
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.
See also
● “SYSSYNC system view” on page 1238
● “SYSPUBLICATION system view” on page 1226
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]
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.
See also
● “SYSSYNC system view” on page 1238
● “SYSPUBLICATION system view” on page 1226
● “SYSSYNCUSERS consolidated view” on page 1277
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.
See also
● “SYSSYNC system view” on page 1238
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
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
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
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
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 )
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.
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
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
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
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]
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
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.
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
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.
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
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
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
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,
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
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
See also
● “SYSUSERAUTHORITY system view” on page 1255
● “SYSUSERPERM compatibility view (deprecated)” on page 1287
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
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
See also
● “SYSUSERAUTHORITY system view” on page 1255
● “SYSUSER system view” on page 1254
● “SYSREMARK system view” on page 1227
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
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.
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
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
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
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
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
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
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
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
Y
YEAR function
syntax, 390
YEARS function
syntax, 391
YMD function
syntax, 392
Z
zip utility
COMPRESS function, 166